commit 917fee86de3947525d91135ae2c5964ef615480f Author: Jeevan Prasad Date: Thu Jun 26 15:10:22 2025 +0530 Add new changes GeoFencing-GeoTaging and hide Manual Inword Option etc diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..2b75303 --- /dev/null +++ b/.gitignore @@ -0,0 +1,13 @@ +*.iml +.gradle +/local.properties +/.idea/caches +/.idea/libraries +/.idea/modules.xml +/.idea/workspace.xml +/.idea/navEditor.xml +/.idea/assetWizardSettings.xml +.DS_Store +/build +/captures +.externalNativeBuild diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..26d3352 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,3 @@ +# Default ignored files +/shelf/ +/workspace.xml diff --git a/.idea/AndroidProjectSystem.xml b/.idea/AndroidProjectSystem.xml new file mode 100644 index 0000000..4a53bee --- /dev/null +++ b/.idea/AndroidProjectSystem.xml @@ -0,0 +1,6 @@ + + + + + \ No newline at end of file diff --git a/.idea/appInsightsSettings.xml b/.idea/appInsightsSettings.xml new file mode 100644 index 0000000..a79a228 --- /dev/null +++ b/.idea/appInsightsSettings.xml @@ -0,0 +1,40 @@ + + + + + + \ No newline at end of file diff --git a/.idea/compiler.xml b/.idea/compiler.xml new file mode 100644 index 0000000..b589d56 --- /dev/null +++ b/.idea/compiler.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/.idea/deploymentTargetSelector.xml b/.idea/deploymentTargetSelector.xml new file mode 100644 index 0000000..b268ef3 --- /dev/null +++ b/.idea/deploymentTargetSelector.xml @@ -0,0 +1,10 @@ + + + + + + + + + \ No newline at end of file diff --git a/.idea/gradle.xml b/.idea/gradle.xml new file mode 100644 index 0000000..d8f4a29 --- /dev/null +++ b/.idea/gradle.xml @@ -0,0 +1,23 @@ + + + + + + + \ No newline at end of file diff --git a/.idea/inspectionProfiles/Project_Default.xml b/.idea/inspectionProfiles/Project_Default.xml new file mode 100644 index 0000000..9bc108a --- /dev/null +++ b/.idea/inspectionProfiles/Project_Default.xml @@ -0,0 +1,8 @@ + + + + \ No newline at end of file diff --git a/.idea/migrations.xml b/.idea/migrations.xml new file mode 100644 index 0000000..f8051a6 --- /dev/null +++ b/.idea/migrations.xml @@ -0,0 +1,10 @@ + + + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..976cf21 --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,10 @@ + + + + + + + + + \ No newline at end of file diff --git a/.idea/runConfigurations.xml b/.idea/runConfigurations.xml new file mode 100644 index 0000000..16660f1 --- /dev/null +++ b/.idea/runConfigurations.xml @@ -0,0 +1,17 @@ + + + + + + \ No newline at end of file diff --git a/annca/.gitignore b/annca/.gitignore new file mode 100644 index 0000000..796b96d --- /dev/null +++ b/annca/.gitignore @@ -0,0 +1 @@ +/build diff --git a/annca/build.gradle b/annca/build.gradle new file mode 100644 index 0000000..c54808d --- /dev/null +++ b/annca/build.gradle @@ -0,0 +1,78 @@ +apply plugin: 'com.android.library' + +buildscript { + repositories { + jcenter() + } +} + +group = 'io.github.memfis19' +version = '0.3.7' + +ext { + PUBLISH_GROUP_ID = 'io.github.memfis19' + PUBLISH_ARTIFACT_ID = 'annca' + PUBLISH_VERSION = '0.3.7' + PUBLISH_VERSION_CODE = 11 + SUPPORT_VERSION = '25.3.1' + TARGET_SDK = 35 + MIN_SDK = 24 +} + +android { + namespace ("io.github.memfis19.annca") + compileSdk(35) + defaultConfig { + minSdkVersion MIN_SDK + targetSdkVersion TARGET_SDK + } + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' + } + } + lintOptions { + abortOnError false + } + +} + +// ✅ Sources JAR +tasks.register('generateSourcesJar', Jar) { + archiveClassifier.set('sources') + from android.sourceSets.main.java.srcDirs +} + +// ✅ Javadocs Task +tasks.register('generateJavadocs', Javadoc) { + failOnError = false + source = android.sourceSets.main.java.srcDirs + classpath += project.files(android.bootClasspath.join(File.pathSeparator)) +} + +// ✅ Javadocs JAR +tasks.register("generateJavadocsJar", Jar) { + archiveClassifier.set("javadoc") + from(tasks.named("generateJavadocs")) +} + +tasks.named("generateJavadocsJar").configure { + dependsOn tasks.named("generateJavadocs") +} + +// ✅ Publishing artifacts +artifacts { + archives(tasks.named("generateSourcesJar")) + archives(tasks.named("generateJavadocsJar")) +} + +dependencies { + implementation 'androidx.appcompat:appcompat:1.3.1' + androidTestImplementation 'androidx.annotation:annotation:1.2.0' + implementation fileTree(include: ['*.jar'], dir: 'libs') +} + +tasks.register('wrapper', Wrapper) { + gradleVersion = '2.4' +} \ No newline at end of file diff --git a/annca/proguard-rules.pro b/annca/proguard-rules.pro new file mode 100644 index 0000000..aa55aa4 --- /dev/null +++ b/annca/proguard-rules.pro @@ -0,0 +1,17 @@ +# Add project specific ProGuard rules here. +# By default, the flags in this file are appended to flags specified +# in /Users/memfis/Library/Android/sdk/tools/proguard/proguard-android.txt +# You can edit the include path and order by changing the proguardFiles +# directive in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# Add any project specific keep options here: + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} diff --git a/annca/src/main/AndroidManifest.xml b/annca/src/main/AndroidManifest.xml new file mode 100644 index 0000000..78a3ef6 --- /dev/null +++ b/annca/src/main/AndroidManifest.xml @@ -0,0 +1,11 @@ + + + + + + + + diff --git a/annca/src/main/java/io/github/memfis19/annca/Annca.java b/annca/src/main/java/io/github/memfis19/annca/Annca.java new file mode 100644 index 0000000..3778f9f --- /dev/null +++ b/annca/src/main/java/io/github/memfis19/annca/Annca.java @@ -0,0 +1,79 @@ +package io.github.memfis19.annca; + +import android.Manifest; +import android.app.Activity; +import android.content.Intent; + +import androidx.annotation.IntRange; +import androidx.annotation.RequiresPermission; +import androidx.fragment.app.Fragment; + +import io.github.memfis19.annca.internal.configuration.AnncaConfiguration; +import io.github.memfis19.annca.internal.ui.camera.Camera1Activity; + +/** + * Created by memfis on 7/6/16. + */ +public class Annca { + + private final AnncaConfiguration anncaConfiguration; + + /*** + * Creates Annca instance with default configuration set to photo with medium quality. + * + * @param activity - fromList which request was invoked + * @param requestCode - request code which will return in onActivityForResult + */ + public Annca(Activity activity, @IntRange(from = 0) int requestCode) { + AnncaConfiguration.Builder builder = new AnncaConfiguration.Builder(activity, requestCode); + anncaConfiguration = builder.build(); + } + + public Annca(Fragment fragment, @IntRange(from = 0) int requestCode) { + AnncaConfiguration.Builder builder = new AnncaConfiguration.Builder(fragment, requestCode); + anncaConfiguration = builder.build(); + } + + /*** + * Creates Annca instance with custom camera configuration. + * + */ + public Annca(AnncaConfiguration cameraConfiguration) { + this.anncaConfiguration = cameraConfiguration; + } + + @RequiresPermission(Manifest.permission.CAMERA) + public void launchCamera(String path, boolean showGrid, int cameraFace) { + if (anncaConfiguration == null || (anncaConfiguration.getActivity() == null && + anncaConfiguration.getFragment() == null)) + return; + Intent cameraIntent; + if (anncaConfiguration.getFragment() != null) { + cameraIntent = new Intent(anncaConfiguration.getFragment().getContext(), Camera1Activity.class); + } else { + cameraIntent = new Intent(anncaConfiguration.getActivity(), Camera1Activity.class); + } + + cameraIntent.putExtra(AnncaConfiguration.Arguments.REQUEST_CODE, anncaConfiguration.getRequestCode()); + cameraIntent.putExtra(AnncaConfiguration.Arguments.CAMERA_FACE, cameraFace); + cameraIntent.putExtra(AnncaConfiguration.Arguments.FILE_PATH, path); + cameraIntent.putExtra(AnncaConfiguration.Arguments.SHOW_GRID, showGrid); + cameraIntent.putExtra(AnncaConfiguration.Arguments.MEDIA_RESULT_BEHAVIOUR, anncaConfiguration.getMediaResultBehaviour()); + if (anncaConfiguration.getMediaAction() > 0) + cameraIntent.putExtra(AnncaConfiguration.Arguments.MEDIA_ACTION, anncaConfiguration.getMediaAction()); + if (anncaConfiguration.getMediaQuality() > 0) + cameraIntent.putExtra(AnncaConfiguration.Arguments.MEDIA_QUALITY, anncaConfiguration.getMediaQuality()); + if (anncaConfiguration.getVideoDuration() > 0) + cameraIntent.putExtra(AnncaConfiguration.Arguments.VIDEO_DURATION, anncaConfiguration.getVideoDuration()); + if (anncaConfiguration.getVideoFileSize() > 0) + cameraIntent.putExtra(AnncaConfiguration.Arguments.VIDEO_FILE_SIZE, anncaConfiguration.getVideoFileSize()); + if (anncaConfiguration.getMinimumVideoDuration() > 0) + cameraIntent.putExtra(AnncaConfiguration.Arguments.MINIMUM_VIDEO_DURATION, anncaConfiguration.getMinimumVideoDuration()); + cameraIntent.putExtra(AnncaConfiguration.Arguments.FLASH_MODE, anncaConfiguration.getFlashMode()); + if (anncaConfiguration.getFragment() != null) { + anncaConfiguration.getFragment().startActivityForResult(cameraIntent, anncaConfiguration.getRequestCode()); + } else { + anncaConfiguration.getActivity().startActivityForResult(cameraIntent, anncaConfiguration.getRequestCode()); + } + } +} diff --git a/annca/src/main/java/io/github/memfis19/annca/internal/configuration/AnncaConfiguration.java b/annca/src/main/java/io/github/memfis19/annca/internal/configuration/AnncaConfiguration.java new file mode 100644 index 0000000..a4e2455 --- /dev/null +++ b/annca/src/main/java/io/github/memfis19/annca/internal/configuration/AnncaConfiguration.java @@ -0,0 +1,270 @@ +package io.github.memfis19.annca.internal.configuration; + +import android.app.Activity; +import androidx.annotation.IntDef; +import androidx.annotation.IntRange; +import androidx.annotation.NonNull; +import androidx.fragment.app.Fragment; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +/** + * Created by memfis on 7/6/16. + */ +public final class AnncaConfiguration { + + public static final int MEDIA_QUALITY_AUTO = 10; + public static final int MEDIA_QUALITY_LOWEST = 15; + public static final int MEDIA_QUALITY_LOW = 11; + public static final int MEDIA_QUALITY_MEDIUM = 12; + public static final int MEDIA_QUALITY_HIGH = 13; + public static final int MEDIA_QUALITY_HIGHEST = 14; + + public static final int MEDIA_ACTION_VIDEO = 100; + public static final int MEDIA_ACTION_PHOTO = 101; + public static final int MEDIA_ACTION_UNSPECIFIED = 102; + + public static final int CAMERA_FACE_FRONT = 0x6; + public static final int CAMERA_FACE_REAR = 0x7; + + public static final int SENSOR_POSITION_UP = 90; + public static final int SENSOR_POSITION_UP_SIDE_DOWN = 270; + public static final int SENSOR_POSITION_LEFT = 0; + public static final int SENSOR_POSITION_RIGHT = 180; + public static final int SENSOR_POSITION_UNSPECIFIED = -1; + + public static final int DISPLAY_ROTATION_0 = 0; + public static final int DISPLAY_ROTATION_90 = 90; + public static final int DISPLAY_ROTATION_180 = 180; + public static final int DISPLAY_ROTATION_270 = 270; + + public static final int ORIENTATION_PORTRAIT = 0x111; + public static final int ORIENTATION_LANDSCAPE = 0x222; + + public static final int FLASH_MODE_ON = 1; + public static final int FLASH_MODE_OFF = 2; + public static final int FLASH_MODE_AUTO = 3; + + public static final int PREVIEW = 1; + public static final int CLOSE = 2; + public static final int CONTINUE = 3; + + public interface Arguments { + String REQUEST_CODE = "io.memfis19.annca.request_code"; + String MEDIA_ACTION = "io.memfis19.annca.media_action"; + String MEDIA_QUALITY = "io.memfis19.annca.camera_media_quality"; + String VIDEO_DURATION = "io.memfis19.annca.video_duration"; + String MINIMUM_VIDEO_DURATION = "io.memfis19.annca.minimum.video_duration"; + String VIDEO_FILE_SIZE = "io.memfis19.annca.camera_video_file_size"; + String FLASH_MODE = "io.memfis19.annca.camera_flash_mode"; + String FILE_PATH = "io.memfis19.annca.camera_video_file_path"; + String SHOW_GRID = "showGrid"; + String CAMERA_FACE = "io.memfis19.annca.camera_face"; + String MEDIA_RESULT_BEHAVIOUR = "io.memfis19.annca.media_result_behaviour"; + } + + @IntDef({MEDIA_QUALITY_AUTO, MEDIA_QUALITY_LOWEST, MEDIA_QUALITY_LOW, MEDIA_QUALITY_MEDIUM, MEDIA_QUALITY_HIGH, MEDIA_QUALITY_HIGHEST}) + @Retention(RetentionPolicy.SOURCE) + public @interface MediaQuality { + } + + @IntDef({PREVIEW, CLOSE, CONTINUE}) + @Retention(RetentionPolicy.SOURCE) + public @interface MediaResultBehaviour { + } + + @IntDef({MEDIA_ACTION_VIDEO, MEDIA_ACTION_PHOTO, MEDIA_ACTION_UNSPECIFIED}) + @Retention(RetentionPolicy.SOURCE) + public @interface MediaAction { + } + + @IntDef({FLASH_MODE_ON, FLASH_MODE_OFF, FLASH_MODE_AUTO}) + @Retention(RetentionPolicy.SOURCE) + public @interface FlashMode { + } + + @IntDef({CAMERA_FACE_FRONT, CAMERA_FACE_REAR}) + @Retention(RetentionPolicy.SOURCE) + public @interface CameraFace { + } + + @IntDef({SENSOR_POSITION_UP, SENSOR_POSITION_UP_SIDE_DOWN, SENSOR_POSITION_LEFT, SENSOR_POSITION_RIGHT, SENSOR_POSITION_UNSPECIFIED}) + @Retention(RetentionPolicy.SOURCE) + public @interface SensorPosition { + } + + @IntDef({DISPLAY_ROTATION_0, DISPLAY_ROTATION_90, DISPLAY_ROTATION_180, DISPLAY_ROTATION_270}) + @Retention(RetentionPolicy.SOURCE) + public @interface DisplayRotation { + } + + @IntDef({ORIENTATION_PORTRAIT, ORIENTATION_LANDSCAPE}) + @Retention(RetentionPolicy.SOURCE) + public @interface DeviceDefaultOrientation { + } + + private Activity activity = null; + private Fragment fragment = null; + + private int requestCode = -1; + + @MediaAction + private int mediaAction = -1; + + @MediaResultBehaviour + private int mediaResultBehaviour = PREVIEW; + + @MediaQuality + private int mediaQuality = -1; + + @CameraFace + private int cameraFace = CAMERA_FACE_REAR; + + private int videoDuration = -1; + + private long videoFileSize = -1; + + private int minimumVideoDuration = -1; + + private String outPutFilePath = ""; + + @FlashMode + private int flashMode = FLASH_MODE_AUTO; + + private AnncaConfiguration(Activity activity, int requestCode) { + this.activity = activity; + this.requestCode = requestCode; + } + + private AnncaConfiguration(@NonNull Fragment fragment, int requestCode) { + this.fragment = fragment; + this.requestCode = requestCode; + } + + public static class Builder { + + private AnncaConfiguration anncaConfiguration; + + + public Builder(@NonNull Activity activity, @IntRange(from = 0) int requestCode) { + anncaConfiguration = new AnncaConfiguration(activity, requestCode); + } + + public Builder(@NonNull Fragment fragment, @IntRange(from = 0) int requestCode) { + anncaConfiguration = new AnncaConfiguration(fragment, requestCode); + } + + public Builder setMediaAction(@MediaAction int mediaAction) { + anncaConfiguration.mediaAction = mediaAction; + return this; + } + + public Builder setCameraFace(@CameraFace int cameraFace) { + anncaConfiguration.cameraFace = cameraFace; + return this; + } + + public Builder setMediaResultBehaviour(@MediaResultBehaviour int mediaResultBehaviour) { + anncaConfiguration.mediaResultBehaviour = mediaResultBehaviour; + return this; + } + + public Builder setMediaQuality(@MediaQuality int mediaQuality) { + anncaConfiguration.mediaQuality = mediaQuality; + return this; + } + + /*** + * @param videoDurationInMilliseconds - video duration in milliseconds + * @return + */ + public Builder setVideoDuration(@IntRange(from = 1000, to = Integer.MAX_VALUE) int videoDurationInMilliseconds) { + anncaConfiguration.videoDuration = videoDurationInMilliseconds; + return this; + } + + /*** + * @param minimumVideoDurationInMilliseconds - minimum video duration in milliseconds, used only in video mode + * for auto quality. + * @return + */ + public Builder setMinimumVideoDuration(@IntRange(from = 1000, to = Integer.MAX_VALUE) int minimumVideoDurationInMilliseconds) { + anncaConfiguration.minimumVideoDuration = minimumVideoDurationInMilliseconds; + return this; + } + + /*** + * @param videoSizeInBytes - file size in bytes + * @return + */ + public Builder setVideoFileSize(@IntRange(from = 1048576, to = Long.MAX_VALUE) long videoSizeInBytes) { + anncaConfiguration.videoFileSize = videoSizeInBytes; + return this; + } + + public Builder setFlashMode(@FlashMode int flashMode) { + anncaConfiguration.flashMode = flashMode; + return this; + } + + public AnncaConfiguration build() throws IllegalArgumentException { + if (anncaConfiguration.requestCode < 0) + throw new IllegalArgumentException("Wrong request code value. Please set the value > 0."); + if (anncaConfiguration.mediaQuality == MEDIA_QUALITY_AUTO && anncaConfiguration.minimumVideoDuration < 0) { + throw new IllegalStateException("Please provide minimum video duration in milliseconds to use auto quality."); + } + + return anncaConfiguration; + } + + } + + public Activity getActivity() { + return activity; + } + + public Fragment getFragment() { + return fragment; + } + + public int getRequestCode() { + return requestCode; + } + + public int getMediaAction() { + return mediaAction; + } + + public int getMediaQuality() { + return mediaQuality; + } + + public int getCameraFace() { + return cameraFace; + } + + public int getMediaResultBehaviour() { + return mediaResultBehaviour; + } + + public String getOutPutFilePath() { + return outPutFilePath; + } + + public int getVideoDuration() { + return videoDuration; + } + + public long getVideoFileSize() { + return videoFileSize; + } + + public int getMinimumVideoDuration() { + return minimumVideoDuration; + } + + public int getFlashMode() { + return flashMode; + } +} diff --git a/annca/src/main/java/io/github/memfis19/annca/internal/configuration/ConfigurationProvider.java b/annca/src/main/java/io/github/memfis19/annca/internal/configuration/ConfigurationProvider.java new file mode 100644 index 0000000..ea8e2b6 --- /dev/null +++ b/annca/src/main/java/io/github/memfis19/annca/internal/configuration/ConfigurationProvider.java @@ -0,0 +1,41 @@ +package io.github.memfis19.annca.internal.configuration; + +import io.github.memfis19.annca.internal.ui.view.CameraSwitchView; + +/** + * Created by memfis on 7/6/16. + */ +public interface ConfigurationProvider { + + int getRequestCode(); + + @AnncaConfiguration.MediaAction + int getMediaAction(); + + @AnncaConfiguration.MediaQuality + int getMediaQuality(); + + int getVideoDuration(); + + long getVideoFileSize(); + + @AnncaConfiguration.SensorPosition + int getSensorPosition(); + + int getDegrees(); + + int getMinimumVideoDuration(); + + @AnncaConfiguration.FlashMode + int getFlashMode(); + + @CameraSwitchView.CameraType + int getCameraFace(); + + String getFilePath(); + + boolean getShowGrid(); + + @AnncaConfiguration.MediaResultBehaviour + int getMediaResultBehaviour(); +} diff --git a/annca/src/main/java/io/github/memfis19/annca/internal/controller/CameraController.java b/annca/src/main/java/io/github/memfis19/annca/internal/controller/CameraController.java new file mode 100644 index 0000000..c9b69dc --- /dev/null +++ b/annca/src/main/java/io/github/memfis19/annca/internal/controller/CameraController.java @@ -0,0 +1,52 @@ +package io.github.memfis19.annca.internal.controller; + +import android.annotation.SuppressLint; +import android.os.Bundle; + +import java.io.File; + +import io.github.memfis19.annca.internal.configuration.AnncaConfiguration; +import io.github.memfis19.annca.internal.manager.CameraManager; + +/** + * Created by memfis on 7/6/16. + */ +public interface CameraController { + + void onCreate(Bundle savedInstanceState); + + void onResume(); + + void onPause(); + + void onDestroy(); + + void takePhoto(); + + void startVideoRecord(); + + void stopVideoRecord(); + + void openCamera(); + + boolean isVideoRecording(); + + void switchCamera(@AnncaConfiguration.CameraFace int cameraFace); + + void switchQuality(); + + void setFlashMode(@AnncaConfiguration.FlashMode int flashMode); + + int getNumberOfCameras(); + + @SuppressLint("SupportAnnotationUsage") + @AnncaConfiguration.MediaAction + + CameraId getCurrentCameraId(); + + int getMediaAction(); + + File getOutputFile(); + + CameraManager getCameraManager(); +} diff --git a/annca/src/main/java/io/github/memfis19/annca/internal/controller/impl/Camera1Controller.java b/annca/src/main/java/io/github/memfis19/annca/internal/controller/impl/Camera1Controller.java new file mode 100644 index 0000000..00ca732 --- /dev/null +++ b/annca/src/main/java/io/github/memfis19/annca/internal/controller/impl/Camera1Controller.java @@ -0,0 +1,189 @@ +package io.github.memfis19.annca.internal.controller.impl; + +import android.hardware.Camera; +import android.os.Bundle; +import android.text.TextUtils; +import android.util.Log; +import android.view.SurfaceHolder; + +import java.io.File; + +import io.github.memfis19.annca.internal.configuration.AnncaConfiguration; +import io.github.memfis19.annca.internal.configuration.ConfigurationProvider; +import io.github.memfis19.annca.internal.controller.view.CameraView; +import io.github.memfis19.annca.internal.manager.CameraManager; +import io.github.memfis19.annca.internal.manager.impl.Camera1Manager; +import io.github.memfis19.annca.internal.manager.listener.CameraCloseListener; +import io.github.memfis19.annca.internal.manager.listener.CameraOpenListener; +import io.github.memfis19.annca.internal.manager.listener.CameraPhotoListener; +import io.github.memfis19.annca.internal.manager.listener.CameraVideoListener; +import io.github.memfis19.annca.internal.ui.view.AutoFitSurfaceView; +import io.github.memfis19.annca.internal.ui.view.CameraSwitchView; +import io.github.memfis19.annca.internal.utils.CameraHelper; +import io.github.memfis19.annca.internal.utils.Size; + +/** + * Created by memfis on 7/7/16. + */ + +@SuppressWarnings("deprecation") +public class Camera1Controller implements io.github.memfis19.annca.internal.controller.CameraController, + CameraOpenListener, CameraPhotoListener, CameraCloseListener, CameraVideoListener { + + private final static String TAG = "Camera1Controller"; + + private Integer currentCameraId; + private ConfigurationProvider configurationProvider; + private CameraManager cameraManager; + private CameraView cameraView; + + private File outputFile; + + public Camera1Controller(CameraView cameraView, ConfigurationProvider configurationProvider) { + this.cameraView = cameraView; + this.configurationProvider = configurationProvider; + } + + @Override + public void onCreate(Bundle savedInstanceState) { + cameraManager = Camera1Manager.getInstance(); + cameraManager.initializeCameraManager(configurationProvider, cameraView.getActivity()); + if (configurationProvider.getCameraFace() == CameraSwitchView.CAMERA_TYPE_FRONT) { + currentCameraId = cameraManager.getFaceFrontCameraId() == null ? cameraManager.getFaceBackCameraId() : cameraManager.getFaceFrontCameraId(); + } else { + currentCameraId = cameraManager.getFaceBackCameraId(); + } + } + + @Override + public void openCamera() { + cameraManager.openCamera(currentCameraId, this); + } + + @Override + public void onResume() { + openCamera(); + } + + @Override + public void onPause() { + cameraManager.closeCamera(null); + } + + @Override + public void onDestroy() { + cameraManager.releaseCameraManager(); + } + + @Override + public void takePhoto() { + outputFile = TextUtils.isEmpty(configurationProvider. getFilePath()) ? CameraHelper.getOutputMediaFile(cameraView.getActivity(), AnncaConfiguration.MEDIA_ACTION_PHOTO) : new File(configurationProvider.getFilePath()); + cameraManager.takePhoto(outputFile, this); + } + + @Override + public void startVideoRecord() { + outputFile = TextUtils.isEmpty(configurationProvider.getFilePath()) ? CameraHelper.getOutputMediaFile(cameraView.getActivity(), AnncaConfiguration.MEDIA_ACTION_VIDEO) : new File(configurationProvider.getFilePath()); + cameraManager.startVideoRecord(outputFile, this); + } + + @Override + public void stopVideoRecord() { + cameraManager.stopVideoRecord(); + } + + @Override + public boolean isVideoRecording() { + return cameraManager.isVideoRecording(); + } + + @Override + public void switchCamera(@AnncaConfiguration.CameraFace final int cameraFace) { + currentCameraId = cameraManager.getCurrentCameraId().equals(cameraManager.getFaceFrontCameraId()) ? + cameraManager.getFaceBackCameraId() : cameraManager.getFaceFrontCameraId(); + cameraManager.closeCamera(this); + } + + @Override + public void setFlashMode(@AnncaConfiguration.FlashMode int flashMode) { + cameraManager.setFlashMode(flashMode); + } + + @Override + public void switchQuality() { + cameraManager.closeCamera(this); + } + + @Override + public int getNumberOfCameras() { + return cameraManager.getNumberOfCameras(); + } + + @Override + public int getMediaAction() { + return configurationProvider.getMediaAction(); + } + + @Override + public File getOutputFile() { + return outputFile; + } + + @Override + public Integer getCurrentCameraId() { + return currentCameraId; + } + + @Override + public void onCameraOpened(Integer cameraId, Size previewSize, SurfaceHolder.Callback surfaceCallback, Camera camera) { + cameraView.updateUiForMediaAction(configurationProvider.getMediaAction()); + cameraView.updateCameraPreview(previewSize, new AutoFitSurfaceView(cameraView.getActivity(), surfaceCallback, camera, configurationProvider.getShowGrid())); + cameraView.updateCameraSwitcher(getNumberOfCameras()); + } + + @Override + public void onCameraReady() { + cameraView.onCameraReady(); + } + + @Override + public void onCameraOpenError() { + //test(TAG, "onCameraOpenError"); + } + + @Override + public void onCameraClosed(Integer closedCameraId) { + cameraView.releaseCameraPreview(); + cameraManager.openCamera(currentCameraId, this); + } + + @Override + public void onPhotoTaken(File photoFile) { + cameraView.onPhotoTaken(); + } + + @Override + public void onPhotoTakeError() { + } + + @Override + public void onVideoRecordStarted(Size videoSize) { + cameraView.onVideoRecordStart(videoSize.getWidth(), videoSize.getHeight()); + } + + @Override + public void onVideoRecordStopped(File videoFile) { + cameraView.onVideoRecordStop(); + } + + @Override + public void onVideoRecordError() { + + } + + @Override + public CameraManager getCameraManager() { + return cameraManager; + } + +} diff --git a/annca/src/main/java/io/github/memfis19/annca/internal/controller/impl/Camera2Controller.java b/annca/src/main/java/io/github/memfis19/annca/internal/controller/impl/Camera2Controller.java new file mode 100644 index 0000000..5b9e9bb --- /dev/null +++ b/annca/src/main/java/io/github/memfis19/annca/internal/controller/impl/Camera2Controller.java @@ -0,0 +1,197 @@ +package io.github.memfis19.annca.internal.controller.impl; + +import android.annotation.TargetApi; +import android.hardware.Camera; +import android.hardware.camera2.CameraDevice; +import android.hardware.camera2.CaptureRequest; +import android.os.Build; +import android.os.Bundle; +import android.text.TextUtils; +import android.util.Log; +import android.view.TextureView; + +import java.io.File; + +import io.github.memfis19.annca.internal.configuration.AnncaConfiguration; +import io.github.memfis19.annca.internal.configuration.ConfigurationProvider; +import io.github.memfis19.annca.internal.controller.CameraController; +import io.github.memfis19.annca.internal.controller.view.CameraView; +import io.github.memfis19.annca.internal.manager.CameraManager; +import io.github.memfis19.annca.internal.manager.impl.Camera2Manager; +import io.github.memfis19.annca.internal.manager.listener.CameraCloseListener; +import io.github.memfis19.annca.internal.manager.listener.CameraOpenListener; +import io.github.memfis19.annca.internal.manager.listener.CameraPhotoListener; +import io.github.memfis19.annca.internal.manager.listener.CameraVideoListener; +import io.github.memfis19.annca.internal.ui.view.AutoFitTextureView; +import io.github.memfis19.annca.internal.ui.view.CameraSwitchView; +import io.github.memfis19.annca.internal.utils.CameraHelper; +import io.github.memfis19.annca.internal.utils.Size; + +/** + * Created by memfis on 7/6/16. + */ +public class Camera2Controller implements CameraController, + CameraOpenListener, + CameraPhotoListener, CameraVideoListener, CameraCloseListener { + + private final static String TAG = "Camera2Controller"; + + private String currentCameraId; + private ConfigurationProvider configurationProvider; + private CameraManager camera2Manager; + private CameraView cameraView; + + private File outputFile; + + public Camera2Controller(CameraView cameraView, ConfigurationProvider configurationProvider) { + this.cameraView = cameraView; + this.configurationProvider = configurationProvider; + } + + @Override + public void onCreate(Bundle savedInstanceState) { + camera2Manager = Camera2Manager.getInstance(); + camera2Manager.initializeCameraManager(configurationProvider, cameraView.getActivity()); + + if (configurationProvider.getCameraFace() == CameraSwitchView.CAMERA_TYPE_FRONT) { + currentCameraId = camera2Manager.getFaceFrontCameraId() == null ? camera2Manager.getFaceBackCameraId() : camera2Manager.getFaceFrontCameraId(); + } else { + currentCameraId = camera2Manager.getFaceBackCameraId(); + } + } + + @Override + public void openCamera() { + camera2Manager.closeCamera(this); + } + + @Override + public void onResume() { + openCamera(); + } + + @Override + public void onPause() { + camera2Manager.closeCamera(null); + cameraView.releaseCameraPreview(); + } + + @Override + public void onDestroy() { + camera2Manager.releaseCameraManager(); + } + + @Override + public void takePhoto() { + outputFile = TextUtils.isEmpty(configurationProvider.getFilePath()) ? CameraHelper.getOutputMediaFile(cameraView.getActivity(), AnncaConfiguration.MEDIA_ACTION_PHOTO) : new File(configurationProvider.getFilePath()); + camera2Manager.takePhoto(outputFile, this); + } + + @Override + public void startVideoRecord() { + outputFile = TextUtils.isEmpty(configurationProvider.getFilePath()) ? CameraHelper.getOutputMediaFile(cameraView.getActivity(), AnncaConfiguration.MEDIA_ACTION_VIDEO) : new File(configurationProvider.getFilePath()); + camera2Manager.startVideoRecord(outputFile, this); + } + + @Override + public void stopVideoRecord() { + camera2Manager.stopVideoRecord(); + } + + @Override + public boolean isVideoRecording() { + return camera2Manager.isVideoRecording(); + } + + @Override + public void switchCamera(final @AnncaConfiguration.CameraFace int cameraFace) { + currentCameraId = camera2Manager.getCurrentCameraId().equals(camera2Manager.getFaceFrontCameraId()) ? + camera2Manager.getFaceBackCameraId() : camera2Manager.getFaceFrontCameraId(); + + camera2Manager.closeCamera(this); + } + + @Override + public void setFlashMode(@AnncaConfiguration.FlashMode int flashMode) { + camera2Manager.setFlashMode(flashMode); + } + + @Override + public void switchQuality() { + camera2Manager.closeCamera(this); + } + + @Override + public int getNumberOfCameras() { + return camera2Manager.getNumberOfCameras(); + } + + @Override + public int getMediaAction() { + return configurationProvider.getMediaAction(); + } + + @Override + public File getOutputFile() { + return outputFile; + } + + @Override + public String getCurrentCameraId() { + return currentCameraId; + } + + @Override + public void onCameraOpened(String openedCameraId, Size previewSize, TextureView.SurfaceTextureListener surfaceTextureListener, Camera camera) { + cameraView.updateUiForMediaAction(AnncaConfiguration.MEDIA_ACTION_UNSPECIFIED); + cameraView.updateCameraPreview(previewSize, new AutoFitTextureView(cameraView.getActivity(), surfaceTextureListener)); + cameraView.updateCameraSwitcher(camera2Manager.getNumberOfCameras()); + } + + @Override + public void onCameraReady() { + cameraView.onCameraReady(); + } + + @Override + public void onCameraOpenError() { + //test(TAG, "onCameraOpenError"); + } + + @Override + public void onCameraClosed(String closedCameraId) { + cameraView.releaseCameraPreview(); + + camera2Manager.openCamera(currentCameraId, this); + } + + @Override + public void onPhotoTaken(File photoFile) { + cameraView.onPhotoTaken(); + } + + @Override + public void onPhotoTakeError() { + } + + @Override + public void onVideoRecordStarted(Size videoSize) { + cameraView.onVideoRecordStart(videoSize.getWidth(), videoSize.getHeight()); + } + + @Override + public void onVideoRecordStopped(File videoFile) { + cameraView.onVideoRecordStop(); + } + + @Override + public void onVideoRecordError() { + + } + + @Override + public CameraManager getCameraManager() { + return camera2Manager; + } + +} diff --git a/annca/src/main/java/io/github/memfis19/annca/internal/controller/view/CameraView.java b/annca/src/main/java/io/github/memfis19/annca/internal/controller/view/CameraView.java new file mode 100644 index 0000000..14ca507 --- /dev/null +++ b/annca/src/main/java/io/github/memfis19/annca/internal/controller/view/CameraView.java @@ -0,0 +1,31 @@ +package io.github.memfis19.annca.internal.controller.view; + +import android.app.Activity; +import android.view.View; + +import io.github.memfis19.annca.internal.configuration.AnncaConfiguration; +import io.github.memfis19.annca.internal.utils.Size; + +/** + * Created by memfis on 7/6/16. + */ +public interface CameraView { + + Activity getActivity(); + + void updateCameraPreview(Size size, View cameraPreview); + + void updateUiForMediaAction(@AnncaConfiguration.MediaAction int mediaAction); + + void updateCameraSwitcher(int numberOfCameras); + + void onPhotoTaken(); + + void onVideoRecordStart(int width, int height); + + void onVideoRecordStop(); + + void releaseCameraPreview(); + + void onCameraReady(); +} diff --git a/annca/src/main/java/io/github/memfis19/annca/internal/manager/CameraManager.java b/annca/src/main/java/io/github/memfis19/annca/internal/manager/CameraManager.java new file mode 100644 index 0000000..197f833 --- /dev/null +++ b/annca/src/main/java/io/github/memfis19/annca/internal/manager/CameraManager.java @@ -0,0 +1,58 @@ +package io.github.memfis19.annca.internal.manager; + +import android.content.Context; + +import java.io.File; + +import io.github.memfis19.annca.internal.configuration.AnncaConfiguration; +import io.github.memfis19.annca.internal.configuration.ConfigurationProvider; +import io.github.memfis19.annca.internal.manager.impl.CameraHandler; +import io.github.memfis19.annca.internal.manager.impl.ParametersHandler; +import io.github.memfis19.annca.internal.manager.listener.CameraCloseListener; +import io.github.memfis19.annca.internal.manager.listener.CameraOpenListener; +import io.github.memfis19.annca.internal.manager.listener.CameraPhotoListener; +import io.github.memfis19.annca.internal.manager.listener.CameraVideoListener; +import io.github.memfis19.annca.internal.utils.Size; + +/** + * Created by memfis on 8/14/16. + */ +public interface CameraManager { + + void initializeCameraManager(ConfigurationProvider configurationProvider, Context context); + + void openCamera(CameraId cameraId, CameraOpenListener cameraOpenListener); + + void closeCamera(CameraCloseListener cameraCloseListener); + + void setFlashMode(@AnncaConfiguration.FlashMode int flashMode); + + void takePhoto(File photoFile, CameraPhotoListener cameraPhotoListener); + + void startVideoRecord(File videoFile, CameraVideoListener cameraVideoListener); + + Size getPhotoSizeForQuality(@AnncaConfiguration.MediaQuality int mediaQuality); + + void stopVideoRecord(); + + void releaseCameraManager(); + + CameraId getCurrentCameraId(); + + CameraId getFaceFrontCameraId(); + + CameraId getFaceBackCameraId(); + + int getNumberOfCameras(); + + int getFaceFrontCameraOrientation(); + + int getFaceBackCameraOrientation(); + + boolean isVideoRecording(); + + boolean handleParameters(ParametersHandler parameters); + + void handleCamera(CameraHandler cameraHandler); + +} diff --git a/annca/src/main/java/io/github/memfis19/annca/internal/manager/impl/BaseCameraManager.java b/annca/src/main/java/io/github/memfis19/annca/internal/manager/impl/BaseCameraManager.java new file mode 100644 index 0000000..2786dbb --- /dev/null +++ b/annca/src/main/java/io/github/memfis19/annca/internal/manager/impl/BaseCameraManager.java @@ -0,0 +1,144 @@ +package io.github.memfis19.annca.internal.manager.impl; + +import android.content.Context; +import android.media.CamcorderProfile; +import android.media.MediaRecorder; +import android.os.Build; +import android.os.Handler; +import android.os.HandlerThread; +import android.os.Looper; +import android.os.Process; +import android.util.Log; +import android.view.ViewGroup; + +import io.github.memfis19.annca.internal.configuration.AnncaConfiguration; +import io.github.memfis19.annca.internal.configuration.ConfigurationProvider; +import io.github.memfis19.annca.internal.utils.Size; + +/** + * Created by memfis on 8/14/16. + */ +abstract class BaseCameraManager + implements io.github.memfis19.annca.internal.manager.CameraManager, MediaRecorder.OnInfoListener { + + private static final String TAG = "BaseCameraManager"; + + protected Context context; + ConfigurationProvider configurationProvider; + + MediaRecorder videoRecorder; + boolean isVideoRecording = false; + + CameraId currentCameraId = null; + CameraId faceFrontCameraId = null; + CameraId faceBackCameraId = null; + int numberOfCameras = 0; + int faceFrontCameraOrientation; + int faceBackCameraOrientation; + + CamcorderProfile camcorderProfile; + Size photoSize; + Size videoSize; + Size previewSize; + Size windowSize; + + HandlerThread backgroundThread; + Handler backgroundHandler; + Handler uiHandler = new Handler(Looper.getMainLooper()); + + @Override + public void initializeCameraManager(ConfigurationProvider configurationProvider, Context context) { + this.context = context; + this.configurationProvider = configurationProvider; + startBackgroundThread(); + } + + @Override + public void releaseCameraManager() { + this.context = null; + stopBackgroundThread(); + } + + protected abstract void prepareCameraOutputs(); + + protected abstract boolean prepareVideoRecorder(); + + protected abstract void onMaxDurationReached(); + + protected abstract void onMaxFileSizeReached(); + + protected abstract int getPhotoOrientation(@AnncaConfiguration.SensorPosition int sensorPosition); + + protected abstract int getVideoOrientation(@AnncaConfiguration.SensorPosition int sensorPosition); + + protected void releaseVideoRecorder() { + try { + if (videoRecorder != null) { + videoRecorder.reset(); + videoRecorder.release(); + } + } catch (Exception ignore) { + + } finally { + videoRecorder = null; + } + } + + private void startBackgroundThread() { + backgroundThread = new HandlerThread(TAG, Process.THREAD_PRIORITY_BACKGROUND); + backgroundThread.start(); + backgroundHandler = new Handler(backgroundThread.getLooper()); + } + + private void stopBackgroundThread() { + backgroundThread.quitSafely(); + + try { + backgroundThread.join(); + } catch (InterruptedException e) { + //test(TAG, "stopBackgroundThread: ", e); + } finally { + backgroundThread = null; + backgroundHandler = null; + } + } + + @Override + public void onInfo(MediaRecorder mediaRecorder, int what, int extra) { + if (MediaRecorder.MEDIA_RECORDER_INFO_MAX_DURATION_REACHED == what) { + onMaxDurationReached(); + } else if (MediaRecorder.MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED == what) { + onMaxFileSizeReached(); + } + } + + public boolean isVideoRecording() { + return isVideoRecording; + } + + public CameraId getCurrentCameraId() { + return currentCameraId; + } + + public CameraId getFaceFrontCameraId() { + return faceFrontCameraId; + } + + public CameraId getFaceBackCameraId() { + return faceBackCameraId; + } + + public int getNumberOfCameras() { + return numberOfCameras; + } + + public int getFaceFrontCameraOrientation() { + return faceFrontCameraOrientation; + } + + public int getFaceBackCameraOrientation() { + return faceBackCameraOrientation; + } + + +} diff --git a/annca/src/main/java/io/github/memfis19/annca/internal/manager/impl/Camera1Manager.java b/annca/src/main/java/io/github/memfis19/annca/internal/manager/impl/Camera1Manager.java new file mode 100644 index 0000000..f303b31 --- /dev/null +++ b/annca/src/main/java/io/github/memfis19/annca/internal/manager/impl/Camera1Manager.java @@ -0,0 +1,694 @@ +package io.github.memfis19.annca.internal.manager.impl; + +import android.content.Context; +import android.content.res.Resources; +import android.graphics.Bitmap; +import android.graphics.BitmapFactory; +import android.graphics.Canvas; +import android.graphics.Color; +import android.graphics.Paint; +import android.graphics.PixelFormat; +import android.graphics.drawable.BitmapDrawable; +import android.hardware.Camera; +import android.media.ExifInterface; +import android.media.MediaRecorder; +import android.os.Build; +import android.util.DisplayMetrics; +import android.util.Log; +import android.view.Surface; +import android.view.SurfaceHolder; +import android.view.WindowManager; + +import androidx.annotation.NonNull; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.List; + +import io.github.memfis19.annca.internal.configuration.AnncaConfiguration; +import io.github.memfis19.annca.internal.configuration.ConfigurationProvider; +import io.github.memfis19.annca.internal.manager.listener.CameraCloseListener; +import io.github.memfis19.annca.internal.manager.listener.CameraOpenListener; +import io.github.memfis19.annca.internal.manager.listener.CameraPhotoListener; +import io.github.memfis19.annca.internal.manager.listener.CameraVideoListener; +import io.github.memfis19.annca.internal.utils.CameraHelper; +import io.github.memfis19.annca.internal.utils.Size; + +/** + * Created by memfis on 8/14/16. + */ +@SuppressWarnings("deprecation") +public class Camera1Manager extends BaseCameraManager + implements SurfaceHolder.Callback, Camera.PictureCallback { + + private static final String TAG = "Camera1Manager"; + private static final int MODE_PRIVATE = 1; + + private Camera camera; + private Surface surface; + + private static Camera1Manager currentInstance; + + private int orientation; + private int displayRotation = 0; + + private File outputPath; + private CameraVideoListener videoListener; + private CameraPhotoListener photoListener; + private CameraOpenListener cameraOpenListener; + private boolean safeToTakePicture = false; + + private Camera1Manager() { + + } + + public static Camera1Manager getInstance() { + if (currentInstance == null) currentInstance = new Camera1Manager(); + return currentInstance; + } + + @Override + public void openCamera(final Integer cameraId, + final CameraOpenListener cameraOpenListener) { + this.currentCameraId = cameraId; + this.cameraOpenListener = cameraOpenListener; + backgroundHandler.post(new Runnable() { + @Override + public void run() { + try { + camera = Camera.open(cameraId); + prepareCameraOutputs(); + if (cameraOpenListener != null) { + uiHandler.post(new Runnable() { + @Override + public void run() { + cameraOpenListener.onCameraOpened(cameraId, previewSize, currentInstance, camera); + } + }); + } + } catch (Exception error) { + //test(TAG, "Can't open camera: " + error.getMessage()); + if (cameraOpenListener != null) { + uiHandler.post(new Runnable() { + @Override + public void run() { + cameraOpenListener.onCameraOpenError(); + } + }); + } + } + } + }); + } + + @Override + public void closeCamera(final CameraCloseListener cameraCloseListener) { + backgroundHandler.post(() -> { + try { + if (camera != null) { + ////changes by jeevan + camera.stopPreview(); + camera.setPreviewCallback(null); + camera.release(); + camera = null; + if (cameraCloseListener != null) { + uiHandler.post(() -> cameraCloseListener.onCameraClosed(currentCameraId)); + } + } + } catch (Exception e) { + throw new RuntimeException(e); + } + }); + } + + @Override + public void setFlashMode(@AnncaConfiguration.FlashMode int flashMode) { + setFlashMode(camera, camera.getParameters(), flashMode); + } + + @Override + public void takePhoto(File photoFile, CameraPhotoListener cameraPhotoListener) { + this.outputPath = photoFile; + this.photoListener = cameraPhotoListener; + backgroundHandler.post(new Runnable() { + @Override + public void run() { + try { + if (safeToTakePicture){ + setCameraPhotoQuality(camera); + camera.takePicture(null, null, currentInstance); + safeToTakePicture = false; + } + } catch (Exception e) { + throw new RuntimeException(e); + } + } + }); + } + + @Override + public void startVideoRecord(final File videoFile, CameraVideoListener cameraVideoListener) { + if (isVideoRecording) return; + + this.outputPath = videoFile; + this.videoListener = cameraVideoListener; + + if (videoListener != null) + backgroundHandler.post(new Runnable() { + @Override + public void run() { + if (prepareVideoRecorder()) { + videoRecorder.start(); + isVideoRecording = true; + uiHandler.post(new Runnable() { + @Override + public void run() { + videoListener.onVideoRecordStarted(videoSize); + } + }); + } + } + }); + } + + @Override + public void stopVideoRecord() { + if (isVideoRecording) + backgroundHandler.post(new Runnable() { + @Override + public void run() { + + try { + if (videoRecorder != null) videoRecorder.stop(); + } catch (Exception ignore) { + // ignore illegal state. + // appear in case time or file size reach limit and stop already called. + } + + isVideoRecording = false; + releaseVideoRecorder(); + + if (videoListener != null) { + uiHandler.post(new Runnable() { + @Override + public void run() { + videoListener.onVideoRecordStopped(outputPath); + } + }); + } + } + }); + } + + @Override + public void releaseCameraManager() { + super.releaseCameraManager(); + } + + @Override + public void initializeCameraManager(ConfigurationProvider configurationProvider, Context context) { + super.initializeCameraManager(configurationProvider, context); + + numberOfCameras = Camera.getNumberOfCameras(); + + for (int i = 0; i < numberOfCameras; ++i) { + Camera.CameraInfo cameraInfo = new Camera.CameraInfo(); + + Camera.getCameraInfo(i, cameraInfo); + if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK) { + faceBackCameraId = i; + faceBackCameraOrientation = cameraInfo.orientation; + } else if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) { + faceFrontCameraId = i; + faceFrontCameraOrientation = cameraInfo.orientation; + } + } + } + + @Override + public Size getPhotoSizeForQuality(@AnncaConfiguration.MediaQuality int mediaQuality) { + return CameraHelper.getPictureSize(Size.fromList(camera.getParameters().getSupportedPictureSizes()), mediaQuality); + } + + @Override + protected void prepareCameraOutputs() { + try { + if (configurationProvider.getMediaQuality() == AnncaConfiguration.MEDIA_QUALITY_AUTO) { + camcorderProfile = CameraHelper.getCamcorderProfile(currentCameraId, configurationProvider.getVideoFileSize(), configurationProvider.getMinimumVideoDuration()); + } else + camcorderProfile = CameraHelper.getCamcorderProfile(configurationProvider.getMediaQuality(), currentCameraId); + + List previewSizes = Size.fromList(camera.getParameters().getSupportedPreviewSizes()); + List pictureSizes = Size.fromList(camera.getParameters().getSupportedPictureSizes()); + List videoSizes; + videoSizes = Size.fromList(camera.getParameters().getSupportedVideoSizes()); + + videoSize = CameraHelper.getSizeWithClosestRatio( + (videoSizes == null || videoSizes.isEmpty()) ? previewSizes : videoSizes, + camcorderProfile.videoFrameWidth, camcorderProfile.videoFrameHeight); + + photoSize = CameraHelper.getPictureSize( + (pictureSizes == null || pictureSizes.isEmpty()) ? previewSizes : pictureSizes, + configurationProvider.getMediaQuality() == AnncaConfiguration.MEDIA_QUALITY_AUTO + ? AnncaConfiguration.MEDIA_QUALITY_HIGHEST : configurationProvider.getMediaQuality()); + + if (configurationProvider.getMediaAction() == AnncaConfiguration.MEDIA_ACTION_PHOTO + || configurationProvider.getMediaAction() == AnncaConfiguration.MEDIA_ACTION_UNSPECIFIED) { + previewSize = CameraHelper.getSizeWithClosestRatio(previewSizes, photoSize.getWidth(), photoSize.getHeight()); + } else { + previewSize = CameraHelper.getSizeWithClosestRatio(previewSizes, videoSize.getWidth(), videoSize.getHeight()); + } + } catch (Exception e) { + //test(TAG, "Error while setup camera sizes."); + } + } + + @Override + protected boolean prepareVideoRecorder() { + videoRecorder = new MediaRecorder(); + try { + camera.lock(); + camera.unlock(); + videoRecorder.setCamera(camera); + + videoRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT); + videoRecorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT); + + videoRecorder.setOutputFormat(camcorderProfile.fileFormat); + videoRecorder.setVideoFrameRate(camcorderProfile.videoFrameRate); + videoRecorder.setVideoSize(videoSize.getWidth(), videoSize.getHeight()); + videoRecorder.setVideoEncodingBitRate(camcorderProfile.videoBitRate); + videoRecorder.setVideoEncoder(camcorderProfile.videoCodec); + + videoRecorder.setAudioEncodingBitRate(camcorderProfile.audioBitRate); + videoRecorder.setAudioChannels(camcorderProfile.audioChannels); + videoRecorder.setAudioSamplingRate(camcorderProfile.audioSampleRate); + videoRecorder.setAudioEncoder(camcorderProfile.audioCodec); + + videoRecorder.setOutputFile(outputPath.toString()); + + if (configurationProvider.getVideoFileSize() > 0) { + videoRecorder.setMaxFileSize(configurationProvider.getVideoFileSize()); + + videoRecorder.setOnInfoListener(this); + } + if (configurationProvider.getVideoDuration() > 0) { + videoRecorder.setMaxDuration(configurationProvider.getVideoDuration()); + + videoRecorder.setOnInfoListener(this); + } + + videoRecorder.setOrientationHint(getVideoOrientation(configurationProvider.getSensorPosition())); + videoRecorder.setPreviewDisplay(surface); + + videoRecorder.prepare(); + + return true; + } catch (IllegalStateException error) { + //test(TAG, "IllegalStateException preparing MediaRecorder: " + error.getMessage()); + } catch (IOException error) { + //test(TAG, "IOException preparing MediaRecorder: " + error.getMessage()); + } catch (Throwable error) { + //test(TAG, "Error during preparing MediaRecorder: " + error.getMessage()); + } + + releaseVideoRecorder(); + return false; + } + + @Override + protected void onMaxDurationReached() { + stopVideoRecord(); + } + + @Override + protected void onMaxFileSizeReached() { + stopVideoRecord(); + } + + @Override + protected void releaseVideoRecorder() { + super.releaseVideoRecorder(); + try { + camera.lock(); // lock camera for later use + } catch (Exception ignore) { + } + } + + //------------------------Implementation------------------ + + private void startPreview(SurfaceHolder surfaceHolder) { + try { + Camera.CameraInfo cameraInfo = new Camera.CameraInfo(); + Camera.getCameraInfo(currentCameraId, cameraInfo); + int cameraRotationOffset = cameraInfo.orientation; + + Camera.Parameters parameters = camera.getParameters(); + + setAutoFocus(camera, parameters); + setFlashMode(configurationProvider.getFlashMode()); + + if (configurationProvider.getMediaAction() == AnncaConfiguration.MEDIA_ACTION_PHOTO + || configurationProvider.getMediaAction() == AnncaConfiguration.MEDIA_ACTION_UNSPECIFIED) + turnPhotoCameraFeaturesOn(camera, parameters); + else if (configurationProvider.getMediaAction() == AnncaConfiguration.MEDIA_ACTION_PHOTO) + turnVideoCameraFeaturesOn(camera, parameters); + + int rotation = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getRotation(); + int degrees = 0; + switch (rotation) { + case Surface.ROTATION_0: + degrees = 0; + break; // Natural orientation + case Surface.ROTATION_90: + degrees = 90; + break; // Landscape left + case Surface.ROTATION_180: + degrees = 180; + break;// Upside down + case Surface.ROTATION_270: + degrees = 270; + break;// Landscape right + } + + if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) { + displayRotation = (cameraRotationOffset + degrees) % 360; + displayRotation = (360 - displayRotation) % 360; // compensate + } else { + displayRotation = (cameraRotationOffset - degrees + 360) % 360; + } + + this.camera.setDisplayOrientation(displayRotation); + + if (configurationProvider.getMediaAction() == AnncaConfiguration.MEDIA_ACTION_VIDEO || configurationProvider.getMediaAction() == AnncaConfiguration.MEDIA_ACTION_UNSPECIFIED) { +// parameters.setRecordingHint(true); + } + + if (parameters.isVideoStabilizationSupported() && (configurationProvider.getMediaAction() == AnncaConfiguration.MEDIA_ACTION_VIDEO || configurationProvider.getMediaAction() == AnncaConfiguration.MEDIA_ACTION_UNSPECIFIED)) { + parameters.setVideoStabilization(true); + } + + parameters.setPreviewSize(previewSize.getWidth(), previewSize.getHeight()); + parameters.setPictureSize(photoSize.getWidth(), photoSize.getHeight()); + + camera.setParameters(parameters); + ///SurfaceTexture st = new SurfaceTexture(MODE_PRIVATE); + // camera.setPreviewTexture(st); + + camera.setPreviewDisplay(surfaceHolder); + camera.startPreview(); + + if (cameraOpenListener != null) cameraOpenListener.onCameraReady(); + } catch (IOException error) { + //test(TAG, "Error setting camera preview: " + error.getMessage()); + } catch (Exception ignore) { + //test(TAG, "Error starting camera preview: " + ignore.getMessage()); + } + } + + private void turnPhotoCameraFeaturesOn(Camera camera, Camera.Parameters parameters) { + if (parameters.getSupportedFocusModes().contains( + Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)) { + parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE); + } + camera.setParameters(parameters); + } + + private void turnVideoCameraFeaturesOn(Camera camera, Camera.Parameters parameters) { + if (parameters.getSupportedFocusModes().contains( + Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)) { + parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO); + } + camera.setParameters(parameters); + } + + @Override + public void handleCamera(CameraHandler cameraHandler) { + cameraHandler.handleCamera(camera); + } + + + @Override + public boolean handleParameters(ParametersHandler parameters) { + try { + camera.setParameters(parameters.getParameters(camera.getParameters())); + return true; + } catch (Throwable ignore) { + } + return false; + } + + private void setAutoFocus(Camera camera, Camera.Parameters parameters) { + try { + if (parameters.getSupportedFocusModes().contains(Camera.Parameters.FOCUS_MODE_AUTO)) { + parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO); + camera.setParameters(parameters); + } + } catch (Exception ignore) { + } + } + + private void setFlashMode(Camera camera, Camera.Parameters parameters, @AnncaConfiguration.FlashMode int flashMode) { + try { + switch (flashMode) { + case AnncaConfiguration.FLASH_MODE_AUTO: + parameters.setFlashMode(Camera.Parameters.FLASH_MODE_AUTO); + break; + case AnncaConfiguration.FLASH_MODE_ON: + parameters.setFlashMode(Camera.Parameters.FLASH_MODE_ON); + break; + case AnncaConfiguration.FLASH_MODE_OFF: + parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF); + break; + default: + parameters.setFlashMode(Camera.Parameters.FLASH_MODE_AUTO); + break; + } + camera.setParameters(parameters); + } catch (Exception ignore) { + } + } + + private void setCameraPhotoQuality(Camera camera) { + Camera.Parameters parameters = camera.getParameters(); + + parameters.setPictureFormat(PixelFormat.JPEG); + + if (configurationProvider.getMediaQuality() == AnncaConfiguration.MEDIA_QUALITY_LOW) { + parameters.setJpegQuality(50); + } else if (configurationProvider.getMediaQuality() == AnncaConfiguration.MEDIA_QUALITY_MEDIUM) { + parameters.setJpegQuality(75); + } else if (configurationProvider.getMediaQuality() == AnncaConfiguration.MEDIA_QUALITY_HIGH) { + parameters.setJpegQuality(100); + } else if (configurationProvider.getMediaQuality() == AnncaConfiguration.MEDIA_QUALITY_HIGHEST) { + parameters.setJpegQuality(100); + } + parameters.setPictureSize(photoSize.getWidth(), photoSize.getHeight()); + + camera.setParameters(parameters); + } + + @Override + protected int getPhotoOrientation(@AnncaConfiguration.SensorPosition int sensorPosition) { + int rotate; + if (currentCameraId.equals(faceFrontCameraId)) { + rotate = (360 + faceFrontCameraOrientation + configurationProvider.getDegrees()) % 360; + } else { + rotate = (360 + faceBackCameraOrientation - configurationProvider.getDegrees()) % 360; + } + + if (rotate == 0) { + orientation = ExifInterface.ORIENTATION_NORMAL; + } else if (rotate == 90) { + orientation = ExifInterface.ORIENTATION_ROTATE_90; + } else if (rotate == 180) { + orientation = ExifInterface.ORIENTATION_ROTATE_180; + } else if (rotate == 270) { + orientation = ExifInterface.ORIENTATION_ROTATE_270; + } + + return orientation; + + } + + @Override + protected int getVideoOrientation(@AnncaConfiguration.SensorPosition int sensorPosition) { + int degrees = 0; + switch (sensorPosition) { + case AnncaConfiguration.SENSOR_POSITION_UP: + degrees = 0; + break; // Natural orientation + case AnncaConfiguration.SENSOR_POSITION_LEFT: + degrees = 90; + break; // Landscape left + case AnncaConfiguration.SENSOR_POSITION_UP_SIDE_DOWN: + degrees = 180; + break;// Upside down + case AnncaConfiguration.SENSOR_POSITION_RIGHT: + degrees = 270; + break;// Landscape right + } + + int rotate; + if (currentCameraId.equals(faceFrontCameraId)) { + rotate = (360 + faceFrontCameraOrientation + degrees) % 360; + } else { + rotate = (360 + faceBackCameraOrientation - degrees) % 360; + } + return rotate; + } + + @Override + public void surfaceCreated(SurfaceHolder surfaceHolder) { + if (surfaceHolder.getSurface() == null) { + return; + } + + surface = surfaceHolder.getSurface(); + + try { + camera.stopPreview(); + } catch (Exception ignore) { + } + + startPreview(surfaceHolder); + } + + @Override + public void surfaceChanged(SurfaceHolder surfaceHolder, int format, int width, int height) { + if (surfaceHolder.getSurface() == null) { + return; + } + + surface = surfaceHolder.getSurface(); + + try { + camera.stopPreview(); + } catch (Exception ignore) { + } + + startPreview(surfaceHolder); + safeToTakePicture = true; + } + + @Override + public void surfaceDestroyed(@NonNull SurfaceHolder surfaceHolder) { + + } + + @Override + public void onPictureTaken(byte[] bytes, Camera camera) { + File pictureFile = outputPath; + if (pictureFile == null) { + //test(TAG, "Error creating media file, check storage permissions."); + return; + } + try { + FileOutputStream fileOutputStream = new FileOutputStream(pictureFile); + fileOutputStream.write(bytes); + fileOutputStream.close(); + + if (configurationProvider.getShowGrid()) { + setGridOnImage(outputPath); + } + } catch (FileNotFoundException error) { + //test(TAG, "File not found: " + error.getMessage()); + } catch (IOException error) { + //test(TAG, "Error accessing file: " + error.getMessage()); + } catch (Throwable error) { + //test(TAG, "Error saving file: " + error.getMessage()); + } + + try { + ExifInterface exif = new ExifInterface(pictureFile.getAbsolutePath()); + exif.setAttribute(ExifInterface.TAG_ORIENTATION, "" + getPhotoOrientation(configurationProvider.getSensorPosition())); + exif.saveAttributes(); + if (photoListener != null) { + uiHandler.post(() -> photoListener.onPhotoTaken(outputPath)); + } + //finished saving picture + safeToTakePicture = true; + } catch (Throwable error) { + //finished saving picture + safeToTakePicture = true; + //test(TAG, "Can't save exif info: " + error.getMessage()); + } + } + + void setGridOnImage(File outputPath) { + Bitmap b = convertBitmap(outputPath.getAbsolutePath()); + // Rectangle Objects + Paint paint = new Paint(); + // Create Temp bitmap + Bitmap tBitmap = Bitmap.createBitmap(b.getWidth(), b.getHeight(), Bitmap.Config.RGB_565); + DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics(); + float screenWidth = metrics.widthPixels; + float screenHeight = (int) (metrics.heightPixels); + // Set paint options + paint.setAntiAlias(true); + paint.setStrokeWidth(3); + paint.setStyle(Paint.Style.STROKE); + paint.setColor(Color.argb(255, 255, 125, 000)); + // Create a new canvas and add Bitmap into it + Canvas canvas = new Canvas(tBitmap); + //Draw the image bitmap into the canvas + canvas.drawBitmap(b, 0, 0, null); + + int width = tBitmap.getWidth(); + int height = tBitmap.getHeight(); + + canvas.drawLine((width / 11) * 3, 0, (width / 11) * 3, height, paint); + canvas.drawLine((width / 11) * 8, 0, (width / 11) * 8, height, paint); + //test("small==" + (screenWidth / 100) * 27 + " large===" + (screenWidth / 100) * 63); + canvas.drawLine(0, (height / 11) * 3, width, (height / 11) * 3, paint); + canvas.drawLine(0, (height / 11) * 8, width, (height / 11) * 8, paint); + + BitmapDrawable btmpDr = new BitmapDrawable(tBitmap); + Bitmap bmp = btmpDr.getBitmap(); + try { + FileOutputStream outStream = new FileOutputStream(outputPath); + bmp.compress(Bitmap.CompressFormat.JPEG, 100, outStream); + /* 100 to keep full quality of the image */ + outStream.flush(); + outStream.close(); + } catch (IOException e) { + e.fillInStackTrace(); + } + } + + public Bitmap convertBitmap(String path) { + Bitmap bitmap = null; + BitmapFactory.Options ourOptions = new BitmapFactory.Options(); + ourOptions.inDither = false; + ourOptions.inPurgeable = true; + ourOptions.inInputShareable = true; + ourOptions.inTempStorage = new byte[32 * 1024]; + File file = new File(path); + FileInputStream fs = null; + try { + fs = new FileInputStream(file); + } catch (FileNotFoundException e) { + e.fillInStackTrace(); + } + try { + if (fs != null) { + bitmap = BitmapFactory.decodeFileDescriptor(fs.getFD(), null, ourOptions); + } + } catch (IOException e) { + e.fillInStackTrace(); + } finally { + if (fs != null) { + try { + fs.close(); + } catch (IOException e) { + e.fillInStackTrace(); + } + } + } + return bitmap; + } + +} diff --git a/annca/src/main/java/io/github/memfis19/annca/internal/manager/impl/Camera2Manager.java b/annca/src/main/java/io/github/memfis19/annca/internal/manager/impl/Camera2Manager.java new file mode 100644 index 0000000..735e9a5 --- /dev/null +++ b/annca/src/main/java/io/github/memfis19/annca/internal/manager/impl/Camera2Manager.java @@ -0,0 +1,804 @@ +package io.github.memfis19.annca.internal.manager.impl; + +import android.Manifest; +import android.annotation.TargetApi; +import android.content.Context; +import android.content.pm.PackageManager; +import android.graphics.ImageFormat; +import android.graphics.Point; +import android.graphics.SurfaceTexture; +import android.hardware.camera2.CameraAccessException; +import android.hardware.camera2.CameraCaptureSession; +import android.hardware.camera2.CameraCharacteristics; +import android.hardware.camera2.CameraDevice; +import android.hardware.camera2.CameraManager; +import android.hardware.camera2.CameraMetadata; +import android.hardware.camera2.CaptureRequest; +import android.hardware.camera2.CaptureResult; +import android.hardware.camera2.TotalCaptureResult; +import android.hardware.camera2.params.StreamConfigurationMap; +import android.media.ImageReader; +import android.media.MediaRecorder; +import android.os.Build; + +import androidx.annotation.IntDef; +import androidx.annotation.NonNull; +import androidx.core.app.ActivityCompat; + +import android.text.TextUtils; +import android.util.Log; +import android.view.Display; +import android.view.Surface; +import android.view.TextureView; +import android.view.WindowManager; + +import java.io.File; +import java.io.IOException; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; + +import io.github.memfis19.annca.internal.configuration.AnncaConfiguration; +import io.github.memfis19.annca.internal.configuration.ConfigurationProvider; +import io.github.memfis19.annca.internal.manager.listener.CameraCloseListener; +import io.github.memfis19.annca.internal.manager.listener.CameraOpenListener; +import io.github.memfis19.annca.internal.manager.listener.CameraPhotoListener; +import io.github.memfis19.annca.internal.manager.listener.CameraVideoListener; +import io.github.memfis19.annca.internal.utils.CameraHelper; +import io.github.memfis19.annca.internal.utils.ImageSaver; +import io.github.memfis19.annca.internal.utils.Size; + +/** + * Created by memfis on 8/9/16. + */ +@TargetApi(Build.VERSION_CODES.LOLLIPOP) +public final class Camera2Manager extends BaseCameraManager + implements ImageReader.OnImageAvailableListener, TextureView.SurfaceTextureListener { + + protected int zoomLevel = 1; + + private final static String TAG = "Camera2Manager"; + + private static Camera2Manager currentInstance; + + private CameraOpenListener cameraOpenListener; + private CameraPhotoListener cameraPhotoListener; + private CameraVideoListener cameraVideoListener; + + private File outputPath; + + @CameraPreviewState + private int previewState = STATE_PREVIEW; + private static final int STATE_PREVIEW = 0; + private static final int STATE_WAITING_LOCK = 1; + private static final int STATE_WAITING_PRE_CAPTURE = 2; + private static final int STATE_WAITING_NON_PRE_CAPTURE = 3; + private static final int STATE_PICTURE_TAKEN = 4; + + @IntDef({STATE_PREVIEW, STATE_WAITING_LOCK, STATE_WAITING_PRE_CAPTURE, STATE_WAITING_NON_PRE_CAPTURE, STATE_PICTURE_TAKEN}) + @Retention(RetentionPolicy.SOURCE) + @interface CameraPreviewState { + } + + private CameraManager manager; + private CameraDevice cameraDevice; + private CaptureRequest previewRequest; + private CaptureRequest.Builder previewRequestBuilder; + private CameraCaptureSession captureSession; + + private CameraCharacteristics frontCameraCharacteristics; + private CameraCharacteristics backCameraCharacteristics; + private StreamConfigurationMap frontCameraStreamConfigurationMap; + private StreamConfigurationMap backCameraStreamConfigurationMap; + + private SurfaceTexture texture; + + private Surface workingSurface; + private ImageReader imageReader; + + private CameraDevice.StateCallback stateCallback = new CameraDevice.StateCallback() { + @Override + public void onOpened(CameraDevice cameraDevice) { + currentInstance.cameraDevice = cameraDevice; + if (cameraOpenListener != null) { + uiHandler.post(new Runnable() { + @Override + public void run() { + if (!TextUtils.isEmpty(currentCameraId) && previewSize != null && currentInstance != null) { + } + //cameraOpenListener.onCameraOpened(currentCameraId, previewSize, currentInstance); + } + }); + } + } + + @Override + public void onDisconnected(CameraDevice cameraDevice) { + cameraDevice.close(); + currentInstance.cameraDevice = null; + + uiHandler.post(() -> cameraOpenListener.onCameraOpenError()); + } + + @Override + public void onError(CameraDevice cameraDevice, int error) { + cameraDevice.close(); + currentInstance.cameraDevice = null; + + uiHandler.post(() -> cameraOpenListener.onCameraOpenError()); + } + }; + + private CameraCaptureSession.CaptureCallback captureCallback + = new CameraCaptureSession.CaptureCallback() { + + @Override + public void onCaptureProgressed(@NonNull CameraCaptureSession session, + @NonNull CaptureRequest request, + @NonNull CaptureResult partialResult) { + processCaptureResult(partialResult); + } + + @Override + public void onCaptureCompleted(@NonNull CameraCaptureSession session, + @NonNull CaptureRequest request, + @NonNull TotalCaptureResult result) { + processCaptureResult(result); + } + + }; + + private Camera2Manager() { + } + + public static Camera2Manager getInstance() { + if (currentInstance == null) currentInstance = new Camera2Manager(); + return currentInstance; + } + + @Override + public void initializeCameraManager(ConfigurationProvider configurationProvider, Context context) { + super.initializeCameraManager(configurationProvider, context); + + this.manager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE); + + WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); + Display display = windowManager.getDefaultDisplay(); + Point size = new Point(); + display.getSize(size); + windowSize = new Size(size.x, size.y); + + try { + String[] ids = manager.getCameraIdList(); + numberOfCameras = ids.length; + for (String id : ids) { + CameraCharacteristics characteristics = manager.getCameraCharacteristics(id); + + int orientation = characteristics.get(CameraCharacteristics.LENS_FACING); + if (orientation == CameraCharacteristics.LENS_FACING_FRONT) { + faceFrontCameraId = id; + faceFrontCameraOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION); + frontCameraCharacteristics = characteristics; + } else { + faceBackCameraId = id; + faceBackCameraOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION); + backCameraCharacteristics = characteristics; + } + } + } catch (Exception e) { + //test(TAG, "Error during camera init"); + } + } + + @Override + public void openCamera(String cameraId, final CameraOpenListener cameraOpenListener) { + this.currentCameraId = cameraId; + this.cameraOpenListener = cameraOpenListener; + backgroundHandler.post(() -> { + if (context == null || configurationProvider == null) { + //test(TAG, "openCamera: "); + if (cameraOpenListener != null) { + uiHandler.post(cameraOpenListener::onCameraOpenError); + } + return; + } + prepareCameraOutputs(); + try { + if (ActivityCompat.checkSelfPermission(context, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { + // TODO: Consider calling + // ActivityCompat#requestPermissions + // here to request the missing permissions, and then overriding + // public void onRequestPermissionsResult(int requestCode, String[] permissions, + // int[] grantResults) + // to handle the case where the user grants the permission. See the documentation + // for ActivityCompat#requestPermissions for more details. + return; + } + manager.openCamera(currentCameraId, stateCallback, backgroundHandler); + } catch (Exception e) { + //test(TAG, "openCamera: ", e); + if (cameraOpenListener != null) { + uiHandler.post(cameraOpenListener::onCameraOpenError); + } + } + }); + } + + @Override + public void closeCamera(final CameraCloseListener cameraCloseListener) { + backgroundHandler.post(() -> { + closeCamera(); + if (cameraCloseListener != null) { + uiHandler.post(() -> cameraCloseListener.onCameraClosed(currentCameraId)); + } + }); + } + + @Override + public void handleCamera(CameraHandler cameraHandler) { + cameraHandler.handleCamera(cameraDevice); + } + + + @Override + public boolean handleParameters(ParametersHandler parameters) { + try { + previewRequestBuilder = parameters.getParameters(previewRequestBuilder); + + previewRequest = previewRequestBuilder.build(); + captureSession.setRepeatingRequest(previewRequest, captureCallback, backgroundHandler); + return true; + } catch (Throwable ignore) { + } + return false; + } + + @Override + public void setFlashMode(@AnncaConfiguration.FlashMode int flashMode) { + setFlashModeAndBuildPreviewRequest(flashMode); + } + + @Override + public void takePhoto(File photoFile, CameraPhotoListener cameraPhotoListener) { + this.outputPath = photoFile; + this.cameraPhotoListener = cameraPhotoListener; + + backgroundHandler.post(this::lockFocus); + + } + + @Override + public Size getPhotoSizeForQuality(@AnncaConfiguration.MediaQuality int mediaQuality) { + StreamConfigurationMap map = currentCameraId.equals(faceBackCameraId) ? backCameraStreamConfigurationMap : frontCameraStreamConfigurationMap; + return CameraHelper.getPictureSize(Size.fromArray2(map.getOutputSizes(ImageFormat.JPEG)), mediaQuality); + } + + @Override + public void startVideoRecord(File videoFile, final CameraVideoListener cameraVideoListener) { + if (isVideoRecording || texture == null) return; + + this.outputPath = videoFile; + this.cameraVideoListener = cameraVideoListener; + + if (cameraVideoListener != null) + backgroundHandler.post(new Runnable() { + @Override + public void run() { + closePreviewSession(); + if (prepareVideoRecorder()) { + + SurfaceTexture texture = currentInstance.texture; + texture.setDefaultBufferSize(videoSize.getWidth(), videoSize.getHeight()); + + try { + previewRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_RECORD); + List surfaces = new ArrayList<>(); + + Surface previewSurface = workingSurface; + surfaces.add(previewSurface); + previewRequestBuilder.addTarget(previewSurface); + + workingSurface = videoRecorder.getSurface(); + surfaces.add(workingSurface); + previewRequestBuilder.addTarget(workingSurface); + + cameraDevice.createCaptureSession(surfaces, new CameraCaptureSession.StateCallback() { + @Override + public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) { + captureSession = cameraCaptureSession; + + previewRequestBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO); + try { + captureSession.setRepeatingRequest(previewRequestBuilder.build(), null, backgroundHandler); + } catch (Exception e) { + } + + try { + videoRecorder.start(); + } catch (Exception ignore) { + //test(TAG, "videoRecorder.start(): ", ignore); + } + + isVideoRecording = true; + + uiHandler.post(new Runnable() { + @Override + public void run() { + cameraVideoListener.onVideoRecordStarted(videoSize); + } + }); + } + + @Override + public void onConfigureFailed(@NonNull CameraCaptureSession cameraCaptureSession) { + //test(TAG, "onConfigureFailed"); + } + }, backgroundHandler); + } catch (Exception e) { + //test(TAG, "startVideoRecord: ", e); + } + } + } + }); + } + + @Override + public void stopVideoRecord() { + if (isVideoRecording) + backgroundHandler.post(new Runnable() { + @Override + public void run() { + closePreviewSession(); + + if (videoRecorder != null) { + try { + videoRecorder.stop(); + } catch (Exception ignore) { + } + } + isVideoRecording = false; + releaseVideoRecorder(); + + if (cameraVideoListener != null) { + uiHandler.post(new Runnable() { + @Override + public void run() { + cameraVideoListener.onVideoRecordStopped(outputPath); + } + }); + } + } + }); + } + + //--------------------Internal methods------------------ + + private void startPreview(SurfaceTexture texture) { + try { + if (texture == null) return; + + this.texture = texture; + + texture.setDefaultBufferSize(previewSize.getWidth(), previewSize.getHeight()); + + workingSurface = new Surface(texture); + + previewRequestBuilder + = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW); + previewRequestBuilder.addTarget(workingSurface); + + cameraDevice.createCaptureSession(Arrays.asList(workingSurface, imageReader.getSurface()), + new CameraCaptureSession.StateCallback() { + @Override + public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) { + updatePreview(cameraCaptureSession); + } + + @Override + public void onConfigureFailed( + @NonNull CameraCaptureSession cameraCaptureSession) { + //test(TAG, "Fail while starting preview: "); + } + }, null); + } catch (Exception e) { + //test(TAG, "Error while preparing surface for preview: ", e); + } + } + + @Override + protected void onMaxDurationReached() { + stopVideoRecord(); + } + + @Override + protected void onMaxFileSizeReached() { + stopVideoRecord(); + } + + @Override + protected int getPhotoOrientation(@AnncaConfiguration.SensorPosition int sensorPosition) { + return getVideoOrientation(sensorPosition); + } + + @Override + protected int getVideoOrientation(@AnncaConfiguration.SensorPosition int sensorPosition) { + int degrees = 0; + switch (sensorPosition) { + case AnncaConfiguration.SENSOR_POSITION_UP: + degrees = 0; + break; // Natural orientation + case AnncaConfiguration.SENSOR_POSITION_LEFT: + degrees = 90; + break; // Landscape left + case AnncaConfiguration.SENSOR_POSITION_UP_SIDE_DOWN: + degrees = 180; + break;// Upside down + case AnncaConfiguration.SENSOR_POSITION_RIGHT: + degrees = 270; + break;// Landscape right + case AnncaConfiguration.SENSOR_POSITION_UNSPECIFIED: + break; + } + + int rotate; + if (Objects.equals(currentCameraId, faceFrontCameraId)) { + rotate = (360 + faceFrontCameraOrientation + degrees) % 360; + } else { + rotate = (360 + faceBackCameraOrientation - degrees) % 360; + } + return rotate; + } + + private void closeCamera() { + closePreviewSession(); + releaseTexture(); + closeCameraDevice(); + closeImageReader(); + releaseVideoRecorder(); + } + + private void releaseTexture() { + if (null != texture) { + texture.release(); + texture = null; + } + } + + private void closeImageReader() { + if (null != imageReader) { + imageReader.close(); + imageReader = null; + } + } + + private void closeCameraDevice() { + if (null != cameraDevice) { + cameraDevice.close(); + cameraDevice = null; + } + } + + @Override + protected void prepareCameraOutputs() { + try { + CameraCharacteristics characteristics = currentCameraId.equals(faceBackCameraId) ? backCameraCharacteristics : frontCameraCharacteristics; + + if (currentCameraId.equals(faceFrontCameraId) && frontCameraStreamConfigurationMap == null) + frontCameraStreamConfigurationMap = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP); + else if (currentCameraId.equals(faceBackCameraId) && backCameraStreamConfigurationMap == null) + backCameraStreamConfigurationMap = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP); + + StreamConfigurationMap map = currentCameraId.equals(faceBackCameraId) ? backCameraStreamConfigurationMap : frontCameraStreamConfigurationMap; + if (configurationProvider.getMediaQuality() == AnncaConfiguration.MEDIA_QUALITY_AUTO) { + camcorderProfile = CameraHelper.getCamcorderProfile(currentCameraId, configurationProvider.getVideoFileSize(), configurationProvider.getMinimumVideoDuration()); + } else + camcorderProfile = CameraHelper.getCamcorderProfile(configurationProvider.getMediaQuality(), currentCameraId); + + videoSize = CameraHelper.chooseOptimalSize(Size.fromArray2(map.getOutputSizes(MediaRecorder.class)), + windowSize.getWidth(), windowSize.getHeight(), new Size(camcorderProfile.videoFrameWidth, camcorderProfile.videoFrameHeight)); + + if (videoSize == null || videoSize.getWidth() > camcorderProfile.videoFrameWidth + || videoSize.getHeight() > camcorderProfile.videoFrameHeight) + videoSize = CameraHelper.getSizeWithClosestRatio(Size.fromArray2(map.getOutputSizes(MediaRecorder.class)), camcorderProfile.videoFrameWidth, camcorderProfile.videoFrameHeight); + else if (videoSize == null || videoSize.getWidth() > camcorderProfile.videoFrameWidth + || videoSize.getHeight() > camcorderProfile.videoFrameHeight) + videoSize = CameraHelper.getSizeWithClosestRatio(Size.fromArray2(map.getOutputSizes(MediaRecorder.class)), camcorderProfile.videoFrameWidth, camcorderProfile.videoFrameHeight); + + photoSize = CameraHelper.getPictureSize(Size.fromArray2(map.getOutputSizes(ImageFormat.JPEG)), + configurationProvider.getMediaQuality() == AnncaConfiguration.MEDIA_QUALITY_AUTO + ? AnncaConfiguration.MEDIA_QUALITY_HIGHEST : configurationProvider.getMediaQuality()); + + imageReader = ImageReader.newInstance(photoSize.getWidth(), photoSize.getHeight(), + ImageFormat.JPEG, 2); + imageReader.setOnImageAvailableListener(this, backgroundHandler); + + if (configurationProvider.getMediaAction() == AnncaConfiguration.MEDIA_ACTION_PHOTO + || configurationProvider.getMediaAction() == AnncaConfiguration.MEDIA_ACTION_UNSPECIFIED) { + + if (windowSize.getHeight() * windowSize.getWidth() > photoSize.getWidth() * photoSize.getHeight()) { + previewSize = CameraHelper.getOptimalPreviewSize(Size.fromArray2(map.getOutputSizes(SurfaceTexture.class)), photoSize.getWidth(), photoSize.getHeight()); + } else { + previewSize = CameraHelper.getOptimalPreviewSize(Size.fromArray2(map.getOutputSizes(SurfaceTexture.class)), windowSize.getWidth(), windowSize.getHeight()); + } + + if (previewSize == null) + previewSize = CameraHelper.chooseOptimalSize(Size.fromArray2(map.getOutputSizes(SurfaceTexture.class)), windowSize.getWidth(), windowSize.getHeight(), photoSize); + + } else { + if (windowSize.getHeight() * windowSize.getWidth() > videoSize.getWidth() * videoSize.getHeight()) { + previewSize = CameraHelper.getOptimalPreviewSize(Size.fromArray2(map.getOutputSizes(SurfaceTexture.class)), videoSize.getWidth(), videoSize.getHeight()); + } else { + previewSize = CameraHelper.getOptimalPreviewSize(Size.fromArray2(map.getOutputSizes(SurfaceTexture.class)), windowSize.getWidth(), windowSize.getHeight()); + } + + if (previewSize == null) + previewSize = CameraHelper.getSizeWithClosestRatio(Size.fromArray2(map.getOutputSizes(SurfaceTexture.class)), videoSize.getWidth(), videoSize.getHeight()); + } + } catch (Exception e) { + //test(TAG, "Error while setup camera sizes.", e); + } + } + + @Override + protected boolean prepareVideoRecorder() { + videoRecorder = new MediaRecorder(); + try { + videoRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER); + videoRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE); + + videoRecorder.setOutputFormat(camcorderProfile.fileFormat); + videoRecorder.setVideoFrameRate(camcorderProfile.videoFrameRate); + videoRecorder.setVideoSize(videoSize.getWidth(), videoSize.getHeight()); + videoRecorder.setVideoEncodingBitRate(camcorderProfile.videoBitRate); + videoRecorder.setVideoEncoder(camcorderProfile.videoCodec); + + videoRecorder.setAudioEncodingBitRate(camcorderProfile.audioBitRate); + videoRecorder.setAudioChannels(camcorderProfile.audioChannels); + videoRecorder.setAudioSamplingRate(camcorderProfile.audioSampleRate); + videoRecorder.setAudioEncoder(camcorderProfile.audioCodec); + + File outputFile = outputPath; + String outputFilePath = outputFile.toString(); + videoRecorder.setOutputFile(outputFilePath); + + if (configurationProvider.getVideoFileSize() > 0) { + videoRecorder.setMaxFileSize(configurationProvider.getVideoFileSize()); + videoRecorder.setOnInfoListener(this); + } + if (configurationProvider.getVideoDuration() > 0) { + videoRecorder.setMaxDuration(configurationProvider.getVideoDuration()); + videoRecorder.setOnInfoListener(this); + } + videoRecorder.setOrientationHint(getVideoOrientation(configurationProvider.getSensorPosition())); + + videoRecorder.prepare(); + + return true; + } catch (IllegalStateException error) { + //test(TAG, "IllegalStateException preparing MediaRecorder: " + error.getMessage()); + } catch (IOException error) { + //test(TAG, "IOException preparing MediaRecorder: " + error.getMessage()); + } catch (Throwable error) { + //test(TAG, "Error during preparing MediaRecorder: " + error.getMessage()); + } + + releaseVideoRecorder(); + return false; + } + + private void updatePreview(CameraCaptureSession cameraCaptureSession) { + if (null == cameraDevice) { + return; + } + captureSession = cameraCaptureSession; + setFlashModeAndBuildPreviewRequest(configurationProvider.getFlashMode()); + + if (cameraOpenListener != null) cameraOpenListener.onCameraReady(); + } + + private void closePreviewSession() { + if (captureSession != null) { + captureSession.close(); + try { + captureSession.abortCaptures(); + } catch (Exception ignore) { + } finally { + captureSession = null; + } + } + } + + private void lockFocus() { + try { + previewRequestBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER, CameraMetadata.CONTROL_AF_TRIGGER_START); + + previewState = STATE_WAITING_LOCK; + captureSession.capture(previewRequestBuilder.build(), captureCallback, backgroundHandler); + } catch (Exception ignore) { + } + } + + private void processCaptureResult(CaptureResult result) { + switch (previewState) { + case STATE_PREVIEW: { + break; + } + case STATE_WAITING_LOCK: { + Integer afState = result.get(CaptureResult.CONTROL_AF_STATE); + if (afState == null) { + captureStillPicture(); + } else if (CaptureResult.CONTROL_AF_STATE_FOCUSED_LOCKED == afState + || CaptureResult.CONTROL_AF_STATE_NOT_FOCUSED_LOCKED == afState + || CaptureResult.CONTROL_AF_STATE_INACTIVE == afState + || CaptureResult.CONTROL_AF_STATE_PASSIVE_SCAN == afState) { + Integer aeState = result.get(CaptureResult.CONTROL_AE_STATE); + if (aeState == null || + aeState == CaptureResult.CONTROL_AE_STATE_CONVERGED) { + previewState = STATE_PICTURE_TAKEN; + captureStillPicture(); + } else { + runPreCaptureSequence(); + } + } + break; + } + case STATE_WAITING_PRE_CAPTURE: { + Integer aeState = result.get(CaptureResult.CONTROL_AE_STATE); + if (aeState == null || + aeState == CaptureResult.CONTROL_AE_STATE_PRECAPTURE || + aeState == CaptureRequest.CONTROL_AE_STATE_FLASH_REQUIRED) { + previewState = STATE_WAITING_NON_PRE_CAPTURE; + } + break; + } + case STATE_WAITING_NON_PRE_CAPTURE: { + Integer aeState = result.get(CaptureResult.CONTROL_AE_STATE); + if (aeState == null || aeState != CaptureResult.CONTROL_AE_STATE_PRECAPTURE) { + previewState = STATE_PICTURE_TAKEN; + captureStillPicture(); + } + break; + } + case STATE_PICTURE_TAKEN: + break; + } + } + + private void runPreCaptureSequence() { + try { + previewRequestBuilder.set(CaptureRequest.CONTROL_AE_PRECAPTURE_TRIGGER, CaptureRequest.CONTROL_AE_PRECAPTURE_TRIGGER_START); + previewState = STATE_WAITING_PRE_CAPTURE; + captureSession.capture(previewRequestBuilder.build(), captureCallback, backgroundHandler); + } catch (CameraAccessException e) { + } + } + + private void captureStillPicture() { + try { + if (null == cameraDevice) { + return; + } + final CaptureRequest.Builder captureBuilder = + cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE); + captureBuilder.addTarget(imageReader.getSurface()); + + captureBuilder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE); + captureBuilder.set(CaptureRequest.JPEG_ORIENTATION, getPhotoOrientation(configurationProvider.getSensorPosition())); + + CameraCaptureSession.CaptureCallback CaptureCallback = new CameraCaptureSession.CaptureCallback() { + @Override + public void onCaptureCompleted(@NonNull CameraCaptureSession session, + @NonNull CaptureRequest request, + @NonNull TotalCaptureResult result) { + //test(TAG, "onCaptureCompleted: "); + } + }; + + captureSession.stopRepeating(); + captureSession.capture(captureBuilder.build(), CaptureCallback, null); + + } catch (CameraAccessException e) { + //test(TAG, "Error during capturing picture"); + } + } + + private void unlockFocus() { + try { + previewRequestBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER, CameraMetadata.CONTROL_AF_TRIGGER_CANCEL); + captureSession.capture(previewRequestBuilder.build(), captureCallback, backgroundHandler); + previewState = STATE_PREVIEW; + captureSession.setRepeatingRequest(previewRequest, captureCallback, backgroundHandler); + } catch (Exception e) { + //test(TAG, "Error during focus unlocking"); + } + } + + private void setFlashModeAndBuildPreviewRequest(@AnncaConfiguration.FlashMode int flashMode) { + try { + + switch (flashMode) { + case AnncaConfiguration.FLASH_MODE_AUTO: + previewRequestBuilder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH); + previewRequestBuilder.set(CaptureRequest.FLASH_MODE, CameraMetadata.FLASH_MODE_SINGLE); + break; + case AnncaConfiguration.FLASH_MODE_ON: + previewRequestBuilder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON); + previewRequestBuilder.set(CaptureRequest.FLASH_MODE, CameraMetadata.FLASH_MODE_SINGLE); + break; + case AnncaConfiguration.FLASH_MODE_OFF: + previewRequestBuilder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON); + previewRequestBuilder.set(CaptureRequest.FLASH_MODE, CameraMetadata.FLASH_MODE_OFF); + break; + default: + previewRequestBuilder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH); + previewRequestBuilder.set(CaptureRequest.FLASH_MODE, CameraMetadata.FLASH_MODE_SINGLE); + break; + } + + previewRequest = previewRequestBuilder.build(); + + try { + captureSession.setRepeatingRequest(previewRequest, captureCallback, backgroundHandler); + } catch (Exception e) { + //test(TAG, "Error updating preview: ", e); + } + } catch (Exception ignore) { + //test(TAG, "Error setting flash: ", ignore); + } + } + + @Override + public void onImageAvailable(ImageReader imageReader) { + File outputFile = outputPath; + backgroundHandler.post(new ImageSaver(imageReader.acquireNextImage(), outputFile, new ImageSaver.ImageSaverCallback() { + @Override + public void onSuccessFinish() { + //test(TAG, "onPhotoSuccessFinish: "); + if (cameraPhotoListener != null) { + uiHandler.post(new Runnable() { + @Override + public void run() { + cameraPhotoListener.onPhotoTaken(outputPath); + } + }); + } + unlockFocus(); + } + + @Override + public void onError() { + //test(TAG, "onPhotoError: "); + uiHandler.post(new Runnable() { + @Override + public void run() { + cameraPhotoListener.onPhotoTakeError(); + } + }); + } + })); + } + + @Override + public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int width, int height) { + if (surfaceTexture != null) startPreview(surfaceTexture); + } + + @Override + public void onSurfaceTextureSizeChanged(SurfaceTexture surfaceTexture, int width, int height) { + if (surfaceTexture != null) startPreview(surfaceTexture); + } + + @Override + public boolean onSurfaceTextureDestroyed(SurfaceTexture surfaceTexture) { + return true; + } + + @Override + public void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture) { + } + + +} diff --git a/annca/src/main/java/io/github/memfis19/annca/internal/manager/impl/CameraHandler.java b/annca/src/main/java/io/github/memfis19/annca/internal/manager/impl/CameraHandler.java new file mode 100644 index 0000000..4f092b8 --- /dev/null +++ b/annca/src/main/java/io/github/memfis19/annca/internal/manager/impl/CameraHandler.java @@ -0,0 +1,9 @@ +package io.github.memfis19.annca.internal.manager.impl; + +/** + * Created by memfis on 1/13/17. + */ + +public interface CameraHandler { + void handleCamera(Camera camera); +} diff --git a/annca/src/main/java/io/github/memfis19/annca/internal/manager/impl/ParametersHandler.java b/annca/src/main/java/io/github/memfis19/annca/internal/manager/impl/ParametersHandler.java new file mode 100644 index 0000000..65861ab --- /dev/null +++ b/annca/src/main/java/io/github/memfis19/annca/internal/manager/impl/ParametersHandler.java @@ -0,0 +1,8 @@ +package io.github.memfis19.annca.internal.manager.impl; + +/** + * Created by memfis on 1/13/17. + */ +public interface ParametersHandler { + CameraParameters getParameters(CameraParameters cameraParameters); +} diff --git a/annca/src/main/java/io/github/memfis19/annca/internal/manager/listener/CameraCloseListener.java b/annca/src/main/java/io/github/memfis19/annca/internal/manager/listener/CameraCloseListener.java new file mode 100644 index 0000000..c8049d3 --- /dev/null +++ b/annca/src/main/java/io/github/memfis19/annca/internal/manager/listener/CameraCloseListener.java @@ -0,0 +1,8 @@ +package io.github.memfis19.annca.internal.manager.listener; + +/** + * Created by memfis on 8/14/16. + */ +public interface CameraCloseListener { + void onCameraClosed(CameraId closedCameraId); +} diff --git a/annca/src/main/java/io/github/memfis19/annca/internal/manager/listener/CameraOpenListener.java b/annca/src/main/java/io/github/memfis19/annca/internal/manager/listener/CameraOpenListener.java new file mode 100644 index 0000000..46d053d --- /dev/null +++ b/annca/src/main/java/io/github/memfis19/annca/internal/manager/listener/CameraOpenListener.java @@ -0,0 +1,16 @@ +package io.github.memfis19.annca.internal.manager.listener; + +import android.hardware.Camera; + +import io.github.memfis19.annca.internal.utils.Size; + +/** + * Created by memfis on 8/14/16. + */ +public interface CameraOpenListener { + void onCameraOpened(CameraId openedCameraId, Size previewSize, SurfaceListener surfaceListener, Camera camera); + + void onCameraReady(); + + void onCameraOpenError(); +} diff --git a/annca/src/main/java/io/github/memfis19/annca/internal/manager/listener/CameraPhotoListener.java b/annca/src/main/java/io/github/memfis19/annca/internal/manager/listener/CameraPhotoListener.java new file mode 100644 index 0000000..f12df4c --- /dev/null +++ b/annca/src/main/java/io/github/memfis19/annca/internal/manager/listener/CameraPhotoListener.java @@ -0,0 +1,12 @@ +package io.github.memfis19.annca.internal.manager.listener; + +import java.io.File; + +/** + * Created by memfis on 8/14/16. + */ +public interface CameraPhotoListener { + void onPhotoTaken(File photoFile); + + void onPhotoTakeError(); +} diff --git a/annca/src/main/java/io/github/memfis19/annca/internal/manager/listener/CameraVideoListener.java b/annca/src/main/java/io/github/memfis19/annca/internal/manager/listener/CameraVideoListener.java new file mode 100644 index 0000000..3036d18 --- /dev/null +++ b/annca/src/main/java/io/github/memfis19/annca/internal/manager/listener/CameraVideoListener.java @@ -0,0 +1,16 @@ +package io.github.memfis19.annca.internal.manager.listener; + +import java.io.File; + +import io.github.memfis19.annca.internal.utils.Size; + +/** + * Created by memfis on 8/14/16. + */ +public interface CameraVideoListener { + void onVideoRecordStarted(Size videoSize); + + void onVideoRecordStopped(File videoFile); + + void onVideoRecordError(); +} diff --git a/annca/src/main/java/io/github/memfis19/annca/internal/ui/AnncaCameraActivity.java b/annca/src/main/java/io/github/memfis19/annca/internal/ui/AnncaCameraActivity.java new file mode 100644 index 0000000..d8a5a9e --- /dev/null +++ b/annca/src/main/java/io/github/memfis19/annca/internal/ui/AnncaCameraActivity.java @@ -0,0 +1,187 @@ +package io.github.memfis19.annca.internal.ui; + +import android.app.Activity; +import android.content.res.Configuration; +import android.hardware.Sensor; +import android.hardware.SensorEvent; +import android.hardware.SensorEventListener; +import android.hardware.SensorManager; +import android.os.Build; +import android.os.Bundle; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; + +import io.github.memfis19.annca.R; +import io.github.memfis19.annca.internal.configuration.AnncaConfiguration; +import io.github.memfis19.annca.internal.configuration.ConfigurationProvider; +import io.github.memfis19.annca.internal.controller.CameraController; +import io.github.memfis19.annca.internal.controller.view.CameraView; +import io.github.memfis19.annca.internal.ui.view.AspectFrameLayout; +import io.github.memfis19.annca.internal.utils.Size; +import io.github.memfis19.annca.internal.utils.Utils; + +/** + * Created by memfis on 12/1/16. + */ + +abstract public class AnncaCameraActivity extends Activity + implements ConfigurationProvider, CameraView, SensorEventListener { + + private SensorManager sensorManager = null; + + protected AspectFrameLayout previewContainer; + protected ViewGroup userContainer; + + private CameraController cameraController; + + @AnncaConfiguration.SensorPosition + protected int sensorPosition = AnncaConfiguration.SENSOR_POSITION_UNSPECIFIED; + @AnncaConfiguration.DeviceDefaultOrientation + protected int deviceDefaultOrientation; + private int degrees = -1; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + onProcessBundle(savedInstanceState); + + cameraController = createCameraController(this, this); + cameraController.onCreate(savedInstanceState); + + sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); + int defaultOrientation = Utils.getDeviceDefaultOrientation(this); + + if (defaultOrientation == Configuration.ORIENTATION_LANDSCAPE) { + deviceDefaultOrientation = AnncaConfiguration.ORIENTATION_LANDSCAPE; + } else if (defaultOrientation == Configuration.ORIENTATION_PORTRAIT) { + deviceDefaultOrientation = AnncaConfiguration.ORIENTATION_PORTRAIT; + } + + View decorView = getWindow().getDecorView(); + int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN; + decorView.setSystemUiVisibility(uiOptions); + setContentView(R.layout.generic_camera_layout); + previewContainer = (AspectFrameLayout) findViewById(R.id.previewContainer); + userContainer = (ViewGroup) findViewById(R.id.userContainer); + + setUserContent(); + } + + protected void onProcessBundle(Bundle savedInstanceState) { + + } + + @Override + protected void onResume() { + super.onResume(); + cameraController.onResume(); + sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL); + } + + @Override + protected void onPause() { + super.onPause(); + cameraController.onPause(); + sensorManager.unregisterListener(this); + } + + @Override + protected void onDestroy() { + super.onDestroy(); + + cameraController.onDestroy(); + } + + public final CameraController getCameraController() { + return cameraController; + } + + public abstract CameraController createCameraController(CameraView cameraView, ConfigurationProvider configurationProvider); + + private void setUserContent() { + userContainer.removeAllViews(); + userContainer.addView(getUserContentView(LayoutInflater.from(this), userContainer)); + } + + public final void setCameraPreview(View preview, Size previewSize) { + try { + if (previewContainer == null || preview == null) return; + previewContainer.removeAllViews(); + previewContainer.addView(preview); + previewContainer.setAspectRatio(previewSize.getHeight() / (double) previewSize.getWidth()); + } catch (Exception e) { + e.fillInStackTrace(); + } + } + + public final void setCustomCameraPreview(View preview, Size previewSize, Size customSize) { + if (previewContainer == null || preview == null) return; + previewContainer.removeAllViews(); + previewContainer.addView(preview); + + previewContainer.setCustomSize(customSize, previewSize); + } + + @Override + public void onCameraReady() { + onCameraControllerReady(); + } + + public final void clearCameraPreview() { + if (previewContainer != null) + previewContainer.removeAllViews(); + } + + protected abstract View getUserContentView(LayoutInflater layoutInflater, ViewGroup parent); + + @Override + public void onSensorChanged(SensorEvent sensorEvent) { + synchronized (this) { + if (sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER) { + if (sensorEvent.values[0] < 4 && sensorEvent.values[0] > -4) { + if (sensorEvent.values[1] > 0) { + // UP + sensorPosition = AnncaConfiguration.SENSOR_POSITION_UP; + degrees = deviceDefaultOrientation == AnncaConfiguration.ORIENTATION_PORTRAIT ? 0 : 90; + } else if (sensorEvent.values[1] < 0) { + // UP SIDE DOWN + sensorPosition = AnncaConfiguration.SENSOR_POSITION_UP_SIDE_DOWN; + degrees = deviceDefaultOrientation == AnncaConfiguration.ORIENTATION_PORTRAIT ? 180 : 270; + } + } else if (sensorEvent.values[1] < 4 && sensorEvent.values[1] > -4) { + if (sensorEvent.values[0] > 0) { + // LEFT + sensorPosition = AnncaConfiguration.SENSOR_POSITION_LEFT; + degrees = deviceDefaultOrientation == AnncaConfiguration.ORIENTATION_PORTRAIT ? 90 : 180; + } else if (sensorEvent.values[0] < 0) { + // RIGHT + sensorPosition = AnncaConfiguration.SENSOR_POSITION_RIGHT; + degrees = deviceDefaultOrientation == AnncaConfiguration.ORIENTATION_PORTRAIT ? 270 : 0; + } + } + onScreenRotation(degrees); + } + } + } + + @Override + public void onAccuracyChanged(Sensor sensor, int accuracy) { + + } + + @Override + public final int getSensorPosition() { + return sensorPosition; + } + + @Override + public final int getDegrees() { + return degrees; + } + + protected abstract void onScreenRotation(int degrees); + + protected void onCameraControllerReady() { + } +} diff --git a/annca/src/main/java/io/github/memfis19/annca/internal/ui/BaseAnncaActivity.java b/annca/src/main/java/io/github/memfis19/annca/internal/ui/BaseAnncaActivity.java new file mode 100644 index 0000000..e47d8df --- /dev/null +++ b/annca/src/main/java/io/github/memfis19/annca/internal/ui/BaseAnncaActivity.java @@ -0,0 +1,536 @@ +package io.github.memfis19.annca.internal.ui; + +import android.annotation.SuppressLint; +import android.app.Activity; +import android.app.AlertDialog; +import android.content.DialogInterface; +import android.content.Intent; +import android.os.Build; +import android.os.Bundle; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.view.WindowManager; + +import io.github.memfis19.annca.R; +import io.github.memfis19.annca.internal.configuration.AnncaConfiguration; +import io.github.memfis19.annca.internal.ui.model.PhotoQualityOption; +import io.github.memfis19.annca.internal.ui.model.VideoQualityOption; +import io.github.memfis19.annca.internal.ui.preview.PreviewActivity; +import io.github.memfis19.annca.internal.ui.view.CameraControlPanel; +import io.github.memfis19.annca.internal.ui.view.CameraSwitchView; +import io.github.memfis19.annca.internal.ui.view.FlashSwitchView; +import io.github.memfis19.annca.internal.ui.view.MediaActionSwitchView; +import io.github.memfis19.annca.internal.ui.view.RecordButton; +import io.github.memfis19.annca.internal.utils.Size; +import io.github.memfis19.annca.internal.utils.Utils; + +/** + * Created by memfis on 12/1/16. + */ + +public abstract class BaseAnncaActivity extends AnncaCameraActivity + implements + RecordButton.RecordButtonListener, + FlashSwitchView.FlashModeSwitchListener, + MediaActionSwitchView.OnMediaActionStateChangeListener, + CameraSwitchView.OnCameraTypeChangeListener, CameraControlPanel.SettingsClickListener { + + private CameraControlPanel cameraControlPanel; + private AlertDialog settingsDialog; + + protected static final int REQUEST_PREVIEW_CODE = 1001; + + public static final int ACTION_CONFIRM = 900; + public static final int ACTION_RETAKE = 901; + public static final int ACTION_CANCEL = 902; + + protected int requestCode = -1; + + @AnncaConfiguration.MediaAction + protected int mediaAction = AnncaConfiguration.MEDIA_ACTION_UNSPECIFIED; + @AnncaConfiguration.MediaQuality + protected int mediaQuality = AnncaConfiguration.MEDIA_QUALITY_MEDIUM; + @AnncaConfiguration.MediaQuality + protected int passedMediaQuality = AnncaConfiguration.MEDIA_QUALITY_MEDIUM; + + @AnncaConfiguration.FlashMode + protected int flashMode = AnncaConfiguration.FLASH_MODE_AUTO; + + protected CharSequence[] videoQualities; + protected CharSequence[] photoQualities; + + protected int videoDuration = -1; + protected long videoFileSize = -1; + protected int minimumVideoDuration = -1; + protected String filePath = ""; + protected boolean showGrid; + + @MediaActionSwitchView.MediaActionState + protected int currentMediaActionState; + + @CameraSwitchView.CameraType + protected int currentCameraType = CameraSwitchView.CAMERA_TYPE_FRONT; + + @AnncaConfiguration.MediaResultBehaviour + private int mediaResultBehaviour = AnncaConfiguration.PREVIEW; + + @SuppressLint("WrongConstant") + @AnncaConfiguration.MediaQuality + protected int newQuality = -1; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + } + + @Override + protected void onProcessBundle(Bundle savedInstanceState) { + super.onProcessBundle(savedInstanceState); + + extractConfiguration(getIntent().getExtras()); + currentMediaActionState = mediaAction == AnncaConfiguration.MEDIA_ACTION_VIDEO ? + MediaActionSwitchView.ACTION_VIDEO : MediaActionSwitchView.ACTION_PHOTO; + } + + @Override + protected void onCameraControllerReady() { + super.onCameraControllerReady(); + + videoQualities = getVideoQualityOptions(); + photoQualities = getPhotoQualityOptions(); + } + + @Override + protected void onResume() { + super.onResume(); + + cameraControlPanel.lockControls(); + cameraControlPanel.allowRecord(false); + } + + @Override + protected void onPause() { + super.onPause(); + + cameraControlPanel.lockControls(); + cameraControlPanel.allowRecord(false); + } + + private void extractConfiguration(Bundle bundle) { + if (bundle != null) { + if (bundle.containsKey(AnncaConfiguration.Arguments.REQUEST_CODE)) + requestCode = bundle.getInt(AnncaConfiguration.Arguments.REQUEST_CODE); + + if (bundle.containsKey(AnncaConfiguration.Arguments.MEDIA_ACTION)) { + switch (bundle.getInt(AnncaConfiguration.Arguments.MEDIA_ACTION)) { + case AnncaConfiguration.MEDIA_ACTION_PHOTO: + mediaAction = AnncaConfiguration.MEDIA_ACTION_PHOTO; + break; + case AnncaConfiguration.MEDIA_ACTION_VIDEO: + mediaAction = AnncaConfiguration.MEDIA_ACTION_VIDEO; + break; + default: + mediaAction = AnncaConfiguration.MEDIA_ACTION_UNSPECIFIED; + break; + } + } + + if (bundle.containsKey(AnncaConfiguration.Arguments.MEDIA_RESULT_BEHAVIOUR)) { + switch (bundle.getInt(AnncaConfiguration.Arguments.MEDIA_RESULT_BEHAVIOUR)) { + case AnncaConfiguration.CLOSE: + mediaResultBehaviour = AnncaConfiguration.CLOSE; + break; + case AnncaConfiguration.PREVIEW: + mediaResultBehaviour = AnncaConfiguration.PREVIEW; + break; + case AnncaConfiguration.CONTINUE: + mediaResultBehaviour = AnncaConfiguration.CONTINUE; + break; + default: + mediaResultBehaviour = AnncaConfiguration.PREVIEW; + break; + } + } + + if (bundle.containsKey(AnncaConfiguration.Arguments.CAMERA_FACE)) { + switch (bundle.getInt(AnncaConfiguration.Arguments.CAMERA_FACE)) { + case AnncaConfiguration.CAMERA_FACE_FRONT: + currentCameraType = CameraSwitchView.CAMERA_TYPE_FRONT; + CameraSwitchView.currentCameraType = CameraSwitchView.CAMERA_TYPE_FRONT; + break; + case AnncaConfiguration.CAMERA_FACE_REAR: + currentCameraType = CameraSwitchView.CAMERA_TYPE_REAR; + CameraSwitchView.currentCameraType = CameraSwitchView.CAMERA_TYPE_REAR; + break; + default: + currentCameraType = CameraSwitchView.CAMERA_TYPE_REAR; + CameraSwitchView.currentCameraType = CameraSwitchView.CAMERA_TYPE_REAR; + break; + } + } + + if (bundle.containsKey(AnncaConfiguration.Arguments.FILE_PATH)) { + filePath = bundle.getString(AnncaConfiguration.Arguments.FILE_PATH); + } + if (bundle.containsKey(AnncaConfiguration.Arguments.SHOW_GRID)) { + showGrid = bundle.getBoolean(AnncaConfiguration.Arguments.SHOW_GRID); + } + + if (bundle.containsKey(AnncaConfiguration.Arguments.MEDIA_QUALITY)) { + switch (bundle.getInt(AnncaConfiguration.Arguments.MEDIA_QUALITY)) { + case AnncaConfiguration.MEDIA_QUALITY_AUTO: + mediaQuality = AnncaConfiguration.MEDIA_QUALITY_AUTO; + break; + case AnncaConfiguration.MEDIA_QUALITY_HIGHEST: + mediaQuality = AnncaConfiguration.MEDIA_QUALITY_HIGHEST; + break; + case AnncaConfiguration.MEDIA_QUALITY_HIGH: + mediaQuality = AnncaConfiguration.MEDIA_QUALITY_HIGH; + break; + case AnncaConfiguration.MEDIA_QUALITY_MEDIUM: + mediaQuality = AnncaConfiguration.MEDIA_QUALITY_MEDIUM; + break; + case AnncaConfiguration.MEDIA_QUALITY_LOW: + mediaQuality = AnncaConfiguration.MEDIA_QUALITY_LOW; + break; + case AnncaConfiguration.MEDIA_QUALITY_LOWEST: + mediaQuality = AnncaConfiguration.MEDIA_QUALITY_LOWEST; + break; + default: + mediaQuality = AnncaConfiguration.MEDIA_QUALITY_MEDIUM; + break; + } + passedMediaQuality = mediaQuality; + } + + if (bundle.containsKey(AnncaConfiguration.Arguments.VIDEO_DURATION)) + videoDuration = bundle.getInt(AnncaConfiguration.Arguments.VIDEO_DURATION); + + if (bundle.containsKey(AnncaConfiguration.Arguments.VIDEO_FILE_SIZE)) + videoFileSize = bundle.getLong(AnncaConfiguration.Arguments.VIDEO_FILE_SIZE); + + if (bundle.containsKey(AnncaConfiguration.Arguments.MINIMUM_VIDEO_DURATION)) + minimumVideoDuration = bundle.getInt(AnncaConfiguration.Arguments.MINIMUM_VIDEO_DURATION); + + if (bundle.containsKey(AnncaConfiguration.Arguments.FLASH_MODE)) + switch (bundle.getInt(AnncaConfiguration.Arguments.FLASH_MODE)) { + case AnncaConfiguration.FLASH_MODE_AUTO: + flashMode = AnncaConfiguration.FLASH_MODE_AUTO; + break; + case AnncaConfiguration.FLASH_MODE_ON: + flashMode = AnncaConfiguration.FLASH_MODE_ON; + break; + case AnncaConfiguration.FLASH_MODE_OFF: + flashMode = AnncaConfiguration.FLASH_MODE_OFF; + break; + default: + flashMode = AnncaConfiguration.FLASH_MODE_AUTO; + break; + } + } + } + + @Override + protected View getUserContentView(LayoutInflater layoutInflater, ViewGroup parent) { + cameraControlPanel = (CameraControlPanel) layoutInflater.inflate(R.layout.user_control_layout, parent, false); + + if (cameraControlPanel != null) { + cameraControlPanel.setup(getMediaAction()); + + switch (flashMode) { + case AnncaConfiguration.FLASH_MODE_AUTO: + cameraControlPanel.setFlasMode(FlashSwitchView.FLASH_AUTO); + break; + case AnncaConfiguration.FLASH_MODE_ON: + cameraControlPanel.setFlasMode(FlashSwitchView.FLASH_ON); + break; + case AnncaConfiguration.FLASH_MODE_OFF: + cameraControlPanel.setFlasMode(FlashSwitchView.FLASH_OFF); + break; + } + + cameraControlPanel.setRecordButtonListener(this); + cameraControlPanel.setFlashModeSwitchListener(this); + cameraControlPanel.setOnMediaActionStateChangeListener(this); + cameraControlPanel.setOnCameraTypeChangeListener(this); + cameraControlPanel.setMaxVideoDuration(getVideoDuration()); + cameraControlPanel.setMaxVideoFileSize(getVideoFileSize()); + cameraControlPanel.setSettingsClickListener(this); + } + + return cameraControlPanel; + } + + @Override + public void onSettingsClick() { + AlertDialog.Builder builder = new AlertDialog.Builder(this); + + if (currentMediaActionState == MediaActionSwitchView.ACTION_VIDEO) { + builder.setSingleChoiceItems(videoQualities, getVideoOptionCheckedIndex(), getVideoOptionSelectedListener()); + if (getVideoFileSize() > 0) + builder.setTitle(String.format(getString(R.string.settings_video_quality_title), + "(Max " + String.valueOf(getVideoFileSize() / (1024 * 1024) + " MB)"))); + else + builder.setTitle(String.format(getString(R.string.settings_video_quality_title), "")); + } else { + builder.setSingleChoiceItems(photoQualities, getPhotoOptionCheckedIndex(), getPhotoOptionSelectedListener()); + builder.setTitle(R.string.settings_photo_quality_title); + } + + builder.setPositiveButton(R.string.ok_label, (dialogInterface, i) -> { + if (newQuality > 0 && newQuality != mediaQuality) { + mediaQuality = newQuality; + dialogInterface.dismiss(); + cameraControlPanel.lockControls(); + getCameraController().switchQuality(); + } + }); + builder.setNegativeButton(R.string.cancel_label, (dialogInterface, i) -> dialogInterface.dismiss()); + settingsDialog = builder.create(); + settingsDialog.show(); + WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams(); + layoutParams.copyFrom(settingsDialog.getWindow().getAttributes()); + layoutParams.width = Utils.convertDipToPixels(this, 350); + layoutParams.height = Utils.convertDipToPixels(this, 350); + settingsDialog.getWindow().setAttributes(layoutParams); + } + + @Override + public void onCameraTypeChanged(@CameraSwitchView.CameraType int cameraType) { + if (currentCameraType == cameraType) return; + currentCameraType = cameraType; + + cameraControlPanel.lockControls(); + cameraControlPanel.allowRecord(false); + + int cameraFace = cameraType == CameraSwitchView.CAMERA_TYPE_FRONT + ? AnncaConfiguration.CAMERA_FACE_FRONT : AnncaConfiguration.CAMERA_FACE_REAR; + + getCameraController().switchCamera(cameraFace); + } + + @Override + public void onFlashModeChanged(@FlashSwitchView.FlashMode int mode) { + switch (mode) { + case FlashSwitchView.FLASH_AUTO: + flashMode = AnncaConfiguration.FLASH_MODE_AUTO; + getCameraController().setFlashMode(AnncaConfiguration.FLASH_MODE_AUTO); + break; + case FlashSwitchView.FLASH_ON: + flashMode = AnncaConfiguration.FLASH_MODE_ON; + getCameraController().setFlashMode(AnncaConfiguration.FLASH_MODE_ON); + break; + case FlashSwitchView.FLASH_OFF: + flashMode = AnncaConfiguration.FLASH_MODE_OFF; + getCameraController().setFlashMode(AnncaConfiguration.FLASH_MODE_OFF); + break; + } + } + + @Override + public void onMediaActionChanged(int mediaActionState) { + if (currentMediaActionState == mediaActionState) return; + currentMediaActionState = mediaActionState; + } + + @Override + public void onTakePhotoButtonPressed() { + getCameraController().takePhoto(); + } + + @Override + public void onStartRecordingButtonPressed() { + getCameraController().startVideoRecord(); + } + + @Override + public void onStopRecordingButtonPressed() { + getCameraController().stopVideoRecord(); + } + + @Override + protected void onScreenRotation(int degrees) { + cameraControlPanel.rotateControls(degrees); + rotateSettingsDialog(degrees); + } + + @Override + public int getRequestCode() { + return requestCode; + } + + @Override + public int getMediaAction() { + return mediaAction; + } + + @Override + public int getMediaQuality() { + return mediaQuality; + } + + @Override + public int getVideoDuration() { + return videoDuration; + } + + @Override + public long getVideoFileSize() { + return videoFileSize; + } + + + @Override + public int getMinimumVideoDuration() { + return minimumVideoDuration / 1000; + } + + @Override + public int getFlashMode() { + return flashMode; + } + + @Override + public Activity getActivity() { + return this; + } + + @Override + public int getCameraFace() { + return currentCameraType; + } + + @Override + public int getMediaResultBehaviour() { + return mediaResultBehaviour; + } + + @Override + public String getFilePath() { + return filePath; + } + + @Override + public boolean getShowGrid () { + return showGrid; + } + + + @Override + public void updateCameraPreview(Size size, View cameraPreview) { + cameraControlPanel.unLockControls(); + cameraControlPanel.allowRecord(true); + + setCameraPreview(cameraPreview, size); + } + + @Override + public void updateUiForMediaAction(@AnncaConfiguration.MediaAction int mediaAction) { + + } + + @Override + public void updateCameraSwitcher(int numberOfCameras) { + cameraControlPanel.allowCameraSwitching(numberOfCameras > 1); + } + + @Override + public void onPhotoTaken() { + startPreviewActivity(); + } + + @Override + public void onVideoRecordStart(int width, int height) { + cameraControlPanel.onStartVideoRecord(getCameraController().getOutputFile()); + } + + @Override + public void onVideoRecordStop() { + cameraControlPanel.allowRecord(false); + cameraControlPanel.onStopVideoRecord(); + startPreviewActivity(); + } + + @Override + public void releaseCameraPreview() { + clearCameraPreview(); + } + + private void startPreviewActivity() { + if (mediaResultBehaviour == AnncaConfiguration.PREVIEW) { + Intent intent = PreviewActivity.newIntent(this, + getMediaAction(), getCameraController().getOutputFile().toString()); + startActivityForResult(intent, REQUEST_PREVIEW_CODE); + } else if (mediaResultBehaviour == AnncaConfiguration.CONTINUE) { + getCameraController().openCamera(); + } else if (mediaResultBehaviour == AnncaConfiguration.CLOSE) { + finish(); + } else { + Intent intent = PreviewActivity.newIntent(this, + getMediaAction(), getCameraController().getOutputFile().toString()); + startActivityForResult(intent, REQUEST_PREVIEW_CODE); + } + } + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + if (resultCode == RESULT_OK) { + if (requestCode == REQUEST_PREVIEW_CODE) { + if (PreviewActivity.isResultConfirm(data)) { + Intent resultIntent = new Intent(); + resultIntent.putExtra(AnncaConfiguration.Arguments.FILE_PATH, PreviewActivity.getMediaFilePatch(data)); + setResult(RESULT_OK, resultIntent); + finish(); + } else if (PreviewActivity.isResultCancel(data)) { + setResult(RESULT_CANCELED); + finish(); + } else if (PreviewActivity.isResultRetake(data)) { + //ignore, just proceed the camera + } + } + } + } + + private void rotateSettingsDialog(int degrees) { + if (settingsDialog != null && settingsDialog.isShowing()) { + ViewGroup dialogView = (ViewGroup) settingsDialog.getWindow().getDecorView(); + for (int i = 0; i < dialogView.getChildCount(); i++) { + dialogView.getChildAt(i).setRotation(degrees); + } + } + } + + protected abstract CharSequence[] getVideoQualityOptions(); + + protected abstract CharSequence[] getPhotoQualityOptions(); + + protected int getVideoOptionCheckedIndex() { + int checkedIndex = -1; + if (mediaQuality == AnncaConfiguration.MEDIA_QUALITY_AUTO) checkedIndex = 0; + else if (mediaQuality == AnncaConfiguration.MEDIA_QUALITY_HIGH) checkedIndex = 1; + else if (mediaQuality == AnncaConfiguration.MEDIA_QUALITY_MEDIUM) checkedIndex = 2; + else if (mediaQuality == AnncaConfiguration.MEDIA_QUALITY_LOW) checkedIndex = 3; + + if (passedMediaQuality != AnncaConfiguration.MEDIA_QUALITY_AUTO) checkedIndex--; + + return checkedIndex; + } + + protected int getPhotoOptionCheckedIndex() { + int checkedIndex = -1; + if (mediaQuality == AnncaConfiguration.MEDIA_QUALITY_HIGHEST) checkedIndex = 0; + else if (mediaQuality == AnncaConfiguration.MEDIA_QUALITY_HIGH) checkedIndex = 1; + else if (mediaQuality == AnncaConfiguration.MEDIA_QUALITY_MEDIUM) checkedIndex = 2; + else if (mediaQuality == AnncaConfiguration.MEDIA_QUALITY_LOWEST) checkedIndex = 3; + return checkedIndex; + } + + protected DialogInterface.OnClickListener getVideoOptionSelectedListener() { + return (dialogInterface, index) -> newQuality = ((VideoQualityOption) videoQualities[index]).getMediaQuality(); + } + + protected DialogInterface.OnClickListener getPhotoOptionSelectedListener() { + return (dialogInterface, index) -> newQuality = ((PhotoQualityOption) photoQualities[index]).getMediaQuality(); + } +} diff --git a/annca/src/main/java/io/github/memfis19/annca/internal/ui/camera/Camera1Activity.java b/annca/src/main/java/io/github/memfis19/annca/internal/ui/camera/Camera1Activity.java new file mode 100644 index 0000000..9db3f71 --- /dev/null +++ b/annca/src/main/java/io/github/memfis19/annca/internal/ui/camera/Camera1Activity.java @@ -0,0 +1,75 @@ +package io.github.memfis19.annca.internal.ui.camera; + +import android.content.res.Resources; +import android.graphics.Canvas; +import android.graphics.Color; +import android.graphics.Paint; +import android.hardware.Camera; +import android.media.CamcorderProfile; +import android.util.DisplayMetrics; +import android.view.ViewGroup; + +import java.util.ArrayList; +import java.util.List; + +import io.github.memfis19.annca.internal.configuration.AnncaConfiguration; +import io.github.memfis19.annca.internal.configuration.ConfigurationProvider; +import io.github.memfis19.annca.internal.controller.CameraController; +import io.github.memfis19.annca.internal.controller.impl.Camera1Controller; +import io.github.memfis19.annca.internal.controller.view.CameraView; +import io.github.memfis19.annca.internal.ui.BaseAnncaActivity; +import io.github.memfis19.annca.internal.ui.model.PhotoQualityOption; +import io.github.memfis19.annca.internal.ui.model.VideoQualityOption; +import io.github.memfis19.annca.internal.utils.CameraHelper; + +/** + * Created by memfis on 7/6/16. + */ +@SuppressWarnings("deprecation") +public class Camera1Activity extends BaseAnncaActivity { + + @Override + public CameraController createCameraController(CameraView cameraView, ConfigurationProvider configurationProvider) { + return new Camera1Controller(cameraView, configurationProvider); + } + + @Override + protected CharSequence[] getVideoQualityOptions() { + List videoQualities = new ArrayList<>(); + + if (getMinimumVideoDuration() > 0) + videoQualities.add(new VideoQualityOption(AnncaConfiguration.MEDIA_QUALITY_AUTO, CameraHelper.getCamcorderProfile(AnncaConfiguration.MEDIA_QUALITY_AUTO, getCameraController().getCurrentCameraId()), getMinimumVideoDuration())); + + CamcorderProfile camcorderProfile = CameraHelper.getCamcorderProfile(AnncaConfiguration.MEDIA_QUALITY_HIGH, getCameraController().getCurrentCameraId()); + double videoDuration = CameraHelper.calculateApproximateVideoDuration(camcorderProfile, getVideoFileSize()); + videoQualities.add(new VideoQualityOption(AnncaConfiguration.MEDIA_QUALITY_HIGH, camcorderProfile, videoDuration)); + + camcorderProfile = CameraHelper.getCamcorderProfile(AnncaConfiguration.MEDIA_QUALITY_MEDIUM, getCameraController().getCurrentCameraId()); + videoDuration = CameraHelper.calculateApproximateVideoDuration(camcorderProfile, getVideoFileSize()); + videoQualities.add(new VideoQualityOption(AnncaConfiguration.MEDIA_QUALITY_MEDIUM, camcorderProfile, videoDuration)); + + camcorderProfile = CameraHelper.getCamcorderProfile(AnncaConfiguration.MEDIA_QUALITY_LOW, getCameraController().getCurrentCameraId()); + videoDuration = CameraHelper.calculateApproximateVideoDuration(camcorderProfile, getVideoFileSize()); + videoQualities.add(new VideoQualityOption(AnncaConfiguration.MEDIA_QUALITY_LOW, camcorderProfile, videoDuration)); + + CharSequence[] array = new CharSequence[videoQualities.size()]; + videoQualities.toArray(array); + + return array; + } + + @Override + protected CharSequence[] getPhotoQualityOptions() { + List photoQualities = new ArrayList<>(); + photoQualities.add(new PhotoQualityOption(AnncaConfiguration.MEDIA_QUALITY_HIGHEST, getCameraController().getCameraManager().getPhotoSizeForQuality(AnncaConfiguration.MEDIA_QUALITY_HIGHEST))); + photoQualities.add(new PhotoQualityOption(AnncaConfiguration.MEDIA_QUALITY_HIGH, getCameraController().getCameraManager().getPhotoSizeForQuality(AnncaConfiguration.MEDIA_QUALITY_HIGH))); + photoQualities.add(new PhotoQualityOption(AnncaConfiguration.MEDIA_QUALITY_MEDIUM, getCameraController().getCameraManager().getPhotoSizeForQuality(AnncaConfiguration.MEDIA_QUALITY_MEDIUM))); + photoQualities.add(new PhotoQualityOption(AnncaConfiguration.MEDIA_QUALITY_LOWEST, getCameraController().getCameraManager().getPhotoSizeForQuality(AnncaConfiguration.MEDIA_QUALITY_LOWEST))); + + CharSequence[] array = new CharSequence[photoQualities.size()]; + photoQualities.toArray(array); + + return array; + } + +} diff --git a/annca/src/main/java/io/github/memfis19/annca/internal/ui/camera2/Camera2Activity.java b/annca/src/main/java/io/github/memfis19/annca/internal/ui/camera2/Camera2Activity.java new file mode 100644 index 0000000..e2466ee --- /dev/null +++ b/annca/src/main/java/io/github/memfis19/annca/internal/ui/camera2/Camera2Activity.java @@ -0,0 +1,70 @@ +package io.github.memfis19.annca.internal.ui.camera2; + +import android.annotation.TargetApi; +import android.media.CamcorderProfile; +import android.os.Build; + +import java.util.ArrayList; +import java.util.List; + +import io.github.memfis19.annca.internal.configuration.AnncaConfiguration; +import io.github.memfis19.annca.internal.configuration.ConfigurationProvider; +import io.github.memfis19.annca.internal.controller.CameraController; +import io.github.memfis19.annca.internal.controller.impl.Camera2Controller; +import io.github.memfis19.annca.internal.controller.view.CameraView; +import io.github.memfis19.annca.internal.ui.BaseAnncaActivity; +import io.github.memfis19.annca.internal.ui.model.PhotoQualityOption; +import io.github.memfis19.annca.internal.ui.model.VideoQualityOption; +import io.github.memfis19.annca.internal.utils.CameraHelper; + +/** + * Created by memfis on 7/6/16. + */ +public class Camera2Activity extends BaseAnncaActivity { + + @Override + public CameraController createCameraController(CameraView cameraView, ConfigurationProvider configurationProvider) { + return new Camera2Controller(cameraView, configurationProvider); + } + + @Override + protected CharSequence[] getVideoQualityOptions() { + List videoQualities = new ArrayList<>(); + + if (getMinimumVideoDuration() > 0) + videoQualities.add(new VideoQualityOption(AnncaConfiguration.MEDIA_QUALITY_AUTO, CameraHelper.getCamcorderProfile(AnncaConfiguration.MEDIA_QUALITY_AUTO, getCameraController().getCurrentCameraId()), getMinimumVideoDuration())); + + + CamcorderProfile camcorderProfile = CameraHelper.getCamcorderProfile(AnncaConfiguration.MEDIA_QUALITY_HIGH, getCameraController().getCurrentCameraId()); + double videoDuration = CameraHelper.calculateApproximateVideoDuration(camcorderProfile, getVideoFileSize()); + videoQualities.add(new VideoQualityOption(AnncaConfiguration.MEDIA_QUALITY_HIGH, camcorderProfile, videoDuration)); + + camcorderProfile = CameraHelper.getCamcorderProfile(AnncaConfiguration.MEDIA_QUALITY_MEDIUM, getCameraController().getCurrentCameraId()); + videoDuration = CameraHelper.calculateApproximateVideoDuration(camcorderProfile, getVideoFileSize()); + videoQualities.add(new VideoQualityOption(AnncaConfiguration.MEDIA_QUALITY_MEDIUM, camcorderProfile, videoDuration)); + + camcorderProfile = CameraHelper.getCamcorderProfile(AnncaConfiguration.MEDIA_QUALITY_LOW, getCameraController().getCurrentCameraId()); + videoDuration = CameraHelper.calculateApproximateVideoDuration(camcorderProfile, getVideoFileSize()); + videoQualities.add(new VideoQualityOption(AnncaConfiguration.MEDIA_QUALITY_LOW, camcorderProfile, videoDuration)); + + CharSequence[] array = new CharSequence[videoQualities.size()]; + videoQualities.toArray(array); + + return array; + } + + @Override + protected CharSequence[] getPhotoQualityOptions() { + List photoQualities = new ArrayList<>(); + photoQualities.add(new PhotoQualityOption(AnncaConfiguration.MEDIA_QUALITY_HIGHEST, getCameraController().getCameraManager().getPhotoSizeForQuality(AnncaConfiguration.MEDIA_QUALITY_HIGHEST))); + photoQualities.add(new PhotoQualityOption(AnncaConfiguration.MEDIA_QUALITY_HIGH, getCameraController().getCameraManager().getPhotoSizeForQuality(AnncaConfiguration.MEDIA_QUALITY_HIGH))); + photoQualities.add(new PhotoQualityOption(AnncaConfiguration.MEDIA_QUALITY_MEDIUM, getCameraController().getCameraManager().getPhotoSizeForQuality(AnncaConfiguration.MEDIA_QUALITY_MEDIUM))); + photoQualities.add(new PhotoQualityOption(AnncaConfiguration.MEDIA_QUALITY_LOWEST, getCameraController().getCameraManager().getPhotoSizeForQuality(AnncaConfiguration.MEDIA_QUALITY_LOWEST))); + + CharSequence[] array = new CharSequence[photoQualities.size()]; + photoQualities.toArray(array); + + return array; + } + +} diff --git a/annca/src/main/java/io/github/memfis19/annca/internal/ui/model/PhotoQualityOption.java b/annca/src/main/java/io/github/memfis19/annca/internal/ui/model/PhotoQualityOption.java new file mode 100644 index 0000000..09545a1 --- /dev/null +++ b/annca/src/main/java/io/github/memfis19/annca/internal/ui/model/PhotoQualityOption.java @@ -0,0 +1,46 @@ +package io.github.memfis19.annca.internal.ui.model; + +import io.github.memfis19.annca.internal.configuration.AnncaConfiguration; +import io.github.memfis19.annca.internal.utils.Size; + +/** + * Created by memfis on 12/1/16. + */ + +public class PhotoQualityOption implements CharSequence { + + @AnncaConfiguration.MediaQuality + private int mediaQuality; + private String title; + + public PhotoQualityOption(@AnncaConfiguration.MediaQuality int mediaQuality, Size size) { + this.mediaQuality = mediaQuality; + + title = String.valueOf(size.getWidth()) + " x " + String.valueOf(size.getHeight()); + } + + @AnncaConfiguration.MediaQuality + public int getMediaQuality() { + return mediaQuality; + } + + @Override + public int length() { + return title.length(); + } + + @Override + public char charAt(int index) { + return title.charAt(index); + } + + @Override + public CharSequence subSequence(int start, int end) { + return title.subSequence(start, end); + } + + @Override + public String toString() { + return title; + } +} diff --git a/annca/src/main/java/io/github/memfis19/annca/internal/ui/model/VideoQualityOption.java b/annca/src/main/java/io/github/memfis19/annca/internal/ui/model/VideoQualityOption.java new file mode 100644 index 0000000..cf4a805 --- /dev/null +++ b/annca/src/main/java/io/github/memfis19/annca/internal/ui/model/VideoQualityOption.java @@ -0,0 +1,59 @@ +package io.github.memfis19.annca.internal.ui.model; + +import android.media.CamcorderProfile; + +import java.util.concurrent.TimeUnit; + +import io.github.memfis19.annca.internal.configuration.AnncaConfiguration; + +/** + * Created by memfis on 12/1/16. + */ + +public class VideoQualityOption implements CharSequence { + + private String title; + + @AnncaConfiguration.MediaQuality + private int mediaQuality; + + public VideoQualityOption(@AnncaConfiguration.MediaQuality int mediaQuality, CamcorderProfile camcorderProfile, double videoDuration) { + this.mediaQuality = mediaQuality; + + long minutes = TimeUnit.SECONDS.toMinutes((long) videoDuration); + long seconds = ((long) videoDuration) - minutes * 60; + + if (mediaQuality == AnncaConfiguration.MEDIA_QUALITY_AUTO) { + title = "Auto " + ", (" + (minutes > 10 ? minutes : ("0" + minutes)) + ":" + (seconds > 10 ? seconds : ("0" + seconds)) + " min)"; + } else { + title = camcorderProfile.videoFrameWidth + + " x " + camcorderProfile.videoFrameHeight + + (videoDuration <= 0 ? "" : ", (" + (minutes > 10 ? minutes : ("0" + minutes)) + ":" + (seconds > 10 ? seconds : ("0" + seconds)) + " min)"); + } + } + + @AnncaConfiguration.MediaQuality + public int getMediaQuality() { + return mediaQuality; + } + + @Override + public int length() { + return title.length(); + } + + @Override + public char charAt(int index) { + return title.charAt(index); + } + + @Override + public CharSequence subSequence(int start, int end) { + return title.subSequence(start, end); + } + + @Override + public String toString() { + return title; + } +} \ No newline at end of file diff --git a/annca/src/main/java/io/github/memfis19/annca/internal/ui/preview/PreviewActivity.java b/annca/src/main/java/io/github/memfis19/annca/internal/ui/preview/PreviewActivity.java new file mode 100644 index 0000000..b51a006 --- /dev/null +++ b/annca/src/main/java/io/github/memfis19/annca/internal/ui/preview/PreviewActivity.java @@ -0,0 +1,365 @@ +package io.github.memfis19.annca.internal.ui.preview; + +import android.annotation.SuppressLint; +import android.content.Context; +import android.content.Intent; +import android.media.AudioManager; +import android.media.MediaPlayer; +import android.os.Bundle; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.appcompat.app.AppCompatActivity; +import android.util.Log; +import android.view.MotionEvent; +import android.view.SurfaceHolder; +import android.view.SurfaceView; +import android.view.View; +import android.view.ViewGroup; +import android.widget.FrameLayout; +import android.widget.ImageView; +import android.widget.MediaController; +import android.widget.TextView; + +import java.io.File; + +import io.github.memfis19.annca.R; +import io.github.memfis19.annca.internal.configuration.AnncaConfiguration; +import io.github.memfis19.annca.internal.ui.BaseAnncaActivity; +import io.github.memfis19.annca.internal.ui.view.AspectFrameLayout; +import io.github.memfis19.annca.internal.utils.AnncaImageLoader; +import io.github.memfis19.annca.internal.utils.Utils; + +/** + * Created by memfis on 7/6/16. + */ +public class PreviewActivity extends AppCompatActivity implements View.OnClickListener { + + private static final String TAG = "PreviewActivity"; + + private final static String MEDIA_ACTION_ARG = "media_action_arg"; + private final static String FILE_PATH_ARG = "file_path_arg"; + private final static String RESPONSE_CODE_ARG = "response_code_arg"; + private final static String VIDEO_POSITION_ARG = "current_video_position"; + private final static String VIDEO_IS_PLAYED_ARG = "is_played"; + private final static String MIME_TYPE_VIDEO = "video"; + private final static String MIME_TYPE_IMAGE = "image"; + + private int mediaAction; + private String previewFilePath; + + private SurfaceView surfaceView; + private FrameLayout photoPreviewContainer; + private ImageView imagePreview; + private ViewGroup buttonPanel; + private AspectFrameLayout videoPreviewContainer; + private View cropMediaAction; + private TextView ratioChanger; + + private MediaController mediaController; + private MediaPlayer mediaPlayer; + + private int currentPlaybackPosition = 0; + private boolean isVideoPlaying = true; + + private int currentRatioIndex = 0; + private float[] ratios; + private String[] ratioLabels; + + private SurfaceHolder.Callback surfaceCallbacks = new SurfaceHolder.Callback() { + @Override + public void surfaceCreated(SurfaceHolder holder) { + showVideoPreview(holder); + } + + @Override + public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { + + } + + @Override + public void surfaceDestroyed(SurfaceHolder holder) { + + } + }; + + private MediaController.MediaPlayerControl MediaPlayerControlImpl = new MediaController.MediaPlayerControl() { + @Override + public void start() { + mediaPlayer.start(); + } + + @Override + public void pause() { + mediaPlayer.pause(); + } + + @Override + public int getDuration() { + return mediaPlayer.getDuration(); + } + + @Override + public int getCurrentPosition() { + return mediaPlayer.getCurrentPosition(); + } + + @Override + public void seekTo(int pos) { + mediaPlayer.seekTo(pos); + } + + @Override + public boolean isPlaying() { + return mediaPlayer.isPlaying(); + } + + @Override + public int getBufferPercentage() { + return 0; + } + + @Override + public boolean canPause() { + return true; + } + + @Override + public boolean canSeekBackward() { + return true; + } + + @Override + public boolean canSeekForward() { + return true; + } + + @Override + public int getAudioSessionId() { + return mediaPlayer.getAudioSessionId(); + } + }; + + public static Intent newIntent(Context context, + @AnncaConfiguration.MediaAction int mediaAction, + String filePath) { + + return new Intent(context, PreviewActivity.class) + .putExtra(MEDIA_ACTION_ARG, mediaAction) + .putExtra(FILE_PATH_ARG, filePath); + } + + @SuppressLint("ClickableViewAccessibility") + @Override + protected void onCreate(@Nullable Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_preview); + + String originalRatioLabel = getString(R.string.preview_controls_original_ratio_label); + ratioLabels = new String[]{originalRatioLabel, "1:1", "4:3", "16:9"}; + ratios = new float[]{0f, 1f, 4f / 3f, 16f / 9f}; + + surfaceView = (SurfaceView) findViewById(R.id.video_preview); + surfaceView.setOnTouchListener((v, event) -> { + if (mediaController == null) return false; + if (mediaController.isShowing()) { + mediaController.hide(); + showButtonPanel(true); + } else { + showButtonPanel(false); + mediaController.show(); + } + return false; + }); + + videoPreviewContainer = (AspectFrameLayout) findViewById(R.id.previewAspectFrameLayout); + photoPreviewContainer = (FrameLayout) findViewById(R.id.photo_preview_container); + buttonPanel = (ViewGroup) findViewById(R.id.preview_control_panel); + View confirmMediaResult = findViewById(R.id.confirm_media_result); + View reTakeMedia = findViewById(R.id.re_take_media); + View cancelMediaAction = findViewById(R.id.cancel_media_action); + cropMediaAction = findViewById(R.id.crop_image); + ratioChanger = (TextView) findViewById(R.id.ratio_image); + ratioChanger.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + currentRatioIndex = (currentRatioIndex + 1) % ratios.length; + ratioChanger.setText(ratioLabels[currentRatioIndex]); + } + }); + + cropMediaAction.setVisibility(View.GONE); + ratioChanger.setVisibility(View.GONE); + + if (cropMediaAction != null) + cropMediaAction.setOnClickListener(view -> { + }); + + if (confirmMediaResult != null) + confirmMediaResult.setOnClickListener(this); + + if (reTakeMedia != null) + reTakeMedia.setOnClickListener(this); + + if (cancelMediaAction != null) + cancelMediaAction.setOnClickListener(this); + + Bundle args = getIntent().getExtras(); + + mediaAction = args.getInt(MEDIA_ACTION_ARG); + previewFilePath = args.getString(FILE_PATH_ARG); + + if (mediaAction == AnncaConfiguration.MEDIA_ACTION_VIDEO) { + displayVideo(savedInstanceState); + } else if (mediaAction == AnncaConfiguration.MEDIA_ACTION_PHOTO) { + displayImage(); + } else { + String mimeType = Utils.getMimeType(previewFilePath); + if (mimeType.contains(MIME_TYPE_VIDEO)) { + displayVideo(savedInstanceState); + } else if (mimeType.contains(MIME_TYPE_IMAGE)) { + displayImage(); + } else finish(); + } + } + + @Override + protected void onSaveInstanceState(@NonNull Bundle outState) { + super.onSaveInstanceState(outState); + saveVideoParams(outState); + } + + @Override + protected void onDestroy() { + super.onDestroy(); + if (mediaPlayer != null) { + mediaPlayer.release(); + mediaPlayer = null; + } + if (mediaController != null) { + mediaController.hide(); + mediaController = null; + } + } + + private void displayImage() { + videoPreviewContainer.setVisibility(View.GONE); + surfaceView.setVisibility(View.GONE); + showImagePreview(); + ratioChanger.setText(ratioLabels[currentRatioIndex]); + } + + private void showImagePreview() { + imagePreview = new ImageView(this); + AnncaImageLoader.Builder builder = new AnncaImageLoader.Builder(this); + builder.load(previewFilePath).build().into(imagePreview); + photoPreviewContainer.removeAllViews(); + photoPreviewContainer.addView(imagePreview); + } + + private void displayVideo(Bundle savedInstanceState) { + cropMediaAction.setVisibility(View.GONE); + ratioChanger.setVisibility(View.GONE); + if (savedInstanceState != null) { + loadVideoParams(savedInstanceState); + } + photoPreviewContainer.setVisibility(View.GONE); + surfaceView.getHolder().addCallback(surfaceCallbacks); + } + + private void showVideoPreview(SurfaceHolder holder) { + try { + mediaPlayer = new MediaPlayer(); + mediaPlayer.setDataSource(previewFilePath); + mediaPlayer.setDisplay(holder); + mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); + mediaPlayer.setOnPreparedListener(mp -> { + mediaController = new MediaController(PreviewActivity.this); + mediaController.setAnchorView(surfaceView); + mediaController.setMediaPlayer(MediaPlayerControlImpl); + + int videoWidth = mp.getVideoWidth(); + int videoHeight = mp.getVideoHeight(); + + videoPreviewContainer.setAspectRatio((double) videoWidth / videoHeight); + + mediaPlayer.start(); + mediaPlayer.seekTo(currentPlaybackPosition); + + if (!isVideoPlaying) + mediaPlayer.pause(); + }); + mediaPlayer.setOnErrorListener((mp, what, extra) -> { + finish(); + return true; + }); + mediaPlayer.prepareAsync(); + } catch (Exception e) { + //test(TAG, "Error media player playing video."); + finish(); + } + } + + private void saveVideoParams(Bundle outState) { + if (mediaPlayer != null) { + outState.putInt(VIDEO_POSITION_ARG, mediaPlayer.getCurrentPosition()); + outState.putBoolean(VIDEO_IS_PLAYED_ARG, mediaPlayer.isPlaying()); + } + } + + private void loadVideoParams(Bundle savedInstanceState) { + currentPlaybackPosition = savedInstanceState.getInt(VIDEO_POSITION_ARG, 0); + isVideoPlaying = savedInstanceState.getBoolean(VIDEO_IS_PLAYED_ARG, true); + } + + private void showButtonPanel(boolean show) { + if (show) { + buttonPanel.setVisibility(View.VISIBLE); + } else { + buttonPanel.setVisibility(View.GONE); + } + } + + @Override + public void onClick(View view) { + Intent resultIntent = new Intent(); + if (view.getId() == R.id.confirm_media_result) { + resultIntent.putExtra(RESPONSE_CODE_ARG, BaseAnncaActivity.ACTION_CONFIRM).putExtra(FILE_PATH_ARG, previewFilePath); + } else if (view.getId() == R.id.re_take_media) { + deleteMediaFile(); + resultIntent.putExtra(RESPONSE_CODE_ARG, BaseAnncaActivity.ACTION_RETAKE); + } else if (view.getId() == R.id.cancel_media_action) { + deleteMediaFile(); + resultIntent.putExtra(RESPONSE_CODE_ARG, BaseAnncaActivity.ACTION_CANCEL); + } + setResult(RESULT_OK, resultIntent); + finish(); + } + + @Override + public void onBackPressed() { + super.onBackPressed(); + deleteMediaFile(); + } + + private boolean deleteMediaFile() { + File mediaFile = new File(previewFilePath); + return mediaFile.delete(); + } + + public static boolean isResultConfirm(@NonNull Intent resultIntent) { + return BaseAnncaActivity.ACTION_CONFIRM == resultIntent.getIntExtra(RESPONSE_CODE_ARG, -1); + } + + public static String getMediaFilePatch(@NonNull Intent resultIntent) { + return resultIntent.getStringExtra(FILE_PATH_ARG); + } + + public static boolean isResultRetake(@NonNull Intent resultIntent) { + return BaseAnncaActivity.ACTION_RETAKE == resultIntent.getIntExtra(RESPONSE_CODE_ARG, -1); + } + + public static boolean isResultCancel(@NonNull Intent resultIntent) { + return BaseAnncaActivity.ACTION_CANCEL == resultIntent.getIntExtra(RESPONSE_CODE_ARG, -1); + } + +} diff --git a/annca/src/main/java/io/github/memfis19/annca/internal/ui/view/AspectFrameLayout.java b/annca/src/main/java/io/github/memfis19/annca/internal/ui/view/AspectFrameLayout.java new file mode 100644 index 0000000..628ceae --- /dev/null +++ b/annca/src/main/java/io/github/memfis19/annca/internal/ui/view/AspectFrameLayout.java @@ -0,0 +1,124 @@ +package io.github.memfis19.annca.internal.ui.view; + +import android.content.Context; +import android.util.AttributeSet; +import android.view.ViewGroup; +import android.view.ViewTreeObserver; +import android.widget.FrameLayout; + +import io.github.memfis19.annca.internal.utils.Size; + +/** + * Layout that adjusts to maintain a specific aspect ratio. + */ +public class AspectFrameLayout extends FrameLayout { + + private static final String TAG = "AspectFrameLayout"; + + private double targetAspectRatio = -1.0; // initially use default window size + + private Size size = null; + private int actualPreviewWidth; + private int actualPreviewHeight; + + public AspectFrameLayout(Context context) { + super(context); + } + + public AspectFrameLayout(Context context, AttributeSet attrs) { + super(context, attrs); + } + + public void setAspectRatio(double aspectRatio) { + if (aspectRatio < 0) { + throw new IllegalArgumentException(); + } + + if (targetAspectRatio != aspectRatio) { + targetAspectRatio = aspectRatio; + requestLayout(); + } + } + + @Override + protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { + if (size != null) { + setMeasuredDimension(size.getWidth(), size.getHeight()); + return; + } + + if (targetAspectRatio > 0) { + int initialWidth = MeasureSpec.getSize(widthMeasureSpec); + int initialHeight = MeasureSpec.getSize(heightMeasureSpec); + + // padding + int horizontalPadding = getPaddingLeft() + getPaddingRight(); + int verticalPadding = getPaddingTop() + getPaddingBottom(); + initialWidth -= horizontalPadding; + initialHeight -= verticalPadding; + + double viewAspectRatio = (double) initialWidth / initialHeight; + double aspectDifference = targetAspectRatio / viewAspectRatio - 1; + + if (Math.abs(aspectDifference) < 0.01) { + //no changes + } else { + if (aspectDifference > 0) { + initialHeight = (int) (initialWidth / targetAspectRatio); + } else { + initialWidth = (int) (initialHeight * targetAspectRatio); + } + initialWidth += horizontalPadding; + initialHeight += verticalPadding; + widthMeasureSpec = MeasureSpec.makeMeasureSpec(initialWidth, MeasureSpec.EXACTLY); + heightMeasureSpec = MeasureSpec.makeMeasureSpec(initialHeight, MeasureSpec.EXACTLY); + } + } + super.onMeasure(widthMeasureSpec, heightMeasureSpec); + } + + @Override + protected void onLayout(boolean changed, int l, int t, int r, int b) { + if (size != null && getChildAt(0) != null) { + getChildAt(0).layout(0, 0, actualPreviewWidth, actualPreviewHeight); + } else super.onLayout(changed, l, t, r, b); + } + + public void setCustomSize(final Size size, Size previewSize) { + if (targetAspectRatio <= 0) { + getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { + @Override + public void onGlobalLayout() { + getViewTreeObserver().removeGlobalOnLayoutListener(this); +// AspectFrameLayout.this.size = size; + + actualPreviewWidth = getMeasuredWidth(); + actualPreviewHeight = getMeasuredHeight(); + + if (actualPreviewHeight < actualPreviewWidth) + AspectFrameLayout.this.size = new Size(actualPreviewHeight, actualPreviewHeight); + else + AspectFrameLayout.this.size = new Size(actualPreviewWidth, actualPreviewWidth); + + ViewGroup.LayoutParams layoutParams = getLayoutParams(); + layoutParams.width = size.getWidth(); + layoutParams.height = size.getHeight(); + + setLayoutParams(layoutParams); + requestLayout(); + } + }); + setAspectRatio(previewSize.getHeight() / (double) previewSize.getWidth()); + } + } + + public int getCroppSize() { + return size.getHeight(); + } + + public void getCameraViewLocation(int[] location) { + if (getChildAt(0) != null) { + getChildAt(0).getLocationInWindow(location); + } else getLocationInWindow(location); + } +} diff --git a/annca/src/main/java/io/github/memfis19/annca/internal/ui/view/AutoFitSurfaceView.java b/annca/src/main/java/io/github/memfis19/annca/internal/ui/view/AutoFitSurfaceView.java new file mode 100644 index 0000000..7676ba5 --- /dev/null +++ b/annca/src/main/java/io/github/memfis19/annca/internal/ui/view/AutoFitSurfaceView.java @@ -0,0 +1,222 @@ +package io.github.memfis19.annca.internal.ui.view; + +import android.annotation.SuppressLint; +import android.content.Context; +import android.content.res.Resources; +import android.graphics.Canvas; +import android.graphics.Color; +import android.graphics.Paint; +import android.hardware.Camera; +import androidx.annotation.NonNull; +import android.util.DisplayMetrics; +import android.view.MotionEvent; +import android.view.SurfaceHolder; +import android.view.SurfaceView; +import android.view.View; +import android.widget.TextView; + +import java.util.List; + +import io.github.memfis19.annca.internal.ui.zoom.ZoomController; + +/** + * Created by memfis on 7/6/16. + */ +@SuppressWarnings("deprecation") +@SuppressLint("ViewConstructor") +public class AutoFitSurfaceView extends SurfaceView implements ZoomController { + private final static String TAG = "AutoFitSurfaceView"; + private final SurfaceHolder surfaceHolder; + + private int ratioWidth; + private int ratioHeight; + + private Camera mCamera; + float mDist = 0; + Paint paint; + TextView tv_zoom; + + public AutoFitSurfaceView(@NonNull Context context, SurfaceHolder.Callback callback, Camera camera, boolean showGrid) { + super(context); + + this.surfaceHolder = getHolder(); + + this.surfaceHolder.addCallback(callback); + this.surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); + + this.mCamera = camera; + paint = new Paint(); + tv_zoom = MyTextview.zoomTextView; + if (showGrid) { + this.setWillNotDraw(false); + } + + } + + /** + * Sets the aspect ratio for this view. The size of the view will be measured based on the ratio + * calculated fromList the parameters. Note that the actual sizes of parameters don't matter, that + * is, calling setAspectRatio(2, 3) and setAspectRatio(4, 6) make the same result. + * + * @param width Relative horizontal size + * @param height Relative vertical size + */ + public void setAspectRatio(int width, int height) { + if (width < 0 || height < 0) { + throw new IllegalArgumentException("Size cannot be negative."); + } + ratioWidth = width; + ratioHeight = height; + requestLayout(); + } + + @Override + protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { + try { + final int width = resolveSize(getSuggestedMinimumWidth(), widthMeasureSpec); + final int height = resolveSize(getSuggestedMinimumHeight(), heightMeasureSpec); + + if (0 == ratioWidth || 0 == ratioHeight) { + setMeasuredDimension(width, height); + } else { + if (width < height * (ratioWidth / (float) ratioHeight)) { + setMeasuredDimension(width, (int) (width * (ratioWidth / (float) ratioHeight))); + } else { + setMeasuredDimension((int) (height * (ratioWidth / (float) ratioHeight)), height); + } + } + } catch (Exception e) { + e.fillInStackTrace(); + } + } + + @SuppressLint("ClickableViewAccessibility") + @Override + public boolean onTouchEvent(MotionEvent event) { + // Get the pointer ID + try { + Camera.Parameters params = mCamera.getParameters(); + int action = event.getAction(); + + if (event.getPointerCount() > 1) { + // handle multi-touch events + if (action == MotionEvent.ACTION_POINTER_DOWN) { + mDist = getFingerSpacing(event); + } else if (action == MotionEvent.ACTION_MOVE + && params.isZoomSupported()) { + mCamera.cancelAutoFocus(); + handleZoom(event, params); + } + } else { + // handle single touch events + if (action == MotionEvent.ACTION_UP) { + handleFocus(event, params); + } + } + } catch (Exception e) { + e.fillInStackTrace(); + } + return true; + } + + private void handleZoom(MotionEvent event, Camera.Parameters params) { + int maxZoom = params.getMaxZoom(); + int zoom = params.getZoom(); + float newDist = getFingerSpacing(event); + if (newDist > mDist) { + // zoom in + if (zoom < maxZoom) + zoom++; + } else if (newDist < mDist) { + // zoom out + if (zoom > 0) + zoom--; + } + mDist = newDist; + params.setZoom(zoom); + + //zoom text + setZoomVisibility(zoom != 0); + if (zoom > 0) { + double data = Math.round(zoom * 1.0) / 10.0; + setZoomData(data); + } + + + mCamera.setParameters(params); + } + + public void handleFocus(MotionEvent event, Camera.Parameters params) { + try { + int pointerId = event.getPointerId(0); + int pointerIndex = event.findPointerIndex(pointerId); + // Get the pointer's current position + float x = event.getX(pointerIndex); + float y = event.getY(pointerIndex); + + List supportedFocusModes = params.getSupportedFocusModes(); + if (supportedFocusModes != null && supportedFocusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO)) { + mCamera.autoFocus(new Camera.AutoFocusCallback() { + @Override + public void onAutoFocus(boolean b, Camera camera) { + // currently set to auto-focus on single touch + } + }); + } + } catch (Exception e) { + e.fillInStackTrace(); + } + } + + /** + * Determine the space between the first two fingers + */ + private float getFingerSpacing(MotionEvent event) { + // ... + float x = event.getX(0) - event.getX(1); + float y = event.getY(0) - event.getY(1); + return (float) Math.sqrt(x * x + y * y); + } + + @Override + public void setZoomVisibility(boolean visibility) { + + if (tv_zoom != null) + if (visibility) { + tv_zoom.setVisibility(View.VISIBLE); + } else { + tv_zoom.setVisibility(View.INVISIBLE); + } + } + + @SuppressLint("SetTextI18n") + @Override + public void setZoomData(double zoom) { + if (tv_zoom != null) + tv_zoom.setText("x " + zoom); + } + + @Override + protected void onDraw(@NonNull Canvas canvas) { + // Find Screen size first + try { + DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics(); + float screenWidth = metrics.widthPixels; + float screenHeight = metrics.heightPixels; + + // Set paint options + paint.setAntiAlias(true); + paint.setStrokeWidth(5); + paint.setStyle(Paint.Style.STROKE); + paint.setColor(Color.argb(255, 255, 125, 000)); + + canvas.drawLine((screenWidth / 110) * 27, 0, (screenWidth / 110) * 27, screenHeight, paint); + canvas.drawLine((screenWidth / 110) * 72, 0, (screenWidth / 110) * 72, screenHeight, paint); + //test("small==" + (screenWidth / 100) * 27 + " large===" + (screenWidth / 100) * 63); + canvas.drawLine(0, (screenHeight / 11) * 3, screenWidth, (screenHeight / 11) * 3, paint); + canvas.drawLine(0, (screenHeight / 11) * 8, screenWidth, (screenHeight / 11) * 8, paint); + } catch (Exception e) { + e.fillInStackTrace(); + } + } +} diff --git a/annca/src/main/java/io/github/memfis19/annca/internal/ui/view/AutoFitTextureView.java b/annca/src/main/java/io/github/memfis19/annca/internal/ui/view/AutoFitTextureView.java new file mode 100644 index 0000000..6907fbb --- /dev/null +++ b/annca/src/main/java/io/github/memfis19/annca/internal/ui/view/AutoFitTextureView.java @@ -0,0 +1,55 @@ +package io.github.memfis19.annca.internal.ui.view; + +import android.annotation.SuppressLint; +import android.annotation.TargetApi; +import android.content.Context; +import android.os.Build; +import android.view.TextureView; + +/** + * Created by memfis on 7/6/16. + */ +@SuppressLint("ViewConstructor") +public class AutoFitTextureView extends TextureView { + private final static String TAG = "AutoFitTextureView"; + private int ratioWidth = 0; + private int ratioHeight = 0; + public AutoFitTextureView(Context context, TextureView.SurfaceTextureListener surfaceTextureListener) { + super(context, null); + setSurfaceTextureListener(surfaceTextureListener); + } + + /** + * Sets the aspect ratio for this view. The size of the view will be measured based on the ratio + * calculated fromList the parameters. Note that the actual sizes of parameters don't matter, that + * is, calling setAspectRatio(2, 3) and setAspectRatio(4, 6) make the same result. + * + * @param width Relative horizontal size + * @param height Relative vertical size + */ + public void setAspectRatio(int width, int height) { + if (width < 0 || height < 0) { + throw new IllegalArgumentException("Size cannot be negative."); + } + ratioWidth = width; + ratioHeight = height; + + requestLayout(); + } + + @Override + protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { + final int width = resolveSize(getSuggestedMinimumWidth(), widthMeasureSpec); + final int height = resolveSize(getSuggestedMinimumHeight(), heightMeasureSpec); + + if (0 == ratioWidth || 0 == ratioHeight) { + setMeasuredDimension(width, height); + } else { + if (width < height * (ratioWidth / (float) ratioHeight)) { + setMeasuredDimension(width, (int) (width * (ratioWidth / (float) ratioHeight))); + } else { + setMeasuredDimension((int) (height * (ratioWidth / (float) ratioHeight)), height); + } + } + } +} diff --git a/annca/src/main/java/io/github/memfis19/annca/internal/ui/view/CameraControlPanel.java b/annca/src/main/java/io/github/memfis19/annca/internal/ui/view/CameraControlPanel.java new file mode 100644 index 0000000..b4cc6f8 --- /dev/null +++ b/annca/src/main/java/io/github/memfis19/annca/internal/ui/view/CameraControlPanel.java @@ -0,0 +1,388 @@ +package io.github.memfis19.annca.internal.ui.view; + +import android.annotation.SuppressLint; +import android.content.Context; +import android.content.pm.PackageManager; +import android.graphics.Color; +import android.os.Build; +import android.os.FileObserver; +import android.os.Handler; +import android.os.Looper; +import android.util.AttributeSet; +import android.util.Log; +import android.view.LayoutInflater; +import android.view.View; +import android.widget.RelativeLayout; +import android.widget.TextView; + +import java.io.File; +import java.util.concurrent.TimeUnit; + +import io.github.memfis19.annca.R; +import io.github.memfis19.annca.internal.configuration.AnncaConfiguration; +import io.github.memfis19.annca.internal.utils.DateTimeUtils; + +/** + * Created by memfis on 7/6/16. + */ +public class CameraControlPanel extends RelativeLayout + implements RecordButton.RecordButtonListener, + MediaActionSwitchView.OnMediaActionStateChangeListener { + + private Context context; + private CameraSwitchView cameraSwitchView; + private RecordButton recordButton; + private MediaActionSwitchView mediaActionSwitchView; + private FlashSwitchView flashSwitchView; + private TextView recordDurationText; + private TextView recordSizeText; + private CameraSettingsView settingsButton; + //for zoom text + private TextView zoomText; + + private RecordButton.RecordButtonListener recordButtonListener; + private MediaActionSwitchView.OnMediaActionStateChangeListener onMediaActionStateChangeListener; + private CameraSwitchView.OnCameraTypeChangeListener onCameraTypeChangeListener; + private FlashSwitchView.FlashModeSwitchListener flashModeSwitchListener; + private SettingsClickListener settingsClickListener; + + private TimerTaskBase countDownTimer; + private long maxVideoFileSize = 0; + private String mediaFilePath; + + public interface SettingsClickListener { + void onSettingsClick(); + } + + private boolean hasFlash = false; + + private + @MediaActionSwitchView.MediaActionState + int mediaActionState; + + private int mediaAction; + + private FileObserver fileObserver; + + public CameraControlPanel(Context context) { + this(context, null); + } + + public CameraControlPanel(Context context, AttributeSet attrs) { + super(context, attrs); + this.context = context; + init(); + } + + private void init() { + hasFlash = context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH); + LayoutInflater.from(context).inflate(R.layout.camera_control_panel_layout, this); + setBackgroundColor(Color.TRANSPARENT); + settingsButton = (CameraSettingsView) findViewById(R.id.settings_view); + cameraSwitchView = (CameraSwitchView) findViewById(R.id.front_back_camera_switcher); + mediaActionSwitchView = (MediaActionSwitchView) findViewById(R.id.photo_video_camera_switcher); + recordButton = (RecordButton) findViewById(R.id.record_button); + flashSwitchView = (FlashSwitchView) findViewById(R.id.flash_switch_view); + recordDurationText = (TextView) findViewById(R.id.record_duration_text); + recordSizeText = (TextView) findViewById(R.id.record_size_mb_text); + zoomText = (TextView) findViewById(R.id.tv_zoom); + + MyTextview.zoomTextView = zoomText; + + cameraSwitchView.setOnCameraTypeChangeListener(onCameraTypeChangeListener); + mediaActionSwitchView.setOnMediaActionStateChangeListener(this); + setOnCameraTypeChangeListener(onCameraTypeChangeListener); + setOnMediaActionStateChangeListener(onMediaActionStateChangeListener); + setFlashModeSwitchListener(flashModeSwitchListener); + setRecordButtonListener(recordButtonListener); + settingsButton.setOnClickListener(view -> { + if (settingsClickListener != null) settingsClickListener.onSettingsClick(); + }); + + if (hasFlash) + flashSwitchView.setVisibility(VISIBLE); + else flashSwitchView.setVisibility(GONE); + + countDownTimer = new TimerTask(recordDurationText); + } + + public void lockControls() { + cameraSwitchView.setEnabled(false); + recordButton.setEnabled(false); + settingsButton.setEnabled(false); + flashSwitchView.setEnabled(false); + } + + public void unLockControls() { + cameraSwitchView.setEnabled(true); + recordButton.setEnabled(true); + settingsButton.setEnabled(true); + flashSwitchView.setEnabled(true); + } + + public void setup(int mediaAction) { + this.mediaAction = mediaAction; + if (AnncaConfiguration.MEDIA_ACTION_VIDEO == mediaAction) { + recordButton.setup(mediaAction, this); + flashSwitchView.setVisibility(GONE); + } else { + recordButton.setup(AnncaConfiguration.MEDIA_ACTION_PHOTO, this); + } + + if (AnncaConfiguration.MEDIA_ACTION_UNSPECIFIED != mediaAction) { + mediaActionSwitchView.setVisibility(GONE); + } //else mediaActionSwitchView.setVisibility(VISIBLE); + } + + public void setFlasMode(@FlashSwitchView.FlashMode int flashMode) { + flashSwitchView.setFlashMode(flashMode); + } + + public void setMediaFilePath(final File mediaFile) { + this.mediaFilePath = mediaFile.toString(); + } + + public void setMaxVideoFileSize(long maxVideoFileSize) { + this.maxVideoFileSize = maxVideoFileSize; + } + + public void setMaxVideoDuration(int maxVideoDurationInMillis) { + if (maxVideoDurationInMillis > 0) + countDownTimer = new CountdownTask(recordDurationText, maxVideoDurationInMillis); + else countDownTimer = new TimerTask(recordDurationText); + } + + public void setMediaActionState(@MediaActionSwitchView.MediaActionState int actionState) { + if (mediaActionState == actionState) return; + if (MediaActionSwitchView.ACTION_PHOTO == actionState) { + recordButton.setMediaAction(AnncaConfiguration.MEDIA_ACTION_PHOTO); + if (hasFlash) + flashSwitchView.setVisibility(VISIBLE); + } else { + recordButton.setMediaAction(AnncaConfiguration.MEDIA_ACTION_VIDEO); + flashSwitchView.setVisibility(GONE); + } + mediaActionState = actionState; + mediaActionSwitchView.setMediaActionState(actionState); + } + + public void setRecordButtonListener(RecordButton.RecordButtonListener recordButtonListener) { + this.recordButtonListener = recordButtonListener; + } + + public void rotateControls(int rotation) { + cameraSwitchView.setRotation(rotation); + mediaActionSwitchView.setRotation(rotation); + flashSwitchView.setRotation(rotation); + recordDurationText.setRotation(rotation); + recordSizeText.setRotation(rotation); + zoomText.setRotation(rotation); + } + + public void setOnMediaActionStateChangeListener(MediaActionSwitchView.OnMediaActionStateChangeListener onMediaActionStateChangeListener) { + this.onMediaActionStateChangeListener = onMediaActionStateChangeListener; + } + + public void setOnCameraTypeChangeListener(CameraSwitchView.OnCameraTypeChangeListener onCameraTypeChangeListener) { + this.onCameraTypeChangeListener = onCameraTypeChangeListener; + if (cameraSwitchView != null) + cameraSwitchView.setOnCameraTypeChangeListener(this.onCameraTypeChangeListener); + } + + public void setFlashModeSwitchListener(FlashSwitchView.FlashModeSwitchListener flashModeSwitchListener) { + this.flashModeSwitchListener = flashModeSwitchListener; + if (flashSwitchView != null) + flashSwitchView.setFlashSwitchListener(this.flashModeSwitchListener); + } + + public void setSettingsClickListener(SettingsClickListener settingsClickListener) { + this.settingsClickListener = settingsClickListener; + } + + @Override + public void onTakePhotoButtonPressed() { + if (recordButtonListener != null) + recordButtonListener.onTakePhotoButtonPressed(); + } + + @SuppressLint("SetTextI18n") + public void onStartVideoRecord(final File mediaFile) { + setMediaFilePath(mediaFile); + if (maxVideoFileSize > 0) { + recordSizeText.setText("1Mb" + " / " + maxVideoFileSize / (1024 * 1024) + "Mb"); + recordSizeText.setVisibility(VISIBLE); + try { + fileObserver = new FileObserver(this.mediaFilePath) { + private long lastUpdateSize = 0; + + @Override + public void onEvent(int event, String path) { + final long fileSize = mediaFile.length() / (1024 * 1024); + if ((fileSize - lastUpdateSize) >= 1) { + lastUpdateSize = fileSize; + recordSizeText.post(() -> recordSizeText.setText(fileSize + "Mb" + " / " + maxVideoFileSize / (1024 * 1024) + "Mb")); + } + } + }; + fileObserver.startWatching(); + } catch (Exception e) { + //test("FileObserver", "setMediaFilePath: ", e); + } + } + countDownTimer.start(); + + } + + public void allowRecord(boolean isAllowed) { + recordButton.setEnabled(isAllowed); + } + + public void allowCameraSwitching(boolean isAllowed) { + cameraSwitchView.setVisibility(isAllowed ? VISIBLE : GONE); + } + + public void onStopVideoRecord() { + if (fileObserver != null) + fileObserver.stopWatching(); + countDownTimer.stop(); + + recordSizeText.setVisibility(GONE); + cameraSwitchView.setVisibility(View.VISIBLE); + settingsButton.setVisibility(VISIBLE); + + if (AnncaConfiguration.MEDIA_ACTION_UNSPECIFIED != mediaAction) { + mediaActionSwitchView.setVisibility(GONE); + } //else mediaActionSwitchView.setVisibility(VISIBLE); + recordButton.setRecordState(RecordButton.READY_FOR_RECORD_STATE); + } + + @Override + public void onStartRecordingButtonPressed() { + + cameraSwitchView.setVisibility(View.GONE); + mediaActionSwitchView.setVisibility(GONE); + settingsButton.setVisibility(GONE); + + if (recordButtonListener != null) + recordButtonListener.onStartRecordingButtonPressed(); + } + + @Override + public void onStopRecordingButtonPressed() { + onStopVideoRecord(); + if (recordButtonListener != null) + recordButtonListener.onStopRecordingButtonPressed(); + } + + @Override + public void onMediaActionChanged(int mediaActionState) { + setMediaActionState(mediaActionState); + if (onMediaActionStateChangeListener != null) + onMediaActionStateChangeListener.onMediaActionChanged(this.mediaActionState); + } + + abstract class TimerTaskBase { + Handler handler = new Handler(Looper.getMainLooper()); + TextView timerView; + boolean alive = false; + long recordingTimeSeconds = 0; + long recordingTimeMinutes = 0; + + TimerTaskBase(TextView timerView) { + this.timerView = timerView; + } + + abstract void stop(); + + abstract void start(); + } + + private class CountdownTask extends TimerTaskBase implements Runnable { + + private int maxDurationMilliseconds = 0; + + public CountdownTask(TextView timerView, int maxDurationMilliseconds) { + super(timerView); + this.maxDurationMilliseconds = maxDurationMilliseconds; + } + + @SuppressLint("DefaultLocale") + @Override + public void run() { + recordingTimeSeconds--; + int millis = (int) recordingTimeSeconds * 1000; + timerView.setText( + String.format("%02d:%02d", + TimeUnit.MILLISECONDS.toMinutes(millis), + TimeUnit.MILLISECONDS.toSeconds(millis) - + TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)) + )); + + if (recordingTimeSeconds < 10) { + timerView.setTextColor(Color.RED); + } + + if (alive && recordingTimeSeconds > 0) handler.postDelayed(this, DateTimeUtils.SECOND); + } + + @Override + void stop() { + timerView.setVisibility(View.INVISIBLE); + alive = false; + } + + @SuppressLint("DefaultLocale") + @Override + void start() { + alive = true; + recordingTimeSeconds = maxDurationMilliseconds / 1000; + timerView.setTextColor(Color.WHITE); + timerView.setText( + String.format("%02d:%02d", + TimeUnit.MILLISECONDS.toMinutes(maxDurationMilliseconds), + TimeUnit.MILLISECONDS.toSeconds(maxDurationMilliseconds) - + TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(maxDurationMilliseconds)) + )); + timerView.setVisibility(View.VISIBLE); + handler.postDelayed(this, DateTimeUtils.SECOND); + } + } + + private class TimerTask extends TimerTaskBase implements Runnable { + + public TimerTask(TextView timerView) { + super(timerView); + } + + @SuppressLint("DefaultLocale") + @Override + public void run() { + recordingTimeSeconds++; + + if (recordingTimeSeconds == 60) { + recordingTimeSeconds = 0; + recordingTimeMinutes++; + } + timerView.setText( + String.format("%02d:%02d", recordingTimeMinutes, recordingTimeSeconds)); + if (alive) handler.postDelayed(this, DateTimeUtils.SECOND); + } + + @SuppressLint("DefaultLocale") + public void start() { + alive = true; + recordingTimeMinutes = 0; + recordingTimeSeconds = 0; + timerView.setText( + String.format("%02d:%02d", recordingTimeMinutes, recordingTimeSeconds)); + timerView.setVisibility(View.VISIBLE); + handler.postDelayed(this, DateTimeUtils.SECOND); + } + + public void stop() { + timerView.setVisibility(View.INVISIBLE); + alive = false; + } + } + +} diff --git a/annca/src/main/java/io/github/memfis19/annca/internal/ui/view/CameraSettingsView.java b/annca/src/main/java/io/github/memfis19/annca/internal/ui/view/CameraSettingsView.java new file mode 100644 index 0000000..4ec3cf1 --- /dev/null +++ b/annca/src/main/java/io/github/memfis19/annca/internal/ui/view/CameraSettingsView.java @@ -0,0 +1,38 @@ +package io.github.memfis19.annca.internal.ui.view; + +import android.annotation.TargetApi; +import android.content.Context; +import android.os.Build; +import android.util.AttributeSet; +import android.widget.ImageButton; + +/** + * Created by memfis on 8/23/16. + */ +public class CameraSettingsView extends ImageButton { + public CameraSettingsView(Context context) { + super(context); + } + + public CameraSettingsView(Context context, AttributeSet attrs) { + super(context, attrs); + } + + public CameraSettingsView(Context context, AttributeSet attrs, int defStyleAttr) { + super(context, attrs, defStyleAttr); + } + + public CameraSettingsView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { + super(context, attrs, defStyleAttr, defStyleRes); + } + + @Override + public void setEnabled(boolean enabled) { + super.setEnabled(enabled); + if (enabled) { + setAlpha(1f); + } else { + setAlpha(0.5f); + } + } +} diff --git a/annca/src/main/java/io/github/memfis19/annca/internal/ui/view/CameraSwitchView.java b/annca/src/main/java/io/github/memfis19/annca/internal/ui/view/CameraSwitchView.java new file mode 100644 index 0000000..1c1f5c1 --- /dev/null +++ b/annca/src/main/java/io/github/memfis19/annca/internal/ui/view/CameraSwitchView.java @@ -0,0 +1,118 @@ +package io.github.memfis19.annca.internal.ui.view; + +import android.content.Context; +import android.graphics.drawable.Drawable; +import android.os.Build; +import androidx.annotation.IntDef; +import androidx.core.content.ContextCompat; +import androidx.core.graphics.drawable.DrawableCompat; +import androidx.appcompat.widget.AppCompatImageButton; +import android.util.AttributeSet; +import android.view.View; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +import io.github.memfis19.annca.R; +import io.github.memfis19.annca.internal.utils.Utils; + +/** + * Created by memfis on 6/24/16. + */ +public class CameraSwitchView extends AppCompatImageButton { + + public static final int CAMERA_TYPE_FRONT = 0; + public static final int CAMERA_TYPE_REAR = 1; + + @IntDef({CAMERA_TYPE_FRONT, CAMERA_TYPE_REAR}) + @Retention(RetentionPolicy.SOURCE) + public @interface CameraType { + } + + private OnCameraTypeChangeListener onCameraTypeChangeListener; + + public interface OnCameraTypeChangeListener { + void onCameraTypeChanged(@CameraType int cameraType); + } + + private Context context; + private Drawable frontCameraDrawable; + private Drawable rearCameraDrawable; + private int padding = 5; + + public + @CameraType + static int currentCameraType = CAMERA_TYPE_FRONT; + + public CameraSwitchView(Context context) { + this(context, null); + } + + public CameraSwitchView(Context context, AttributeSet attrs) { + super(context, attrs); + this.context = context; + initializeView(); + } + + public CameraSwitchView(Context context, AttributeSet attrs, int defStyleAttr) { + this(context, attrs); + } + + private void initializeView() { + frontCameraDrawable = ContextCompat.getDrawable(context, R.drawable.ic_camera_front_white_24dp); + frontCameraDrawable = DrawableCompat.wrap(frontCameraDrawable); + DrawableCompat.setTintList(frontCameraDrawable.mutate(), ContextCompat.getColorStateList(context, R.drawable.switch_camera_mode_selector)); + + rearCameraDrawable = ContextCompat.getDrawable(context, R.drawable.ic_camera_rear_white_24dp); + rearCameraDrawable = DrawableCompat.wrap(rearCameraDrawable); + DrawableCompat.setTintList(rearCameraDrawable.mutate(), ContextCompat.getColorStateList(context, R.drawable.switch_camera_mode_selector)); + + setBackgroundResource(R.drawable.circle_frame_background_dark); + setOnClickListener(new CameraTypeClickListener()); + setIcons(); + padding = Utils.convertDipToPixels(context, padding); + setPadding(padding, padding, padding, padding); + } + + private void setIcons() { + if (currentCameraType == CAMERA_TYPE_REAR) { + setImageDrawable(rearCameraDrawable); + } else setImageDrawable(frontCameraDrawable); + } + + @Override + public void setEnabled(boolean enabled) { + super.setEnabled(enabled); + if (enabled) { + setAlpha(1f); + } else { + setAlpha(0.5f); + } + } + + + public + @CameraType + int getCameraType() { + return currentCameraType; + } + + public void setOnCameraTypeChangeListener(OnCameraTypeChangeListener onCameraTypeChangeListener) { + this.onCameraTypeChangeListener = onCameraTypeChangeListener; + } + + private class CameraTypeClickListener implements OnClickListener { + + @Override + public void onClick(View view) { + if (currentCameraType == CAMERA_TYPE_REAR) { + currentCameraType = CAMERA_TYPE_FRONT; + } else currentCameraType = CAMERA_TYPE_REAR; + + setIcons(); + + if (onCameraTypeChangeListener != null) + onCameraTypeChangeListener.onCameraTypeChanged(currentCameraType); + } + } +} diff --git a/annca/src/main/java/io/github/memfis19/annca/internal/ui/view/FlashSwitchView.java b/annca/src/main/java/io/github/memfis19/annca/internal/ui/view/FlashSwitchView.java new file mode 100644 index 0000000..ee79bcd --- /dev/null +++ b/annca/src/main/java/io/github/memfis19/annca/internal/ui/view/FlashSwitchView.java @@ -0,0 +1,124 @@ +package io.github.memfis19.annca.internal.ui.view; + +import android.content.Context; +import android.graphics.Color; +import android.graphics.PorterDuff; +import android.graphics.drawable.Drawable; +import android.os.Build; +import androidx.annotation.ColorInt; +import androidx.annotation.IntDef; +import androidx.annotation.NonNull; +import androidx.core.content.ContextCompat; +import android.util.AttributeSet; +import android.view.View; +import android.widget.ImageButton; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +import io.github.memfis19.annca.R; + + +/** + * Created by memfis on 7/6/16. + */ +public class FlashSwitchView extends ImageButton { + @FlashMode + private int currentMode = FLASH_AUTO; + + private FlashModeSwitchListener switchListener; + private Drawable flashOnDrawable; + private Drawable flashOffDrawable; + private Drawable flashAutoDrawable; + + private int tintColor = Color.WHITE; + + public static final int FLASH_ON = 0; + public static final int FLASH_OFF = 1; + public static final int FLASH_AUTO = 2; + + @IntDef({FLASH_ON, FLASH_OFF, FLASH_AUTO}) + @Retention(RetentionPolicy.SOURCE) + public @interface FlashMode { + } + + public interface FlashModeSwitchListener { + void onFlashModeChanged(@FlashMode int mode); + } + + public FlashSwitchView(@NonNull Context context) { + this(context, null); + } + + public FlashSwitchView(@NonNull Context context, AttributeSet attrs) { + super(context, attrs); + flashOnDrawable = ContextCompat.getDrawable(context, R.drawable.ic_flash_on_white_24dp); + flashOffDrawable = ContextCompat.getDrawable(context, R.drawable.ic_flash_off_white_24dp); + flashAutoDrawable = ContextCompat.getDrawable(context, R.drawable.ic_flash_auto_white_24dp); + init(); + } + + private void init() { + setBackgroundColor(Color.TRANSPARENT); + setOnClickListener(new FlashButtonClickListener()); + setIcon(); + } + + private void setIcon() { + if (FLASH_OFF == currentMode) { + setImageDrawable(flashOffDrawable); + } else if (FLASH_ON == currentMode) { + setImageDrawable(flashOnDrawable); + } else setImageDrawable(flashAutoDrawable); + + } + + private void setIconsTint(@ColorInt int tintColor) { + this.tintColor = tintColor; + flashOnDrawable.setColorFilter(tintColor, PorterDuff.Mode.MULTIPLY); + flashOffDrawable.setColorFilter(tintColor, PorterDuff.Mode.MULTIPLY); + flashAutoDrawable.setColorFilter(tintColor, PorterDuff.Mode.MULTIPLY); + } + + public void setFlashMode(@FlashMode int mode) { + this.currentMode = mode; + setIcon(); + } + + @FlashMode + public int getCurrentFlasMode() { + return currentMode; + } + + public void setFlashSwitchListener(@NonNull FlashModeSwitchListener switchListener) { + this.switchListener = switchListener; + } + + @Override + public void setEnabled(boolean enabled) { + super.setEnabled(enabled); + if (enabled) { + setAlpha(1f); + } else { + setAlpha(0.5f); + } + } + + private class FlashButtonClickListener implements OnClickListener { + + @Override + public void onClick(View v) { + if (FLASH_AUTO == currentMode) { + currentMode = FLASH_OFF; + } else if (FLASH_OFF == currentMode) { + currentMode = FLASH_ON; + } else if (FLASH_ON == currentMode) { + currentMode = FLASH_AUTO; + } + setIcon(); + if (switchListener != null) { + switchListener.onFlashModeChanged(currentMode); + } + } + } +} diff --git a/annca/src/main/java/io/github/memfis19/annca/internal/ui/view/MediaActionSwitchView.java b/annca/src/main/java/io/github/memfis19/annca/internal/ui/view/MediaActionSwitchView.java new file mode 100644 index 0000000..b717f3a --- /dev/null +++ b/annca/src/main/java/io/github/memfis19/annca/internal/ui/view/MediaActionSwitchView.java @@ -0,0 +1,112 @@ +package io.github.memfis19.annca.internal.ui.view; + +import android.content.Context; +import android.graphics.drawable.Drawable; +import android.os.Build; +import androidx.annotation.IntDef; +import androidx.core.content.ContextCompat; +import androidx.core.graphics.drawable.DrawableCompat; +import android.util.AttributeSet; +import android.view.View; +import android.widget.ImageButton; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +import io.github.memfis19.annca.R; +import io.github.memfis19.annca.internal.utils.Utils; + +/** + * Created by memfis on 6/24/16. + */ +public class MediaActionSwitchView extends ImageButton { + public final static int ACTION_PHOTO = 0; + public final static int ACTION_VIDEO = 1; + + @IntDef({ACTION_PHOTO, ACTION_VIDEO}) + @Retention(RetentionPolicy.SOURCE) + public @interface MediaActionState { + } + + private int currentMediaActionState = ACTION_PHOTO; + private OnMediaActionStateChangeListener onMediaActionStateChangeListener; + + public interface OnMediaActionStateChangeListener { + void onMediaActionChanged(int mediaActionState); + } + + private Context context; + private Drawable photoDrawable; + private Drawable videoDrawable; + private int padding = 5; + + public MediaActionSwitchView(Context context) { + this(context, null); + } + + public MediaActionSwitchView(Context context, AttributeSet attrs) { + super(context, attrs); + this.context = context; + initializeView(); + } + + public MediaActionSwitchView(Context context, AttributeSet attrs, int defStyleAttr) { + this(context, attrs); + } + + private void initializeView() { + photoDrawable = ContextCompat.getDrawable(context, R.drawable.ic_photo_camera_white_24dp); + photoDrawable = DrawableCompat.wrap(photoDrawable); + DrawableCompat.setTintList(photoDrawable.mutate(), ContextCompat.getColorStateList(context, R.drawable.switch_camera_mode_selector)); + + videoDrawable = ContextCompat.getDrawable(context, R.drawable.ic_videocam_white_24dp); + videoDrawable = DrawableCompat.wrap(videoDrawable); + DrawableCompat.setTintList(videoDrawable.mutate(), ContextCompat.getColorStateList(context, R.drawable.switch_camera_mode_selector)); + + setBackgroundResource(R.drawable.circle_frame_background_dark); + setOnClickListener(new MediaActionClickListener()); + setIcons(); + padding = Utils.convertDipToPixels(context, padding); + setPadding(padding, padding, padding, padding); + } + + private void setIcons() { + if (currentMediaActionState == ACTION_PHOTO) { + setImageDrawable(videoDrawable); + } else setImageDrawable(photoDrawable); + } + + public void setMediaActionState(@MediaActionState int currentMediaActionState) { + this.currentMediaActionState = currentMediaActionState; + setIcons(); + } + + public void setOnMediaActionStateChangeListener(OnMediaActionStateChangeListener onMediaActionStateChangeListener) { + this.onMediaActionStateChangeListener = onMediaActionStateChangeListener; + } + + @Override + public void setEnabled(boolean enabled) { + super.setEnabled(enabled); + if (enabled) { + setAlpha(1f); + } else { + setAlpha(0.5f); + } + } + + private class MediaActionClickListener implements OnClickListener { + + @Override + public void onClick(View view) { + if (currentMediaActionState == ACTION_PHOTO) { + currentMediaActionState = ACTION_VIDEO; + } else currentMediaActionState = ACTION_PHOTO; + + setIcons(); + if (onMediaActionStateChangeListener != null) + onMediaActionStateChangeListener.onMediaActionChanged(currentMediaActionState); + } + } + +} diff --git a/annca/src/main/java/io/github/memfis19/annca/internal/ui/view/MyTextview.java b/annca/src/main/java/io/github/memfis19/annca/internal/ui/view/MyTextview.java new file mode 100644 index 0000000..7023b43 --- /dev/null +++ b/annca/src/main/java/io/github/memfis19/annca/internal/ui/view/MyTextview.java @@ -0,0 +1,9 @@ +package io.github.memfis19.annca.internal.ui.view; + +import android.annotation.SuppressLint; +import android.widget.TextView; + +public class MyTextview { + @SuppressLint("StaticFieldLeak") + public static TextView zoomTextView; +} diff --git a/annca/src/main/java/io/github/memfis19/annca/internal/ui/view/RecordButton.java b/annca/src/main/java/io/github/memfis19/annca/internal/ui/view/RecordButton.java new file mode 100644 index 0000000..dc23dc4 --- /dev/null +++ b/annca/src/main/java/io/github/memfis19/annca/internal/ui/view/RecordButton.java @@ -0,0 +1,186 @@ +package io.github.memfis19.annca.internal.ui.view; + +import android.annotation.TargetApi; +import android.content.Context; +import android.graphics.drawable.Drawable; +import android.media.MediaActionSound; +import android.os.Build; +import androidx.annotation.IntDef; +import androidx.annotation.NonNull; +import androidx.core.content.ContextCompat; +import android.util.AttributeSet; +import android.view.View; +import android.widget.ImageButton; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +import io.github.memfis19.annca.R; +import io.github.memfis19.annca.internal.configuration.AnncaConfiguration; +import io.github.memfis19.annca.internal.utils.Utils; + +/** + * Created by memfis on 7/6/16. + */ +public class RecordButton extends ImageButton { + + public static final int TAKE_PHOTO_STATE = 0; + public static final int READY_FOR_RECORD_STATE = 1; + public static final int RECORD_IN_PROGRESS_STATE = 2; + + @IntDef({TAKE_PHOTO_STATE, READY_FOR_RECORD_STATE, RECORD_IN_PROGRESS_STATE}) + @Retention(RetentionPolicy.SOURCE) + public @interface RecordState { + } + + public interface RecordButtonListener { + + void onTakePhotoButtonPressed(); + + void onStartRecordingButtonPressed(); + + void onStopRecordingButtonPressed(); + } + + private Context context; + private int mediaAction = AnncaConfiguration.MEDIA_ACTION_PHOTO; + + private + @RecordState + int currentState = TAKE_PHOTO_STATE; + + private Drawable takePhotoDrawable; + private Drawable startRecordDrawable; + private Drawable stopRecordDrawable; + private int iconPadding = 8; + private int iconPaddingStop = 18; + + private RecordButtonListener listener; + + public RecordButton(@NonNull Context context) { + this(context, null, 0); + } + + public RecordButton(@NonNull Context context, AttributeSet attrs) { + this(context, attrs, 0); + } + + public RecordButton(@NonNull Context context, AttributeSet attrs, int defStyleAttr) { + super(context, attrs, defStyleAttr); + this.context = context; + takePhotoDrawable = ContextCompat.getDrawable(context, R.drawable.take_photo_button); + startRecordDrawable = ContextCompat.getDrawable(context, R.drawable.start_video_record_button); + stopRecordDrawable = ContextCompat.getDrawable(context, R.drawable.stop_button_background); + } + + public void setup(@AnncaConfiguration.MediaAction int mediaAction, @NonNull RecordButtonListener listener) { + setMediaAction(mediaAction); + this.listener = listener; + setBackground(ContextCompat.getDrawable(context, R.drawable.circle_frame_background)); + setIcon(); + setOnClickListener(new RecordClickListener()); + setSoundEffectsEnabled(false); + setIconPadding(iconPadding); + } + + private void setIconPadding(int paddingDP) { + int padding = Utils.convertDipToPixels(context, paddingDP); + setPadding(padding, padding, padding, padding); + } + + public void setMediaAction(@AnncaConfiguration.MediaAction int mediaAction) { + this.mediaAction = mediaAction; + if (AnncaConfiguration.MEDIA_ACTION_PHOTO == mediaAction) + currentState = TAKE_PHOTO_STATE; + else currentState = READY_FOR_RECORD_STATE; + setRecordState(currentState); + setIcon(); + } + + public void setRecordState(@RecordState int state) { + currentState = state; + setIcon(); + } + + public + @RecordState + int getRecordState() { + return currentState; + } + + public void setRecordButtonListener(@NonNull RecordButtonListener listener) { + this.listener = listener; + } + + private void setIcon() { + if (AnncaConfiguration.MEDIA_ACTION_VIDEO == mediaAction) { + if (READY_FOR_RECORD_STATE == currentState) { + setImageDrawable(startRecordDrawable); + setIconPadding(iconPadding); + } else if (RECORD_IN_PROGRESS_STATE == currentState) { + setImageDrawable(stopRecordDrawable); + setIconPadding(iconPaddingStop); + } + } else { + setImageDrawable(takePhotoDrawable); + setIconPadding(iconPadding); + } + } + + private void takePhoto(MediaActionSound sound) { + //sound.play(MediaActionSound.SHUTTER_CLICK); + takePhoto(); + } + + private void takePhoto() { + if (listener != null) + listener.onTakePhotoButtonPressed(); + } + + private void startRecording(MediaActionSound sound) { + //sound.play(MediaActionSound.START_VIDEO_RECORDING); + startRecording(); + } + + private void startRecording() { + currentState = RECORD_IN_PROGRESS_STATE; + if (listener != null) { + listener.onStartRecordingButtonPressed(); + } + } + + private void stopRecording(MediaActionSound sound) { + //sound.play(MediaActionSound.STOP_VIDEO_RECORDING); + stopRecording(); + } + + private void stopRecording() { + currentState = READY_FOR_RECORD_STATE; + if (listener != null) { + listener.onStopRecordingButtonPressed(); + } + } + + private class RecordClickListener implements OnClickListener { + private final static int CLICK_DELAY = 1000; + private long lastClickTime = 0; + + @Override + public void onClick(View view) { + if (System.currentTimeMillis() - lastClickTime < CLICK_DELAY) { + return; + } else lastClickTime = System.currentTimeMillis(); + + MediaActionSound sound = new MediaActionSound(); + if (TAKE_PHOTO_STATE == currentState) { + takePhoto(sound); + } else if (READY_FOR_RECORD_STATE == currentState) { + startRecording(sound); + } else if (RECORD_IN_PROGRESS_STATE == currentState) { + stopRecording(sound); + } + setIcon(); + } + } + +} diff --git a/annca/src/main/java/io/github/memfis19/annca/internal/ui/zoom/ZoomController.java b/annca/src/main/java/io/github/memfis19/annca/internal/ui/zoom/ZoomController.java new file mode 100644 index 0000000..767f546 --- /dev/null +++ b/annca/src/main/java/io/github/memfis19/annca/internal/ui/zoom/ZoomController.java @@ -0,0 +1,7 @@ +package io.github.memfis19.annca.internal.ui.zoom; + +public interface ZoomController { + + void setZoomVisibility(boolean visibility); + void setZoomData(double zoom); +} diff --git a/annca/src/main/java/io/github/memfis19/annca/internal/utils/AnncaImageLoader.java b/annca/src/main/java/io/github/memfis19/annca/internal/utils/AnncaImageLoader.java new file mode 100644 index 0000000..691d624 --- /dev/null +++ b/annca/src/main/java/io/github/memfis19/annca/internal/utils/AnncaImageLoader.java @@ -0,0 +1,198 @@ +package io.github.memfis19.annca.internal.utils; + +import android.content.Context; +import android.graphics.Bitmap; +import android.graphics.BitmapFactory; +import android.graphics.Matrix; +import android.graphics.Point; +import android.media.ExifInterface; +import android.os.Build; +import android.os.Handler; +import android.os.Looper; +import android.os.Process; +import androidx.annotation.NonNull; +import android.view.Display; +import android.view.ViewTreeObserver; +import android.view.WindowManager; +import android.widget.ImageView; + +import java.io.IOException; + +/** + * Created by memfis on 7/18/16. + */ +public final class AnncaImageLoader { + + private static final String TAG = "AnncaImageLoader"; + + private Context context; + private String url; + + private AnncaImageLoader(Context context) { + this.context = context; + } + + public static class Builder { + + private AnncaImageLoader anncaImageLoader; + + public Builder(@NonNull Context context) { + anncaImageLoader = new AnncaImageLoader(context); + } + + public Builder load(String url) { + anncaImageLoader.url = url; + return this; + } + + public AnncaImageLoader build() { + return anncaImageLoader; + } + } + + public void into(final ImageView target) { + ViewTreeObserver viewTreeObserver = target.getViewTreeObserver(); + viewTreeObserver.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { + public boolean onPreDraw() { + target.getViewTreeObserver().removeOnPreDrawListener(this); + + new ImageLoaderThread(target, url).start(); + + return true; + } + }); + } + + private class ImageLoaderThread extends Thread { + + private ImageView target; + private String url; + private Handler mainHandler = new Handler(Looper.getMainLooper()); + + private ImageLoaderThread(ImageView target, String url) { + this.target = target; + this.url = url; + } + + @Override + public void run() { + Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); + + WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); + Display display = windowManager.getDefaultDisplay(); + + int imageViewHeight; + int imageViewWidth; + + if (Build.VERSION.SDK_INT < 13) { + imageViewHeight = display.getHeight(); + imageViewWidth = display.getWidth(); + } else { + Point size = new Point(); + display.getSize(size); + imageViewHeight = size.y; + imageViewWidth = size.x; + } + +// int imageViewHeight = target.getMeasuredHeight(); +// int imageViewWidth = target.getMeasuredWidth(); + + Bitmap decodedBitmap = decodeSampledBitmapFromResource(url, imageViewWidth, imageViewHeight); + final Bitmap resultBitmap = rotateBitmap(decodedBitmap, getExifOrientation()); + + mainHandler.post(new Runnable() { + @Override + public void run() { + target.setImageBitmap(resultBitmap); + } + }); + } + + private Bitmap rotateBitmap(Bitmap bitmap, int orientation) { + Matrix matrix = new Matrix(); + switch (orientation) { + case ExifInterface.ORIENTATION_NORMAL: + return bitmap; + case ExifInterface.ORIENTATION_FLIP_HORIZONTAL: + matrix.setScale(-1, 1); + break; + case ExifInterface.ORIENTATION_ROTATE_180: + matrix.setRotate(180); + break; + case ExifInterface.ORIENTATION_FLIP_VERTICAL: + matrix.setRotate(180); + matrix.postScale(-1, 1); + break; + case ExifInterface.ORIENTATION_TRANSPOSE: + matrix.setRotate(90); + matrix.postScale(-1, 1); + break; + case ExifInterface.ORIENTATION_ROTATE_90: + matrix.setRotate(90); + break; + case ExifInterface.ORIENTATION_TRANSVERSE: + matrix.setRotate(-90); + matrix.postScale(-1, 1); + break; + case ExifInterface.ORIENTATION_ROTATE_270: + matrix.setRotate(-90); + break; + default: + return bitmap; + } + + try { + Bitmap bmRotated = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true); + bitmap.recycle(); + return bmRotated; + } catch (OutOfMemoryError ignore) { + return null; + } + } + + private int getExifOrientation() { + ExifInterface exif = null; + try { + exif = new ExifInterface(url); + } catch (IOException ignore) { + } + return exif == null ? ExifInterface.ORIENTATION_UNDEFINED : + exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED); + } + + private Bitmap decodeSampledBitmapFromResource(String url, + int requestedWidth, int requestedHeight) { + + final BitmapFactory.Options options = new BitmapFactory.Options(); + options.inJustDecodeBounds = true; + BitmapFactory.decodeFile(url, options); + + options.inSampleSize = calculateInSampleSize(options, requestedWidth, requestedHeight); + options.inJustDecodeBounds = false; + options.inPreferredConfig = Bitmap.Config.RGB_565; + return BitmapFactory.decodeFile(url, options); + } + + private int calculateInSampleSize(BitmapFactory.Options options, + int requestedWidth, int requestedHeight) { + + final int height = options.outHeight; + final int width = options.outWidth; + int inSampleSize = 1; + + if (height > requestedHeight || width > requestedWidth) { + + final int halfHeight = height / inSampleSize; + final int halfWidth = width / inSampleSize; + + while ((halfHeight / inSampleSize) > requestedHeight + && (halfWidth / inSampleSize) > requestedWidth) { + inSampleSize *= 2; + } + } + return inSampleSize; + } + } + +} + diff --git a/annca/src/main/java/io/github/memfis19/annca/internal/utils/CameraHelper.java b/annca/src/main/java/io/github/memfis19/annca/internal/utils/CameraHelper.java new file mode 100644 index 0000000..945acf4 --- /dev/null +++ b/annca/src/main/java/io/github/memfis19/annca/internal/utils/CameraHelper.java @@ -0,0 +1,393 @@ +package io.github.memfis19.annca.internal.utils; + +import android.annotation.SuppressLint; +import android.annotation.TargetApi; +import android.content.Context; +import android.content.pm.PackageManager; +import android.hardware.camera2.CameraCharacteristics; +import android.hardware.camera2.CameraManager; +import android.media.CamcorderProfile; +import android.os.Build; +import android.os.Environment; +import android.text.TextUtils; +import android.util.Log; + +import java.io.File; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.Date; +import java.util.List; + +import io.github.memfis19.annca.internal.configuration.AnncaConfiguration; + +/** + * Created by memfis on 7/6/16. + *

+ * Class with some common methods to work with camera. + */ +public final class CameraHelper { + + public final static String TAG = "CameraHelper"; + + + private CameraHelper() { + + } + + public static boolean hasCamera(Context context) { + return context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY) || + context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FRONT); + } + + public static boolean hasCamera2(Context context) { + if (context == null) return false; + try { + CameraManager manager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE); + String[] idList = manager.getCameraIdList(); + boolean notNull = true; + if (idList.length == 0) { + notNull = false; + } else { + for (final String str : idList) { + if (str == null || str.trim().isEmpty()) { + notNull = false; + break; + } + final CameraCharacteristics characteristics = manager.getCameraCharacteristics(str); + final int supportLevel = characteristics.get(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL); + if (supportLevel == CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY) { + notNull = false; + break; + } + } + } + return notNull; + } catch (Throwable ignore) { + return false; + } + } + + public static File getOutputMediaFile(Context context, @AnncaConfiguration.MediaAction int mediaAction) { + File mediaStorageDir = new File(Environment.getExternalStorageDirectory() + "/MyCustomCamera"); + if (!mediaStorageDir.exists()) { + if (!mediaStorageDir.mkdirs()) { + //test(TAG, "Failed to create directory."); + return null; + } + } + + @SuppressLint("SimpleDateFormat") String timeStamp = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss").format(new Date()); + File mediaFile; + if (mediaAction == AnncaConfiguration.MEDIA_ACTION_PHOTO) { + mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg"); + } else if (mediaAction == AnncaConfiguration.MEDIA_ACTION_VIDEO) { + mediaFile = new File(mediaStorageDir.getPath() + File.separator + "VID_" + timeStamp + ".mp4"); + } else { + return null; + } + + return mediaFile; + } + + @SuppressWarnings("deprecation") + public static Size getPictureSize(List choices, @AnncaConfiguration.MediaQuality int mediaQuality) { + if (choices == null || choices.isEmpty()) return null; + if (choices.size() == 1) return choices.get(0); + + Size result = null; + Size maxPictureSize = Collections.max(choices, new CompareSizesByArea2()); + Size minPictureSize = Collections.min(choices, new CompareSizesByArea2()); + + Collections.sort(choices, new CompareSizesByArea2()); + + if (mediaQuality == AnncaConfiguration.MEDIA_QUALITY_HIGHEST) { + result = maxPictureSize; + } else if (mediaQuality == AnncaConfiguration.MEDIA_QUALITY_LOW) { + if (choices.size() == 2) result = minPictureSize; + else { + int half = choices.size() / 2; + int lowQualityIndex = (choices.size() - half) / 2; + result = choices.get(lowQualityIndex + 1); + } + } else if (mediaQuality == AnncaConfiguration.MEDIA_QUALITY_HIGH) { + if (choices.size() == 2) result = maxPictureSize; + else { + int half = choices.size() / 2; + int highQualityIndex = (choices.size() - half) / 2; + result = choices.get(choices.size() - highQualityIndex - 1); + } + } else if (mediaQuality == AnncaConfiguration.MEDIA_QUALITY_MEDIUM) { + if (choices.size() == 2) result = minPictureSize; + else { + int mediumQualityIndex = choices.size() / 2; + result = choices.get(mediumQualityIndex); + } + } else if (mediaQuality == AnncaConfiguration.MEDIA_QUALITY_LOWEST) { + result = minPictureSize; + } + + return result; + } + + public static Size getPictureSize(Size[] sizes, @AnncaConfiguration.MediaQuality int mediaQuality) { + if (sizes == null || sizes.length == 0) return null; + + List choices = Arrays.asList(sizes); + + if (choices.size() == 1) return choices.get(0); + + Size result = null; + Size maxPictureSize = Collections.max(choices, new CompareSizesByArea2()); + Size minPictureSize = Collections.min(choices, new CompareSizesByArea2()); + + Collections.sort(choices, new CompareSizesByArea2()); + + if (mediaQuality == AnncaConfiguration.MEDIA_QUALITY_HIGHEST) { + result = maxPictureSize; + } else if (mediaQuality == AnncaConfiguration.MEDIA_QUALITY_LOW) { + if (choices.size() == 2) result = minPictureSize; + else { + int half = choices.size() / 2; + int lowQualityIndex = (choices.size() - half) / 2; + result = choices.get(lowQualityIndex + 1); + } + } else if (mediaQuality == AnncaConfiguration.MEDIA_QUALITY_HIGH) { + if (choices.size() == 2) result = maxPictureSize; + else { + int half = choices.size() / 2; + int highQualityIndex = (choices.size() - half) / 2; + result = choices.get(choices.size() - highQualityIndex - 1); + } + } else if (mediaQuality == AnncaConfiguration.MEDIA_QUALITY_MEDIUM) { + if (choices.size() == 2) result = minPictureSize; + else { + int mediumQualityIndex = choices.size() / 2; + result = choices.get(mediumQualityIndex); + } + } else if (mediaQuality == AnncaConfiguration.MEDIA_QUALITY_LOWEST) { + result = minPictureSize; + } + + return result; + } + + @SuppressWarnings("deprecation") + public static Size getSizeWithClosestRatio(List sizes, int width, int height) { + if (sizes == null) return null; + double MIN_TOLERANCE = 100; + double targetRatio = (double) height / width; + Size optimalSize = null; + double minDiff = Double.MAX_VALUE; + int targetHeight = height; + for (Size size : sizes) { + if (size.getWidth() == width && size.getHeight() == height) + return size; + + double ratio = (double) size.getHeight() / size.getWidth(); + + if (Math.abs(ratio - targetRatio) < MIN_TOLERANCE) MIN_TOLERANCE = ratio; + else continue; + + if (Math.abs(size.getHeight() - targetHeight) < minDiff) { + optimalSize = size; + minDiff = Math.abs(size.getHeight() - targetHeight); + } + } + + if (optimalSize == null) { + minDiff = Double.MAX_VALUE; + for (Size size : sizes) { + if (Math.abs(size.getHeight() - targetHeight) < minDiff) { + optimalSize = size; + minDiff = Math.abs(size.getHeight() - targetHeight); + } + } + } + return optimalSize; + } + + public static Size getOptimalPreviewSize(Size[] sizes, int width, int height) { + if (sizes == null) return null; + final double ASPECT_TOLERANCE = 0.1; + double targetRatio = (double) height / width; + Size optimalSize = null; + double minDiff = Double.MAX_VALUE; + int targetHeight = height; + for (Size size : sizes) { + double ratio = (double) size.getWidth() / size.getHeight(); + if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue; + if (Math.abs(size.getHeight() - targetHeight) < minDiff) { + optimalSize = size; + minDiff = Math.abs(size.getHeight() - targetHeight); + } + } + + if (optimalSize == null) { + minDiff = Double.MAX_VALUE; + for (Size size : sizes) { + if (Math.abs(size.getHeight() - targetHeight) < minDiff) { + optimalSize = size; + minDiff = Math.abs(size.getHeight() - targetHeight); + } + } + } + return optimalSize; + } + + public static Size getSizeWithClosestRatio(Size[] sizes, int width, int height) { + + if (sizes == null) return null; + + double MIN_TOLERANCE = 100; + double targetRatio = (double) height / width; + Size optimalSize = null; + double minDiff = Double.MAX_VALUE; + + int targetHeight = height; + + for (Size size : sizes) { +// if (size.getWidth() == width && size.getHeight() == height) +// return size; + + double ratio = (double) size.getHeight() / size.getWidth(); + + if (Math.abs(ratio - targetRatio) < MIN_TOLERANCE) MIN_TOLERANCE = ratio; + else continue; + + if (Math.abs(size.getHeight() - targetHeight) < minDiff) { + optimalSize = size; + minDiff = Math.abs(size.getHeight() - targetHeight); + } + } + + if (optimalSize == null) { + minDiff = Double.MAX_VALUE; + for (Size size : sizes) { + if (Math.abs(size.getHeight() - targetHeight) < minDiff) { + optimalSize = size; + minDiff = Math.abs(size.getHeight() - targetHeight); + } + } + } + return optimalSize; + } + + public static Size chooseOptimalSize(Size[] choices, int width, int height, Size aspectRatio) { + // Collect the supported resolutions that are at least as big as the preview Surface + List bigEnough = new ArrayList<>(); + int w = aspectRatio.getWidth(); + int h = aspectRatio.getHeight(); + for (Size option : choices) { + if (option.getHeight() == option.getWidth() * h / w && + option.getWidth() >= width && option.getHeight() >= height) { + bigEnough.add(option); + } + } + + // Pick the smallest of those, assuming we found any + if (!bigEnough.isEmpty()) { + return Collections.min(bigEnough, new CompareSizesByArea2()); + } else { + //test(TAG, "Couldn't find any suitable preview size"); + return null; + } + } + + private static double calculateApproximateVideoSize(CamcorderProfile camcorderProfile, int seconds) { + return ((camcorderProfile.videoBitRate / (float) 1 + camcorderProfile.audioBitRate / (float) 1) * seconds) / (float) 8; + } + + public static double calculateApproximateVideoDuration(CamcorderProfile camcorderProfile, long maxFileSize) { + return 8 * maxFileSize / (camcorderProfile.videoBitRate + camcorderProfile.audioBitRate); + } + + private static long calculateMinimumRequiredBitRate(CamcorderProfile camcorderProfile, long maxFileSize, int seconds) { + return 8 * maxFileSize / seconds - camcorderProfile.audioBitRate; + } + + public static CamcorderProfile getCamcorderProfile(String cameraId, long maximumFileSize, int minimumDurationInSeconds) { + if (TextUtils.isEmpty(cameraId)) { + return null; + } + int cameraIdInt = Integer.parseInt(cameraId); + return getCamcorderProfile(cameraIdInt, maximumFileSize, minimumDurationInSeconds); + } + + public static CamcorderProfile getCamcorderProfile(int currentCameraId, long maximumFileSize, int minimumDurationInSeconds) { + if (maximumFileSize <= 0) + return CamcorderProfile.get(currentCameraId, AnncaConfiguration.MEDIA_QUALITY_HIGHEST); + + int[] qualities = new int[]{AnncaConfiguration.MEDIA_QUALITY_HIGHEST, + AnncaConfiguration.MEDIA_QUALITY_HIGH, AnncaConfiguration.MEDIA_QUALITY_MEDIUM, + AnncaConfiguration.MEDIA_QUALITY_LOW, AnncaConfiguration.MEDIA_QUALITY_LOWEST}; + + CamcorderProfile camcorderProfile; + for (int i = 0; i < qualities.length; ++i) { + camcorderProfile = CameraHelper.getCamcorderProfile(qualities[i], currentCameraId); + double fileSize = CameraHelper.calculateApproximateVideoSize(camcorderProfile, minimumDurationInSeconds); + + if (fileSize > maximumFileSize) { + long minimumRequiredBitRate = calculateMinimumRequiredBitRate(camcorderProfile, maximumFileSize, minimumDurationInSeconds); + + if (minimumRequiredBitRate >= camcorderProfile.videoBitRate / 4 && minimumRequiredBitRate <= camcorderProfile.videoBitRate) { + camcorderProfile.videoBitRate = (int) minimumRequiredBitRate; + return camcorderProfile; + } + } else return camcorderProfile; + } + return CameraHelper.getCamcorderProfile(AnncaConfiguration.MEDIA_QUALITY_LOWEST, currentCameraId); + } + + public static CamcorderProfile getCamcorderProfile(@AnncaConfiguration.MediaQuality int mediaQuality, String cameraId) { + if (TextUtils.isEmpty(cameraId)) { + return null; + } + int cameraIdInt = Integer.parseInt(cameraId); + return getCamcorderProfile(mediaQuality, cameraIdInt); + } + + public static CamcorderProfile getCamcorderProfile(@AnncaConfiguration.MediaQuality int mediaQuality, int cameraId) { + if (mediaQuality == AnncaConfiguration.MEDIA_QUALITY_HIGHEST) { + return CamcorderProfile.get(cameraId, CamcorderProfile.QUALITY_HIGH); + } else if (mediaQuality == AnncaConfiguration.MEDIA_QUALITY_HIGH) { + if (CamcorderProfile.hasProfile(cameraId, CamcorderProfile.QUALITY_1080P)) { + return CamcorderProfile.get(cameraId, CamcorderProfile.QUALITY_1080P); + } else if (CamcorderProfile.hasProfile(cameraId, CamcorderProfile.QUALITY_720P)) { + return CamcorderProfile.get(cameraId, CamcorderProfile.QUALITY_720P); + } else { + return CamcorderProfile.get(cameraId, CamcorderProfile.QUALITY_HIGH); + } + } else if (mediaQuality == AnncaConfiguration.MEDIA_QUALITY_MEDIUM) { + if (CamcorderProfile.hasProfile(cameraId, CamcorderProfile.QUALITY_720P)) { + return CamcorderProfile.get(cameraId, CamcorderProfile.QUALITY_720P); + } else if (CamcorderProfile.hasProfile(cameraId, CamcorderProfile.QUALITY_480P)) { + return CamcorderProfile.get(cameraId, CamcorderProfile.QUALITY_480P); + } else { + return CamcorderProfile.get(cameraId, CamcorderProfile.QUALITY_LOW); + } + } else if (mediaQuality == AnncaConfiguration.MEDIA_QUALITY_LOW) { + if (CamcorderProfile.hasProfile(cameraId, CamcorderProfile.QUALITY_480P)) { + return CamcorderProfile.get(cameraId, CamcorderProfile.QUALITY_480P); + } else { + return CamcorderProfile.get(cameraId, CamcorderProfile.QUALITY_LOW); + } + } else if (mediaQuality == AnncaConfiguration.MEDIA_QUALITY_LOWEST) { + return CamcorderProfile.get(cameraId, CamcorderProfile.QUALITY_LOW); + } else { + return CamcorderProfile.get(cameraId, CamcorderProfile.QUALITY_HIGH); + } + } + + private static class CompareSizesByArea2 implements Comparator { + @Override + public int compare(Size lhs, Size rhs) { + // We cast here to ensure the multiplications won't overflow + return Long.signum((long) lhs.getWidth() * lhs.getHeight() - + (long) rhs.getWidth() * rhs.getHeight()); + } + + } +} diff --git a/annca/src/main/java/io/github/memfis19/annca/internal/utils/DateTimeUtils.java b/annca/src/main/java/io/github/memfis19/annca/internal/utils/DateTimeUtils.java new file mode 100644 index 0000000..5b2daf8 --- /dev/null +++ b/annca/src/main/java/io/github/memfis19/annca/internal/utils/DateTimeUtils.java @@ -0,0 +1,12 @@ +package io.github.memfis19.annca.internal.utils; + +/** + * Created by memfis on 6/27/16. + */ +public final class DateTimeUtils { + + public static final long SECOND = 1000; + public static final long MINUTE = 60 * SECOND; + public static final long HOUR = 60 * MINUTE; + public static final long DAY = 24 * HOUR; +} diff --git a/annca/src/main/java/io/github/memfis19/annca/internal/utils/ImageSaver.java b/annca/src/main/java/io/github/memfis19/annca/internal/utils/ImageSaver.java new file mode 100644 index 0000000..dd3dd98 --- /dev/null +++ b/annca/src/main/java/io/github/memfis19/annca/internal/utils/ImageSaver.java @@ -0,0 +1,62 @@ +package io.github.memfis19.annca.internal.utils; + +import android.annotation.TargetApi; +import android.media.Image; +import android.os.Build; +import android.util.Log; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.nio.ByteBuffer; + +/** + * Created by memfis on 7/6/16. + */ +public class ImageSaver implements Runnable { + + private final static String TAG = "ImageSaver"; + + private final Image image; + private final File file; + private ImageSaverCallback imageSaverCallback; + + public interface ImageSaverCallback { + void onSuccessFinish(); + + void onError(); + } + + public ImageSaver(Image image, File file, ImageSaverCallback imageSaverCallback) { + this.image = image; + this.file = file; + this.imageSaverCallback = imageSaverCallback; + } + + @TargetApi(Build.VERSION_CODES.KITKAT) + @Override + public void run() { + ByteBuffer buffer = image.getPlanes()[0].getBuffer(); + byte[] bytes = new byte[buffer.remaining()]; + buffer.get(bytes); + FileOutputStream output = null; + try { + output = new FileOutputStream(file); + output.write(bytes); + imageSaverCallback.onSuccessFinish(); + } catch (IOException ignore) { + //test(TAG, "Can't save_icon the image file."); + imageSaverCallback.onError(); + } finally { + image.close(); + if (null != output) { + try { + output.close(); + } catch (IOException e) { + //test(TAG, "Can't release image or close the output stream."); + } + } + } + } + +} diff --git a/annca/src/main/java/io/github/memfis19/annca/internal/utils/Size.java b/annca/src/main/java/io/github/memfis19/annca/internal/utils/Size.java new file mode 100644 index 0000000..72584cc --- /dev/null +++ b/annca/src/main/java/io/github/memfis19/annca/internal/utils/Size.java @@ -0,0 +1,104 @@ +package io.github.memfis19.annca.internal.utils; + +import android.annotation.TargetApi; +import android.hardware.Camera; +import android.os.Build; + +import java.util.ArrayList; +import java.util.List; + +/** + * Created by memfis on 12/1/16. + */ + +public class Size { + + private int width; + private int height; + + public Size() { + width = 0; + height = 0; + } + + public Size(int width, int height) { + this.width = width; + this.height = height; + } + + @TargetApi(Build.VERSION_CODES.LOLLIPOP) + public Size(android.util.Size size) { + this.width = size.getWidth(); + this.height = size.getHeight(); + } + + @SuppressWarnings("deprecation") + public Size(Camera.Size size) { + this.width = size.width; + this.height = size.height; + } + + public int getWidth() { + return width; + } + + public void setWidth(int width) { + this.width = width; + } + + public int getHeight() { + return height; + } + + public void setHeight(int height) { + this.height = height; + } + + @TargetApi(Build.VERSION_CODES.LOLLIPOP) + public static List fromList2(List sizes) { + if (sizes == null) return null; + List result = new ArrayList<>(sizes.size()); + + for (android.util.Size size : sizes) { + result.add(new Size(size)); + } + + return result; + } + + @SuppressWarnings("deprecation") + public static List fromList(List sizes) { + if (sizes == null) return null; + List result = new ArrayList<>(sizes.size()); + + for (Camera.Size size : sizes) { + result.add(new Size(size)); + } + + return result; + } + + @TargetApi(Build.VERSION_CODES.LOLLIPOP) + public static Size[] fromArray2(android.util.Size[] sizes) { + if (sizes == null) return null; + Size[] result = new Size[sizes.length]; + + for (int i = 0; i < sizes.length; ++i) { + result[i] = new Size(sizes[i]); + } + + return result; + } + + @SuppressWarnings("deprecation") + public static Size[] fromArray(Camera.Size[] sizes) { + if (sizes == null) return null; + Size[] result = new Size[sizes.length]; + + for (int i = 0; i < sizes.length; ++i) { + result[i] = new Size(sizes[i]); + } + + return result; + } +} diff --git a/annca/src/main/java/io/github/memfis19/annca/internal/utils/Utils.java b/annca/src/main/java/io/github/memfis19/annca/internal/utils/Utils.java new file mode 100644 index 0000000..cc7d21f --- /dev/null +++ b/annca/src/main/java/io/github/memfis19/annca/internal/utils/Utils.java @@ -0,0 +1,53 @@ +package io.github.memfis19.annca.internal.utils; + +import android.content.Context; +import android.content.res.Configuration; +import android.content.res.Resources; +import android.text.TextUtils; +import android.util.TypedValue; +import android.view.Surface; +import android.view.WindowManager; +import android.webkit.MimeTypeMap; + +/** + * Created by memfis on 7/18/16. + */ +public class Utils { + + public static int getDeviceDefaultOrientation(Context context) { + WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); + Configuration config = context.getResources().getConfiguration(); + + int rotation = windowManager.getDefaultDisplay().getRotation(); + + if (((rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_180) && + config.orientation == Configuration.ORIENTATION_LANDSCAPE) + || ((rotation == Surface.ROTATION_90 || rotation == Surface.ROTATION_270) && + config.orientation == Configuration.ORIENTATION_PORTRAIT)) { + return Configuration.ORIENTATION_LANDSCAPE; + } else { + return Configuration.ORIENTATION_PORTRAIT; + } + } + + public static String getMimeType(String url) { + String type = ""; + String extension = MimeTypeMap.getFileExtensionFromUrl(url); + if (!TextUtils.isEmpty(extension)) { + type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); + } else { + String reCheckExtension = MimeTypeMap.getFileExtensionFromUrl(url.replaceAll("\\s+", "")); + if (!TextUtils.isEmpty(reCheckExtension)) { + type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(reCheckExtension); + } + } + return type; + } + + public static int convertDipToPixels(Context context, int dip) { + Resources resources = context.getResources(); + float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip, resources.getDisplayMetrics()); + return (int) px; + } + +} diff --git a/annca/src/main/res/drawable-hdpi/ic_camera_front_white_24dp.png b/annca/src/main/res/drawable-hdpi/ic_camera_front_white_24dp.png new file mode 100644 index 0000000..f36dcd4 Binary files /dev/null and b/annca/src/main/res/drawable-hdpi/ic_camera_front_white_24dp.png differ diff --git a/annca/src/main/res/drawable-hdpi/ic_camera_rear_white_24dp.png b/annca/src/main/res/drawable-hdpi/ic_camera_rear_white_24dp.png new file mode 100644 index 0000000..4a5494f Binary files /dev/null and b/annca/src/main/res/drawable-hdpi/ic_camera_rear_white_24dp.png differ diff --git a/annca/src/main/res/drawable-hdpi/ic_clear_white_24dp.png b/annca/src/main/res/drawable-hdpi/ic_clear_white_24dp.png new file mode 100644 index 0000000..ceb1a1e Binary files /dev/null and b/annca/src/main/res/drawable-hdpi/ic_clear_white_24dp.png differ diff --git a/annca/src/main/res/drawable-hdpi/ic_content_cut_white_24dp.png b/annca/src/main/res/drawable-hdpi/ic_content_cut_white_24dp.png new file mode 100644 index 0000000..c32c747 Binary files /dev/null and b/annca/src/main/res/drawable-hdpi/ic_content_cut_white_24dp.png differ diff --git a/annca/src/main/res/drawable-hdpi/ic_crop_white_24dp.png b/annca/src/main/res/drawable-hdpi/ic_crop_white_24dp.png new file mode 100644 index 0000000..9bfca35 Binary files /dev/null and b/annca/src/main/res/drawable-hdpi/ic_crop_white_24dp.png differ diff --git a/annca/src/main/res/drawable-hdpi/ic_done_white_24dp.png b/annca/src/main/res/drawable-hdpi/ic_done_white_24dp.png new file mode 100644 index 0000000..c278b6c Binary files /dev/null and b/annca/src/main/res/drawable-hdpi/ic_done_white_24dp.png differ diff --git a/annca/src/main/res/drawable-hdpi/ic_flash_auto_white_24dp.png b/annca/src/main/res/drawable-hdpi/ic_flash_auto_white_24dp.png new file mode 100644 index 0000000..3eb32b2 Binary files /dev/null and b/annca/src/main/res/drawable-hdpi/ic_flash_auto_white_24dp.png differ diff --git a/annca/src/main/res/drawable-hdpi/ic_flash_off_white_24dp.png b/annca/src/main/res/drawable-hdpi/ic_flash_off_white_24dp.png new file mode 100644 index 0000000..948446b Binary files /dev/null and b/annca/src/main/res/drawable-hdpi/ic_flash_off_white_24dp.png differ diff --git a/annca/src/main/res/drawable-hdpi/ic_flash_on_white_24dp.png b/annca/src/main/res/drawable-hdpi/ic_flash_on_white_24dp.png new file mode 100644 index 0000000..4747a11 Binary files /dev/null and b/annca/src/main/res/drawable-hdpi/ic_flash_on_white_24dp.png differ diff --git a/annca/src/main/res/drawable-hdpi/ic_image_aspect_ratio_white_24dp.png b/annca/src/main/res/drawable-hdpi/ic_image_aspect_ratio_white_24dp.png new file mode 100644 index 0000000..35a566c Binary files /dev/null and b/annca/src/main/res/drawable-hdpi/ic_image_aspect_ratio_white_24dp.png differ diff --git a/annca/src/main/res/drawable-hdpi/ic_photo_camera_white_24dp.png b/annca/src/main/res/drawable-hdpi/ic_photo_camera_white_24dp.png new file mode 100644 index 0000000..497c88c Binary files /dev/null and b/annca/src/main/res/drawable-hdpi/ic_photo_camera_white_24dp.png differ diff --git a/annca/src/main/res/drawable-hdpi/ic_replay_white_24dp.png b/annca/src/main/res/drawable-hdpi/ic_replay_white_24dp.png new file mode 100644 index 0000000..5ef425a Binary files /dev/null and b/annca/src/main/res/drawable-hdpi/ic_replay_white_24dp.png differ diff --git a/annca/src/main/res/drawable-hdpi/ic_settings_white_24dp.png b/annca/src/main/res/drawable-hdpi/ic_settings_white_24dp.png new file mode 100644 index 0000000..97ded33 Binary files /dev/null and b/annca/src/main/res/drawable-hdpi/ic_settings_white_24dp.png differ diff --git a/annca/src/main/res/drawable-hdpi/ic_videocam_white_24dp.png b/annca/src/main/res/drawable-hdpi/ic_videocam_white_24dp.png new file mode 100644 index 0000000..d83e0d5 Binary files /dev/null and b/annca/src/main/res/drawable-hdpi/ic_videocam_white_24dp.png differ diff --git a/annca/src/main/res/drawable-hdpi/tile.9.png b/annca/src/main/res/drawable-hdpi/tile.9.png new file mode 100644 index 0000000..1358628 Binary files /dev/null and b/annca/src/main/res/drawable-hdpi/tile.9.png differ diff --git a/annca/src/main/res/drawable-mdpi/ic_camera_front_white_24dp.png b/annca/src/main/res/drawable-mdpi/ic_camera_front_white_24dp.png new file mode 100644 index 0000000..0392d64 Binary files /dev/null and b/annca/src/main/res/drawable-mdpi/ic_camera_front_white_24dp.png differ diff --git a/annca/src/main/res/drawable-mdpi/ic_camera_rear_white_24dp.png b/annca/src/main/res/drawable-mdpi/ic_camera_rear_white_24dp.png new file mode 100644 index 0000000..e1f0f1f Binary files /dev/null and b/annca/src/main/res/drawable-mdpi/ic_camera_rear_white_24dp.png differ diff --git a/annca/src/main/res/drawable-mdpi/ic_clear_white_24dp.png b/annca/src/main/res/drawable-mdpi/ic_clear_white_24dp.png new file mode 100644 index 0000000..af7f828 Binary files /dev/null and b/annca/src/main/res/drawable-mdpi/ic_clear_white_24dp.png differ diff --git a/annca/src/main/res/drawable-mdpi/ic_content_cut_white_24dp.png b/annca/src/main/res/drawable-mdpi/ic_content_cut_white_24dp.png new file mode 100644 index 0000000..7eab26f Binary files /dev/null and b/annca/src/main/res/drawable-mdpi/ic_content_cut_white_24dp.png differ diff --git a/annca/src/main/res/drawable-mdpi/ic_crop_white_24dp.png b/annca/src/main/res/drawable-mdpi/ic_crop_white_24dp.png new file mode 100644 index 0000000..8e78d8e Binary files /dev/null and b/annca/src/main/res/drawable-mdpi/ic_crop_white_24dp.png differ diff --git a/annca/src/main/res/drawable-mdpi/ic_done_white_24dp.png b/annca/src/main/res/drawable-mdpi/ic_done_white_24dp.png new file mode 100644 index 0000000..6d84e14 Binary files /dev/null and b/annca/src/main/res/drawable-mdpi/ic_done_white_24dp.png differ diff --git a/annca/src/main/res/drawable-mdpi/ic_flash_auto_white_24dp.png b/annca/src/main/res/drawable-mdpi/ic_flash_auto_white_24dp.png new file mode 100644 index 0000000..2f7bcc3 Binary files /dev/null and b/annca/src/main/res/drawable-mdpi/ic_flash_auto_white_24dp.png differ diff --git a/annca/src/main/res/drawable-mdpi/ic_flash_off_white_24dp.png b/annca/src/main/res/drawable-mdpi/ic_flash_off_white_24dp.png new file mode 100644 index 0000000..156df5e Binary files /dev/null and b/annca/src/main/res/drawable-mdpi/ic_flash_off_white_24dp.png differ diff --git a/annca/src/main/res/drawable-mdpi/ic_flash_on_white_24dp.png b/annca/src/main/res/drawable-mdpi/ic_flash_on_white_24dp.png new file mode 100644 index 0000000..9e57cde Binary files /dev/null and b/annca/src/main/res/drawable-mdpi/ic_flash_on_white_24dp.png differ diff --git a/annca/src/main/res/drawable-mdpi/ic_image_aspect_ratio_white_24dp.png b/annca/src/main/res/drawable-mdpi/ic_image_aspect_ratio_white_24dp.png new file mode 100644 index 0000000..13241cd Binary files /dev/null and b/annca/src/main/res/drawable-mdpi/ic_image_aspect_ratio_white_24dp.png differ diff --git a/annca/src/main/res/drawable-mdpi/ic_photo_camera_white_24dp.png b/annca/src/main/res/drawable-mdpi/ic_photo_camera_white_24dp.png new file mode 100644 index 0000000..e830522 Binary files /dev/null and b/annca/src/main/res/drawable-mdpi/ic_photo_camera_white_24dp.png differ diff --git a/annca/src/main/res/drawable-mdpi/ic_replay_white_24dp.png b/annca/src/main/res/drawable-mdpi/ic_replay_white_24dp.png new file mode 100644 index 0000000..5a79970 Binary files /dev/null and b/annca/src/main/res/drawable-mdpi/ic_replay_white_24dp.png differ diff --git a/annca/src/main/res/drawable-mdpi/ic_settings_white_24dp.png b/annca/src/main/res/drawable-mdpi/ic_settings_white_24dp.png new file mode 100644 index 0000000..8909c35 Binary files /dev/null and b/annca/src/main/res/drawable-mdpi/ic_settings_white_24dp.png differ diff --git a/annca/src/main/res/drawable-mdpi/ic_videocam_white_24dp.png b/annca/src/main/res/drawable-mdpi/ic_videocam_white_24dp.png new file mode 100644 index 0000000..d146209 Binary files /dev/null and b/annca/src/main/res/drawable-mdpi/ic_videocam_white_24dp.png differ diff --git a/annca/src/main/res/drawable-xhdpi/ic_camera_front_white_24dp.png b/annca/src/main/res/drawable-xhdpi/ic_camera_front_white_24dp.png new file mode 100644 index 0000000..a80ccde Binary files /dev/null and b/annca/src/main/res/drawable-xhdpi/ic_camera_front_white_24dp.png differ diff --git a/annca/src/main/res/drawable-xhdpi/ic_camera_rear_white_24dp.png b/annca/src/main/res/drawable-xhdpi/ic_camera_rear_white_24dp.png new file mode 100644 index 0000000..b0768e3 Binary files /dev/null and b/annca/src/main/res/drawable-xhdpi/ic_camera_rear_white_24dp.png differ diff --git a/annca/src/main/res/drawable-xhdpi/ic_clear_white_24dp.png b/annca/src/main/res/drawable-xhdpi/ic_clear_white_24dp.png new file mode 100644 index 0000000..b7c7ffd Binary files /dev/null and b/annca/src/main/res/drawable-xhdpi/ic_clear_white_24dp.png differ diff --git a/annca/src/main/res/drawable-xhdpi/ic_content_cut_white_24dp.png b/annca/src/main/res/drawable-xhdpi/ic_content_cut_white_24dp.png new file mode 100644 index 0000000..6ddf0b6 Binary files /dev/null and b/annca/src/main/res/drawable-xhdpi/ic_content_cut_white_24dp.png differ diff --git a/annca/src/main/res/drawable-xhdpi/ic_crop_white_24dp.png b/annca/src/main/res/drawable-xhdpi/ic_crop_white_24dp.png new file mode 100644 index 0000000..859cdf7 Binary files /dev/null and b/annca/src/main/res/drawable-xhdpi/ic_crop_white_24dp.png differ diff --git a/annca/src/main/res/drawable-xhdpi/ic_done_white_24dp.png b/annca/src/main/res/drawable-xhdpi/ic_done_white_24dp.png new file mode 100644 index 0000000..3b2b65d Binary files /dev/null and b/annca/src/main/res/drawable-xhdpi/ic_done_white_24dp.png differ diff --git a/annca/src/main/res/drawable-xhdpi/ic_flash_auto_white_24dp.png b/annca/src/main/res/drawable-xhdpi/ic_flash_auto_white_24dp.png new file mode 100644 index 0000000..185fa40 Binary files /dev/null and b/annca/src/main/res/drawable-xhdpi/ic_flash_auto_white_24dp.png differ diff --git a/annca/src/main/res/drawable-xhdpi/ic_flash_off_white_24dp.png b/annca/src/main/res/drawable-xhdpi/ic_flash_off_white_24dp.png new file mode 100644 index 0000000..23c854e Binary files /dev/null and b/annca/src/main/res/drawable-xhdpi/ic_flash_off_white_24dp.png differ diff --git a/annca/src/main/res/drawable-xhdpi/ic_flash_on_white_24dp.png b/annca/src/main/res/drawable-xhdpi/ic_flash_on_white_24dp.png new file mode 100644 index 0000000..bedc4eb Binary files /dev/null and b/annca/src/main/res/drawable-xhdpi/ic_flash_on_white_24dp.png differ diff --git a/annca/src/main/res/drawable-xhdpi/ic_image_aspect_ratio_white_24dp.png b/annca/src/main/res/drawable-xhdpi/ic_image_aspect_ratio_white_24dp.png new file mode 100644 index 0000000..e22ef2a Binary files /dev/null and b/annca/src/main/res/drawable-xhdpi/ic_image_aspect_ratio_white_24dp.png differ diff --git a/annca/src/main/res/drawable-xhdpi/ic_photo_camera_white_24dp.png b/annca/src/main/res/drawable-xhdpi/ic_photo_camera_white_24dp.png new file mode 100644 index 0000000..be9fb22 Binary files /dev/null and b/annca/src/main/res/drawable-xhdpi/ic_photo_camera_white_24dp.png differ diff --git a/annca/src/main/res/drawable-xhdpi/ic_replay_white_24dp.png b/annca/src/main/res/drawable-xhdpi/ic_replay_white_24dp.png new file mode 100644 index 0000000..3b41913 Binary files /dev/null and b/annca/src/main/res/drawable-xhdpi/ic_replay_white_24dp.png differ diff --git a/annca/src/main/res/drawable-xhdpi/ic_settings_white_24dp.png b/annca/src/main/res/drawable-xhdpi/ic_settings_white_24dp.png new file mode 100644 index 0000000..5caedc8 Binary files /dev/null and b/annca/src/main/res/drawable-xhdpi/ic_settings_white_24dp.png differ diff --git a/annca/src/main/res/drawable-xhdpi/ic_videocam_white_24dp.png b/annca/src/main/res/drawable-xhdpi/ic_videocam_white_24dp.png new file mode 100644 index 0000000..1b2583d Binary files /dev/null and b/annca/src/main/res/drawable-xhdpi/ic_videocam_white_24dp.png differ diff --git a/annca/src/main/res/drawable-xxhdpi/ic_camera_front_white_24dp.png b/annca/src/main/res/drawable-xxhdpi/ic_camera_front_white_24dp.png new file mode 100644 index 0000000..3eb24d1 Binary files /dev/null and b/annca/src/main/res/drawable-xxhdpi/ic_camera_front_white_24dp.png differ diff --git a/annca/src/main/res/drawable-xxhdpi/ic_camera_rear_white_24dp.png b/annca/src/main/res/drawable-xxhdpi/ic_camera_rear_white_24dp.png new file mode 100644 index 0000000..8392b2a Binary files /dev/null and b/annca/src/main/res/drawable-xxhdpi/ic_camera_rear_white_24dp.png differ diff --git a/annca/src/main/res/drawable-xxhdpi/ic_clear_white_24dp.png b/annca/src/main/res/drawable-xxhdpi/ic_clear_white_24dp.png new file mode 100644 index 0000000..6b717e0 Binary files /dev/null and b/annca/src/main/res/drawable-xxhdpi/ic_clear_white_24dp.png differ diff --git a/annca/src/main/res/drawable-xxhdpi/ic_content_cut_white_24dp.png b/annca/src/main/res/drawable-xxhdpi/ic_content_cut_white_24dp.png new file mode 100644 index 0000000..006a5e2 Binary files /dev/null and b/annca/src/main/res/drawable-xxhdpi/ic_content_cut_white_24dp.png differ diff --git a/annca/src/main/res/drawable-xxhdpi/ic_crop_white_24dp.png b/annca/src/main/res/drawable-xxhdpi/ic_crop_white_24dp.png new file mode 100644 index 0000000..c0246cf Binary files /dev/null and b/annca/src/main/res/drawable-xxhdpi/ic_crop_white_24dp.png differ diff --git a/annca/src/main/res/drawable-xxhdpi/ic_done_white_24dp.png b/annca/src/main/res/drawable-xxhdpi/ic_done_white_24dp.png new file mode 100644 index 0000000..0ebb555 Binary files /dev/null and b/annca/src/main/res/drawable-xxhdpi/ic_done_white_24dp.png differ diff --git a/annca/src/main/res/drawable-xxhdpi/ic_flash_auto_white_24dp.png b/annca/src/main/res/drawable-xxhdpi/ic_flash_auto_white_24dp.png new file mode 100644 index 0000000..087aa59 Binary files /dev/null and b/annca/src/main/res/drawable-xxhdpi/ic_flash_auto_white_24dp.png differ diff --git a/annca/src/main/res/drawable-xxhdpi/ic_flash_off_white_24dp.png b/annca/src/main/res/drawable-xxhdpi/ic_flash_off_white_24dp.png new file mode 100644 index 0000000..3cf30f3 Binary files /dev/null and b/annca/src/main/res/drawable-xxhdpi/ic_flash_off_white_24dp.png differ diff --git a/annca/src/main/res/drawable-xxhdpi/ic_flash_on_white_24dp.png b/annca/src/main/res/drawable-xxhdpi/ic_flash_on_white_24dp.png new file mode 100644 index 0000000..4e116af Binary files /dev/null and b/annca/src/main/res/drawable-xxhdpi/ic_flash_on_white_24dp.png differ diff --git a/annca/src/main/res/drawable-xxhdpi/ic_image_aspect_ratio_white_24dp.png b/annca/src/main/res/drawable-xxhdpi/ic_image_aspect_ratio_white_24dp.png new file mode 100644 index 0000000..b136fb2 Binary files /dev/null and b/annca/src/main/res/drawable-xxhdpi/ic_image_aspect_ratio_white_24dp.png differ diff --git a/annca/src/main/res/drawable-xxhdpi/ic_photo_camera_white_24dp.png b/annca/src/main/res/drawable-xxhdpi/ic_photo_camera_white_24dp.png new file mode 100644 index 0000000..c8e69dc Binary files /dev/null and b/annca/src/main/res/drawable-xxhdpi/ic_photo_camera_white_24dp.png differ diff --git a/annca/src/main/res/drawable-xxhdpi/ic_replay_white_24dp.png b/annca/src/main/res/drawable-xxhdpi/ic_replay_white_24dp.png new file mode 100644 index 0000000..fcddcf0 Binary files /dev/null and b/annca/src/main/res/drawable-xxhdpi/ic_replay_white_24dp.png differ diff --git a/annca/src/main/res/drawable-xxhdpi/ic_settings_white_24dp.png b/annca/src/main/res/drawable-xxhdpi/ic_settings_white_24dp.png new file mode 100644 index 0000000..eabb0a2 Binary files /dev/null and b/annca/src/main/res/drawable-xxhdpi/ic_settings_white_24dp.png differ diff --git a/annca/src/main/res/drawable-xxhdpi/ic_videocam_white_24dp.png b/annca/src/main/res/drawable-xxhdpi/ic_videocam_white_24dp.png new file mode 100644 index 0000000..44c28e2 Binary files /dev/null and b/annca/src/main/res/drawable-xxhdpi/ic_videocam_white_24dp.png differ diff --git a/annca/src/main/res/drawable-xxxhdpi/ic_camera_front_white_24dp.png b/annca/src/main/res/drawable-xxxhdpi/ic_camera_front_white_24dp.png new file mode 100644 index 0000000..951bc12 Binary files /dev/null and b/annca/src/main/res/drawable-xxxhdpi/ic_camera_front_white_24dp.png differ diff --git a/annca/src/main/res/drawable-xxxhdpi/ic_camera_rear_white_24dp.png b/annca/src/main/res/drawable-xxxhdpi/ic_camera_rear_white_24dp.png new file mode 100644 index 0000000..8b2415b Binary files /dev/null and b/annca/src/main/res/drawable-xxxhdpi/ic_camera_rear_white_24dp.png differ diff --git a/annca/src/main/res/drawable-xxxhdpi/ic_clear_white_24dp.png b/annca/src/main/res/drawable-xxxhdpi/ic_clear_white_24dp.png new file mode 100644 index 0000000..3964192 Binary files /dev/null and b/annca/src/main/res/drawable-xxxhdpi/ic_clear_white_24dp.png differ diff --git a/annca/src/main/res/drawable-xxxhdpi/ic_content_cut_white_24dp.png b/annca/src/main/res/drawable-xxxhdpi/ic_content_cut_white_24dp.png new file mode 100644 index 0000000..06df922 Binary files /dev/null and b/annca/src/main/res/drawable-xxxhdpi/ic_content_cut_white_24dp.png differ diff --git a/annca/src/main/res/drawable-xxxhdpi/ic_crop_white_24dp.png b/annca/src/main/res/drawable-xxxhdpi/ic_crop_white_24dp.png new file mode 100644 index 0000000..3c027ef Binary files /dev/null and b/annca/src/main/res/drawable-xxxhdpi/ic_crop_white_24dp.png differ diff --git a/annca/src/main/res/drawable-xxxhdpi/ic_done_white_24dp.png b/annca/src/main/res/drawable-xxxhdpi/ic_done_white_24dp.png new file mode 100644 index 0000000..d670618 Binary files /dev/null and b/annca/src/main/res/drawable-xxxhdpi/ic_done_white_24dp.png differ diff --git a/annca/src/main/res/drawable-xxxhdpi/ic_flash_auto_white_24dp.png b/annca/src/main/res/drawable-xxxhdpi/ic_flash_auto_white_24dp.png new file mode 100644 index 0000000..899276f Binary files /dev/null and b/annca/src/main/res/drawable-xxxhdpi/ic_flash_auto_white_24dp.png differ diff --git a/annca/src/main/res/drawable-xxxhdpi/ic_flash_off_white_24dp.png b/annca/src/main/res/drawable-xxxhdpi/ic_flash_off_white_24dp.png new file mode 100644 index 0000000..1d774f2 Binary files /dev/null and b/annca/src/main/res/drawable-xxxhdpi/ic_flash_off_white_24dp.png differ diff --git a/annca/src/main/res/drawable-xxxhdpi/ic_flash_on_white_24dp.png b/annca/src/main/res/drawable-xxxhdpi/ic_flash_on_white_24dp.png new file mode 100644 index 0000000..cb60611 Binary files /dev/null and b/annca/src/main/res/drawable-xxxhdpi/ic_flash_on_white_24dp.png differ diff --git a/annca/src/main/res/drawable-xxxhdpi/ic_image_aspect_ratio_white_24dp.png b/annca/src/main/res/drawable-xxxhdpi/ic_image_aspect_ratio_white_24dp.png new file mode 100644 index 0000000..bd0863c Binary files /dev/null and b/annca/src/main/res/drawable-xxxhdpi/ic_image_aspect_ratio_white_24dp.png differ diff --git a/annca/src/main/res/drawable-xxxhdpi/ic_photo_camera_white_24dp.png b/annca/src/main/res/drawable-xxxhdpi/ic_photo_camera_white_24dp.png new file mode 100644 index 0000000..777658e Binary files /dev/null and b/annca/src/main/res/drawable-xxxhdpi/ic_photo_camera_white_24dp.png differ diff --git a/annca/src/main/res/drawable-xxxhdpi/ic_replay_white_24dp.png b/annca/src/main/res/drawable-xxxhdpi/ic_replay_white_24dp.png new file mode 100644 index 0000000..1573fb1 Binary files /dev/null and b/annca/src/main/res/drawable-xxxhdpi/ic_replay_white_24dp.png differ diff --git a/annca/src/main/res/drawable-xxxhdpi/ic_settings_white_24dp.png b/annca/src/main/res/drawable-xxxhdpi/ic_settings_white_24dp.png new file mode 100644 index 0000000..507c5ed Binary files /dev/null and b/annca/src/main/res/drawable-xxxhdpi/ic_settings_white_24dp.png differ diff --git a/annca/src/main/res/drawable-xxxhdpi/ic_videocam_white_24dp.png b/annca/src/main/res/drawable-xxxhdpi/ic_videocam_white_24dp.png new file mode 100644 index 0000000..ed20c07 Binary files /dev/null and b/annca/src/main/res/drawable-xxxhdpi/ic_videocam_white_24dp.png differ diff --git a/annca/src/main/res/drawable/circle_frame_background.xml b/annca/src/main/res/drawable/circle_frame_background.xml new file mode 100644 index 0000000..f1eaa1d --- /dev/null +++ b/annca/src/main/res/drawable/circle_frame_background.xml @@ -0,0 +1,5 @@ + + + + \ No newline at end of file diff --git a/annca/src/main/res/drawable/circle_frame_background_dark.xml b/annca/src/main/res/drawable/circle_frame_background_dark.xml new file mode 100644 index 0000000..1a2a2f1 --- /dev/null +++ b/annca/src/main/res/drawable/circle_frame_background_dark.xml @@ -0,0 +1,5 @@ + + + + \ No newline at end of file diff --git a/annca/src/main/res/drawable/start_video_record_button.xml b/annca/src/main/res/drawable/start_video_record_button.xml new file mode 100644 index 0000000..470f51f --- /dev/null +++ b/annca/src/main/res/drawable/start_video_record_button.xml @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/annca/src/main/res/drawable/stop_button_background.xml b/annca/src/main/res/drawable/stop_button_background.xml new file mode 100644 index 0000000..7ee9a6f --- /dev/null +++ b/annca/src/main/res/drawable/stop_button_background.xml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/annca/src/main/res/drawable/switch_camera_mode_selector.xml b/annca/src/main/res/drawable/switch_camera_mode_selector.xml new file mode 100644 index 0000000..2399709 --- /dev/null +++ b/annca/src/main/res/drawable/switch_camera_mode_selector.xml @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/annca/src/main/res/drawable/take_photo_button.xml b/annca/src/main/res/drawable/take_photo_button.xml new file mode 100644 index 0000000..9a0c8c2 --- /dev/null +++ b/annca/src/main/res/drawable/take_photo_button.xml @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/annca/src/main/res/layout/activity_preview.xml b/annca/src/main/res/layout/activity_preview.xml new file mode 100644 index 0000000..2fd1093 --- /dev/null +++ b/annca/src/main/res/layout/activity_preview.xml @@ -0,0 +1,68 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/annca/src/main/res/layout/camera_control_panel_layout.xml b/annca/src/main/res/layout/camera_control_panel_layout.xml new file mode 100644 index 0000000..702e162 --- /dev/null +++ b/annca/src/main/res/layout/camera_control_panel_layout.xml @@ -0,0 +1,108 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/annca/src/main/res/layout/generic_camera_layout.xml b/annca/src/main/res/layout/generic_camera_layout.xml new file mode 100644 index 0000000..5c2bfab --- /dev/null +++ b/annca/src/main/res/layout/generic_camera_layout.xml @@ -0,0 +1,19 @@ + + + + + + + + \ No newline at end of file diff --git a/annca/src/main/res/layout/user_control_layout.xml b/annca/src/main/res/layout/user_control_layout.xml new file mode 100644 index 0000000..d303b02 --- /dev/null +++ b/annca/src/main/res/layout/user_control_layout.xml @@ -0,0 +1,5 @@ + + \ No newline at end of file diff --git a/annca/src/main/res/values-da/strings.xml b/annca/src/main/res/values-da/strings.xml new file mode 100644 index 0000000..10056cc --- /dev/null +++ b/annca/src/main/res/values-da/strings.xml @@ -0,0 +1,16 @@ + + + Annuller + Ok + + Video størrelse %s + Billed størrelse + + + Færdig + Gentag + Fortryd + Beskær + Original + + \ No newline at end of file diff --git a/annca/src/main/res/values-sw600dp/configuration.xml b/annca/src/main/res/values-sw600dp/configuration.xml new file mode 100644 index 0000000..13d442e --- /dev/null +++ b/annca/src/main/res/values-sw600dp/configuration.xml @@ -0,0 +1,6 @@ + + + true + 0 + 0 + \ No newline at end of file diff --git a/annca/src/main/res/values/colors.xml b/annca/src/main/res/values/colors.xml new file mode 100644 index 0000000..e7d375b --- /dev/null +++ b/annca/src/main/res/values/colors.xml @@ -0,0 +1,6 @@ + + + #EEEEEE + #FFFFFF + #e21c22 + diff --git a/annca/src/main/res/values/configuration.xml b/annca/src/main/res/values/configuration.xml new file mode 100644 index 0000000..2b14221 --- /dev/null +++ b/annca/src/main/res/values/configuration.xml @@ -0,0 +1,6 @@ + + + false + 270 + 90 + \ No newline at end of file diff --git a/annca/src/main/res/values/strings.xml b/annca/src/main/res/values/strings.xml new file mode 100644 index 0000000..7d14c90 --- /dev/null +++ b/annca/src/main/res/values/strings.xml @@ -0,0 +1,30 @@ + + + Cancel + Ok + + Video size %s + Photo size + + + Save + Retake + Cancel + Crop + Original + + diff --git a/annca/src/main/res/values/styles.xml b/annca/src/main/res/values/styles.xml new file mode 100644 index 0000000..d95683a --- /dev/null +++ b/annca/src/main/res/values/styles.xml @@ -0,0 +1,14 @@ + + + + + diff --git a/app/.gitignore b/app/.gitignore new file mode 100644 index 0000000..aa724b7 --- /dev/null +++ b/app/.gitignore @@ -0,0 +1,15 @@ +*.iml +.gradle +/local.properties +/.idea/caches +/.idea/libraries +/.idea/modules.xml +/.idea/workspace.xml +/.idea/navEditor.xml +/.idea/assetWizardSettings.xml +.DS_Store +/build +/captures +.externalNativeBuild +.cxx +local.properties diff --git a/app/build.gradle b/app/build.gradle new file mode 100644 index 0000000..7f38c60 --- /dev/null +++ b/app/build.gradle @@ -0,0 +1,122 @@ +apply plugin: 'com.android.application' +apply plugin: 'com.google.gms.google-services' +apply plugin: 'com.google.firebase.crashlytics' +apply plugin: 'org.jetbrains.kotlin.android' + + +android { + namespace("com.cpm.lorealbaautomation") + compileSdk(35) + defaultConfig { + minSdkVersion 29 + applicationId "com.cpm.lorealbaautomation" + //noinspection OldTargetApi + targetSdk 34 + versionCode 20 + versionName "2.9" + multiDexEnabled true + useLibrary 'org.apache.http.legacy' + testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" + ndk { + abiFilters.add("armeabi-v7a") + abiFilters.add("arm64-v8a") + } + + } + signingConfigs { + config { + keyAlias 'hp' + keyPassword 'android' + storeFile file('D:\\jeevanp_cpm_projects\\keystore\\hp.dat') + storePassword 'android' + } + } + buildTypes { + release { + buildConfigField "boolean", "LOG_ENABLED", "true" + debuggable true + minifyEnabled true + shrinkResources true + signingConfig signingConfigs.config + proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' + firebaseCrashlytics { + mappingFileUploadEnabled false // or false if you want to disable + } + } + // 👇 Add this block to force override + + } + + android { + compileOptions { + sourceCompatibility JavaVersion.VERSION_17 + targetCompatibility JavaVersion.VERSION_17 + } + } + buildFeatures { + viewBinding true + } + buildFeatures { + buildConfig true + } + + configurations { + cleanedAnnotations + implementation.exclude group: 'org.jetbrains' , module:'annotations' + } +} +dependencies { + implementation fileTree(dir: 'libs', include: ['*.jar']) + //noinspection GradleDependency + implementation 'androidx.appcompat:appcompat:1.3.1' + //noinspection GradleDependency + implementation 'androidx.constraintlayout:constraintlayout:2.1.4' + implementation 'androidx.cardview:cardview:1.0.0' + //noinspection GradleDependency + implementation 'com.google.android.material:material:1.4.0' + implementation 'androidx.legacy:legacy-support-v4:1.0.0' + //noinspection GradleDependency + implementation 'androidx.recyclerview:recyclerview:1.2.1' + testImplementation 'junit:junit:4.13.2' + androidTestImplementation 'androidx.test.ext:junit:1.2.1' + androidTestImplementation 'androidx.test.espresso:espresso-core:3.6.1' + implementation 'org.jetbrains:annotations-java5:15.0' + implementation 'com.squareup.retrofit2:retrofit:2.9.0' + implementation 'com.squareup.retrofit:converter-gson:2.0.0-beta1' + implementation 'com.squareup.retrofit2:converter-gson:2.9.0' + implementation 'com.github.bumptech.glide:glide:4.16.0' + annotationProcessor 'com.github.bumptech.glide:compiler:4.15.1' + implementation 'de.hdodenhof:circleimageview:3.1.0' + implementation 'androidx.multidex:multidex:2.0.1' + implementation 'com.google.code.gson:gson:2.11.0' + // Import the BoM for the Firebase platform + implementation platform('com.google.firebase:firebase-bom:33.13.0') + // Declare the dependencies for the Crashlytics and Analytics libraries + // When using the BoM, you don't specify versions in Firebase library dependencies + implementation 'com.google.firebase:firebase-analytics' + implementation 'com.google.firebase:firebase-crashlytics-ndk' + implementation 'com.google.firebase:firebase-messaging' + implementation 'com.google.android.gms:play-services-maps:19.2.0' + implementation 'com.google.android.gms:play-services-location:21.3.0' + + implementation 'com.github.lecho:hellocharts-library:1.5.8@aar' + implementation project(path: ':annca') + implementation 'com.google.zxing:core:3.5.3' + ///new lib + implementation 'com.journeyapps:zxing-android-embedded:4.3.0' + implementation files('libs/hoinsdk.jar') + //noinspection GradleDependency + implementation 'com.squareup.picasso:picasso:2.5.2' + implementation project(':library') + implementation 'me.relex:circleindicator:1.2.2@aar' + implementation project(':pinview') + implementation 'com.github.delight-im:Android-AdvancedWebView:v3.0.0' + ////Gauges Graph Android + implementation 'com.github.Gruzer:simple-gauge-android:0.3.1' + implementation 'com.github.PhilJay:MPAndroidChart:v3.1.0' + implementation 'com.github.prolificinteractive:material-calendarview:2.0.0' + implementation 'com.jakewharton.threetenabp:threetenabp:1.4.4' + implementation files('libs/donutprogress-1.2.0.aar') +} + +apply plugin: 'com.google.gms.google-services' diff --git a/app/google-services.json b/app/google-services.json new file mode 100644 index 0000000..ceac768 --- /dev/null +++ b/app/google-services.json @@ -0,0 +1,5103 @@ +{ + "project_info": { + "project_number": "629309347341", + "firebase_url": "https://silicon-airlock-129611.firebaseio.com", + "project_id": "silicon-airlock-129611", + "storage_bucket": "silicon-airlock-129611.appspot.com" + }, + "client": [ + { + "client_info": { + "mobilesdk_app_id": "1:629309347341:android:b5ad1b8f3e588c3137a744", + "android_client_info": { + "package_name": "com.cpm.Abbott" + } + }, + "oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyB4uUMb8N-u4MhmY5ChEg-PDMgavWpqxeU" + }, + { + "current_key": "AIzaSyDorbLzXasW-n7sSc-5rGcx1-SKVGsru9c" + }, + { + "current_key": "AIzaSyDdJpvBFUO_osfPn3Yuj_vEG9VdjmEg0IY" + }, + { + "current_key": "AIzaSyDutR97NK5gRLdW839IpizIWj_fXrIUtNI" + }, + { + "current_key": "AIzaSyAIPnRocVJOWDTGWaQgVaSMU7FLRcbMHxk" + }, + { + "current_key": "AIzaSyAqNEuTX8MW9ySEbD-cmxg68dVho0n_3fU" + }, + { + "current_key": "AIzaSyDv_ajWs5TIdgiNwhcjnUSjpi-WveoeNFo" + }, + { + "current_key": "AIzaSyDT-fAaaa9bf3Bu4SAGyNqre_OSUQZ9YuE" + }, + { + "current_key": "AIzaSyDUxoSE0qe0emKM1MCUA4Y_EiittrWi_EM" + }, + { + "current_key": "AIzaSyAysaL8XPHO7STS3kOVGqM-0F0n3_09Sws" + }, + { + "current_key": "AIzaSyDadOjxdJsBIt-hDrEOG90kMDNxSG2RUzU" + }, + { + "current_key": "AIzaSyA-MIPQ2JhVqtewf3nx2MJHwIdniVzuoaI" + }, + { + "current_key": "AIzaSyAPlSHAPRYXJQSOjpw1dlvOaQaBOdLBJpg" + }, + { + "current_key": "AIzaSyBLWyW5ih6FlpRN0ec_62HVwMFcrLw6Tic" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + }, + { + "client_info": { + "mobilesdk_app_id": "1:629309347341:android:8697659bf52f66af37a744", + "android_client_info": { + "package_name": "com.cpm.Himalaya" + } + }, + "oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyB4uUMb8N-u4MhmY5ChEg-PDMgavWpqxeU" + }, + { + "current_key": "AIzaSyDorbLzXasW-n7sSc-5rGcx1-SKVGsru9c" + }, + { + "current_key": "AIzaSyDdJpvBFUO_osfPn3Yuj_vEG9VdjmEg0IY" + }, + { + "current_key": "AIzaSyDutR97NK5gRLdW839IpizIWj_fXrIUtNI" + }, + { + "current_key": "AIzaSyAIPnRocVJOWDTGWaQgVaSMU7FLRcbMHxk" + }, + { + "current_key": "AIzaSyAqNEuTX8MW9ySEbD-cmxg68dVho0n_3fU" + }, + { + "current_key": "AIzaSyDv_ajWs5TIdgiNwhcjnUSjpi-WveoeNFo" + }, + { + "current_key": "AIzaSyDT-fAaaa9bf3Bu4SAGyNqre_OSUQZ9YuE" + }, + { + "current_key": "AIzaSyDUxoSE0qe0emKM1MCUA4Y_EiittrWi_EM" + }, + { + "current_key": "AIzaSyAysaL8XPHO7STS3kOVGqM-0F0n3_09Sws" + }, + { + "current_key": "AIzaSyDadOjxdJsBIt-hDrEOG90kMDNxSG2RUzU" + }, + { + "current_key": "AIzaSyA-MIPQ2JhVqtewf3nx2MJHwIdniVzuoaI" + }, + { + "current_key": "AIzaSyAPlSHAPRYXJQSOjpw1dlvOaQaBOdLBJpg" + }, + { + "current_key": "AIzaSyBLWyW5ih6FlpRN0ec_62HVwMFcrLw6Tic" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + }, + { + "client_info": { + "mobilesdk_app_id": "1:629309347341:android:b801a5a8744343b037a744", + "android_client_info": { + "package_name": "com.cpm.InterGrow" + } + }, + "oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyB4uUMb8N-u4MhmY5ChEg-PDMgavWpqxeU" + }, + { + "current_key": "AIzaSyDorbLzXasW-n7sSc-5rGcx1-SKVGsru9c" + }, + { + "current_key": "AIzaSyDdJpvBFUO_osfPn3Yuj_vEG9VdjmEg0IY" + }, + { + "current_key": "AIzaSyDutR97NK5gRLdW839IpizIWj_fXrIUtNI" + }, + { + "current_key": "AIzaSyAIPnRocVJOWDTGWaQgVaSMU7FLRcbMHxk" + }, + { + "current_key": "AIzaSyAqNEuTX8MW9ySEbD-cmxg68dVho0n_3fU" + }, + { + "current_key": "AIzaSyDv_ajWs5TIdgiNwhcjnUSjpi-WveoeNFo" + }, + { + "current_key": "AIzaSyDT-fAaaa9bf3Bu4SAGyNqre_OSUQZ9YuE" + }, + { + "current_key": "AIzaSyDUxoSE0qe0emKM1MCUA4Y_EiittrWi_EM" + }, + { + "current_key": "AIzaSyAysaL8XPHO7STS3kOVGqM-0F0n3_09Sws" + }, + { + "current_key": "AIzaSyDadOjxdJsBIt-hDrEOG90kMDNxSG2RUzU" + }, + { + "current_key": "AIzaSyA-MIPQ2JhVqtewf3nx2MJHwIdniVzuoaI" + }, + { + "current_key": "AIzaSyAPlSHAPRYXJQSOjpw1dlvOaQaBOdLBJpg" + }, + { + "current_key": "AIzaSyBLWyW5ih6FlpRN0ec_62HVwMFcrLw6Tic" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + }, + { + "client_info": { + "mobilesdk_app_id": "1:629309347341:android:b6715dd38c9396f8", + "android_client_info": { + "package_name": "com.cpm.JuulMer" + } + }, + "oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyB4uUMb8N-u4MhmY5ChEg-PDMgavWpqxeU" + }, + { + "current_key": "AIzaSyDorbLzXasW-n7sSc-5rGcx1-SKVGsru9c" + }, + { + "current_key": "AIzaSyDdJpvBFUO_osfPn3Yuj_vEG9VdjmEg0IY" + }, + { + "current_key": "AIzaSyDutR97NK5gRLdW839IpizIWj_fXrIUtNI" + }, + { + "current_key": "AIzaSyAIPnRocVJOWDTGWaQgVaSMU7FLRcbMHxk" + }, + { + "current_key": "AIzaSyAqNEuTX8MW9ySEbD-cmxg68dVho0n_3fU" + }, + { + "current_key": "AIzaSyDv_ajWs5TIdgiNwhcjnUSjpi-WveoeNFo" + }, + { + "current_key": "AIzaSyDT-fAaaa9bf3Bu4SAGyNqre_OSUQZ9YuE" + }, + { + "current_key": "AIzaSyDUxoSE0qe0emKM1MCUA4Y_EiittrWi_EM" + }, + { + "current_key": "AIzaSyAysaL8XPHO7STS3kOVGqM-0F0n3_09Sws" + }, + { + "current_key": "AIzaSyDadOjxdJsBIt-hDrEOG90kMDNxSG2RUzU" + }, + { + "current_key": "AIzaSyA-MIPQ2JhVqtewf3nx2MJHwIdniVzuoaI" + }, + { + "current_key": "AIzaSyAPlSHAPRYXJQSOjpw1dlvOaQaBOdLBJpg" + }, + { + "current_key": "AIzaSyBLWyW5ih6FlpRN0ec_62HVwMFcrLw6Tic" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + }, + { + "client_info": { + "mobilesdk_app_id": "1:629309347341:android:dc58fe5f1c67e36937a744", + "android_client_info": { + "package_name": "com.cpm.KelloggsMT" + } + }, + "oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyB4uUMb8N-u4MhmY5ChEg-PDMgavWpqxeU" + }, + { + "current_key": "AIzaSyDorbLzXasW-n7sSc-5rGcx1-SKVGsru9c" + }, + { + "current_key": "AIzaSyDdJpvBFUO_osfPn3Yuj_vEG9VdjmEg0IY" + }, + { + "current_key": "AIzaSyDutR97NK5gRLdW839IpizIWj_fXrIUtNI" + }, + { + "current_key": "AIzaSyAIPnRocVJOWDTGWaQgVaSMU7FLRcbMHxk" + }, + { + "current_key": "AIzaSyAqNEuTX8MW9ySEbD-cmxg68dVho0n_3fU" + }, + { + "current_key": "AIzaSyDv_ajWs5TIdgiNwhcjnUSjpi-WveoeNFo" + }, + { + "current_key": "AIzaSyDT-fAaaa9bf3Bu4SAGyNqre_OSUQZ9YuE" + }, + { + "current_key": "AIzaSyDUxoSE0qe0emKM1MCUA4Y_EiittrWi_EM" + }, + { + "current_key": "AIzaSyAysaL8XPHO7STS3kOVGqM-0F0n3_09Sws" + }, + { + "current_key": "AIzaSyDadOjxdJsBIt-hDrEOG90kMDNxSG2RUzU" + }, + { + "current_key": "AIzaSyA-MIPQ2JhVqtewf3nx2MJHwIdniVzuoaI" + }, + { + "current_key": "AIzaSyAPlSHAPRYXJQSOjpw1dlvOaQaBOdLBJpg" + }, + { + "current_key": "AIzaSyBLWyW5ih6FlpRN0ec_62HVwMFcrLw6Tic" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + }, + { + "client_info": { + "mobilesdk_app_id": "1:629309347341:android:9e3bdc4182c156d737a744", + "android_client_info": { + "package_name": "com.cpm.KellogsMTSupervisor" + } + }, + "oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyB4uUMb8N-u4MhmY5ChEg-PDMgavWpqxeU" + }, + { + "current_key": "AIzaSyDorbLzXasW-n7sSc-5rGcx1-SKVGsru9c" + }, + { + "current_key": "AIzaSyDdJpvBFUO_osfPn3Yuj_vEG9VdjmEg0IY" + }, + { + "current_key": "AIzaSyDutR97NK5gRLdW839IpizIWj_fXrIUtNI" + }, + { + "current_key": "AIzaSyAIPnRocVJOWDTGWaQgVaSMU7FLRcbMHxk" + }, + { + "current_key": "AIzaSyAqNEuTX8MW9ySEbD-cmxg68dVho0n_3fU" + }, + { + "current_key": "AIzaSyDv_ajWs5TIdgiNwhcjnUSjpi-WveoeNFo" + }, + { + "current_key": "AIzaSyDT-fAaaa9bf3Bu4SAGyNqre_OSUQZ9YuE" + }, + { + "current_key": "AIzaSyDUxoSE0qe0emKM1MCUA4Y_EiittrWi_EM" + }, + { + "current_key": "AIzaSyAysaL8XPHO7STS3kOVGqM-0F0n3_09Sws" + }, + { + "current_key": "AIzaSyDadOjxdJsBIt-hDrEOG90kMDNxSG2RUzU" + }, + { + "current_key": "AIzaSyA-MIPQ2JhVqtewf3nx2MJHwIdniVzuoaI" + }, + { + "current_key": "AIzaSyAPlSHAPRYXJQSOjpw1dlvOaQaBOdLBJpg" + }, + { + "current_key": "AIzaSyBLWyW5ih6FlpRN0ec_62HVwMFcrLw6Tic" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + }, + { + "client_info": { + "mobilesdk_app_id": "1:629309347341:android:52eff943897b15fd", + "android_client_info": { + "package_name": "com.cpm.LorealGt" + } + }, + "oauth_client": [ + { + "client_id": "629309347341-uljbor88e9g2lju39i72lrmmu5c3f7s0.apps.googleusercontent.com", + "client_type": 1, + "android_info": { + "package_name": "com.cpm.LorealGt", + "certificate_hash": "95d49e939c2b2ac2229560df2ec290bccc0e9819" + } + }, + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyB4uUMb8N-u4MhmY5ChEg-PDMgavWpqxeU" + }, + { + "current_key": "AIzaSyDorbLzXasW-n7sSc-5rGcx1-SKVGsru9c" + }, + { + "current_key": "AIzaSyDdJpvBFUO_osfPn3Yuj_vEG9VdjmEg0IY" + }, + { + "current_key": "AIzaSyDutR97NK5gRLdW839IpizIWj_fXrIUtNI" + }, + { + "current_key": "AIzaSyAIPnRocVJOWDTGWaQgVaSMU7FLRcbMHxk" + }, + { + "current_key": "AIzaSyAqNEuTX8MW9ySEbD-cmxg68dVho0n_3fU" + }, + { + "current_key": "AIzaSyDv_ajWs5TIdgiNwhcjnUSjpi-WveoeNFo" + }, + { + "current_key": "AIzaSyDT-fAaaa9bf3Bu4SAGyNqre_OSUQZ9YuE" + }, + { + "current_key": "AIzaSyDUxoSE0qe0emKM1MCUA4Y_EiittrWi_EM" + }, + { + "current_key": "AIzaSyAysaL8XPHO7STS3kOVGqM-0F0n3_09Sws" + }, + { + "current_key": "AIzaSyDadOjxdJsBIt-hDrEOG90kMDNxSG2RUzU" + }, + { + "current_key": "AIzaSyA-MIPQ2JhVqtewf3nx2MJHwIdniVzuoaI" + }, + { + "current_key": "AIzaSyAPlSHAPRYXJQSOjpw1dlvOaQaBOdLBJpg" + }, + { + "current_key": "AIzaSyBLWyW5ih6FlpRN0ec_62HVwMFcrLw6Tic" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + }, + { + "client_info": { + "mobilesdk_app_id": "1:629309347341:android:874a6f0f9510fa7f", + "android_client_info": { + "package_name": "com.cpm.Marico" + } + }, + "oauth_client": [ + { + "client_id": "629309347341-9bl3oc6sgvc5h8u4s4j66u8df06rrusf.apps.googleusercontent.com", + "client_type": 1, + "android_info": { + "package_name": "com.cpm.Marico", + "certificate_hash": "a4f0e90c2dc8a9768444ce201463438047640327" + } + }, + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyB4uUMb8N-u4MhmY5ChEg-PDMgavWpqxeU" + }, + { + "current_key": "AIzaSyDorbLzXasW-n7sSc-5rGcx1-SKVGsru9c" + }, + { + "current_key": "AIzaSyDdJpvBFUO_osfPn3Yuj_vEG9VdjmEg0IY" + }, + { + "current_key": "AIzaSyDutR97NK5gRLdW839IpizIWj_fXrIUtNI" + }, + { + "current_key": "AIzaSyAIPnRocVJOWDTGWaQgVaSMU7FLRcbMHxk" + }, + { + "current_key": "AIzaSyAqNEuTX8MW9ySEbD-cmxg68dVho0n_3fU" + }, + { + "current_key": "AIzaSyDv_ajWs5TIdgiNwhcjnUSjpi-WveoeNFo" + }, + { + "current_key": "AIzaSyDT-fAaaa9bf3Bu4SAGyNqre_OSUQZ9YuE" + }, + { + "current_key": "AIzaSyDUxoSE0qe0emKM1MCUA4Y_EiittrWi_EM" + }, + { + "current_key": "AIzaSyAysaL8XPHO7STS3kOVGqM-0F0n3_09Sws" + }, + { + "current_key": "AIzaSyDadOjxdJsBIt-hDrEOG90kMDNxSG2RUzU" + }, + { + "current_key": "AIzaSyA-MIPQ2JhVqtewf3nx2MJHwIdniVzuoaI" + }, + { + "current_key": "AIzaSyAPlSHAPRYXJQSOjpw1dlvOaQaBOdLBJpg" + }, + { + "current_key": "AIzaSyBLWyW5ih6FlpRN0ec_62HVwMFcrLw6Tic" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + }, + { + "client_info": { + "mobilesdk_app_id": "1:629309347341:android:edff751afd3e164f", + "android_client_info": { + "package_name": "com.cpm.MaricoGT" + } + }, + "oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyB4uUMb8N-u4MhmY5ChEg-PDMgavWpqxeU" + }, + { + "current_key": "AIzaSyDorbLzXasW-n7sSc-5rGcx1-SKVGsru9c" + }, + { + "current_key": "AIzaSyDdJpvBFUO_osfPn3Yuj_vEG9VdjmEg0IY" + }, + { + "current_key": "AIzaSyDutR97NK5gRLdW839IpizIWj_fXrIUtNI" + }, + { + "current_key": "AIzaSyAIPnRocVJOWDTGWaQgVaSMU7FLRcbMHxk" + }, + { + "current_key": "AIzaSyAqNEuTX8MW9ySEbD-cmxg68dVho0n_3fU" + }, + { + "current_key": "AIzaSyDv_ajWs5TIdgiNwhcjnUSjpi-WveoeNFo" + }, + { + "current_key": "AIzaSyDT-fAaaa9bf3Bu4SAGyNqre_OSUQZ9YuE" + }, + { + "current_key": "AIzaSyDUxoSE0qe0emKM1MCUA4Y_EiittrWi_EM" + }, + { + "current_key": "AIzaSyAysaL8XPHO7STS3kOVGqM-0F0n3_09Sws" + }, + { + "current_key": "AIzaSyDadOjxdJsBIt-hDrEOG90kMDNxSG2RUzU" + }, + { + "current_key": "AIzaSyA-MIPQ2JhVqtewf3nx2MJHwIdniVzuoaI" + }, + { + "current_key": "AIzaSyAPlSHAPRYXJQSOjpw1dlvOaQaBOdLBJpg" + }, + { + "current_key": "AIzaSyBLWyW5ih6FlpRN0ec_62HVwMFcrLw6Tic" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + }, + { + "client_info": { + "mobilesdk_app_id": "1:629309347341:android:1e711b18da13822e", + "android_client_info": { + "package_name": "com.cpm.MaricoSupervisor" + } + }, + "oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyB4uUMb8N-u4MhmY5ChEg-PDMgavWpqxeU" + }, + { + "current_key": "AIzaSyDorbLzXasW-n7sSc-5rGcx1-SKVGsru9c" + }, + { + "current_key": "AIzaSyDdJpvBFUO_osfPn3Yuj_vEG9VdjmEg0IY" + }, + { + "current_key": "AIzaSyDutR97NK5gRLdW839IpizIWj_fXrIUtNI" + }, + { + "current_key": "AIzaSyAIPnRocVJOWDTGWaQgVaSMU7FLRcbMHxk" + }, + { + "current_key": "AIzaSyAqNEuTX8MW9ySEbD-cmxg68dVho0n_3fU" + }, + { + "current_key": "AIzaSyDv_ajWs5TIdgiNwhcjnUSjpi-WveoeNFo" + }, + { + "current_key": "AIzaSyDT-fAaaa9bf3Bu4SAGyNqre_OSUQZ9YuE" + }, + { + "current_key": "AIzaSyDUxoSE0qe0emKM1MCUA4Y_EiittrWi_EM" + }, + { + "current_key": "AIzaSyAysaL8XPHO7STS3kOVGqM-0F0n3_09Sws" + }, + { + "current_key": "AIzaSyDadOjxdJsBIt-hDrEOG90kMDNxSG2RUzU" + }, + { + "current_key": "AIzaSyA-MIPQ2JhVqtewf3nx2MJHwIdniVzuoaI" + }, + { + "current_key": "AIzaSyAPlSHAPRYXJQSOjpw1dlvOaQaBOdLBJpg" + }, + { + "current_key": "AIzaSyBLWyW5ih6FlpRN0ec_62HVwMFcrLw6Tic" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + }, + { + "client_info": { + "mobilesdk_app_id": "1:629309347341:android:b98b76c0c81a899437a744", + "android_client_info": { + "package_name": "com.cpm.Marico_so" + } + }, + "oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyB4uUMb8N-u4MhmY5ChEg-PDMgavWpqxeU" + }, + { + "current_key": "AIzaSyDorbLzXasW-n7sSc-5rGcx1-SKVGsru9c" + }, + { + "current_key": "AIzaSyDdJpvBFUO_osfPn3Yuj_vEG9VdjmEg0IY" + }, + { + "current_key": "AIzaSyDutR97NK5gRLdW839IpizIWj_fXrIUtNI" + }, + { + "current_key": "AIzaSyAIPnRocVJOWDTGWaQgVaSMU7FLRcbMHxk" + }, + { + "current_key": "AIzaSyAqNEuTX8MW9ySEbD-cmxg68dVho0n_3fU" + }, + { + "current_key": "AIzaSyDv_ajWs5TIdgiNwhcjnUSjpi-WveoeNFo" + }, + { + "current_key": "AIzaSyDT-fAaaa9bf3Bu4SAGyNqre_OSUQZ9YuE" + }, + { + "current_key": "AIzaSyDUxoSE0qe0emKM1MCUA4Y_EiittrWi_EM" + }, + { + "current_key": "AIzaSyAysaL8XPHO7STS3kOVGqM-0F0n3_09Sws" + }, + { + "current_key": "AIzaSyDadOjxdJsBIt-hDrEOG90kMDNxSG2RUzU" + }, + { + "current_key": "AIzaSyA-MIPQ2JhVqtewf3nx2MJHwIdniVzuoaI" + }, + { + "current_key": "AIzaSyAPlSHAPRYXJQSOjpw1dlvOaQaBOdLBJpg" + }, + { + "current_key": "AIzaSyBLWyW5ih6FlpRN0ec_62HVwMFcrLw6Tic" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + }, + { + "client_info": { + "mobilesdk_app_id": "1:629309347341:android:e7df3b06fd53917937a744", + "android_client_info": { + "package_name": "com.cpm.McCormick" + } + }, + "oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyB4uUMb8N-u4MhmY5ChEg-PDMgavWpqxeU" + }, + { + "current_key": "AIzaSyDorbLzXasW-n7sSc-5rGcx1-SKVGsru9c" + }, + { + "current_key": "AIzaSyDdJpvBFUO_osfPn3Yuj_vEG9VdjmEg0IY" + }, + { + "current_key": "AIzaSyDutR97NK5gRLdW839IpizIWj_fXrIUtNI" + }, + { + "current_key": "AIzaSyAIPnRocVJOWDTGWaQgVaSMU7FLRcbMHxk" + }, + { + "current_key": "AIzaSyAqNEuTX8MW9ySEbD-cmxg68dVho0n_3fU" + }, + { + "current_key": "AIzaSyDv_ajWs5TIdgiNwhcjnUSjpi-WveoeNFo" + }, + { + "current_key": "AIzaSyDT-fAaaa9bf3Bu4SAGyNqre_OSUQZ9YuE" + }, + { + "current_key": "AIzaSyDUxoSE0qe0emKM1MCUA4Y_EiittrWi_EM" + }, + { + "current_key": "AIzaSyAysaL8XPHO7STS3kOVGqM-0F0n3_09Sws" + }, + { + "current_key": "AIzaSyDadOjxdJsBIt-hDrEOG90kMDNxSG2RUzU" + }, + { + "current_key": "AIzaSyA-MIPQ2JhVqtewf3nx2MJHwIdniVzuoaI" + }, + { + "current_key": "AIzaSyAPlSHAPRYXJQSOjpw1dlvOaQaBOdLBJpg" + }, + { + "current_key": "AIzaSyBLWyW5ih6FlpRN0ec_62HVwMFcrLw6Tic" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + }, + { + "client_info": { + "mobilesdk_app_id": "1:629309347341:android:3c3da52ca4ed888b37a744", + "android_client_info": { + "package_name": "com.cpm.MccormickSupervisor" + } + }, + "oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyB4uUMb8N-u4MhmY5ChEg-PDMgavWpqxeU" + }, + { + "current_key": "AIzaSyDorbLzXasW-n7sSc-5rGcx1-SKVGsru9c" + }, + { + "current_key": "AIzaSyDdJpvBFUO_osfPn3Yuj_vEG9VdjmEg0IY" + }, + { + "current_key": "AIzaSyDutR97NK5gRLdW839IpizIWj_fXrIUtNI" + }, + { + "current_key": "AIzaSyAIPnRocVJOWDTGWaQgVaSMU7FLRcbMHxk" + }, + { + "current_key": "AIzaSyAqNEuTX8MW9ySEbD-cmxg68dVho0n_3fU" + }, + { + "current_key": "AIzaSyDv_ajWs5TIdgiNwhcjnUSjpi-WveoeNFo" + }, + { + "current_key": "AIzaSyDT-fAaaa9bf3Bu4SAGyNqre_OSUQZ9YuE" + }, + { + "current_key": "AIzaSyDUxoSE0qe0emKM1MCUA4Y_EiittrWi_EM" + }, + { + "current_key": "AIzaSyAysaL8XPHO7STS3kOVGqM-0F0n3_09Sws" + }, + { + "current_key": "AIzaSyDadOjxdJsBIt-hDrEOG90kMDNxSG2RUzU" + }, + { + "current_key": "AIzaSyA-MIPQ2JhVqtewf3nx2MJHwIdniVzuoaI" + }, + { + "current_key": "AIzaSyAPlSHAPRYXJQSOjpw1dlvOaQaBOdLBJpg" + }, + { + "current_key": "AIzaSyBLWyW5ih6FlpRN0ec_62HVwMFcrLw6Tic" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + }, + { + "client_info": { + "mobilesdk_app_id": "1:629309347341:android:e9fda6cf5d947a9337a744", + "android_client_info": { + "package_name": "com.cpm.Perfetti" + } + }, + "oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyB4uUMb8N-u4MhmY5ChEg-PDMgavWpqxeU" + }, + { + "current_key": "AIzaSyDorbLzXasW-n7sSc-5rGcx1-SKVGsru9c" + }, + { + "current_key": "AIzaSyDdJpvBFUO_osfPn3Yuj_vEG9VdjmEg0IY" + }, + { + "current_key": "AIzaSyDutR97NK5gRLdW839IpizIWj_fXrIUtNI" + }, + { + "current_key": "AIzaSyAIPnRocVJOWDTGWaQgVaSMU7FLRcbMHxk" + }, + { + "current_key": "AIzaSyAqNEuTX8MW9ySEbD-cmxg68dVho0n_3fU" + }, + { + "current_key": "AIzaSyDv_ajWs5TIdgiNwhcjnUSjpi-WveoeNFo" + }, + { + "current_key": "AIzaSyDT-fAaaa9bf3Bu4SAGyNqre_OSUQZ9YuE" + }, + { + "current_key": "AIzaSyDUxoSE0qe0emKM1MCUA4Y_EiittrWi_EM" + }, + { + "current_key": "AIzaSyAysaL8XPHO7STS3kOVGqM-0F0n3_09Sws" + }, + { + "current_key": "AIzaSyDadOjxdJsBIt-hDrEOG90kMDNxSG2RUzU" + }, + { + "current_key": "AIzaSyA-MIPQ2JhVqtewf3nx2MJHwIdniVzuoaI" + }, + { + "current_key": "AIzaSyAPlSHAPRYXJQSOjpw1dlvOaQaBOdLBJpg" + }, + { + "current_key": "AIzaSyBLWyW5ih6FlpRN0ec_62HVwMFcrLw6Tic" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + }, + { + "client_info": { + "mobilesdk_app_id": "1:629309347341:android:170999901e5b948e37a744", + "android_client_info": { + "package_name": "com.cpm.Prayagh" + } + }, + "oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyB4uUMb8N-u4MhmY5ChEg-PDMgavWpqxeU" + }, + { + "current_key": "AIzaSyDorbLzXasW-n7sSc-5rGcx1-SKVGsru9c" + }, + { + "current_key": "AIzaSyDdJpvBFUO_osfPn3Yuj_vEG9VdjmEg0IY" + }, + { + "current_key": "AIzaSyDutR97NK5gRLdW839IpizIWj_fXrIUtNI" + }, + { + "current_key": "AIzaSyAIPnRocVJOWDTGWaQgVaSMU7FLRcbMHxk" + }, + { + "current_key": "AIzaSyAqNEuTX8MW9ySEbD-cmxg68dVho0n_3fU" + }, + { + "current_key": "AIzaSyDv_ajWs5TIdgiNwhcjnUSjpi-WveoeNFo" + }, + { + "current_key": "AIzaSyDT-fAaaa9bf3Bu4SAGyNqre_OSUQZ9YuE" + }, + { + "current_key": "AIzaSyDUxoSE0qe0emKM1MCUA4Y_EiittrWi_EM" + }, + { + "current_key": "AIzaSyAysaL8XPHO7STS3kOVGqM-0F0n3_09Sws" + }, + { + "current_key": "AIzaSyDadOjxdJsBIt-hDrEOG90kMDNxSG2RUzU" + }, + { + "current_key": "AIzaSyA-MIPQ2JhVqtewf3nx2MJHwIdniVzuoaI" + }, + { + "current_key": "AIzaSyAPlSHAPRYXJQSOjpw1dlvOaQaBOdLBJpg" + }, + { + "current_key": "AIzaSyBLWyW5ih6FlpRN0ec_62HVwMFcrLw6Tic" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + }, + { + "client_info": { + "mobilesdk_app_id": "1:629309347341:android:9fe997995479a4b837a744", + "android_client_info": { + "package_name": "com.cpm.RBGTHealthSupervisor" + } + }, + "oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyB4uUMb8N-u4MhmY5ChEg-PDMgavWpqxeU" + }, + { + "current_key": "AIzaSyDorbLzXasW-n7sSc-5rGcx1-SKVGsru9c" + }, + { + "current_key": "AIzaSyDdJpvBFUO_osfPn3Yuj_vEG9VdjmEg0IY" + }, + { + "current_key": "AIzaSyDutR97NK5gRLdW839IpizIWj_fXrIUtNI" + }, + { + "current_key": "AIzaSyAIPnRocVJOWDTGWaQgVaSMU7FLRcbMHxk" + }, + { + "current_key": "AIzaSyAqNEuTX8MW9ySEbD-cmxg68dVho0n_3fU" + }, + { + "current_key": "AIzaSyDv_ajWs5TIdgiNwhcjnUSjpi-WveoeNFo" + }, + { + "current_key": "AIzaSyDT-fAaaa9bf3Bu4SAGyNqre_OSUQZ9YuE" + }, + { + "current_key": "AIzaSyDUxoSE0qe0emKM1MCUA4Y_EiittrWi_EM" + }, + { + "current_key": "AIzaSyAysaL8XPHO7STS3kOVGqM-0F0n3_09Sws" + }, + { + "current_key": "AIzaSyDadOjxdJsBIt-hDrEOG90kMDNxSG2RUzU" + }, + { + "current_key": "AIzaSyA-MIPQ2JhVqtewf3nx2MJHwIdniVzuoaI" + }, + { + "current_key": "AIzaSyAPlSHAPRYXJQSOjpw1dlvOaQaBOdLBJpg" + }, + { + "current_key": "AIzaSyBLWyW5ih6FlpRN0ec_62HVwMFcrLw6Tic" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + }, + { + "client_info": { + "mobilesdk_app_id": "1:629309347341:android:3d29e30a3f6593e2", + "android_client_info": { + "package_name": "com.cpm.Tcl" + } + }, + "oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyB4uUMb8N-u4MhmY5ChEg-PDMgavWpqxeU" + }, + { + "current_key": "AIzaSyDorbLzXasW-n7sSc-5rGcx1-SKVGsru9c" + }, + { + "current_key": "AIzaSyDdJpvBFUO_osfPn3Yuj_vEG9VdjmEg0IY" + }, + { + "current_key": "AIzaSyDutR97NK5gRLdW839IpizIWj_fXrIUtNI" + }, + { + "current_key": "AIzaSyAIPnRocVJOWDTGWaQgVaSMU7FLRcbMHxk" + }, + { + "current_key": "AIzaSyAqNEuTX8MW9ySEbD-cmxg68dVho0n_3fU" + }, + { + "current_key": "AIzaSyDv_ajWs5TIdgiNwhcjnUSjpi-WveoeNFo" + }, + { + "current_key": "AIzaSyDT-fAaaa9bf3Bu4SAGyNqre_OSUQZ9YuE" + }, + { + "current_key": "AIzaSyDUxoSE0qe0emKM1MCUA4Y_EiittrWi_EM" + }, + { + "current_key": "AIzaSyAysaL8XPHO7STS3kOVGqM-0F0n3_09Sws" + }, + { + "current_key": "AIzaSyDadOjxdJsBIt-hDrEOG90kMDNxSG2RUzU" + }, + { + "current_key": "AIzaSyA-MIPQ2JhVqtewf3nx2MJHwIdniVzuoaI" + }, + { + "current_key": "AIzaSyAPlSHAPRYXJQSOjpw1dlvOaQaBOdLBJpg" + }, + { + "current_key": "AIzaSyBLWyW5ih6FlpRN0ec_62HVwMFcrLw6Tic" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + }, + { + "client_info": { + "mobilesdk_app_id": "1:629309347341:android:faf02f88429f03e0", + "android_client_info": { + "package_name": "com.cpm.abbott" + } + }, + "oauth_client": [ + { + "client_id": "629309347341-28ojb3t1tmoh1q2log14avp1dj5e74mi.apps.googleusercontent.com", + "client_type": 1, + "android_info": { + "package_name": "com.cpm.abbott", + "certificate_hash": "f4469c047dfd3b33b1a34b8c38bd770cd43698e5" + } + }, + { + "client_id": "629309347341-hvjk4q7195vt8nh4uhhpsdt0acbkl2sf.apps.googleusercontent.com", + "client_type": 1, + "android_info": { + "package_name": "com.cpm.abbott", + "certificate_hash": "65b3e7895b38f52816092df3f55ba516ae1cf016" + } + }, + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyB4uUMb8N-u4MhmY5ChEg-PDMgavWpqxeU" + }, + { + "current_key": "AIzaSyDorbLzXasW-n7sSc-5rGcx1-SKVGsru9c" + }, + { + "current_key": "AIzaSyDdJpvBFUO_osfPn3Yuj_vEG9VdjmEg0IY" + }, + { + "current_key": "AIzaSyDutR97NK5gRLdW839IpizIWj_fXrIUtNI" + }, + { + "current_key": "AIzaSyAIPnRocVJOWDTGWaQgVaSMU7FLRcbMHxk" + }, + { + "current_key": "AIzaSyAqNEuTX8MW9ySEbD-cmxg68dVho0n_3fU" + }, + { + "current_key": "AIzaSyDv_ajWs5TIdgiNwhcjnUSjpi-WveoeNFo" + }, + { + "current_key": "AIzaSyDT-fAaaa9bf3Bu4SAGyNqre_OSUQZ9YuE" + }, + { + "current_key": "AIzaSyDUxoSE0qe0emKM1MCUA4Y_EiittrWi_EM" + }, + { + "current_key": "AIzaSyAysaL8XPHO7STS3kOVGqM-0F0n3_09Sws" + }, + { + "current_key": "AIzaSyDadOjxdJsBIt-hDrEOG90kMDNxSG2RUzU" + }, + { + "current_key": "AIzaSyA-MIPQ2JhVqtewf3nx2MJHwIdniVzuoaI" + }, + { + "current_key": "AIzaSyAPlSHAPRYXJQSOjpw1dlvOaQaBOdLBJpg" + }, + { + "current_key": "AIzaSyBLWyW5ih6FlpRN0ec_62HVwMFcrLw6Tic" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + }, + { + "client_info": { + "mobilesdk_app_id": "1:629309347341:android:c4b9a6fcd08a42a9", + "android_client_info": { + "package_name": "com.cpm.bira" + } + }, + "oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyB4uUMb8N-u4MhmY5ChEg-PDMgavWpqxeU" + }, + { + "current_key": "AIzaSyDorbLzXasW-n7sSc-5rGcx1-SKVGsru9c" + }, + { + "current_key": "AIzaSyDdJpvBFUO_osfPn3Yuj_vEG9VdjmEg0IY" + }, + { + "current_key": "AIzaSyDutR97NK5gRLdW839IpizIWj_fXrIUtNI" + }, + { + "current_key": "AIzaSyAIPnRocVJOWDTGWaQgVaSMU7FLRcbMHxk" + }, + { + "current_key": "AIzaSyAqNEuTX8MW9ySEbD-cmxg68dVho0n_3fU" + }, + { + "current_key": "AIzaSyDv_ajWs5TIdgiNwhcjnUSjpi-WveoeNFo" + }, + { + "current_key": "AIzaSyDT-fAaaa9bf3Bu4SAGyNqre_OSUQZ9YuE" + }, + { + "current_key": "AIzaSyDUxoSE0qe0emKM1MCUA4Y_EiittrWi_EM" + }, + { + "current_key": "AIzaSyAysaL8XPHO7STS3kOVGqM-0F0n3_09Sws" + }, + { + "current_key": "AIzaSyDadOjxdJsBIt-hDrEOG90kMDNxSG2RUzU" + }, + { + "current_key": "AIzaSyA-MIPQ2JhVqtewf3nx2MJHwIdniVzuoaI" + }, + { + "current_key": "AIzaSyAPlSHAPRYXJQSOjpw1dlvOaQaBOdLBJpg" + }, + { + "current_key": "AIzaSyBLWyW5ih6FlpRN0ec_62HVwMFcrLw6Tic" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + }, + { + "client_info": { + "mobilesdk_app_id": "1:629309347341:android:a27af603cc17cd15", + "android_client_info": { + "package_name": "com.cpm.exxon" + } + }, + "oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyB4uUMb8N-u4MhmY5ChEg-PDMgavWpqxeU" + }, + { + "current_key": "AIzaSyDorbLzXasW-n7sSc-5rGcx1-SKVGsru9c" + }, + { + "current_key": "AIzaSyDdJpvBFUO_osfPn3Yuj_vEG9VdjmEg0IY" + }, + { + "current_key": "AIzaSyDutR97NK5gRLdW839IpizIWj_fXrIUtNI" + }, + { + "current_key": "AIzaSyAIPnRocVJOWDTGWaQgVaSMU7FLRcbMHxk" + }, + { + "current_key": "AIzaSyAqNEuTX8MW9ySEbD-cmxg68dVho0n_3fU" + }, + { + "current_key": "AIzaSyDv_ajWs5TIdgiNwhcjnUSjpi-WveoeNFo" + }, + { + "current_key": "AIzaSyDT-fAaaa9bf3Bu4SAGyNqre_OSUQZ9YuE" + }, + { + "current_key": "AIzaSyDUxoSE0qe0emKM1MCUA4Y_EiittrWi_EM" + }, + { + "current_key": "AIzaSyAysaL8XPHO7STS3kOVGqM-0F0n3_09Sws" + }, + { + "current_key": "AIzaSyDadOjxdJsBIt-hDrEOG90kMDNxSG2RUzU" + }, + { + "current_key": "AIzaSyA-MIPQ2JhVqtewf3nx2MJHwIdniVzuoaI" + }, + { + "current_key": "AIzaSyAPlSHAPRYXJQSOjpw1dlvOaQaBOdLBJpg" + }, + { + "current_key": "AIzaSyBLWyW5ih6FlpRN0ec_62HVwMFcrLw6Tic" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + }, + { + "client_info": { + "mobilesdk_app_id": "1:629309347341:android:ea978225052d10fe", + "android_client_info": { + "package_name": "com.cpm.fcmmessaging" + } + }, + "oauth_client": [ + { + "client_id": "629309347341-bv92md45tdpneq9ejo2sjfai996g1a20.apps.googleusercontent.com", + "client_type": 1, + "android_info": { + "package_name": "com.cpm.fcmmessaging", + "certificate_hash": "f4469c047dfd3b33b1a34b8c38bd770cd43698e5" + } + }, + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyB4uUMb8N-u4MhmY5ChEg-PDMgavWpqxeU" + }, + { + "current_key": "AIzaSyDorbLzXasW-n7sSc-5rGcx1-SKVGsru9c" + }, + { + "current_key": "AIzaSyDdJpvBFUO_osfPn3Yuj_vEG9VdjmEg0IY" + }, + { + "current_key": "AIzaSyDutR97NK5gRLdW839IpizIWj_fXrIUtNI" + }, + { + "current_key": "AIzaSyAIPnRocVJOWDTGWaQgVaSMU7FLRcbMHxk" + }, + { + "current_key": "AIzaSyAqNEuTX8MW9ySEbD-cmxg68dVho0n_3fU" + }, + { + "current_key": "AIzaSyDv_ajWs5TIdgiNwhcjnUSjpi-WveoeNFo" + }, + { + "current_key": "AIzaSyDT-fAaaa9bf3Bu4SAGyNqre_OSUQZ9YuE" + }, + { + "current_key": "AIzaSyDUxoSE0qe0emKM1MCUA4Y_EiittrWi_EM" + }, + { + "current_key": "AIzaSyAysaL8XPHO7STS3kOVGqM-0F0n3_09Sws" + }, + { + "current_key": "AIzaSyDadOjxdJsBIt-hDrEOG90kMDNxSG2RUzU" + }, + { + "current_key": "AIzaSyA-MIPQ2JhVqtewf3nx2MJHwIdniVzuoaI" + }, + { + "current_key": "AIzaSyAPlSHAPRYXJQSOjpw1dlvOaQaBOdLBJpg" + }, + { + "current_key": "AIzaSyBLWyW5ih6FlpRN0ec_62HVwMFcrLw6Tic" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + }, + { + "client_info": { + "mobilesdk_app_id": "1:629309347341:android:cd10a9f2e7f4bc4e", + "android_client_info": { + "package_name": "com.cpm.godrejsupervisor" + } + }, + "oauth_client": [ + { + "client_id": "629309347341-s68halcdpnu55ujuehossolab2tqovh9.apps.googleusercontent.com", + "client_type": 1, + "android_info": { + "package_name": "com.cpm.godrejsupervisor", + "certificate_hash": "2c33c124346971cca5ed7da54ee42779822d5bfe" + } + }, + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyB4uUMb8N-u4MhmY5ChEg-PDMgavWpqxeU" + }, + { + "current_key": "AIzaSyDorbLzXasW-n7sSc-5rGcx1-SKVGsru9c" + }, + { + "current_key": "AIzaSyDdJpvBFUO_osfPn3Yuj_vEG9VdjmEg0IY" + }, + { + "current_key": "AIzaSyDutR97NK5gRLdW839IpizIWj_fXrIUtNI" + }, + { + "current_key": "AIzaSyAIPnRocVJOWDTGWaQgVaSMU7FLRcbMHxk" + }, + { + "current_key": "AIzaSyAqNEuTX8MW9ySEbD-cmxg68dVho0n_3fU" + }, + { + "current_key": "AIzaSyDv_ajWs5TIdgiNwhcjnUSjpi-WveoeNFo" + }, + { + "current_key": "AIzaSyDT-fAaaa9bf3Bu4SAGyNqre_OSUQZ9YuE" + }, + { + "current_key": "AIzaSyDUxoSE0qe0emKM1MCUA4Y_EiittrWi_EM" + }, + { + "current_key": "AIzaSyAysaL8XPHO7STS3kOVGqM-0F0n3_09Sws" + }, + { + "current_key": "AIzaSyDadOjxdJsBIt-hDrEOG90kMDNxSG2RUzU" + }, + { + "current_key": "AIzaSyA-MIPQ2JhVqtewf3nx2MJHwIdniVzuoaI" + }, + { + "current_key": "AIzaSyAPlSHAPRYXJQSOjpw1dlvOaQaBOdLBJpg" + }, + { + "current_key": "AIzaSyBLWyW5ih6FlpRN0ec_62HVwMFcrLw6Tic" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + }, + { + "client_info": { + "mobilesdk_app_id": "1:629309347341:android:f6bd56d16568e38037a744", + "android_client_info": { + "package_name": "com.cpm.greenlamtactical" + } + }, + "oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyB4uUMb8N-u4MhmY5ChEg-PDMgavWpqxeU" + }, + { + "current_key": "AIzaSyDorbLzXasW-n7sSc-5rGcx1-SKVGsru9c" + }, + { + "current_key": "AIzaSyDdJpvBFUO_osfPn3Yuj_vEG9VdjmEg0IY" + }, + { + "current_key": "AIzaSyDutR97NK5gRLdW839IpizIWj_fXrIUtNI" + }, + { + "current_key": "AIzaSyAIPnRocVJOWDTGWaQgVaSMU7FLRcbMHxk" + }, + { + "current_key": "AIzaSyAqNEuTX8MW9ySEbD-cmxg68dVho0n_3fU" + }, + { + "current_key": "AIzaSyDv_ajWs5TIdgiNwhcjnUSjpi-WveoeNFo" + }, + { + "current_key": "AIzaSyDT-fAaaa9bf3Bu4SAGyNqre_OSUQZ9YuE" + }, + { + "current_key": "AIzaSyDUxoSE0qe0emKM1MCUA4Y_EiittrWi_EM" + }, + { + "current_key": "AIzaSyAysaL8XPHO7STS3kOVGqM-0F0n3_09Sws" + }, + { + "current_key": "AIzaSyDadOjxdJsBIt-hDrEOG90kMDNxSG2RUzU" + }, + { + "current_key": "AIzaSyA-MIPQ2JhVqtewf3nx2MJHwIdniVzuoaI" + }, + { + "current_key": "AIzaSyAPlSHAPRYXJQSOjpw1dlvOaQaBOdLBJpg" + }, + { + "current_key": "AIzaSyBLWyW5ih6FlpRN0ec_62HVwMFcrLw6Tic" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + }, + { + "client_info": { + "mobilesdk_app_id": "1:629309347341:android:5fd620facb4d4313", + "android_client_info": { + "package_name": "com.cpm.gskgtsupervisor" + } + }, + "oauth_client": [ + { + "client_id": "629309347341-otcbc8vgkg64eocv2749glurc2llglpa.apps.googleusercontent.com", + "client_type": 1, + "android_info": { + "package_name": "com.cpm.gskgtsupervisor", + "certificate_hash": "8875b411191ba9f692c6a30409c36cbb8e35e0b5" + } + }, + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyB4uUMb8N-u4MhmY5ChEg-PDMgavWpqxeU" + }, + { + "current_key": "AIzaSyDorbLzXasW-n7sSc-5rGcx1-SKVGsru9c" + }, + { + "current_key": "AIzaSyDdJpvBFUO_osfPn3Yuj_vEG9VdjmEg0IY" + }, + { + "current_key": "AIzaSyDutR97NK5gRLdW839IpizIWj_fXrIUtNI" + }, + { + "current_key": "AIzaSyAIPnRocVJOWDTGWaQgVaSMU7FLRcbMHxk" + }, + { + "current_key": "AIzaSyAqNEuTX8MW9ySEbD-cmxg68dVho0n_3fU" + }, + { + "current_key": "AIzaSyDv_ajWs5TIdgiNwhcjnUSjpi-WveoeNFo" + }, + { + "current_key": "AIzaSyDT-fAaaa9bf3Bu4SAGyNqre_OSUQZ9YuE" + }, + { + "current_key": "AIzaSyDUxoSE0qe0emKM1MCUA4Y_EiittrWi_EM" + }, + { + "current_key": "AIzaSyAysaL8XPHO7STS3kOVGqM-0F0n3_09Sws" + }, + { + "current_key": "AIzaSyDadOjxdJsBIt-hDrEOG90kMDNxSG2RUzU" + }, + { + "current_key": "AIzaSyA-MIPQ2JhVqtewf3nx2MJHwIdniVzuoaI" + }, + { + "current_key": "AIzaSyAPlSHAPRYXJQSOjpw1dlvOaQaBOdLBJpg" + }, + { + "current_key": "AIzaSyBLWyW5ih6FlpRN0ec_62HVwMFcrLw6Tic" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + }, + { + "client_info": { + "mobilesdk_app_id": "1:629309347341:android:668747f586c42392", + "android_client_info": { + "package_name": "com.cpm.gt_gsk1" + } + }, + "oauth_client": [ + { + "client_id": "629309347341-fml2r5aqpn0b6qbgavp7oksfgr3arejd.apps.googleusercontent.com", + "client_type": 1, + "android_info": { + "package_name": "com.cpm.gt_gsk1", + "certificate_hash": "95d49e939c2b2ac2229560df2ec290bccc0e9819" + } + }, + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyB4uUMb8N-u4MhmY5ChEg-PDMgavWpqxeU" + }, + { + "current_key": "AIzaSyDorbLzXasW-n7sSc-5rGcx1-SKVGsru9c" + }, + { + "current_key": "AIzaSyDdJpvBFUO_osfPn3Yuj_vEG9VdjmEg0IY" + }, + { + "current_key": "AIzaSyDutR97NK5gRLdW839IpizIWj_fXrIUtNI" + }, + { + "current_key": "AIzaSyAIPnRocVJOWDTGWaQgVaSMU7FLRcbMHxk" + }, + { + "current_key": "AIzaSyAqNEuTX8MW9ySEbD-cmxg68dVho0n_3fU" + }, + { + "current_key": "AIzaSyDv_ajWs5TIdgiNwhcjnUSjpi-WveoeNFo" + }, + { + "current_key": "AIzaSyDT-fAaaa9bf3Bu4SAGyNqre_OSUQZ9YuE" + }, + { + "current_key": "AIzaSyDUxoSE0qe0emKM1MCUA4Y_EiittrWi_EM" + }, + { + "current_key": "AIzaSyAysaL8XPHO7STS3kOVGqM-0F0n3_09Sws" + }, + { + "current_key": "AIzaSyDadOjxdJsBIt-hDrEOG90kMDNxSG2RUzU" + }, + { + "current_key": "AIzaSyA-MIPQ2JhVqtewf3nx2MJHwIdniVzuoaI" + }, + { + "current_key": "AIzaSyAPlSHAPRYXJQSOjpw1dlvOaQaBOdLBJpg" + }, + { + "current_key": "AIzaSyBLWyW5ih6FlpRN0ec_62HVwMFcrLw6Tic" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + }, + { + "client_info": { + "mobilesdk_app_id": "1:629309347341:android:446a75e73820b34a", + "android_client_info": { + "package_name": "com.cpm.haldiram" + } + }, + "oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyB4uUMb8N-u4MhmY5ChEg-PDMgavWpqxeU" + }, + { + "current_key": "AIzaSyDorbLzXasW-n7sSc-5rGcx1-SKVGsru9c" + }, + { + "current_key": "AIzaSyDdJpvBFUO_osfPn3Yuj_vEG9VdjmEg0IY" + }, + { + "current_key": "AIzaSyDutR97NK5gRLdW839IpizIWj_fXrIUtNI" + }, + { + "current_key": "AIzaSyAIPnRocVJOWDTGWaQgVaSMU7FLRcbMHxk" + }, + { + "current_key": "AIzaSyAqNEuTX8MW9ySEbD-cmxg68dVho0n_3fU" + }, + { + "current_key": "AIzaSyDv_ajWs5TIdgiNwhcjnUSjpi-WveoeNFo" + }, + { + "current_key": "AIzaSyDT-fAaaa9bf3Bu4SAGyNqre_OSUQZ9YuE" + }, + { + "current_key": "AIzaSyDUxoSE0qe0emKM1MCUA4Y_EiittrWi_EM" + }, + { + "current_key": "AIzaSyAysaL8XPHO7STS3kOVGqM-0F0n3_09Sws" + }, + { + "current_key": "AIzaSyDadOjxdJsBIt-hDrEOG90kMDNxSG2RUzU" + }, + { + "current_key": "AIzaSyA-MIPQ2JhVqtewf3nx2MJHwIdniVzuoaI" + }, + { + "current_key": "AIzaSyAPlSHAPRYXJQSOjpw1dlvOaQaBOdLBJpg" + }, + { + "current_key": "AIzaSyBLWyW5ih6FlpRN0ec_62HVwMFcrLw6Tic" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + }, + { + "client_info": { + "mobilesdk_app_id": "1:629309347341:android:47e6edaf642707a0", + "android_client_info": { + "package_name": "com.cpm.himalayaMTSupervisor" + } + }, + "oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyB4uUMb8N-u4MhmY5ChEg-PDMgavWpqxeU" + }, + { + "current_key": "AIzaSyDorbLzXasW-n7sSc-5rGcx1-SKVGsru9c" + }, + { + "current_key": "AIzaSyDdJpvBFUO_osfPn3Yuj_vEG9VdjmEg0IY" + }, + { + "current_key": "AIzaSyDutR97NK5gRLdW839IpizIWj_fXrIUtNI" + }, + { + "current_key": "AIzaSyAIPnRocVJOWDTGWaQgVaSMU7FLRcbMHxk" + }, + { + "current_key": "AIzaSyAqNEuTX8MW9ySEbD-cmxg68dVho0n_3fU" + }, + { + "current_key": "AIzaSyDv_ajWs5TIdgiNwhcjnUSjpi-WveoeNFo" + }, + { + "current_key": "AIzaSyDT-fAaaa9bf3Bu4SAGyNqre_OSUQZ9YuE" + }, + { + "current_key": "AIzaSyDUxoSE0qe0emKM1MCUA4Y_EiittrWi_EM" + }, + { + "current_key": "AIzaSyAysaL8XPHO7STS3kOVGqM-0F0n3_09Sws" + }, + { + "current_key": "AIzaSyDadOjxdJsBIt-hDrEOG90kMDNxSG2RUzU" + }, + { + "current_key": "AIzaSyA-MIPQ2JhVqtewf3nx2MJHwIdniVzuoaI" + }, + { + "current_key": "AIzaSyAPlSHAPRYXJQSOjpw1dlvOaQaBOdLBJpg" + }, + { + "current_key": "AIzaSyBLWyW5ih6FlpRN0ec_62HVwMFcrLw6Tic" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + }, + { + "client_info": { + "mobilesdk_app_id": "1:629309347341:android:fddea4bf858b1a7337a744", + "android_client_info": { + "package_name": "com.cpm.kelloggs" + } + }, + "oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyB4uUMb8N-u4MhmY5ChEg-PDMgavWpqxeU" + }, + { + "current_key": "AIzaSyDorbLzXasW-n7sSc-5rGcx1-SKVGsru9c" + }, + { + "current_key": "AIzaSyDdJpvBFUO_osfPn3Yuj_vEG9VdjmEg0IY" + }, + { + "current_key": "AIzaSyDutR97NK5gRLdW839IpizIWj_fXrIUtNI" + }, + { + "current_key": "AIzaSyAIPnRocVJOWDTGWaQgVaSMU7FLRcbMHxk" + }, + { + "current_key": "AIzaSyAqNEuTX8MW9ySEbD-cmxg68dVho0n_3fU" + }, + { + "current_key": "AIzaSyDv_ajWs5TIdgiNwhcjnUSjpi-WveoeNFo" + }, + { + "current_key": "AIzaSyDT-fAaaa9bf3Bu4SAGyNqre_OSUQZ9YuE" + }, + { + "current_key": "AIzaSyDUxoSE0qe0emKM1MCUA4Y_EiittrWi_EM" + }, + { + "current_key": "AIzaSyAysaL8XPHO7STS3kOVGqM-0F0n3_09Sws" + }, + { + "current_key": "AIzaSyDadOjxdJsBIt-hDrEOG90kMDNxSG2RUzU" + }, + { + "current_key": "AIzaSyA-MIPQ2JhVqtewf3nx2MJHwIdniVzuoaI" + }, + { + "current_key": "AIzaSyAPlSHAPRYXJQSOjpw1dlvOaQaBOdLBJpg" + }, + { + "current_key": "AIzaSyBLWyW5ih6FlpRN0ec_62HVwMFcrLw6Tic" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + }, + { + "client_info": { + "mobilesdk_app_id": "1:629309347341:android:2b4e2ef6f3282dc537a744", + "android_client_info": { + "package_name": "com.cpm.kelloggssales" + } + }, + "oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyB4uUMb8N-u4MhmY5ChEg-PDMgavWpqxeU" + }, + { + "current_key": "AIzaSyDorbLzXasW-n7sSc-5rGcx1-SKVGsru9c" + }, + { + "current_key": "AIzaSyDdJpvBFUO_osfPn3Yuj_vEG9VdjmEg0IY" + }, + { + "current_key": "AIzaSyDutR97NK5gRLdW839IpizIWj_fXrIUtNI" + }, + { + "current_key": "AIzaSyAIPnRocVJOWDTGWaQgVaSMU7FLRcbMHxk" + }, + { + "current_key": "AIzaSyAqNEuTX8MW9ySEbD-cmxg68dVho0n_3fU" + }, + { + "current_key": "AIzaSyDv_ajWs5TIdgiNwhcjnUSjpi-WveoeNFo" + }, + { + "current_key": "AIzaSyDT-fAaaa9bf3Bu4SAGyNqre_OSUQZ9YuE" + }, + { + "current_key": "AIzaSyDUxoSE0qe0emKM1MCUA4Y_EiittrWi_EM" + }, + { + "current_key": "AIzaSyAysaL8XPHO7STS3kOVGqM-0F0n3_09Sws" + }, + { + "current_key": "AIzaSyDadOjxdJsBIt-hDrEOG90kMDNxSG2RUzU" + }, + { + "current_key": "AIzaSyA-MIPQ2JhVqtewf3nx2MJHwIdniVzuoaI" + }, + { + "current_key": "AIzaSyAPlSHAPRYXJQSOjpw1dlvOaQaBOdLBJpg" + }, + { + "current_key": "AIzaSyBLWyW5ih6FlpRN0ec_62HVwMFcrLw6Tic" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + }, + { + "client_info": { + "mobilesdk_app_id": "1:629309347341:android:a14728688dd0025337a744", + "android_client_info": { + "package_name": "com.cpm.kellogsMTSupervisor" + } + }, + "oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyB4uUMb8N-u4MhmY5ChEg-PDMgavWpqxeU" + }, + { + "current_key": "AIzaSyDorbLzXasW-n7sSc-5rGcx1-SKVGsru9c" + }, + { + "current_key": "AIzaSyDdJpvBFUO_osfPn3Yuj_vEG9VdjmEg0IY" + }, + { + "current_key": "AIzaSyDutR97NK5gRLdW839IpizIWj_fXrIUtNI" + }, + { + "current_key": "AIzaSyAIPnRocVJOWDTGWaQgVaSMU7FLRcbMHxk" + }, + { + "current_key": "AIzaSyAqNEuTX8MW9ySEbD-cmxg68dVho0n_3fU" + }, + { + "current_key": "AIzaSyDv_ajWs5TIdgiNwhcjnUSjpi-WveoeNFo" + }, + { + "current_key": "AIzaSyDT-fAaaa9bf3Bu4SAGyNqre_OSUQZ9YuE" + }, + { + "current_key": "AIzaSyDUxoSE0qe0emKM1MCUA4Y_EiittrWi_EM" + }, + { + "current_key": "AIzaSyAysaL8XPHO7STS3kOVGqM-0F0n3_09Sws" + }, + { + "current_key": "AIzaSyDadOjxdJsBIt-hDrEOG90kMDNxSG2RUzU" + }, + { + "current_key": "AIzaSyA-MIPQ2JhVqtewf3nx2MJHwIdniVzuoaI" + }, + { + "current_key": "AIzaSyAPlSHAPRYXJQSOjpw1dlvOaQaBOdLBJpg" + }, + { + "current_key": "AIzaSyBLWyW5ih6FlpRN0ec_62HVwMFcrLw6Tic" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + }, + { + "client_info": { + "mobilesdk_app_id": "1:629309347341:android:d8b581d97214764437a744", + "android_client_info": { + "package_name": "com.cpm.lorealMT" + } + }, + "oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyB4uUMb8N-u4MhmY5ChEg-PDMgavWpqxeU" + }, + { + "current_key": "AIzaSyDorbLzXasW-n7sSc-5rGcx1-SKVGsru9c" + }, + { + "current_key": "AIzaSyDdJpvBFUO_osfPn3Yuj_vEG9VdjmEg0IY" + }, + { + "current_key": "AIzaSyDutR97NK5gRLdW839IpizIWj_fXrIUtNI" + }, + { + "current_key": "AIzaSyAIPnRocVJOWDTGWaQgVaSMU7FLRcbMHxk" + }, + { + "current_key": "AIzaSyAqNEuTX8MW9ySEbD-cmxg68dVho0n_3fU" + }, + { + "current_key": "AIzaSyDv_ajWs5TIdgiNwhcjnUSjpi-WveoeNFo" + }, + { + "current_key": "AIzaSyDT-fAaaa9bf3Bu4SAGyNqre_OSUQZ9YuE" + }, + { + "current_key": "AIzaSyDUxoSE0qe0emKM1MCUA4Y_EiittrWi_EM" + }, + { + "current_key": "AIzaSyAysaL8XPHO7STS3kOVGqM-0F0n3_09Sws" + }, + { + "current_key": "AIzaSyDadOjxdJsBIt-hDrEOG90kMDNxSG2RUzU" + }, + { + "current_key": "AIzaSyA-MIPQ2JhVqtewf3nx2MJHwIdniVzuoaI" + }, + { + "current_key": "AIzaSyAPlSHAPRYXJQSOjpw1dlvOaQaBOdLBJpg" + }, + { + "current_key": "AIzaSyBLWyW5ih6FlpRN0ec_62HVwMFcrLw6Tic" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + }, + { + "client_info": { + "mobilesdk_app_id": "1:629309347341:android:79b6975868639be937a744", + "android_client_info": { + "package_name": "com.cpm.lorealbaMabeline" + } + }, + "oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyB4uUMb8N-u4MhmY5ChEg-PDMgavWpqxeU" + }, + { + "current_key": "AIzaSyDorbLzXasW-n7sSc-5rGcx1-SKVGsru9c" + }, + { + "current_key": "AIzaSyDdJpvBFUO_osfPn3Yuj_vEG9VdjmEg0IY" + }, + { + "current_key": "AIzaSyDutR97NK5gRLdW839IpizIWj_fXrIUtNI" + }, + { + "current_key": "AIzaSyAIPnRocVJOWDTGWaQgVaSMU7FLRcbMHxk" + }, + { + "current_key": "AIzaSyAqNEuTX8MW9ySEbD-cmxg68dVho0n_3fU" + }, + { + "current_key": "AIzaSyDv_ajWs5TIdgiNwhcjnUSjpi-WveoeNFo" + }, + { + "current_key": "AIzaSyDT-fAaaa9bf3Bu4SAGyNqre_OSUQZ9YuE" + }, + { + "current_key": "AIzaSyDUxoSE0qe0emKM1MCUA4Y_EiittrWi_EM" + }, + { + "current_key": "AIzaSyAysaL8XPHO7STS3kOVGqM-0F0n3_09Sws" + }, + { + "current_key": "AIzaSyDadOjxdJsBIt-hDrEOG90kMDNxSG2RUzU" + }, + { + "current_key": "AIzaSyA-MIPQ2JhVqtewf3nx2MJHwIdniVzuoaI" + }, + { + "current_key": "AIzaSyAPlSHAPRYXJQSOjpw1dlvOaQaBOdLBJpg" + }, + { + "current_key": "AIzaSyBLWyW5ih6FlpRN0ec_62HVwMFcrLw6Tic" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + }, + { + "client_info": { + "mobilesdk_app_id": "1:629309347341:android:f9490de7c22042e2", + "android_client_info": { + "package_name": "com.cpm.lorealbaautomation" + } + }, + "oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyB4uUMb8N-u4MhmY5ChEg-PDMgavWpqxeU" + }, + { + "current_key": "AIzaSyDorbLzXasW-n7sSc-5rGcx1-SKVGsru9c" + }, + { + "current_key": "AIzaSyDdJpvBFUO_osfPn3Yuj_vEG9VdjmEg0IY" + }, + { + "current_key": "AIzaSyDutR97NK5gRLdW839IpizIWj_fXrIUtNI" + }, + { + "current_key": "AIzaSyAIPnRocVJOWDTGWaQgVaSMU7FLRcbMHxk" + }, + { + "current_key": "AIzaSyAqNEuTX8MW9ySEbD-cmxg68dVho0n_3fU" + }, + { + "current_key": "AIzaSyDv_ajWs5TIdgiNwhcjnUSjpi-WveoeNFo" + }, + { + "current_key": "AIzaSyDT-fAaaa9bf3Bu4SAGyNqre_OSUQZ9YuE" + }, + { + "current_key": "AIzaSyDUxoSE0qe0emKM1MCUA4Y_EiittrWi_EM" + }, + { + "current_key": "AIzaSyAysaL8XPHO7STS3kOVGqM-0F0n3_09Sws" + }, + { + "current_key": "AIzaSyDadOjxdJsBIt-hDrEOG90kMDNxSG2RUzU" + }, + { + "current_key": "AIzaSyA-MIPQ2JhVqtewf3nx2MJHwIdniVzuoaI" + }, + { + "current_key": "AIzaSyAPlSHAPRYXJQSOjpw1dlvOaQaBOdLBJpg" + }, + { + "current_key": "AIzaSyBLWyW5ih6FlpRN0ec_62HVwMFcrLw6Tic" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + }, + { + "client_info": { + "mobilesdk_app_id": "1:629309347341:android:7b8a2f149991e5f3", + "android_client_info": { + "package_name": "com.cpm.lorealispsupervisorflutter" + } + }, + "oauth_client": [ + { + "client_id": "629309347341-e63an8tlliesmttnhs2ub046m37n7dru.apps.googleusercontent.com", + "client_type": 1, + "android_info": { + "package_name": "com.cpm.lorealispsupervisorflutter", + "certificate_hash": "65b3e7895b38f52816092df3f55ba516ae1cf016" + } + }, + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyB4uUMb8N-u4MhmY5ChEg-PDMgavWpqxeU" + }, + { + "current_key": "AIzaSyDorbLzXasW-n7sSc-5rGcx1-SKVGsru9c" + }, + { + "current_key": "AIzaSyDdJpvBFUO_osfPn3Yuj_vEG9VdjmEg0IY" + }, + { + "current_key": "AIzaSyDutR97NK5gRLdW839IpizIWj_fXrIUtNI" + }, + { + "current_key": "AIzaSyAIPnRocVJOWDTGWaQgVaSMU7FLRcbMHxk" + }, + { + "current_key": "AIzaSyAqNEuTX8MW9ySEbD-cmxg68dVho0n_3fU" + }, + { + "current_key": "AIzaSyDv_ajWs5TIdgiNwhcjnUSjpi-WveoeNFo" + }, + { + "current_key": "AIzaSyDT-fAaaa9bf3Bu4SAGyNqre_OSUQZ9YuE" + }, + { + "current_key": "AIzaSyDUxoSE0qe0emKM1MCUA4Y_EiittrWi_EM" + }, + { + "current_key": "AIzaSyAysaL8XPHO7STS3kOVGqM-0F0n3_09Sws" + }, + { + "current_key": "AIzaSyDadOjxdJsBIt-hDrEOG90kMDNxSG2RUzU" + }, + { + "current_key": "AIzaSyA-MIPQ2JhVqtewf3nx2MJHwIdniVzuoaI" + }, + { + "current_key": "AIzaSyAPlSHAPRYXJQSOjpw1dlvOaQaBOdLBJpg" + }, + { + "current_key": "AIzaSyBLWyW5ih6FlpRN0ec_62HVwMFcrLw6Tic" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + }, + { + "client_info": { + "mobilesdk_app_id": "1:629309347341:android:12d80bf4582fe855", + "android_client_info": { + "package_name": "com.cpm.lorealpromoter" + } + }, + "oauth_client": [ + { + "client_id": "629309347341-c9rhlpsqdg06su38oid993itbs5utma1.apps.googleusercontent.com", + "client_type": 1, + "android_info": { + "package_name": "com.cpm.lorealpromoter", + "certificate_hash": "b18b4acbf3fdcd122e94365fe82d8211efc2f82a" + } + }, + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyB4uUMb8N-u4MhmY5ChEg-PDMgavWpqxeU" + }, + { + "current_key": "AIzaSyDorbLzXasW-n7sSc-5rGcx1-SKVGsru9c" + }, + { + "current_key": "AIzaSyDdJpvBFUO_osfPn3Yuj_vEG9VdjmEg0IY" + }, + { + "current_key": "AIzaSyDutR97NK5gRLdW839IpizIWj_fXrIUtNI" + }, + { + "current_key": "AIzaSyAIPnRocVJOWDTGWaQgVaSMU7FLRcbMHxk" + }, + { + "current_key": "AIzaSyAqNEuTX8MW9ySEbD-cmxg68dVho0n_3fU" + }, + { + "current_key": "AIzaSyDv_ajWs5TIdgiNwhcjnUSjpi-WveoeNFo" + }, + { + "current_key": "AIzaSyDT-fAaaa9bf3Bu4SAGyNqre_OSUQZ9YuE" + }, + { + "current_key": "AIzaSyDUxoSE0qe0emKM1MCUA4Y_EiittrWi_EM" + }, + { + "current_key": "AIzaSyAysaL8XPHO7STS3kOVGqM-0F0n3_09Sws" + }, + { + "current_key": "AIzaSyDadOjxdJsBIt-hDrEOG90kMDNxSG2RUzU" + }, + { + "current_key": "AIzaSyA-MIPQ2JhVqtewf3nx2MJHwIdniVzuoaI" + }, + { + "current_key": "AIzaSyAPlSHAPRYXJQSOjpw1dlvOaQaBOdLBJpg" + }, + { + "current_key": "AIzaSyBLWyW5ih6FlpRN0ec_62HVwMFcrLw6Tic" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + }, + { + "client_info": { + "mobilesdk_app_id": "1:629309347341:android:fcbe577dde3174cd", + "android_client_info": { + "package_name": "com.cpm.lorealsupervisor" + } + }, + "oauth_client": [ + { + "client_id": "629309347341-q5de7pmios8bmfqmfbjlbs9ah7sgjlck.apps.googleusercontent.com", + "client_type": 1, + "android_info": { + "package_name": "com.cpm.lorealsupervisor", + "certificate_hash": "8875b411191ba9f692c6a30409c36cbb8e35e0b5" + } + }, + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyB4uUMb8N-u4MhmY5ChEg-PDMgavWpqxeU" + }, + { + "current_key": "AIzaSyDorbLzXasW-n7sSc-5rGcx1-SKVGsru9c" + }, + { + "current_key": "AIzaSyDdJpvBFUO_osfPn3Yuj_vEG9VdjmEg0IY" + }, + { + "current_key": "AIzaSyDutR97NK5gRLdW839IpizIWj_fXrIUtNI" + }, + { + "current_key": "AIzaSyAIPnRocVJOWDTGWaQgVaSMU7FLRcbMHxk" + }, + { + "current_key": "AIzaSyAqNEuTX8MW9ySEbD-cmxg68dVho0n_3fU" + }, + { + "current_key": "AIzaSyDv_ajWs5TIdgiNwhcjnUSjpi-WveoeNFo" + }, + { + "current_key": "AIzaSyDT-fAaaa9bf3Bu4SAGyNqre_OSUQZ9YuE" + }, + { + "current_key": "AIzaSyDUxoSE0qe0emKM1MCUA4Y_EiittrWi_EM" + }, + { + "current_key": "AIzaSyAysaL8XPHO7STS3kOVGqM-0F0n3_09Sws" + }, + { + "current_key": "AIzaSyDadOjxdJsBIt-hDrEOG90kMDNxSG2RUzU" + }, + { + "current_key": "AIzaSyA-MIPQ2JhVqtewf3nx2MJHwIdniVzuoaI" + }, + { + "current_key": "AIzaSyAPlSHAPRYXJQSOjpw1dlvOaQaBOdLBJpg" + }, + { + "current_key": "AIzaSyBLWyW5ih6FlpRN0ec_62HVwMFcrLw6Tic" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + }, + { + "client_info": { + "mobilesdk_app_id": "1:629309347341:android:67044ef95eaaaf78", + "android_client_info": { + "package_name": "com.cpm.meadjohnson" + } + }, + "oauth_client": [ + { + "client_id": "629309347341-4gq8hl2hv2vrm4bdumh0c833nph7f4nh.apps.googleusercontent.com", + "client_type": 1, + "android_info": { + "package_name": "com.cpm.meadjohnson", + "certificate_hash": "f4469c047dfd3b33b1a34b8c38bd770cd43698e5" + } + }, + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyB4uUMb8N-u4MhmY5ChEg-PDMgavWpqxeU" + }, + { + "current_key": "AIzaSyDorbLzXasW-n7sSc-5rGcx1-SKVGsru9c" + }, + { + "current_key": "AIzaSyDdJpvBFUO_osfPn3Yuj_vEG9VdjmEg0IY" + }, + { + "current_key": "AIzaSyDutR97NK5gRLdW839IpizIWj_fXrIUtNI" + }, + { + "current_key": "AIzaSyAIPnRocVJOWDTGWaQgVaSMU7FLRcbMHxk" + }, + { + "current_key": "AIzaSyAqNEuTX8MW9ySEbD-cmxg68dVho0n_3fU" + }, + { + "current_key": "AIzaSyDv_ajWs5TIdgiNwhcjnUSjpi-WveoeNFo" + }, + { + "current_key": "AIzaSyDT-fAaaa9bf3Bu4SAGyNqre_OSUQZ9YuE" + }, + { + "current_key": "AIzaSyDUxoSE0qe0emKM1MCUA4Y_EiittrWi_EM" + }, + { + "current_key": "AIzaSyAysaL8XPHO7STS3kOVGqM-0F0n3_09Sws" + }, + { + "current_key": "AIzaSyDadOjxdJsBIt-hDrEOG90kMDNxSG2RUzU" + }, + { + "current_key": "AIzaSyA-MIPQ2JhVqtewf3nx2MJHwIdniVzuoaI" + }, + { + "current_key": "AIzaSyAPlSHAPRYXJQSOjpw1dlvOaQaBOdLBJpg" + }, + { + "current_key": "AIzaSyBLWyW5ih6FlpRN0ec_62HVwMFcrLw6Tic" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + }, + { + "client_info": { + "mobilesdk_app_id": "1:629309347341:android:606bce12772e8f49", + "android_client_info": { + "package_name": "com.cpm.mondelezgt" + } + }, + "oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyB4uUMb8N-u4MhmY5ChEg-PDMgavWpqxeU" + }, + { + "current_key": "AIzaSyDorbLzXasW-n7sSc-5rGcx1-SKVGsru9c" + }, + { + "current_key": "AIzaSyDdJpvBFUO_osfPn3Yuj_vEG9VdjmEg0IY" + }, + { + "current_key": "AIzaSyDutR97NK5gRLdW839IpizIWj_fXrIUtNI" + }, + { + "current_key": "AIzaSyAIPnRocVJOWDTGWaQgVaSMU7FLRcbMHxk" + }, + { + "current_key": "AIzaSyAqNEuTX8MW9ySEbD-cmxg68dVho0n_3fU" + }, + { + "current_key": "AIzaSyDv_ajWs5TIdgiNwhcjnUSjpi-WveoeNFo" + }, + { + "current_key": "AIzaSyDT-fAaaa9bf3Bu4SAGyNqre_OSUQZ9YuE" + }, + { + "current_key": "AIzaSyDUxoSE0qe0emKM1MCUA4Y_EiittrWi_EM" + }, + { + "current_key": "AIzaSyAysaL8XPHO7STS3kOVGqM-0F0n3_09Sws" + }, + { + "current_key": "AIzaSyDadOjxdJsBIt-hDrEOG90kMDNxSG2RUzU" + }, + { + "current_key": "AIzaSyA-MIPQ2JhVqtewf3nx2MJHwIdniVzuoaI" + }, + { + "current_key": "AIzaSyAPlSHAPRYXJQSOjpw1dlvOaQaBOdLBJpg" + }, + { + "current_key": "AIzaSyBLWyW5ih6FlpRN0ec_62HVwMFcrLw6Tic" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + }, + { + "client_info": { + "mobilesdk_app_id": "1:629309347341:android:245f6b7a99b348fc", + "android_client_info": { + "package_name": "com.cpm.mondlezSupervisor" + } + }, + "oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyB4uUMb8N-u4MhmY5ChEg-PDMgavWpqxeU" + }, + { + "current_key": "AIzaSyDorbLzXasW-n7sSc-5rGcx1-SKVGsru9c" + }, + { + "current_key": "AIzaSyDdJpvBFUO_osfPn3Yuj_vEG9VdjmEg0IY" + }, + { + "current_key": "AIzaSyDutR97NK5gRLdW839IpizIWj_fXrIUtNI" + }, + { + "current_key": "AIzaSyAIPnRocVJOWDTGWaQgVaSMU7FLRcbMHxk" + }, + { + "current_key": "AIzaSyAqNEuTX8MW9ySEbD-cmxg68dVho0n_3fU" + }, + { + "current_key": "AIzaSyDv_ajWs5TIdgiNwhcjnUSjpi-WveoeNFo" + }, + { + "current_key": "AIzaSyDT-fAaaa9bf3Bu4SAGyNqre_OSUQZ9YuE" + }, + { + "current_key": "AIzaSyDUxoSE0qe0emKM1MCUA4Y_EiittrWi_EM" + }, + { + "current_key": "AIzaSyAysaL8XPHO7STS3kOVGqM-0F0n3_09Sws" + }, + { + "current_key": "AIzaSyDadOjxdJsBIt-hDrEOG90kMDNxSG2RUzU" + }, + { + "current_key": "AIzaSyA-MIPQ2JhVqtewf3nx2MJHwIdniVzuoaI" + }, + { + "current_key": "AIzaSyAPlSHAPRYXJQSOjpw1dlvOaQaBOdLBJpg" + }, + { + "current_key": "AIzaSyBLWyW5ih6FlpRN0ec_62HVwMFcrLw6Tic" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + }, + { + "client_info": { + "mobilesdk_app_id": "1:629309347341:android:010ee6dade8a1971", + "android_client_info": { + "package_name": "com.cpm.mycpm" + } + }, + "oauth_client": [ + { + "client_id": "629309347341-ojabgbgp73vgapk08a34n5ove5hodqnm.apps.googleusercontent.com", + "client_type": 1, + "android_info": { + "package_name": "com.cpm.mycpm", + "certificate_hash": "65b3e7895b38f52816092df3f55ba516ae1cf016" + } + }, + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyB4uUMb8N-u4MhmY5ChEg-PDMgavWpqxeU" + }, + { + "current_key": "AIzaSyDorbLzXasW-n7sSc-5rGcx1-SKVGsru9c" + }, + { + "current_key": "AIzaSyDdJpvBFUO_osfPn3Yuj_vEG9VdjmEg0IY" + }, + { + "current_key": "AIzaSyDutR97NK5gRLdW839IpizIWj_fXrIUtNI" + }, + { + "current_key": "AIzaSyAIPnRocVJOWDTGWaQgVaSMU7FLRcbMHxk" + }, + { + "current_key": "AIzaSyAqNEuTX8MW9ySEbD-cmxg68dVho0n_3fU" + }, + { + "current_key": "AIzaSyDv_ajWs5TIdgiNwhcjnUSjpi-WveoeNFo" + }, + { + "current_key": "AIzaSyDT-fAaaa9bf3Bu4SAGyNqre_OSUQZ9YuE" + }, + { + "current_key": "AIzaSyDUxoSE0qe0emKM1MCUA4Y_EiittrWi_EM" + }, + { + "current_key": "AIzaSyAysaL8XPHO7STS3kOVGqM-0F0n3_09Sws" + }, + { + "current_key": "AIzaSyDadOjxdJsBIt-hDrEOG90kMDNxSG2RUzU" + }, + { + "current_key": "AIzaSyA-MIPQ2JhVqtewf3nx2MJHwIdniVzuoaI" + }, + { + "current_key": "AIzaSyAPlSHAPRYXJQSOjpw1dlvOaQaBOdLBJpg" + }, + { + "current_key": "AIzaSyBLWyW5ih6FlpRN0ec_62HVwMFcrLw6Tic" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + }, + { + "client_info": { + "mobilesdk_app_id": "1:629309347341:android:671c903a37239cd5", + "android_client_info": { + "package_name": "com.cpm.mycustomcamera" + } + }, + "oauth_client": [ + { + "client_id": "629309347341-hif2q3b0fcjaggnqm2lkhhfelepbn0mk.apps.googleusercontent.com", + "client_type": 1, + "android_info": { + "package_name": "com.cpm.mycustomcamera", + "certificate_hash": "f4469c047dfd3b33b1a34b8c38bd770cd43698e5" + } + }, + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyB4uUMb8N-u4MhmY5ChEg-PDMgavWpqxeU" + }, + { + "current_key": "AIzaSyDorbLzXasW-n7sSc-5rGcx1-SKVGsru9c" + }, + { + "current_key": "AIzaSyDdJpvBFUO_osfPn3Yuj_vEG9VdjmEg0IY" + }, + { + "current_key": "AIzaSyDutR97NK5gRLdW839IpizIWj_fXrIUtNI" + }, + { + "current_key": "AIzaSyAIPnRocVJOWDTGWaQgVaSMU7FLRcbMHxk" + }, + { + "current_key": "AIzaSyAqNEuTX8MW9ySEbD-cmxg68dVho0n_3fU" + }, + { + "current_key": "AIzaSyDv_ajWs5TIdgiNwhcjnUSjpi-WveoeNFo" + }, + { + "current_key": "AIzaSyDT-fAaaa9bf3Bu4SAGyNqre_OSUQZ9YuE" + }, + { + "current_key": "AIzaSyDUxoSE0qe0emKM1MCUA4Y_EiittrWi_EM" + }, + { + "current_key": "AIzaSyAysaL8XPHO7STS3kOVGqM-0F0n3_09Sws" + }, + { + "current_key": "AIzaSyDadOjxdJsBIt-hDrEOG90kMDNxSG2RUzU" + }, + { + "current_key": "AIzaSyA-MIPQ2JhVqtewf3nx2MJHwIdniVzuoaI" + }, + { + "current_key": "AIzaSyAPlSHAPRYXJQSOjpw1dlvOaQaBOdLBJpg" + }, + { + "current_key": "AIzaSyBLWyW5ih6FlpRN0ec_62HVwMFcrLw6Tic" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + }, + { + "client_info": { + "mobilesdk_app_id": "1:629309347341:android:9e10593f11b718ba", + "android_client_info": { + "package_name": "com.cpm.new.abbott" + } + }, + "oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyB4uUMb8N-u4MhmY5ChEg-PDMgavWpqxeU" + }, + { + "current_key": "AIzaSyDorbLzXasW-n7sSc-5rGcx1-SKVGsru9c" + }, + { + "current_key": "AIzaSyDdJpvBFUO_osfPn3Yuj_vEG9VdjmEg0IY" + }, + { + "current_key": "AIzaSyDutR97NK5gRLdW839IpizIWj_fXrIUtNI" + }, + { + "current_key": "AIzaSyAIPnRocVJOWDTGWaQgVaSMU7FLRcbMHxk" + }, + { + "current_key": "AIzaSyAqNEuTX8MW9ySEbD-cmxg68dVho0n_3fU" + }, + { + "current_key": "AIzaSyDv_ajWs5TIdgiNwhcjnUSjpi-WveoeNFo" + }, + { + "current_key": "AIzaSyDT-fAaaa9bf3Bu4SAGyNqre_OSUQZ9YuE" + }, + { + "current_key": "AIzaSyDUxoSE0qe0emKM1MCUA4Y_EiittrWi_EM" + }, + { + "current_key": "AIzaSyAysaL8XPHO7STS3kOVGqM-0F0n3_09Sws" + }, + { + "current_key": "AIzaSyDadOjxdJsBIt-hDrEOG90kMDNxSG2RUzU" + }, + { + "current_key": "AIzaSyA-MIPQ2JhVqtewf3nx2MJHwIdniVzuoaI" + }, + { + "current_key": "AIzaSyAPlSHAPRYXJQSOjpw1dlvOaQaBOdLBJpg" + }, + { + "current_key": "AIzaSyBLWyW5ih6FlpRN0ec_62HVwMFcrLw6Tic" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + }, + { + "client_info": { + "mobilesdk_app_id": "1:629309347341:android:f72191a7c9bfbe8a", + "android_client_info": { + "package_name": "com.cpm.oralbpohe" + } + }, + "oauth_client": [ + { + "client_id": "629309347341-8pst7ivvcauugeaevq5lcljsvq3vmd5f.apps.googleusercontent.com", + "client_type": 1, + "android_info": { + "package_name": "com.cpm.oralbpohe", + "certificate_hash": "8875b411191ba9f692c6a30409c36cbb8e35e0b5" + } + }, + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyB4uUMb8N-u4MhmY5ChEg-PDMgavWpqxeU" + }, + { + "current_key": "AIzaSyDorbLzXasW-n7sSc-5rGcx1-SKVGsru9c" + }, + { + "current_key": "AIzaSyDdJpvBFUO_osfPn3Yuj_vEG9VdjmEg0IY" + }, + { + "current_key": "AIzaSyDutR97NK5gRLdW839IpizIWj_fXrIUtNI" + }, + { + "current_key": "AIzaSyAIPnRocVJOWDTGWaQgVaSMU7FLRcbMHxk" + }, + { + "current_key": "AIzaSyAqNEuTX8MW9ySEbD-cmxg68dVho0n_3fU" + }, + { + "current_key": "AIzaSyDv_ajWs5TIdgiNwhcjnUSjpi-WveoeNFo" + }, + { + "current_key": "AIzaSyDT-fAaaa9bf3Bu4SAGyNqre_OSUQZ9YuE" + }, + { + "current_key": "AIzaSyDUxoSE0qe0emKM1MCUA4Y_EiittrWi_EM" + }, + { + "current_key": "AIzaSyAysaL8XPHO7STS3kOVGqM-0F0n3_09Sws" + }, + { + "current_key": "AIzaSyDadOjxdJsBIt-hDrEOG90kMDNxSG2RUzU" + }, + { + "current_key": "AIzaSyA-MIPQ2JhVqtewf3nx2MJHwIdniVzuoaI" + }, + { + "current_key": "AIzaSyAPlSHAPRYXJQSOjpw1dlvOaQaBOdLBJpg" + }, + { + "current_key": "AIzaSyBLWyW5ih6FlpRN0ec_62HVwMFcrLw6Tic" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + }, + { + "client_info": { + "mobilesdk_app_id": "1:629309347341:android:eb7e9a84fec3422c", + "android_client_info": { + "package_name": "com.cpm.parinaampepsicoo" + } + }, + "oauth_client": [ + { + "client_id": "629309347341-kurr4f3dduko6jmuk5jeg014lbnvitja.apps.googleusercontent.com", + "client_type": 1, + "android_info": { + "package_name": "com.cpm.parinaampepsicoo", + "certificate_hash": "95d49e939c2b2ac2229560df2ec290bccc0e9819" + } + }, + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyB4uUMb8N-u4MhmY5ChEg-PDMgavWpqxeU" + }, + { + "current_key": "AIzaSyDorbLzXasW-n7sSc-5rGcx1-SKVGsru9c" + }, + { + "current_key": "AIzaSyDdJpvBFUO_osfPn3Yuj_vEG9VdjmEg0IY" + }, + { + "current_key": "AIzaSyDutR97NK5gRLdW839IpizIWj_fXrIUtNI" + }, + { + "current_key": "AIzaSyAIPnRocVJOWDTGWaQgVaSMU7FLRcbMHxk" + }, + { + "current_key": "AIzaSyAqNEuTX8MW9ySEbD-cmxg68dVho0n_3fU" + }, + { + "current_key": "AIzaSyDv_ajWs5TIdgiNwhcjnUSjpi-WveoeNFo" + }, + { + "current_key": "AIzaSyDT-fAaaa9bf3Bu4SAGyNqre_OSUQZ9YuE" + }, + { + "current_key": "AIzaSyDUxoSE0qe0emKM1MCUA4Y_EiittrWi_EM" + }, + { + "current_key": "AIzaSyAysaL8XPHO7STS3kOVGqM-0F0n3_09Sws" + }, + { + "current_key": "AIzaSyDadOjxdJsBIt-hDrEOG90kMDNxSG2RUzU" + }, + { + "current_key": "AIzaSyA-MIPQ2JhVqtewf3nx2MJHwIdniVzuoaI" + }, + { + "current_key": "AIzaSyAPlSHAPRYXJQSOjpw1dlvOaQaBOdLBJpg" + }, + { + "current_key": "AIzaSyBLWyW5ih6FlpRN0ec_62HVwMFcrLw6Tic" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + }, + { + "client_info": { + "mobilesdk_app_id": "1:629309347341:android:c150baa45302cd82", + "android_client_info": { + "package_name": "com.cpm.pgattendance" + } + }, + "oauth_client": [ + { + "client_id": "629309347341-9roncgt1vf683lneim5ulf42l8iu82ku.apps.googleusercontent.com", + "client_type": 1, + "android_info": { + "package_name": "com.cpm.pgattendance", + "certificate_hash": "95d49e939c2b2ac2229560df2ec290bccc0e9819" + } + }, + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyB4uUMb8N-u4MhmY5ChEg-PDMgavWpqxeU" + }, + { + "current_key": "AIzaSyDorbLzXasW-n7sSc-5rGcx1-SKVGsru9c" + }, + { + "current_key": "AIzaSyDdJpvBFUO_osfPn3Yuj_vEG9VdjmEg0IY" + }, + { + "current_key": "AIzaSyDutR97NK5gRLdW839IpizIWj_fXrIUtNI" + }, + { + "current_key": "AIzaSyAIPnRocVJOWDTGWaQgVaSMU7FLRcbMHxk" + }, + { + "current_key": "AIzaSyAqNEuTX8MW9ySEbD-cmxg68dVho0n_3fU" + }, + { + "current_key": "AIzaSyDv_ajWs5TIdgiNwhcjnUSjpi-WveoeNFo" + }, + { + "current_key": "AIzaSyDT-fAaaa9bf3Bu4SAGyNqre_OSUQZ9YuE" + }, + { + "current_key": "AIzaSyDUxoSE0qe0emKM1MCUA4Y_EiittrWi_EM" + }, + { + "current_key": "AIzaSyAysaL8XPHO7STS3kOVGqM-0F0n3_09Sws" + }, + { + "current_key": "AIzaSyDadOjxdJsBIt-hDrEOG90kMDNxSG2RUzU" + }, + { + "current_key": "AIzaSyA-MIPQ2JhVqtewf3nx2MJHwIdniVzuoaI" + }, + { + "current_key": "AIzaSyAPlSHAPRYXJQSOjpw1dlvOaQaBOdLBJpg" + }, + { + "current_key": "AIzaSyBLWyW5ih6FlpRN0ec_62HVwMFcrLw6Tic" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + }, + { + "client_info": { + "mobilesdk_app_id": "1:629309347341:android:2c19a23e62057200", + "android_client_info": { + "package_name": "com.cpm.phillips" + } + }, + "oauth_client": [ + { + "client_id": "629309347341-69urr0gm27goh7k5fmsts52t0qd9tt1p.apps.googleusercontent.com", + "client_type": 1, + "android_info": { + "package_name": "com.cpm.phillips", + "certificate_hash": "8ab20329082aa45376fcf5903996a69416a8e122" + } + }, + { + "client_id": "629309347341-nhverstqq9sdgm6c5d606d7l923t6es1.apps.googleusercontent.com", + "client_type": 1, + "android_info": { + "package_name": "com.cpm.phillips", + "certificate_hash": "8875b411191ba9f692c6a30409c36cbb8e35e0b5" + } + }, + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyB4uUMb8N-u4MhmY5ChEg-PDMgavWpqxeU" + }, + { + "current_key": "AIzaSyDorbLzXasW-n7sSc-5rGcx1-SKVGsru9c" + }, + { + "current_key": "AIzaSyDdJpvBFUO_osfPn3Yuj_vEG9VdjmEg0IY" + }, + { + "current_key": "AIzaSyDutR97NK5gRLdW839IpizIWj_fXrIUtNI" + }, + { + "current_key": "AIzaSyAIPnRocVJOWDTGWaQgVaSMU7FLRcbMHxk" + }, + { + "current_key": "AIzaSyAqNEuTX8MW9ySEbD-cmxg68dVho0n_3fU" + }, + { + "current_key": "AIzaSyDv_ajWs5TIdgiNwhcjnUSjpi-WveoeNFo" + }, + { + "current_key": "AIzaSyDT-fAaaa9bf3Bu4SAGyNqre_OSUQZ9YuE" + }, + { + "current_key": "AIzaSyDUxoSE0qe0emKM1MCUA4Y_EiittrWi_EM" + }, + { + "current_key": "AIzaSyAysaL8XPHO7STS3kOVGqM-0F0n3_09Sws" + }, + { + "current_key": "AIzaSyDadOjxdJsBIt-hDrEOG90kMDNxSG2RUzU" + }, + { + "current_key": "AIzaSyA-MIPQ2JhVqtewf3nx2MJHwIdniVzuoaI" + }, + { + "current_key": "AIzaSyAPlSHAPRYXJQSOjpw1dlvOaQaBOdLBJpg" + }, + { + "current_key": "AIzaSyBLWyW5ih6FlpRN0ec_62HVwMFcrLw6Tic" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + }, + { + "client_info": { + "mobilesdk_app_id": "1:629309347341:android:fae817a66bd9b6a8", + "android_client_info": { + "package_name": "com.cpm.phillipsFC" + } + }, + "oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyB4uUMb8N-u4MhmY5ChEg-PDMgavWpqxeU" + }, + { + "current_key": "AIzaSyDorbLzXasW-n7sSc-5rGcx1-SKVGsru9c" + }, + { + "current_key": "AIzaSyDdJpvBFUO_osfPn3Yuj_vEG9VdjmEg0IY" + }, + { + "current_key": "AIzaSyDutR97NK5gRLdW839IpizIWj_fXrIUtNI" + }, + { + "current_key": "AIzaSyAIPnRocVJOWDTGWaQgVaSMU7FLRcbMHxk" + }, + { + "current_key": "AIzaSyAqNEuTX8MW9ySEbD-cmxg68dVho0n_3fU" + }, + { + "current_key": "AIzaSyDv_ajWs5TIdgiNwhcjnUSjpi-WveoeNFo" + }, + { + "current_key": "AIzaSyDT-fAaaa9bf3Bu4SAGyNqre_OSUQZ9YuE" + }, + { + "current_key": "AIzaSyDUxoSE0qe0emKM1MCUA4Y_EiittrWi_EM" + }, + { + "current_key": "AIzaSyAysaL8XPHO7STS3kOVGqM-0F0n3_09Sws" + }, + { + "current_key": "AIzaSyDadOjxdJsBIt-hDrEOG90kMDNxSG2RUzU" + }, + { + "current_key": "AIzaSyA-MIPQ2JhVqtewf3nx2MJHwIdniVzuoaI" + }, + { + "current_key": "AIzaSyAPlSHAPRYXJQSOjpw1dlvOaQaBOdLBJpg" + }, + { + "current_key": "AIzaSyBLWyW5ih6FlpRN0ec_62HVwMFcrLw6Tic" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + }, + { + "client_info": { + "mobilesdk_app_id": "1:629309347341:android:73b5a58de0cb9d03", + "android_client_info": { + "package_name": "com.cpm.phillipspc" + } + }, + "oauth_client": [ + { + "client_id": "629309347341-65m70364m7sk844q3jtng3nkkf9o2bd2.apps.googleusercontent.com", + "client_type": 1, + "android_info": { + "package_name": "com.cpm.phillipspc", + "certificate_hash": "8875b411191ba9f692c6a30409c36cbb8e35e0b5" + } + }, + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyB4uUMb8N-u4MhmY5ChEg-PDMgavWpqxeU" + }, + { + "current_key": "AIzaSyDorbLzXasW-n7sSc-5rGcx1-SKVGsru9c" + }, + { + "current_key": "AIzaSyDdJpvBFUO_osfPn3Yuj_vEG9VdjmEg0IY" + }, + { + "current_key": "AIzaSyDutR97NK5gRLdW839IpizIWj_fXrIUtNI" + }, + { + "current_key": "AIzaSyAIPnRocVJOWDTGWaQgVaSMU7FLRcbMHxk" + }, + { + "current_key": "AIzaSyAqNEuTX8MW9ySEbD-cmxg68dVho0n_3fU" + }, + { + "current_key": "AIzaSyDv_ajWs5TIdgiNwhcjnUSjpi-WveoeNFo" + }, + { + "current_key": "AIzaSyDT-fAaaa9bf3Bu4SAGyNqre_OSUQZ9YuE" + }, + { + "current_key": "AIzaSyDUxoSE0qe0emKM1MCUA4Y_EiittrWi_EM" + }, + { + "current_key": "AIzaSyAysaL8XPHO7STS3kOVGqM-0F0n3_09Sws" + }, + { + "current_key": "AIzaSyDadOjxdJsBIt-hDrEOG90kMDNxSG2RUzU" + }, + { + "current_key": "AIzaSyA-MIPQ2JhVqtewf3nx2MJHwIdniVzuoaI" + }, + { + "current_key": "AIzaSyAPlSHAPRYXJQSOjpw1dlvOaQaBOdLBJpg" + }, + { + "current_key": "AIzaSyBLWyW5ih6FlpRN0ec_62HVwMFcrLw6Tic" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + }, + { + "client_info": { + "mobilesdk_app_id": "1:629309347341:android:f4d8ac961f159117", + "android_client_info": { + "package_name": "com.cpm.reckitt_benckiser_gt" + } + }, + "oauth_client": [ + { + "client_id": "629309347341-ceqb54rvshjkb9a6pnjhieajueohj0v0.apps.googleusercontent.com", + "client_type": 1, + "android_info": { + "package_name": "com.cpm.reckitt_benckiser_gt", + "certificate_hash": "95d49e939c2b2ac2229560df2ec290bccc0e9819" + } + }, + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyB4uUMb8N-u4MhmY5ChEg-PDMgavWpqxeU" + }, + { + "current_key": "AIzaSyDorbLzXasW-n7sSc-5rGcx1-SKVGsru9c" + }, + { + "current_key": "AIzaSyDdJpvBFUO_osfPn3Yuj_vEG9VdjmEg0IY" + }, + { + "current_key": "AIzaSyDutR97NK5gRLdW839IpizIWj_fXrIUtNI" + }, + { + "current_key": "AIzaSyAIPnRocVJOWDTGWaQgVaSMU7FLRcbMHxk" + }, + { + "current_key": "AIzaSyAqNEuTX8MW9ySEbD-cmxg68dVho0n_3fU" + }, + { + "current_key": "AIzaSyDv_ajWs5TIdgiNwhcjnUSjpi-WveoeNFo" + }, + { + "current_key": "AIzaSyDT-fAaaa9bf3Bu4SAGyNqre_OSUQZ9YuE" + }, + { + "current_key": "AIzaSyDUxoSE0qe0emKM1MCUA4Y_EiittrWi_EM" + }, + { + "current_key": "AIzaSyAysaL8XPHO7STS3kOVGqM-0F0n3_09Sws" + }, + { + "current_key": "AIzaSyDadOjxdJsBIt-hDrEOG90kMDNxSG2RUzU" + }, + { + "current_key": "AIzaSyA-MIPQ2JhVqtewf3nx2MJHwIdniVzuoaI" + }, + { + "current_key": "AIzaSyAPlSHAPRYXJQSOjpw1dlvOaQaBOdLBJpg" + }, + { + "current_key": "AIzaSyBLWyW5ih6FlpRN0ec_62HVwMFcrLw6Tic" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + }, + { + "client_info": { + "mobilesdk_app_id": "1:629309347341:android:24c6b36f714a5f4a", + "android_client_info": { + "package_name": "com.cpm.reckitt_benckiser_hyho" + } + }, + "oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyB4uUMb8N-u4MhmY5ChEg-PDMgavWpqxeU" + }, + { + "current_key": "AIzaSyDorbLzXasW-n7sSc-5rGcx1-SKVGsru9c" + }, + { + "current_key": "AIzaSyDdJpvBFUO_osfPn3Yuj_vEG9VdjmEg0IY" + }, + { + "current_key": "AIzaSyDutR97NK5gRLdW839IpizIWj_fXrIUtNI" + }, + { + "current_key": "AIzaSyAIPnRocVJOWDTGWaQgVaSMU7FLRcbMHxk" + }, + { + "current_key": "AIzaSyAqNEuTX8MW9ySEbD-cmxg68dVho0n_3fU" + }, + { + "current_key": "AIzaSyDv_ajWs5TIdgiNwhcjnUSjpi-WveoeNFo" + }, + { + "current_key": "AIzaSyDT-fAaaa9bf3Bu4SAGyNqre_OSUQZ9YuE" + }, + { + "current_key": "AIzaSyDUxoSE0qe0emKM1MCUA4Y_EiittrWi_EM" + }, + { + "current_key": "AIzaSyAysaL8XPHO7STS3kOVGqM-0F0n3_09Sws" + }, + { + "current_key": "AIzaSyDadOjxdJsBIt-hDrEOG90kMDNxSG2RUzU" + }, + { + "current_key": "AIzaSyA-MIPQ2JhVqtewf3nx2MJHwIdniVzuoaI" + }, + { + "current_key": "AIzaSyAPlSHAPRYXJQSOjpw1dlvOaQaBOdLBJpg" + }, + { + "current_key": "AIzaSyBLWyW5ih6FlpRN0ec_62HVwMFcrLw6Tic" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + }, + { + "client_info": { + "mobilesdk_app_id": "1:629309347341:android:ad1445b4f05160cd37a744", + "android_client_info": { + "package_name": "com.cpm.solv" + } + }, + "oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyB4uUMb8N-u4MhmY5ChEg-PDMgavWpqxeU" + }, + { + "current_key": "AIzaSyDorbLzXasW-n7sSc-5rGcx1-SKVGsru9c" + }, + { + "current_key": "AIzaSyDdJpvBFUO_osfPn3Yuj_vEG9VdjmEg0IY" + }, + { + "current_key": "AIzaSyDutR97NK5gRLdW839IpizIWj_fXrIUtNI" + }, + { + "current_key": "AIzaSyAIPnRocVJOWDTGWaQgVaSMU7FLRcbMHxk" + }, + { + "current_key": "AIzaSyAqNEuTX8MW9ySEbD-cmxg68dVho0n_3fU" + }, + { + "current_key": "AIzaSyDv_ajWs5TIdgiNwhcjnUSjpi-WveoeNFo" + }, + { + "current_key": "AIzaSyDT-fAaaa9bf3Bu4SAGyNqre_OSUQZ9YuE" + }, + { + "current_key": "AIzaSyDUxoSE0qe0emKM1MCUA4Y_EiittrWi_EM" + }, + { + "current_key": "AIzaSyAysaL8XPHO7STS3kOVGqM-0F0n3_09Sws" + }, + { + "current_key": "AIzaSyDadOjxdJsBIt-hDrEOG90kMDNxSG2RUzU" + }, + { + "current_key": "AIzaSyA-MIPQ2JhVqtewf3nx2MJHwIdniVzuoaI" + }, + { + "current_key": "AIzaSyAPlSHAPRYXJQSOjpw1dlvOaQaBOdLBJpg" + }, + { + "current_key": "AIzaSyBLWyW5ih6FlpRN0ec_62HVwMFcrLw6Tic" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + }, + { + "client_info": { + "mobilesdk_app_id": "1:629309347341:android:3ee057aa520433d7", + "android_client_info": { + "package_name": "com.cpm.tclSupervisor" + } + }, + "oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyB4uUMb8N-u4MhmY5ChEg-PDMgavWpqxeU" + }, + { + "current_key": "AIzaSyDorbLzXasW-n7sSc-5rGcx1-SKVGsru9c" + }, + { + "current_key": "AIzaSyDdJpvBFUO_osfPn3Yuj_vEG9VdjmEg0IY" + }, + { + "current_key": "AIzaSyDutR97NK5gRLdW839IpizIWj_fXrIUtNI" + }, + { + "current_key": "AIzaSyAIPnRocVJOWDTGWaQgVaSMU7FLRcbMHxk" + }, + { + "current_key": "AIzaSyAqNEuTX8MW9ySEbD-cmxg68dVho0n_3fU" + }, + { + "current_key": "AIzaSyDv_ajWs5TIdgiNwhcjnUSjpi-WveoeNFo" + }, + { + "current_key": "AIzaSyDT-fAaaa9bf3Bu4SAGyNqre_OSUQZ9YuE" + }, + { + "current_key": "AIzaSyDUxoSE0qe0emKM1MCUA4Y_EiittrWi_EM" + }, + { + "current_key": "AIzaSyAysaL8XPHO7STS3kOVGqM-0F0n3_09Sws" + }, + { + "current_key": "AIzaSyDadOjxdJsBIt-hDrEOG90kMDNxSG2RUzU" + }, + { + "current_key": "AIzaSyA-MIPQ2JhVqtewf3nx2MJHwIdniVzuoaI" + }, + { + "current_key": "AIzaSyAPlSHAPRYXJQSOjpw1dlvOaQaBOdLBJpg" + }, + { + "current_key": "AIzaSyBLWyW5ih6FlpRN0ec_62HVwMFcrLw6Tic" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + }, + { + "client_info": { + "mobilesdk_app_id": "1:629309347341:android:88dbf9745166410b", + "android_client_info": { + "package_name": "com.cpm.whirlpool" + } + }, + "oauth_client": [ + { + "client_id": "629309347341-tbaug7tsj91ntn2vjm92opeb1sj82d79.apps.googleusercontent.com", + "client_type": 1, + "android_info": { + "package_name": "com.cpm.whirlpool", + "certificate_hash": "8875b411191ba9f692c6a30409c36cbb8e35e0b5" + } + }, + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyB4uUMb8N-u4MhmY5ChEg-PDMgavWpqxeU" + }, + { + "current_key": "AIzaSyDorbLzXasW-n7sSc-5rGcx1-SKVGsru9c" + }, + { + "current_key": "AIzaSyDdJpvBFUO_osfPn3Yuj_vEG9VdjmEg0IY" + }, + { + "current_key": "AIzaSyDutR97NK5gRLdW839IpizIWj_fXrIUtNI" + }, + { + "current_key": "AIzaSyAIPnRocVJOWDTGWaQgVaSMU7FLRcbMHxk" + }, + { + "current_key": "AIzaSyAqNEuTX8MW9ySEbD-cmxg68dVho0n_3fU" + }, + { + "current_key": "AIzaSyDv_ajWs5TIdgiNwhcjnUSjpi-WveoeNFo" + }, + { + "current_key": "AIzaSyDT-fAaaa9bf3Bu4SAGyNqre_OSUQZ9YuE" + }, + { + "current_key": "AIzaSyDUxoSE0qe0emKM1MCUA4Y_EiittrWi_EM" + }, + { + "current_key": "AIzaSyAysaL8XPHO7STS3kOVGqM-0F0n3_09Sws" + }, + { + "current_key": "AIzaSyDadOjxdJsBIt-hDrEOG90kMDNxSG2RUzU" + }, + { + "current_key": "AIzaSyA-MIPQ2JhVqtewf3nx2MJHwIdniVzuoaI" + }, + { + "current_key": "AIzaSyAPlSHAPRYXJQSOjpw1dlvOaQaBOdLBJpg" + }, + { + "current_key": "AIzaSyBLWyW5ih6FlpRN0ec_62HVwMFcrLw6Tic" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + }, + { + "client_info": { + "mobilesdk_app_id": "1:629309347341:android:2101497c203d3af2", + "android_client_info": { + "package_name": "com.cpm.yadu" + } + }, + "oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyB4uUMb8N-u4MhmY5ChEg-PDMgavWpqxeU" + }, + { + "current_key": "AIzaSyDorbLzXasW-n7sSc-5rGcx1-SKVGsru9c" + }, + { + "current_key": "AIzaSyDdJpvBFUO_osfPn3Yuj_vEG9VdjmEg0IY" + }, + { + "current_key": "AIzaSyDutR97NK5gRLdW839IpizIWj_fXrIUtNI" + }, + { + "current_key": "AIzaSyAIPnRocVJOWDTGWaQgVaSMU7FLRcbMHxk" + }, + { + "current_key": "AIzaSyAqNEuTX8MW9ySEbD-cmxg68dVho0n_3fU" + }, + { + "current_key": "AIzaSyDv_ajWs5TIdgiNwhcjnUSjpi-WveoeNFo" + }, + { + "current_key": "AIzaSyDT-fAaaa9bf3Bu4SAGyNqre_OSUQZ9YuE" + }, + { + "current_key": "AIzaSyDUxoSE0qe0emKM1MCUA4Y_EiittrWi_EM" + }, + { + "current_key": "AIzaSyAysaL8XPHO7STS3kOVGqM-0F0n3_09Sws" + }, + { + "current_key": "AIzaSyDadOjxdJsBIt-hDrEOG90kMDNxSG2RUzU" + }, + { + "current_key": "AIzaSyA-MIPQ2JhVqtewf3nx2MJHwIdniVzuoaI" + }, + { + "current_key": "AIzaSyAPlSHAPRYXJQSOjpw1dlvOaQaBOdLBJpg" + }, + { + "current_key": "AIzaSyBLWyW5ih6FlpRN0ec_62HVwMFcrLw6Tic" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + }, + { + "client_info": { + "mobilesdk_app_id": "1:629309347341:android:b649ef81ba03b46837a744", + "android_client_info": { + "package_name": "com.example.gsk_mt_sup" + } + }, + "oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyB4uUMb8N-u4MhmY5ChEg-PDMgavWpqxeU" + }, + { + "current_key": "AIzaSyDorbLzXasW-n7sSc-5rGcx1-SKVGsru9c" + }, + { + "current_key": "AIzaSyDdJpvBFUO_osfPn3Yuj_vEG9VdjmEg0IY" + }, + { + "current_key": "AIzaSyDutR97NK5gRLdW839IpizIWj_fXrIUtNI" + }, + { + "current_key": "AIzaSyAIPnRocVJOWDTGWaQgVaSMU7FLRcbMHxk" + }, + { + "current_key": "AIzaSyAqNEuTX8MW9ySEbD-cmxg68dVho0n_3fU" + }, + { + "current_key": "AIzaSyDv_ajWs5TIdgiNwhcjnUSjpi-WveoeNFo" + }, + { + "current_key": "AIzaSyDT-fAaaa9bf3Bu4SAGyNqre_OSUQZ9YuE" + }, + { + "current_key": "AIzaSyDUxoSE0qe0emKM1MCUA4Y_EiittrWi_EM" + }, + { + "current_key": "AIzaSyAysaL8XPHO7STS3kOVGqM-0F0n3_09Sws" + }, + { + "current_key": "AIzaSyDadOjxdJsBIt-hDrEOG90kMDNxSG2RUzU" + }, + { + "current_key": "AIzaSyA-MIPQ2JhVqtewf3nx2MJHwIdniVzuoaI" + }, + { + "current_key": "AIzaSyAPlSHAPRYXJQSOjpw1dlvOaQaBOdLBJpg" + }, + { + "current_key": "AIzaSyBLWyW5ih6FlpRN0ec_62HVwMFcrLw6Tic" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + }, + { + "client_info": { + "mobilesdk_app_id": "1:629309347341:android:09546560b4505797", + "android_client_info": { + "package_name": "com.google.firebase.samples.apps.mlkit" + } + }, + "oauth_client": [ + { + "client_id": "629309347341-vvkpqgm59n6685utplh132u62durvaci.apps.googleusercontent.com", + "client_type": 1, + "android_info": { + "package_name": "com.google.firebase.samples.apps.mlkit", + "certificate_hash": "f4469c047dfd3b33b1a34b8c38bd770cd43698e5" + } + }, + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyB4uUMb8N-u4MhmY5ChEg-PDMgavWpqxeU" + }, + { + "current_key": "AIzaSyDorbLzXasW-n7sSc-5rGcx1-SKVGsru9c" + }, + { + "current_key": "AIzaSyDdJpvBFUO_osfPn3Yuj_vEG9VdjmEg0IY" + }, + { + "current_key": "AIzaSyDutR97NK5gRLdW839IpizIWj_fXrIUtNI" + }, + { + "current_key": "AIzaSyAIPnRocVJOWDTGWaQgVaSMU7FLRcbMHxk" + }, + { + "current_key": "AIzaSyAqNEuTX8MW9ySEbD-cmxg68dVho0n_3fU" + }, + { + "current_key": "AIzaSyDv_ajWs5TIdgiNwhcjnUSjpi-WveoeNFo" + }, + { + "current_key": "AIzaSyDT-fAaaa9bf3Bu4SAGyNqre_OSUQZ9YuE" + }, + { + "current_key": "AIzaSyDUxoSE0qe0emKM1MCUA4Y_EiittrWi_EM" + }, + { + "current_key": "AIzaSyAysaL8XPHO7STS3kOVGqM-0F0n3_09Sws" + }, + { + "current_key": "AIzaSyDadOjxdJsBIt-hDrEOG90kMDNxSG2RUzU" + }, + { + "current_key": "AIzaSyA-MIPQ2JhVqtewf3nx2MJHwIdniVzuoaI" + }, + { + "current_key": "AIzaSyAPlSHAPRYXJQSOjpw1dlvOaQaBOdLBJpg" + }, + { + "current_key": "AIzaSyBLWyW5ih6FlpRN0ec_62HVwMFcrLw6Tic" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + }, + { + "client_info": { + "mobilesdk_app_id": "1:629309347341:android:e8c53ea22b22003737a744", + "android_client_info": { + "package_name": "com.lorealba_supervisor" + } + }, + "oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyB4uUMb8N-u4MhmY5ChEg-PDMgavWpqxeU" + }, + { + "current_key": "AIzaSyDorbLzXasW-n7sSc-5rGcx1-SKVGsru9c" + }, + { + "current_key": "AIzaSyDdJpvBFUO_osfPn3Yuj_vEG9VdjmEg0IY" + }, + { + "current_key": "AIzaSyDutR97NK5gRLdW839IpizIWj_fXrIUtNI" + }, + { + "current_key": "AIzaSyAIPnRocVJOWDTGWaQgVaSMU7FLRcbMHxk" + }, + { + "current_key": "AIzaSyAqNEuTX8MW9ySEbD-cmxg68dVho0n_3fU" + }, + { + "current_key": "AIzaSyDv_ajWs5TIdgiNwhcjnUSjpi-WveoeNFo" + }, + { + "current_key": "AIzaSyDT-fAaaa9bf3Bu4SAGyNqre_OSUQZ9YuE" + }, + { + "current_key": "AIzaSyDUxoSE0qe0emKM1MCUA4Y_EiittrWi_EM" + }, + { + "current_key": "AIzaSyAysaL8XPHO7STS3kOVGqM-0F0n3_09Sws" + }, + { + "current_key": "AIzaSyDadOjxdJsBIt-hDrEOG90kMDNxSG2RUzU" + }, + { + "current_key": "AIzaSyA-MIPQ2JhVqtewf3nx2MJHwIdniVzuoaI" + }, + { + "current_key": "AIzaSyAPlSHAPRYXJQSOjpw1dlvOaQaBOdLBJpg" + }, + { + "current_key": "AIzaSyBLWyW5ih6FlpRN0ec_62HVwMFcrLw6Tic" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + }, + { + "client_info": { + "mobilesdk_app_id": "1:629309347341:android:79952cb1a657cfcc", + "android_client_info": { + "package_name": "com.yadu.myfirebasenotification" + } + }, + "oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyB4uUMb8N-u4MhmY5ChEg-PDMgavWpqxeU" + }, + { + "current_key": "AIzaSyDorbLzXasW-n7sSc-5rGcx1-SKVGsru9c" + }, + { + "current_key": "AIzaSyDdJpvBFUO_osfPn3Yuj_vEG9VdjmEg0IY" + }, + { + "current_key": "AIzaSyDutR97NK5gRLdW839IpizIWj_fXrIUtNI" + }, + { + "current_key": "AIzaSyAIPnRocVJOWDTGWaQgVaSMU7FLRcbMHxk" + }, + { + "current_key": "AIzaSyAqNEuTX8MW9ySEbD-cmxg68dVho0n_3fU" + }, + { + "current_key": "AIzaSyDv_ajWs5TIdgiNwhcjnUSjpi-WveoeNFo" + }, + { + "current_key": "AIzaSyDT-fAaaa9bf3Bu4SAGyNqre_OSUQZ9YuE" + }, + { + "current_key": "AIzaSyDUxoSE0qe0emKM1MCUA4Y_EiittrWi_EM" + }, + { + "current_key": "AIzaSyAysaL8XPHO7STS3kOVGqM-0F0n3_09Sws" + }, + { + "current_key": "AIzaSyDadOjxdJsBIt-hDrEOG90kMDNxSG2RUzU" + }, + { + "current_key": "AIzaSyA-MIPQ2JhVqtewf3nx2MJHwIdniVzuoaI" + }, + { + "current_key": "AIzaSyAPlSHAPRYXJQSOjpw1dlvOaQaBOdLBJpg" + }, + { + "current_key": "AIzaSyBLWyW5ih6FlpRN0ec_62HVwMFcrLw6Tic" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + }, + { + "client_info": { + "mobilesdk_app_id": "1:629309347341:android:a93714e4fd084096", + "android_client_info": { + "package_name": "com.yadu.myfirestore" + } + }, + "oauth_client": [ + { + "client_id": "629309347341-hcrk3tspevuiie8bnnigejbm5m0ccfi9.apps.googleusercontent.com", + "client_type": 1, + "android_info": { + "package_name": "com.yadu.myfirestore", + "certificate_hash": "124b531f404f1deb57c5e5d45e19a8b89a0fb4be" + } + }, + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyB4uUMb8N-u4MhmY5ChEg-PDMgavWpqxeU" + }, + { + "current_key": "AIzaSyDorbLzXasW-n7sSc-5rGcx1-SKVGsru9c" + }, + { + "current_key": "AIzaSyDdJpvBFUO_osfPn3Yuj_vEG9VdjmEg0IY" + }, + { + "current_key": "AIzaSyDutR97NK5gRLdW839IpizIWj_fXrIUtNI" + }, + { + "current_key": "AIzaSyAIPnRocVJOWDTGWaQgVaSMU7FLRcbMHxk" + }, + { + "current_key": "AIzaSyAqNEuTX8MW9ySEbD-cmxg68dVho0n_3fU" + }, + { + "current_key": "AIzaSyDv_ajWs5TIdgiNwhcjnUSjpi-WveoeNFo" + }, + { + "current_key": "AIzaSyDT-fAaaa9bf3Bu4SAGyNqre_OSUQZ9YuE" + }, + { + "current_key": "AIzaSyDUxoSE0qe0emKM1MCUA4Y_EiittrWi_EM" + }, + { + "current_key": "AIzaSyAysaL8XPHO7STS3kOVGqM-0F0n3_09Sws" + }, + { + "current_key": "AIzaSyDadOjxdJsBIt-hDrEOG90kMDNxSG2RUzU" + }, + { + "current_key": "AIzaSyA-MIPQ2JhVqtewf3nx2MJHwIdniVzuoaI" + }, + { + "current_key": "AIzaSyAPlSHAPRYXJQSOjpw1dlvOaQaBOdLBJpg" + }, + { + "current_key": "AIzaSyBLWyW5ih6FlpRN0ec_62HVwMFcrLw6Tic" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + }, + { + "client_info": { + "mobilesdk_app_id": "1:629309347341:android:deb177852b2bbf25", + "android_client_info": { + "package_name": "com.yadu.ychat" + } + }, + "oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyB4uUMb8N-u4MhmY5ChEg-PDMgavWpqxeU" + }, + { + "current_key": "AIzaSyDorbLzXasW-n7sSc-5rGcx1-SKVGsru9c" + }, + { + "current_key": "AIzaSyDdJpvBFUO_osfPn3Yuj_vEG9VdjmEg0IY" + }, + { + "current_key": "AIzaSyDutR97NK5gRLdW839IpizIWj_fXrIUtNI" + }, + { + "current_key": "AIzaSyAIPnRocVJOWDTGWaQgVaSMU7FLRcbMHxk" + }, + { + "current_key": "AIzaSyAqNEuTX8MW9ySEbD-cmxg68dVho0n_3fU" + }, + { + "current_key": "AIzaSyDv_ajWs5TIdgiNwhcjnUSjpi-WveoeNFo" + }, + { + "current_key": "AIzaSyDT-fAaaa9bf3Bu4SAGyNqre_OSUQZ9YuE" + }, + { + "current_key": "AIzaSyDUxoSE0qe0emKM1MCUA4Y_EiittrWi_EM" + }, + { + "current_key": "AIzaSyAysaL8XPHO7STS3kOVGqM-0F0n3_09Sws" + }, + { + "current_key": "AIzaSyDadOjxdJsBIt-hDrEOG90kMDNxSG2RUzU" + }, + { + "current_key": "AIzaSyA-MIPQ2JhVqtewf3nx2MJHwIdniVzuoaI" + }, + { + "current_key": "AIzaSyAPlSHAPRYXJQSOjpw1dlvOaQaBOdLBJpg" + }, + { + "current_key": "AIzaSyBLWyW5ih6FlpRN0ec_62HVwMFcrLw6Tic" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + }, + { + "client_info": { + "mobilesdk_app_id": "1:629309347341:android:66e3f94d320f540c", + "android_client_info": { + "package_name": "cpm.com.audit" + } + }, + "oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyB4uUMb8N-u4MhmY5ChEg-PDMgavWpqxeU" + }, + { + "current_key": "AIzaSyDorbLzXasW-n7sSc-5rGcx1-SKVGsru9c" + }, + { + "current_key": "AIzaSyDdJpvBFUO_osfPn3Yuj_vEG9VdjmEg0IY" + }, + { + "current_key": "AIzaSyDutR97NK5gRLdW839IpizIWj_fXrIUtNI" + }, + { + "current_key": "AIzaSyAIPnRocVJOWDTGWaQgVaSMU7FLRcbMHxk" + }, + { + "current_key": "AIzaSyAqNEuTX8MW9ySEbD-cmxg68dVho0n_3fU" + }, + { + "current_key": "AIzaSyDv_ajWs5TIdgiNwhcjnUSjpi-WveoeNFo" + }, + { + "current_key": "AIzaSyDT-fAaaa9bf3Bu4SAGyNqre_OSUQZ9YuE" + }, + { + "current_key": "AIzaSyDUxoSE0qe0emKM1MCUA4Y_EiittrWi_EM" + }, + { + "current_key": "AIzaSyAysaL8XPHO7STS3kOVGqM-0F0n3_09Sws" + }, + { + "current_key": "AIzaSyDadOjxdJsBIt-hDrEOG90kMDNxSG2RUzU" + }, + { + "current_key": "AIzaSyA-MIPQ2JhVqtewf3nx2MJHwIdniVzuoaI" + }, + { + "current_key": "AIzaSyAPlSHAPRYXJQSOjpw1dlvOaQaBOdLBJpg" + }, + { + "current_key": "AIzaSyBLWyW5ih6FlpRN0ec_62HVwMFcrLw6Tic" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + }, + { + "client_info": { + "mobilesdk_app_id": "1:629309347341:android:5ca821c2e7144dce", + "android_client_info": { + "package_name": "cpm.com.bosch" + } + }, + "oauth_client": [ + { + "client_id": "629309347341-h1cfq3qg648nuh2v8aakjilmbm3ljkr0.apps.googleusercontent.com", + "client_type": 1, + "android_info": { + "package_name": "cpm.com.bosch", + "certificate_hash": "2c33c124346971cca5ed7da54ee42779822d5bfe" + } + }, + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyB4uUMb8N-u4MhmY5ChEg-PDMgavWpqxeU" + }, + { + "current_key": "AIzaSyDorbLzXasW-n7sSc-5rGcx1-SKVGsru9c" + }, + { + "current_key": "AIzaSyDdJpvBFUO_osfPn3Yuj_vEG9VdjmEg0IY" + }, + { + "current_key": "AIzaSyDutR97NK5gRLdW839IpizIWj_fXrIUtNI" + }, + { + "current_key": "AIzaSyAIPnRocVJOWDTGWaQgVaSMU7FLRcbMHxk" + }, + { + "current_key": "AIzaSyAqNEuTX8MW9ySEbD-cmxg68dVho0n_3fU" + }, + { + "current_key": "AIzaSyDv_ajWs5TIdgiNwhcjnUSjpi-WveoeNFo" + }, + { + "current_key": "AIzaSyDT-fAaaa9bf3Bu4SAGyNqre_OSUQZ9YuE" + }, + { + "current_key": "AIzaSyDUxoSE0qe0emKM1MCUA4Y_EiittrWi_EM" + }, + { + "current_key": "AIzaSyAysaL8XPHO7STS3kOVGqM-0F0n3_09Sws" + }, + { + "current_key": "AIzaSyDadOjxdJsBIt-hDrEOG90kMDNxSG2RUzU" + }, + { + "current_key": "AIzaSyA-MIPQ2JhVqtewf3nx2MJHwIdniVzuoaI" + }, + { + "current_key": "AIzaSyAPlSHAPRYXJQSOjpw1dlvOaQaBOdLBJpg" + }, + { + "current_key": "AIzaSyBLWyW5ih6FlpRN0ec_62HVwMFcrLw6Tic" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + }, + { + "client_info": { + "mobilesdk_app_id": "1:629309347341:android:b20085c2d5609ea237a744", + "android_client_info": { + "package_name": "cpm.com.boschtactical" + } + }, + "oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyB4uUMb8N-u4MhmY5ChEg-PDMgavWpqxeU" + }, + { + "current_key": "AIzaSyDorbLzXasW-n7sSc-5rGcx1-SKVGsru9c" + }, + { + "current_key": "AIzaSyDdJpvBFUO_osfPn3Yuj_vEG9VdjmEg0IY" + }, + { + "current_key": "AIzaSyDutR97NK5gRLdW839IpizIWj_fXrIUtNI" + }, + { + "current_key": "AIzaSyAIPnRocVJOWDTGWaQgVaSMU7FLRcbMHxk" + }, + { + "current_key": "AIzaSyAqNEuTX8MW9ySEbD-cmxg68dVho0n_3fU" + }, + { + "current_key": "AIzaSyDv_ajWs5TIdgiNwhcjnUSjpi-WveoeNFo" + }, + { + "current_key": "AIzaSyDT-fAaaa9bf3Bu4SAGyNqre_OSUQZ9YuE" + }, + { + "current_key": "AIzaSyDUxoSE0qe0emKM1MCUA4Y_EiittrWi_EM" + }, + { + "current_key": "AIzaSyAysaL8XPHO7STS3kOVGqM-0F0n3_09Sws" + }, + { + "current_key": "AIzaSyDadOjxdJsBIt-hDrEOG90kMDNxSG2RUzU" + }, + { + "current_key": "AIzaSyA-MIPQ2JhVqtewf3nx2MJHwIdniVzuoaI" + }, + { + "current_key": "AIzaSyAPlSHAPRYXJQSOjpw1dlvOaQaBOdLBJpg" + }, + { + "current_key": "AIzaSyBLWyW5ih6FlpRN0ec_62HVwMFcrLw6Tic" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + }, + { + "client_info": { + "mobilesdk_app_id": "1:629309347341:android:0228cd3efb7ae104", + "android_client_info": { + "package_name": "cpm.com.cavinkare" + } + }, + "oauth_client": [ + { + "client_id": "629309347341-638f0lnr8gn6mpvbkplvm0it0bgbm97t.apps.googleusercontent.com", + "client_type": 1, + "android_info": { + "package_name": "cpm.com.cavinkare", + "certificate_hash": "2c33c124346971cca5ed7da54ee42779822d5bfe" + } + }, + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyB4uUMb8N-u4MhmY5ChEg-PDMgavWpqxeU" + }, + { + "current_key": "AIzaSyDorbLzXasW-n7sSc-5rGcx1-SKVGsru9c" + }, + { + "current_key": "AIzaSyDdJpvBFUO_osfPn3Yuj_vEG9VdjmEg0IY" + }, + { + "current_key": "AIzaSyDutR97NK5gRLdW839IpizIWj_fXrIUtNI" + }, + { + "current_key": "AIzaSyAIPnRocVJOWDTGWaQgVaSMU7FLRcbMHxk" + }, + { + "current_key": "AIzaSyAqNEuTX8MW9ySEbD-cmxg68dVho0n_3fU" + }, + { + "current_key": "AIzaSyDv_ajWs5TIdgiNwhcjnUSjpi-WveoeNFo" + }, + { + "current_key": "AIzaSyDT-fAaaa9bf3Bu4SAGyNqre_OSUQZ9YuE" + }, + { + "current_key": "AIzaSyDUxoSE0qe0emKM1MCUA4Y_EiittrWi_EM" + }, + { + "current_key": "AIzaSyAysaL8XPHO7STS3kOVGqM-0F0n3_09Sws" + }, + { + "current_key": "AIzaSyDadOjxdJsBIt-hDrEOG90kMDNxSG2RUzU" + }, + { + "current_key": "AIzaSyA-MIPQ2JhVqtewf3nx2MJHwIdniVzuoaI" + }, + { + "current_key": "AIzaSyAPlSHAPRYXJQSOjpw1dlvOaQaBOdLBJpg" + }, + { + "current_key": "AIzaSyBLWyW5ih6FlpRN0ec_62HVwMFcrLw6Tic" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + }, + { + "client_info": { + "mobilesdk_app_id": "1:629309347341:android:a22154109918d791", + "android_client_info": { + "package_name": "cpm.com.cipla" + } + }, + "oauth_client": [ + { + "client_id": "629309347341-e04189mbhrkv2rld0m09ue7v9722ghth.apps.googleusercontent.com", + "client_type": 1, + "android_info": { + "package_name": "cpm.com.cipla", + "certificate_hash": "e15d7a8b1dd92a8d6c05090e0604c12d3063fe57" + } + }, + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyB4uUMb8N-u4MhmY5ChEg-PDMgavWpqxeU" + }, + { + "current_key": "AIzaSyDorbLzXasW-n7sSc-5rGcx1-SKVGsru9c" + }, + { + "current_key": "AIzaSyDdJpvBFUO_osfPn3Yuj_vEG9VdjmEg0IY" + }, + { + "current_key": "AIzaSyDutR97NK5gRLdW839IpizIWj_fXrIUtNI" + }, + { + "current_key": "AIzaSyAIPnRocVJOWDTGWaQgVaSMU7FLRcbMHxk" + }, + { + "current_key": "AIzaSyAqNEuTX8MW9ySEbD-cmxg68dVho0n_3fU" + }, + { + "current_key": "AIzaSyDv_ajWs5TIdgiNwhcjnUSjpi-WveoeNFo" + }, + { + "current_key": "AIzaSyDT-fAaaa9bf3Bu4SAGyNqre_OSUQZ9YuE" + }, + { + "current_key": "AIzaSyDUxoSE0qe0emKM1MCUA4Y_EiittrWi_EM" + }, + { + "current_key": "AIzaSyAysaL8XPHO7STS3kOVGqM-0F0n3_09Sws" + }, + { + "current_key": "AIzaSyDadOjxdJsBIt-hDrEOG90kMDNxSG2RUzU" + }, + { + "current_key": "AIzaSyA-MIPQ2JhVqtewf3nx2MJHwIdniVzuoaI" + }, + { + "current_key": "AIzaSyAPlSHAPRYXJQSOjpw1dlvOaQaBOdLBJpg" + }, + { + "current_key": "AIzaSyBLWyW5ih6FlpRN0ec_62HVwMFcrLw6Tic" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + }, + { + "client_info": { + "mobilesdk_app_id": "1:629309347341:android:de3cc00c9ce78a7c", + "android_client_info": { + "package_name": "cpm.com.gskgttactical" + } + }, + "oauth_client": [ + { + "client_id": "629309347341-6a401oio4e9898cr4bv3bfdcfr47v84l.apps.googleusercontent.com", + "client_type": 1, + "android_info": { + "package_name": "cpm.com.gskgttactical", + "certificate_hash": "2c33c124346971cca5ed7da54ee42779822d5bfe" + } + }, + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyB4uUMb8N-u4MhmY5ChEg-PDMgavWpqxeU" + }, + { + "current_key": "AIzaSyDorbLzXasW-n7sSc-5rGcx1-SKVGsru9c" + }, + { + "current_key": "AIzaSyDdJpvBFUO_osfPn3Yuj_vEG9VdjmEg0IY" + }, + { + "current_key": "AIzaSyDutR97NK5gRLdW839IpizIWj_fXrIUtNI" + }, + { + "current_key": "AIzaSyAIPnRocVJOWDTGWaQgVaSMU7FLRcbMHxk" + }, + { + "current_key": "AIzaSyAqNEuTX8MW9ySEbD-cmxg68dVho0n_3fU" + }, + { + "current_key": "AIzaSyDv_ajWs5TIdgiNwhcjnUSjpi-WveoeNFo" + }, + { + "current_key": "AIzaSyDT-fAaaa9bf3Bu4SAGyNqre_OSUQZ9YuE" + }, + { + "current_key": "AIzaSyDUxoSE0qe0emKM1MCUA4Y_EiittrWi_EM" + }, + { + "current_key": "AIzaSyAysaL8XPHO7STS3kOVGqM-0F0n3_09Sws" + }, + { + "current_key": "AIzaSyDadOjxdJsBIt-hDrEOG90kMDNxSG2RUzU" + }, + { + "current_key": "AIzaSyA-MIPQ2JhVqtewf3nx2MJHwIdniVzuoaI" + }, + { + "current_key": "AIzaSyAPlSHAPRYXJQSOjpw1dlvOaQaBOdLBJpg" + }, + { + "current_key": "AIzaSyBLWyW5ih6FlpRN0ec_62HVwMFcrLw6Tic" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + }, + { + "client_info": { + "mobilesdk_app_id": "1:629309347341:android:fc7344f5ebbccd0d", + "android_client_info": { + "package_name": "cpm.com.gskmtorange" + } + }, + "oauth_client": [ + { + "client_id": "629309347341-8uvuq4m1r17e40j69djksdjlpnj75ofk.apps.googleusercontent.com", + "client_type": 1, + "android_info": { + "package_name": "cpm.com.gskmtorange", + "certificate_hash": "124b531f404f1deb57c5e5d45e19a8b89a0fb4be" + } + }, + { + "client_id": "629309347341-9vle41ingne4d8itn8cf8ge4gqg3nth4.apps.googleusercontent.com", + "client_type": 1, + "android_info": { + "package_name": "cpm.com.gskmtorange", + "certificate_hash": "f4469c047dfd3b33b1a34b8c38bd770cd43698e5" + } + }, + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyB4uUMb8N-u4MhmY5ChEg-PDMgavWpqxeU" + }, + { + "current_key": "AIzaSyDorbLzXasW-n7sSc-5rGcx1-SKVGsru9c" + }, + { + "current_key": "AIzaSyDdJpvBFUO_osfPn3Yuj_vEG9VdjmEg0IY" + }, + { + "current_key": "AIzaSyDutR97NK5gRLdW839IpizIWj_fXrIUtNI" + }, + { + "current_key": "AIzaSyAIPnRocVJOWDTGWaQgVaSMU7FLRcbMHxk" + }, + { + "current_key": "AIzaSyAqNEuTX8MW9ySEbD-cmxg68dVho0n_3fU" + }, + { + "current_key": "AIzaSyDv_ajWs5TIdgiNwhcjnUSjpi-WveoeNFo" + }, + { + "current_key": "AIzaSyDT-fAaaa9bf3Bu4SAGyNqre_OSUQZ9YuE" + }, + { + "current_key": "AIzaSyDUxoSE0qe0emKM1MCUA4Y_EiittrWi_EM" + }, + { + "current_key": "AIzaSyAysaL8XPHO7STS3kOVGqM-0F0n3_09Sws" + }, + { + "current_key": "AIzaSyDadOjxdJsBIt-hDrEOG90kMDNxSG2RUzU" + }, + { + "current_key": "AIzaSyA-MIPQ2JhVqtewf3nx2MJHwIdniVzuoaI" + }, + { + "current_key": "AIzaSyAPlSHAPRYXJQSOjpw1dlvOaQaBOdLBJpg" + }, + { + "current_key": "AIzaSyBLWyW5ih6FlpRN0ec_62HVwMFcrLw6Tic" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + }, + { + "client_info": { + "mobilesdk_app_id": "1:629309347341:android:c5511f6ea520fc55", + "android_client_info": { + "package_name": "cpm.com.hulcnc" + } + }, + "oauth_client": [ + { + "client_id": "629309347341-vv7rlenc93glvma9umknjbmo52m1856i.apps.googleusercontent.com", + "client_type": 1, + "android_info": { + "package_name": "cpm.com.hulcnc", + "certificate_hash": "e7860cb7fda70fb93d9bb372f158ce2303d59465" + } + }, + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyB4uUMb8N-u4MhmY5ChEg-PDMgavWpqxeU" + }, + { + "current_key": "AIzaSyDorbLzXasW-n7sSc-5rGcx1-SKVGsru9c" + }, + { + "current_key": "AIzaSyDdJpvBFUO_osfPn3Yuj_vEG9VdjmEg0IY" + }, + { + "current_key": "AIzaSyDutR97NK5gRLdW839IpizIWj_fXrIUtNI" + }, + { + "current_key": "AIzaSyAIPnRocVJOWDTGWaQgVaSMU7FLRcbMHxk" + }, + { + "current_key": "AIzaSyAqNEuTX8MW9ySEbD-cmxg68dVho0n_3fU" + }, + { + "current_key": "AIzaSyDv_ajWs5TIdgiNwhcjnUSjpi-WveoeNFo" + }, + { + "current_key": "AIzaSyDT-fAaaa9bf3Bu4SAGyNqre_OSUQZ9YuE" + }, + { + "current_key": "AIzaSyDUxoSE0qe0emKM1MCUA4Y_EiittrWi_EM" + }, + { + "current_key": "AIzaSyAysaL8XPHO7STS3kOVGqM-0F0n3_09Sws" + }, + { + "current_key": "AIzaSyDadOjxdJsBIt-hDrEOG90kMDNxSG2RUzU" + }, + { + "current_key": "AIzaSyA-MIPQ2JhVqtewf3nx2MJHwIdniVzuoaI" + }, + { + "current_key": "AIzaSyAPlSHAPRYXJQSOjpw1dlvOaQaBOdLBJpg" + }, + { + "current_key": "AIzaSyBLWyW5ih6FlpRN0ec_62HVwMFcrLw6Tic" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + }, + { + "client_info": { + "mobilesdk_app_id": "1:629309347341:android:a71c1fa09957cdab", + "android_client_info": { + "package_name": "cpm.com.intelre" + } + }, + "oauth_client": [ + { + "client_id": "629309347341-8irkpjkupn1iqa14o00fa8io09bnrni1.apps.googleusercontent.com", + "client_type": 1, + "android_info": { + "package_name": "cpm.com.intelre", + "certificate_hash": "2c33c124346971cca5ed7da54ee42779822d5bfe" + } + }, + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyB4uUMb8N-u4MhmY5ChEg-PDMgavWpqxeU" + }, + { + "current_key": "AIzaSyDorbLzXasW-n7sSc-5rGcx1-SKVGsru9c" + }, + { + "current_key": "AIzaSyDdJpvBFUO_osfPn3Yuj_vEG9VdjmEg0IY" + }, + { + "current_key": "AIzaSyDutR97NK5gRLdW839IpizIWj_fXrIUtNI" + }, + { + "current_key": "AIzaSyAIPnRocVJOWDTGWaQgVaSMU7FLRcbMHxk" + }, + { + "current_key": "AIzaSyAqNEuTX8MW9ySEbD-cmxg68dVho0n_3fU" + }, + { + "current_key": "AIzaSyDv_ajWs5TIdgiNwhcjnUSjpi-WveoeNFo" + }, + { + "current_key": "AIzaSyDT-fAaaa9bf3Bu4SAGyNqre_OSUQZ9YuE" + }, + { + "current_key": "AIzaSyDUxoSE0qe0emKM1MCUA4Y_EiittrWi_EM" + }, + { + "current_key": "AIzaSyAysaL8XPHO7STS3kOVGqM-0F0n3_09Sws" + }, + { + "current_key": "AIzaSyDadOjxdJsBIt-hDrEOG90kMDNxSG2RUzU" + }, + { + "current_key": "AIzaSyA-MIPQ2JhVqtewf3nx2MJHwIdniVzuoaI" + }, + { + "current_key": "AIzaSyAPlSHAPRYXJQSOjpw1dlvOaQaBOdLBJpg" + }, + { + "current_key": "AIzaSyBLWyW5ih6FlpRN0ec_62HVwMFcrLw6Tic" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + }, + { + "client_info": { + "mobilesdk_app_id": "1:629309347341:android:9a64baa25def3f59", + "android_client_info": { + "package_name": "cpm.com.lorealbapitch" + } + }, + "oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyB4uUMb8N-u4MhmY5ChEg-PDMgavWpqxeU" + }, + { + "current_key": "AIzaSyDorbLzXasW-n7sSc-5rGcx1-SKVGsru9c" + }, + { + "current_key": "AIzaSyDdJpvBFUO_osfPn3Yuj_vEG9VdjmEg0IY" + }, + { + "current_key": "AIzaSyDutR97NK5gRLdW839IpizIWj_fXrIUtNI" + }, + { + "current_key": "AIzaSyAIPnRocVJOWDTGWaQgVaSMU7FLRcbMHxk" + }, + { + "current_key": "AIzaSyAqNEuTX8MW9ySEbD-cmxg68dVho0n_3fU" + }, + { + "current_key": "AIzaSyDv_ajWs5TIdgiNwhcjnUSjpi-WveoeNFo" + }, + { + "current_key": "AIzaSyDT-fAaaa9bf3Bu4SAGyNqre_OSUQZ9YuE" + }, + { + "current_key": "AIzaSyDUxoSE0qe0emKM1MCUA4Y_EiittrWi_EM" + }, + { + "current_key": "AIzaSyAysaL8XPHO7STS3kOVGqM-0F0n3_09Sws" + }, + { + "current_key": "AIzaSyDadOjxdJsBIt-hDrEOG90kMDNxSG2RUzU" + }, + { + "current_key": "AIzaSyA-MIPQ2JhVqtewf3nx2MJHwIdniVzuoaI" + }, + { + "current_key": "AIzaSyAPlSHAPRYXJQSOjpw1dlvOaQaBOdLBJpg" + }, + { + "current_key": "AIzaSyBLWyW5ih6FlpRN0ec_62HVwMFcrLw6Tic" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + }, + { + "client_info": { + "mobilesdk_app_id": "1:629309347341:android:3f252ef45a3b9577", + "android_client_info": { + "package_name": "quaker.cpm.com.quakeroats" + } + }, + "oauth_client": [ + { + "client_id": "629309347341-bp6hs057n4mtfc9ntt6jlbh5c9vej7a0.apps.googleusercontent.com", + "client_type": 1, + "android_info": { + "package_name": "quaker.cpm.com.quakeroats", + "certificate_hash": "2c33c124346971cca5ed7da54ee42779822d5bfe" + } + }, + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyB4uUMb8N-u4MhmY5ChEg-PDMgavWpqxeU" + }, + { + "current_key": "AIzaSyDorbLzXasW-n7sSc-5rGcx1-SKVGsru9c" + }, + { + "current_key": "AIzaSyDdJpvBFUO_osfPn3Yuj_vEG9VdjmEg0IY" + }, + { + "current_key": "AIzaSyDutR97NK5gRLdW839IpizIWj_fXrIUtNI" + }, + { + "current_key": "AIzaSyAIPnRocVJOWDTGWaQgVaSMU7FLRcbMHxk" + }, + { + "current_key": "AIzaSyAqNEuTX8MW9ySEbD-cmxg68dVho0n_3fU" + }, + { + "current_key": "AIzaSyDv_ajWs5TIdgiNwhcjnUSjpi-WveoeNFo" + }, + { + "current_key": "AIzaSyDT-fAaaa9bf3Bu4SAGyNqre_OSUQZ9YuE" + }, + { + "current_key": "AIzaSyDUxoSE0qe0emKM1MCUA4Y_EiittrWi_EM" + }, + { + "current_key": "AIzaSyAysaL8XPHO7STS3kOVGqM-0F0n3_09Sws" + }, + { + "current_key": "AIzaSyDadOjxdJsBIt-hDrEOG90kMDNxSG2RUzU" + }, + { + "current_key": "AIzaSyA-MIPQ2JhVqtewf3nx2MJHwIdniVzuoaI" + }, + { + "current_key": "AIzaSyAPlSHAPRYXJQSOjpw1dlvOaQaBOdLBJpg" + }, + { + "current_key": "AIzaSyBLWyW5ih6FlpRN0ec_62HVwMFcrLw6Tic" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "629309347341-j8l60e4hivqtaddronejlrq2njb5nk9f.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + } + ], + "configuration_version": "1" +} \ No newline at end of file diff --git a/app/libs/donutprogress-1.2.0.aar b/app/libs/donutprogress-1.2.0.aar new file mode 100644 index 0000000..9b40653 Binary files /dev/null and b/app/libs/donutprogress-1.2.0.aar differ diff --git a/app/libs/hoinsdk.jar b/app/libs/hoinsdk.jar new file mode 100644 index 0000000..27bcd79 Binary files /dev/null and b/app/libs/hoinsdk.jar differ diff --git a/app/libs/tscsdk.jar b/app/libs/tscsdk.jar new file mode 100644 index 0000000..ed07c6b Binary files /dev/null and b/app/libs/tscsdk.jar differ diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro new file mode 100644 index 0000000..295d386 --- /dev/null +++ b/app/proguard-rules.pro @@ -0,0 +1,99 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile + + +# Firebase Crashlytics +-keep class com.google.firebase.** { *; } +-dontwarn com.google.firebase.** + +# Firebase Analytics +-keep class com.google.firebase.analytics.** { *; } +-dontwarn com.google.firebase.analytics.** + +# Firebase Messaging +-keep class com.google.firebase.messaging.** { *; } +-dontwarn com.google.firebase.messaging.** + +# Firebase Firestore (if used) +-keep class com.google.firebase.firestore.** { *; } +-dontwarn com.google.firebase.firestore.** + +# Firebase Auth (if used) +-keep class com.google.firebase.auth.** { *; } +-dontwarn com.google.firebase.auth.** + +# Retrofit +-keep class retrofit2.** { *; } +-dontwarn retrofit2.** + +# Gson (used by Retrofit) +-keep class com.google.gson.** { *; } +-dontwarn com.google.gson.** + +# Glide +-keep class com.bumptech.glide.** { *; } +-dontwarn com.bumptech.glide.** + +# Picasso +-keep class com.squareup.picasso.** { *; } +-dontwarn com.squareup.picasso.** + +# Gson library +-keep class com.google.gson.stream.** { *; } +-dontwarn com.google.gson.stream.** + +# AndroidX +-keep class androidx.** { *; } +-dontwarn androidx.** + +# CircleImageView +-keep class de.hdodenhof.circleimageview.** { *; } +-dontwarn de.hdodenhof.circleimageview.** + +# Multidex +-keep class androidx.multidex.** { *; } +-dontwarn androidx.multidex.** + +# For Kotlin extensions and reflection +-keepclassmembers class * extends java.lang.Exception { + (...); +} + +# For keeping specific classes with reflection in libraries like Firebase +-keep class com.google.firebase.** { *; } + +# Exclude the following logs for shrinking +-keep class android.util.Log { *; } +-dontwarn android.util.Log + +# Keep annotations (needed for Retrofit, Gson, etc.) +-keep @interface * { *; } + + +-assumenosideeffects class android.util.Log { + public static *** d(...); + public static *** v(...); + public static *** i(...); + public static *** w(...); + public static *** e(...); +} + diff --git a/app/release/Loreal-Ba-LP-T-3.apk b/app/release/Loreal-Ba-LP-T-3.apk new file mode 100644 index 0000000..daa18f2 Binary files /dev/null and b/app/release/Loreal-Ba-LP-T-3.apk differ diff --git a/app/release/output-metadata.json b/app/release/output-metadata.json new file mode 100644 index 0000000..c7720d5 --- /dev/null +++ b/app/release/output-metadata.json @@ -0,0 +1,20 @@ +{ + "version": 3, + "artifactType": { + "type": "APK", + "kind": "Directory" + }, + "applicationId": "com.cpm.lorealbaautomation", + "variantName": "release", + "elements": [ + { + "type": "SINGLE", + "filters": [], + "attributes": [], + "versionCode": 20, + "versionName": "2.9", + "outputFile": "app-release.apk" + } + ], + "elementType": "File" +} \ No newline at end of file diff --git a/app/src/androidTest/java/com/lorealbaautomation/ExampleInstrumentedTest.java b/app/src/androidTest/java/com/lorealbaautomation/ExampleInstrumentedTest.java new file mode 100644 index 0000000..c62f0cd --- /dev/null +++ b/app/src/androidTest/java/com/lorealbaautomation/ExampleInstrumentedTest.java @@ -0,0 +1,26 @@ +package com.cpm.lorealbaautomation; + +import android.content.Context; +import androidx.test.platform.app.InstrumentationRegistry; +import androidx.test.ext.junit.runners.AndroidJUnit4; + +import org.junit.Test; +import org.junit.runner.RunWith; + +import static org.junit.Assert.*; + +/** + * Instrumented test, which will execute on an Android device. + * + * @see Testing documentation + */ +@RunWith(AndroidJUnit4.class) +public class ExampleInstrumentedTest { + @Test + public void useAppContext() { + // Context of the app under test. + Context appContext = InstrumentationRegistry.getInstrumentation().getContext(); + + assertEquals("com.cpm.lorealbaautomation", appContext.getPackageName()); + } +} diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..5a9ae70 --- /dev/null +++ b/app/src/main/AndroidManifest.xml @@ -0,0 +1,688 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/java/com/cpm/lorealbaautomation/AutoUpdateActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/AutoUpdateActivity.java new file mode 100644 index 0000000..710fad3 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/AutoUpdateActivity.java @@ -0,0 +1,174 @@ +package com.cpm.lorealbaautomation; + +import android.annotation.SuppressLint; +import android.app.Activity; +import android.app.AlertDialog; +import android.app.Dialog; +import android.content.Context; +import android.content.Intent; +import android.content.pm.PackageManager; +import android.graphics.drawable.ColorDrawable; +import android.net.Uri; +import android.os.AsyncTask; +import android.os.Build; +import android.os.Bundle; +import androidx.core.content.FileProvider; +import androidx.appcompat.app.AppCompatActivity; +import android.view.Window; +import android.widget.ProgressBar; +import android.widget.TextView; +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.constant.AlertandMessages; +import com.cpm.lorealbaautomation.constant.CommonString; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.URL; +import java.text.DecimalFormat; + +public class AutoUpdateActivity extends AppCompatActivity { + private static final int PERMISSION_ALL = 99; + private Dialog dialog; + private ProgressBar pb; + private TextView percentage, message; + private String path = ""; + Lorealba_Database db; + Context context; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_auto_update); + context = this; + db = new Lorealba_Database(context); + db.open(); + Intent intent = getIntent(); + path = intent.getStringExtra(CommonString.KEY_PATH); + AlertDialog.Builder builder = new AlertDialog.Builder(context); + builder.setTitle(getString(R.string.parinaam)); + builder.setMessage(getString(R.string.new_update_available)) + .setCancelable(false) + .setPositiveButton(R.string.ok, (dialog, id) -> new DownloadTask(AutoUpdateActivity.this).execute()); + AlertDialog alert = builder.create(); + alert.show(); + } + + private class DownloadTask extends AsyncTask { + private final Context context; + + DownloadTask(Context context) { + this.context = context; + } + + @SuppressWarnings("ConstantConditions") + @Override + protected void onPreExecute() { + super.onPreExecute(); + dialog = new Dialog(context); + dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); + dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT)); + dialog.setContentView(R.layout.custom_dialog_progress); + pb = (ProgressBar) dialog.findViewById(R.id.progressBar1); + percentage = (TextView) dialog.findViewById(R.id.percentage); + message = (TextView) dialog.findViewById(R.id.message); + dialog.setCancelable(false); + dialog.show(); + } + + @Override + protected String doInBackground(Void... params) { + try { + Data data = new Data(); + data.name = "Downloading Application"; + publishProgress(data); + String versionCode = getPackageManager().getPackageInfo(getPackageName(), 0).versionName; + data.name = "Upgrading Version : " + versionCode; + publishProgress(data); + // download application + URL url = new URL(path); + HttpURLConnection c = (HttpURLConnection) url.openConnection(); + c.setRequestMethod("GET"); + c.getResponseCode(); + c.connect(); + int length = c.getContentLength(); + String size = new DecimalFormat("##.##").format((double) length / 1024 / 1024) + " MB"; + String PATH = CommonString.getLorealBaApkFolder(context); + File outputFile = new File(PATH, "app.apk"); + FileOutputStream fos = new FileOutputStream(outputFile); + InputStream is = c.getInputStream(); + int bytes = 0; + byte[] buffer = new byte[1024]; + int len1; + while ((len1 = is.read(buffer)) != -1) { + bytes = (bytes + len1); + String s = new DecimalFormat("##.##").format((double) (bytes / 1024) / 1024); + String p = s.length() == 3 ? s + "0" : s; + p = p + " MB"; + data.value = (int) (((double) bytes) / length * 100); + data.name = "Download " + p + "/" + size; + publishProgress(data); + fos.write(buffer, 0, len1); + } + fos.close(); + is.close(); + return CommonString.KEY_SUCCESS; + } catch (PackageManager.NameNotFoundException | MalformedURLException e) { + // TODO Auto-generated catch block + runOnUiThread(() -> { + // TODO Auto-generated method stub + AlertandMessages.showAlert((Activity) context, CommonString.MESSAGE_EXCEPTION + "\n" + e.getLocalizedMessage(), true); + }); + } catch (IOException e) { + runOnUiThread(() -> { + // TODO Auto-generated method stub + AlertandMessages.showAlert((Activity) context, CommonString.MESSAGE_SOCKETEXCEPTION + "\n" + e.getLocalizedMessage(), true); + }); + } catch (Exception e) { + runOnUiThread(() -> AlertandMessages.showAlert((Activity) context, CommonString.MESSAGE_EXCEPTION + "\n" + e.getLocalizedMessage(), true)); + } + return ""; + } + + @SuppressLint("SetTextI18n") + @Override + protected void onProgressUpdate(Data... values) { + // TODO Auto-generated method stub + pb.setProgress(values[0].value); + percentage.setText(values[0].value + "%"); + message.setText(values[0].name); + } + + @Override + protected void onPostExecute(String result) { + super.onPostExecute(result); + dialog.dismiss(); + if (result.equalsIgnoreCase(CommonString.KEY_SUCCESS)) { + File toInstall = new File(CommonString.getLorealBaApkFolder(context) + "app.apk"); + Uri apkUri; + Intent intent; + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { + apkUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".fileprovider", toInstall); + intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); + intent.setData(apkUri); + intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); + } else { + apkUri = Uri.fromFile(toInstall); + intent = new Intent(Intent.ACTION_VIEW); + intent.setDataAndType(apkUri, "application/vnd.android.package-archive"); + intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + } + startActivity(intent); + finish(); + } + } + } + + class Data { + int value; + String name; + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/CounterLoginActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/CounterLoginActivity.java new file mode 100644 index 0000000..ebe42a7 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/CounterLoginActivity.java @@ -0,0 +1,1068 @@ +package com.cpm.lorealbaautomation; + +import static com.cpm.lorealbaautomation.constant.CommonFunctions.checkincomplete_upload_data; + +import android.Manifest; +import android.annotation.SuppressLint; +import android.app.Activity; +import android.app.AlertDialog; +import android.app.DatePickerDialog; +import android.app.Dialog; +import android.app.ProgressDialog; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.IntentSender; +import android.content.SharedPreferences; +import android.content.pm.PackageInfo; +import android.content.pm.PackageManager; +import android.graphics.Color; +import android.graphics.drawable.ColorDrawable; +import android.location.LocationManager; +import android.net.ConnectivityManager; +import android.net.NetworkInfo; +import android.os.Build; +import android.provider.Settings; + +import com.google.android.gms.common.api.ResolvableApiException; +import com.google.android.gms.location.FusedLocationProviderClient; +import com.google.android.gms.location.LocationRequest; +import com.google.android.gms.location.LocationServices; +import com.google.android.gms.location.LocationSettingsRequest; +import com.google.android.gms.location.SettingsClient; +import com.cpm.lorealbaautomation.delegates.PrefHelper; + +import androidx.annotation.NonNull; +import androidx.core.app.ActivityCompat; +import androidx.core.content.ContextCompat; +import androidx.appcompat.app.AppCompatActivity; +import androidx.recyclerview.widget.LinearLayoutManager; + +import android.os.Bundle; +import android.text.InputFilter; +import android.view.View; +import android.view.ViewGroup; +import android.view.Window; +import android.view.WindowManager; +import android.view.inputmethod.EditorInfo; +import android.widget.AdapterView; +import android.widget.ArrayAdapter; +import android.widget.Button; +import android.widget.EditText; +import android.widget.LinearLayout; +import android.widget.Spinner; +import android.widget.TextView; +import android.widget.Toast; +import com.google.gson.Gson; +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.Get_IMEI_number.ImeiNumberClass; +import com.cpm.lorealbaautomation.adapter.LeaveDetailAdapter; +import com.cpm.lorealbaautomation.constant.AlertandMessages; +import com.cpm.lorealbaautomation.constant.CommonFunctions; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.dailyactivity.NotificationDetailActivity; +import com.cpm.lorealbaautomation.databinding.DialogApplyLeaveBinding; +import com.cpm.lorealbaautomation.gsonGetterSetter.CounterDeviceLoginGetterSetter; +import com.cpm.lorealbaautomation.retrofit.PostApi; +import com.cpm.lorealbaautomation.tbaleavemodel.Common; +import com.cpm.lorealbaautomation.tbaleavemodel.TBAMESearch; +import com.cpm.lorealbaautomation.upload.ManualUploadActivity; +import com.cpm.lorealbaautomation.utils.DrawableClickListener; + +import org.json.JSONException; +import org.json.JSONObject; + +import java.util.ArrayList; +import java.util.Calendar; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.TimeUnit; + +import okhttp3.MediaType; +import okhttp3.OkHttpClient; +import okhttp3.RequestBody; +import okhttp3.ResponseBody; +import retrofit2.Call; +import retrofit2.Callback; +import retrofit2.Response; +import retrofit2.Retrofit; +import retrofit2.converter.gson.GsonConverterFactory; + + +public class CounterLoginActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemSelectedListener { + String str_counter_id = ""; + EditText counter_id; + Button btncontinue; + private String[] imeiNumbers; + private String app_ver; + private Context context; + ProgressDialog loading; + private SharedPreferences.Editor editor = null; + private double lat = 0.0; + private double lon = 0.0; + private String manufacturer; + + private String model; + private String os_version; + private static final int REQUEST_LOCATION = 1; + private static final int PERMISSIONS_REQUEST_READ_PHONE_STATE = 999; + private ImeiNumberClass imei; + Lorealba_Database db; + String title = "", body = "", path = "", visited_date = "", type; + LinearLayout rlMarkLeave; + TextView versioncode_txt; + + Spinner leaveSpin; + int mYear, mMonth, mDay; + DatePickerDialog dpd; + Calendar c; + private TBAMESearch tbameSearch = null; + private CustomDialogLeaveApply customDialogLeave = null; + String blockCharacterSet = "[';:-+{('}@=#$%^&*?)\"]"; + InputFilter filter = (source, start, end, dest, dstart, dend) -> { + if (source != null && blockCharacterSet.contains(("" + source))) { + return ""; + } + return null; + }; + private FusedLocationProviderClient fusedLocationClient; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); + setContentView(R.layout.activity_counter); + fusedLocationClient = LocationServices.getFusedLocationProviderClient(this); + getViewId(); + callSpinAdapter(); + checkAndRequestPermissions(); + if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) + != PackageManager.PERMISSION_GRANTED) { + ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_PHONE_STATE}, + PERMISSIONS_REQUEST_READ_PHONE_STATE); + } else { + imeiNumbers = imei.getDeviceImei(); + } + getDeviceName(); + // getLastLocation(); + } + + private void callSpinAdapter() { + ArrayAdapter reason_adapter = new ArrayAdapter(context, R.layout.spinner_leave); + reason_adapter.add("Mark Leave(TBA/ME)"); + reason_adapter.add("Mark Leave"); + reason_adapter.add("Leave History"); + leaveSpin.setAdapter(reason_adapter); + reason_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); + leaveSpin.setOnItemSelectedListener(this); + } + + @Override + public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { + super.onRequestPermissionsResult(requestCode, permissions, grantResults); + //test("", "Permission callback called-------"); + if (requestCode == CommonString.PERMISSION_ALL) { + Map perms = new HashMap<>(); + // Initialize the map with both permissions + perms.put(Manifest.permission.CAMERA, PackageManager.PERMISSION_GRANTED); + perms.put(Manifest.permission.ACCESS_NETWORK_STATE, PackageManager.PERMISSION_GRANTED); + perms.put(Manifest.permission.ACCESS_COARSE_LOCATION, PackageManager.PERMISSION_GRANTED); + perms.put(Manifest.permission.ACCESS_FINE_LOCATION, PackageManager.PERMISSION_GRANTED); + perms.put(Manifest.permission.READ_PHONE_STATE, PackageManager.PERMISSION_GRANTED); + // Fill with actual results from user + if (grantResults.length > 0) { + for (int i = 0; i < permissions.length; i++) + perms.put(permissions[i], grantResults[i]); + boolean allPermissionsGranted = + Integer.valueOf(PackageManager.PERMISSION_GRANTED).equals(perms.get(Manifest.permission.CAMERA)) && + Integer.valueOf(PackageManager.PERMISSION_GRANTED).equals(perms.get(Manifest.permission.ACCESS_NETWORK_STATE)) && + Integer.valueOf(PackageManager.PERMISSION_GRANTED).equals(perms.get(Manifest.permission.ACCESS_COARSE_LOCATION)) && + Integer.valueOf(PackageManager.PERMISSION_GRANTED).equals(perms.get(Manifest.permission.ACCESS_FINE_LOCATION)) && + Integer.valueOf(PackageManager.PERMISSION_GRANTED).equals(perms.get(Manifest.permission.READ_PHONE_STATE)); + + if (allPermissionsGranted) { + //test("Permissions", "All required permissions granted"); + fusedLocationClient = LocationServices.getFusedLocationProviderClient((Activity) context); + getLastLocation(); + getDeviceName(); + imeiNumbers = imei.getDeviceImei(); + } + // Check for both permissions + else{ + //test("", "Some permissions are not granted ask again "); + if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA) + || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_NETWORK_STATE) + || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_COARSE_LOCATION) + || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION) + || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_PHONE_STATE)) { + showDialogOK("Location,File,Call and Camera Services Permission required for this app", (dialog, which) -> { + switch (which) { + case DialogInterface.BUTTON_POSITIVE: + checkAndRequestPermissions(); + break; + case DialogInterface.BUTTON_NEGATIVE: + // proceed with logic by disabling the related features or quit the app. + Intent startMain = new Intent(Intent.ACTION_MAIN); + startMain.addCategory(Intent.CATEGORY_HOME); + startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + startActivity(startMain); + break; + } + }); + } + //permission is denied (and never ask again is checked) + //shouldShowRequestPermissionRationale will return false + else { + Toast.makeText(this, "Go to settings and enable permissions", Toast.LENGTH_LONG).show(); + // //proceed with logic by disabling the related features or quit the app. + } + } + } + } + } + + private void getLastLocation() { + if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && + ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { + // Request location permissions + return; + } + try { + fusedLocationClient.getLastLocation() + .addOnSuccessListener(this, location -> { + if (location != null) { + lat = location.getLatitude(); + lon = location.getLongitude(); + //test("Location", "Lat: " + lat + ", Lng: " + lon); + } + }); + } catch (Exception e) { + e.fillInStackTrace(); //test("Location", "Lat: " + lat + ", Lng: " + lon);} + } + + } + @Override + protected void onResume() { + super.onResume(); + checkgpsEnableDevice(); + imeiNumbers = imei.getDeviceImei(); + getDeviceName(); + } + + private void checkgpsEnableDevice() { + if (!hasGPSDevice(context)) { + Toast.makeText(context, "Gps not Supported", Toast.LENGTH_SHORT).show(); + } + + final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); + if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER) && hasGPSDevice(context)) { + enableLocationSettings(); + } else { + if (manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { + hasGPSDevice(context); + } + } + } + + private void enableLocationSettings() { + @SuppressLint("VisibleForTests") LocationRequest locationRequest = LocationRequest.create() + .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY) // new Priority constant + .setInterval(30 * 1000) + .setFastestInterval(5 * 1000); + LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder() + .addLocationRequest(locationRequest) + .setAlwaysShow(true); // show dialog if GPS is off + + SettingsClient settingsClient = LocationServices.getSettingsClient(this); + + settingsClient.checkLocationSettings(builder.build()) + .addOnSuccessListener(locationSettingsResponse -> { + // All location settings are satisfied. You can request location updates here. + }).addOnFailureListener(e -> { + if (e instanceof ResolvableApiException) { + try { + ResolvableApiException resolvable = (ResolvableApiException) e; + resolvable.startResolutionForResult((Activity) context, REQUEST_LOCATION); + } catch (IntentSender.SendIntentException sendEx) { + // Ignore the error. + sendEx.fillInStackTrace(); + } + } + }); + } + + private boolean hasGPSDevice(Context context) { + final LocationManager mgr = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); + if (mgr == null) return false; + final List providers = mgr.getAllProviders(); + if (providers == null) return false; + return providers.contains(LocationManager.GPS_PROVIDER); + } + + private void AttempLogin() { + try { + loading = ProgressDialog.show(CounterLoginActivity.this, "Processing", "Please wait...", false, false); + JSONObject jsonObject = new JSONObject(); + jsonObject.put("Latitude", lat); + jsonObject.put("Longitude", lon); + jsonObject.put("Appversion", app_ver); + jsonObject.put("Attmode", "0"); + jsonObject.put("Networkstatus", "0"); + jsonObject.put("Manufacturer", manufacturer); + jsonObject.put("ModelNumber", model); + jsonObject.put("OSVersion", os_version); + jsonObject.put("CounterCode", str_counter_id); + jsonObject.put("AppId", BuildConfig.APPLICATION_ID); + if (Build.VERSION.SDK_INT > Build.VERSION_CODES.P) { + @SuppressLint("HardwareIds") String android_id = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID); + jsonObject.put("IMEINumber1", android_id); + } else { + if (imeiNumbers != null && imeiNumbers.length > 0) { + jsonObject.put("IMEINumber1", imeiNumbers[0]); + } else { + jsonObject.put("IMEINumber1", "0"); + } + } + + String jsonString = jsonObject.toString(); + //test("jsondata",jsonString); + try { + OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build(); + + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsonString); + Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build(); + PostApi api = adapter.create(PostApi.class); + Call call = api.getLogindetail(jsonData); + call.enqueue(new Callback() { + @Override + public void onResponse(@NonNull Call call, @NonNull Response response) { + ResponseBody responseBody = response.body(); + String data = null; + if (responseBody != null && response.isSuccessful()) { + try { + assert response.body() != null; + data = response.body().string(); + data = data.substring(1, data.length() - 1).replace("\\", ""); + Gson gson = new Gson(); + CounterDeviceLoginGetterSetter userObject = gson.fromJson(data, CounterDeviceLoginGetterSetter.class); + if (data.equalsIgnoreCase(CommonString.KEY_FAILURE)) { + AlertandMessages.showAlertCounterlogin(CounterLoginActivity.this, CommonString.KEY_FAILURE + " Please try again"); + loading.dismiss(); + } else if (userObject != null && userObject.getCounterDeviceLogin().get(0).getCounterId().equals(0)) { + loading.dismiss(); + AlertDialog.Builder builder = new AlertDialog.Builder(context); + builder.setTitle(R.string.parinaam); + builder.setMessage("This counter code is already mapped to different device.please contact your supervisor.").setCancelable(false).setPositiveButton(android.R.string.ok, (dialog, id) -> dialog.dismiss()); + AlertDialog alert = builder.create(); + alert.show(); + } else { + assert userObject != null; + if (userObject.getCounterDeviceLogin().get(0).getCounterId().equals(-1)) { + loading.dismiss(); + AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle(R.string.parinaam); + builder.setMessage("This counter not exist").setCancelable(false).setPositiveButton(android.R.string.ok, (dialog, id) -> dialog.dismiss()); + AlertDialog alert = builder.create(); + alert.show(); + } else { + editor.putString(CommonString.KEY_COUNTER_ID, userObject.getCounterDeviceLogin().get(0).getCounterId().toString()); + editor.putString(CommonString.KEY_COUNTER_CODE, userObject.getCounterDeviceLogin().get(0).getCounterCode()); + editor.putString(CommonString.KEY_COUNTER_NAME, userObject.getCounterDeviceLogin().get(0).getCounterName()); + editor.commit(); + ////chjecking previus data is pending + db.open(); + if (!db.getmasterTransaction(userObject.getCounterDeviceLogin().get(0).getVisitDate(), + userObject.getCounterDeviceLogin().get(0).getCounterId().toString(), true).isEmpty() + || !checkincomplete_upload_data(userObject.getCounterDeviceLogin().get(0).getVisitDate(), + userObject.getCounterDeviceLogin().get(0).getCounterId().toString(), db, true)) { + startActivity(new Intent(context, ManualUploadActivity.class).putExtra(CommonString.TAG_OBJECT, + userObject.getCounterDeviceLogin().get(0).getCounterId())); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + finish(); + } else { + Intent intent = new Intent(getBaseContext(), UserLoginActivity.class); + startActivity(intent); + finish(); + } + } + } + } catch (Exception e) { + loading.dismiss(); + e.fillInStackTrace(); + AlertandMessages.showAlertlogin(CounterLoginActivity.this, CommonString.MESSAGE_SOCKETEXCEPTION + "(" + e.toString() + ")"); + } + } else { + loading.dismiss(); + AlertandMessages.showAlertlogin(CounterLoginActivity.this, CommonString.MESSAGE_NO_RESPONSE_SERVER); + } + } + + @Override + public void onFailure(@NonNull Call call, @NonNull Throwable t) { + loading.dismiss(); + AlertandMessages.showAlertlogin(CounterLoginActivity.this, CommonString.MESSAGE_SOCKETEXCEPTION); + } + }); + + } catch (Exception e) { + loading.dismiss(); + e.fillInStackTrace(); + AlertandMessages.showAlertlogin(CounterLoginActivity.this, CommonString.MESSAGE_SOCKETEXCEPTION + "(" + e + ")"); + } + } catch (JSONException e) { + loading.dismiss(); + AlertandMessages.showAlertlogin(CounterLoginActivity.this, CommonString.MESSAGE_SOCKETEXCEPTION + "(" + e + ")"); + + } + } + + public void getDeviceName() { + manufacturer = Build.MANUFACTURER; + model = Build.MODEL; + os_version = android.os.Build.VERSION.RELEASE; + } + + @Override + protected void onDestroy() { + super.onDestroy(); + if (isFinishing()) { + if (loading != null) { + loading.dismiss(); + loading = null; + } + } + } + + @SuppressLint("SetTextI18n") + void getViewId() { + context = this; + SharedPreferences preferences = PrefHelper.getPrefs(context); + editor = preferences.edit(); + counter_id = (EditText) findViewById(R.id.counter_id); + db = new Lorealba_Database(this); + db.open(); + leaveSpin = (com.cpm.lorealbaautomation.utils.Spinner) findViewById(R.id.leaveSpin); + versioncode_txt = (TextView) findViewById(R.id.versioncode_txt); + rlMarkLeave = (LinearLayout) findViewById(R.id.rlMarkLeave); + btncontinue = (Button) findViewById(R.id.btncontinue); + rlMarkLeave.setVisibility(View.VISIBLE); + btncontinue.setOnClickListener(this); + imei = new ImeiNumberClass(context); + if (checkAndRequestPermissions()) { + imeiNumbers = imei.getDeviceImei(); + getDeviceName(); + } + try { + app_ver = String.valueOf(getPackageManager().getPackageInfo(getPackageName(), 0).versionName); + + } catch (PackageManager.NameNotFoundException e) { + // TODO Auto-generated catch block + e.fillInStackTrace(); + } + + if (getIntent().getExtras() != null) { + for (String key : getIntent().getExtras().keySet()) { + if (key.equalsIgnoreCase("title")) { + title = getIntent().getExtras().getString(key); + } else if (key.equalsIgnoreCase("body")) { + body = getIntent().getExtras().getString(key); + } else if (key.equalsIgnoreCase("path")) { + path = getIntent().getExtras().getString(key); + } else if (key.equalsIgnoreCase("Currentdate")) { + visited_date = getIntent().getExtras().getString(key); + } else if (key.equalsIgnoreCase("type")) { + type = getIntent().getExtras().getString(key); + } + } + + assert title != null; + assert body != null; + if (!title.equalsIgnoreCase("") && !body.equalsIgnoreCase("")) { + db.open(); + long value = db.insertNotificationData(title, body, path, visited_date, type, str_counter_id); + if (value > 0) { + Toast.makeText(context, "Notification Inserted", Toast.LENGTH_SHORT).show(); + } else { + Toast.makeText(context, "Notification Not Inserted", Toast.LENGTH_SHORT).show(); + } + } + + if (!title.isEmpty()) { + Intent in = new Intent(this, NotificationDetailActivity.class); + in.putExtra("Type", type); + in.putExtra("Title", title); + in.putExtra("Body", body); + in.putExtra("Path", path); + startActivity(in); + } + } + + + try { + PackageInfo pInfo = context.getPackageManager().getPackageInfo(getPackageName(), 0); + String version = pInfo.versionName; + versioncode_txt.setText("Version : " + version); + } catch (PackageManager.NameNotFoundException e) { + e.fillInStackTrace(); + versioncode_txt.setText("Version : 0.0"); + } + + } + + public boolean CheckNetAvailability() { + boolean connected = false; + ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); + if (Objects.requireNonNull(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)).getState() == NetworkInfo.State.CONNECTED || Objects.requireNonNull(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI)).getState() == NetworkInfo.State.CONNECTED) { + connected = true; + } + return connected; + } + + + @Override + public void onClick(View v) { + int id = v.getId(); + if (id == R.id.btncontinue) { + str_counter_id = counter_id.getText().toString().trim().replaceAll("[&^<>{}'$]", ""); + if (str_counter_id.isEmpty()) { + Toast.makeText(this, "Please enter Counter Code", Toast.LENGTH_SHORT).show(); + } else if (CheckNetAvailability()) { + AttempLogin(); + } else { + Toast.makeText(this, "No internet connection! try again later", Toast.LENGTH_LONG).show(); + } + } + + } + + private boolean checkAndRequestPermissions() { + int CAMERA = ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA); + int ACCESS_NETWORK_STATE = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_NETWORK_STATE); + int ACCESS_COARSE_LOCATION = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION); + int locationPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION); + int READ_PHONE_STATE = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE); + List listPermissionsNeeded = new ArrayList<>(); + + if (CAMERA != PackageManager.PERMISSION_GRANTED) { + listPermissionsNeeded.add(Manifest.permission.CAMERA); + } + + if (ACCESS_NETWORK_STATE != PackageManager.PERMISSION_GRANTED) { + listPermissionsNeeded.add(Manifest.permission.ACCESS_NETWORK_STATE); + } + if (ACCESS_COARSE_LOCATION != PackageManager.PERMISSION_GRANTED) { + listPermissionsNeeded.add(Manifest.permission.ACCESS_COARSE_LOCATION); + } + if (locationPermission != PackageManager.PERMISSION_GRANTED) { + listPermissionsNeeded.add(Manifest.permission.ACCESS_FINE_LOCATION); + } + + if (READ_PHONE_STATE != PackageManager.PERMISSION_GRANTED) { + listPermissionsNeeded.add(Manifest.permission.READ_PHONE_STATE); + } + + + if (!listPermissionsNeeded.isEmpty()) { + ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), CommonString.PERMISSION_ALL); + return false; + } + return true; + } + + private void showDialogOK(String message, DialogInterface.OnClickListener okListener) { + new AlertDialog.Builder(this).setMessage(message).setPositiveButton("OK", okListener).setNegativeButton("Cancel", okListener).create().show(); + } + + @Override + public void onItemSelected(AdapterView parent, View view, int position, long id) { + if (position != 0) { + customDialogLeave = new CustomDialogLeaveApply((AppCompatActivity) context); + customDialogLeave.show(); + } + } + + @Override + public void onNothingSelected(AdapterView parent) { + + } + + public class CustomDialogLeaveApply extends Dialog { + private CustomDialogLeaveApply oneButtonDialog; + private DialogApplyLeaveBinding binding = null; + + public CustomDialogLeaveApply(AppCompatActivity activity) { + super(activity); + } + + public CustomDialogLeaveApply getInstance(AppCompatActivity activity) { + return oneButtonDialog = (oneButtonDialog == null) ? new CustomDialogLeaveApply(activity) : oneButtonDialog; + } + + @SuppressLint("SetTextI18n") + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + requestWindowFeature(Window.FEATURE_NO_TITLE); + binding = DialogApplyLeaveBinding.inflate(getLayoutInflater()); + setContentView(binding.getRoot()); + if (leaveSpin.getSelectedItem().toString().equals("Leave History")) { + Objects.requireNonNull(getWindow()).setLayout(ViewGroup.LayoutParams.MATCH_PARENT, + ViewGroup.LayoutParams.WRAP_CONTENT); + } + Objects.requireNonNull(getWindow()).setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); + binding.edtapplyForleaveReason.setFilters(new InputFilter[]{filter, new InputFilter.LengthFilter(550)}); + binding.imgClose.setOnClickListener(v -> { + leaveSpin.setSelection(0); + dismiss(); + }); + + binding.etEmployeeCode.setOnEditorActionListener((v, actionId, event) -> { + if (actionId == EditorInfo.IME_ACTION_DONE) { + // Your action on done + if (Objects.requireNonNull(binding.etEmployeeCode.getText()).toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter Employee/Legacy Code"); + } else { + CommonFunctions.dismissKeyboard(binding.getRoot()); + getEmployeeDetails(binding.etEmployeeCode.getText().toString(), binding.tvEmpName, binding.tvEmpCode, + binding.tvEmpDesignation); + } + return true; + } + return false; + }); + + binding.etEmployeeCode.setDrawableClickListener(target -> { + if (Objects.requireNonNull(target) == DrawableClickListener.DrawablePosition.RIGHT) { + if (Objects.requireNonNull(binding.etEmployeeCode.getText()).toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter Employee/Legacy Code"); + } else { + CommonFunctions.dismissKeyboard(binding.getRoot()); + getEmployeeDetails(binding.etEmployeeCode.getText().toString(), binding.tvEmpName, binding.tvEmpCode, binding.tvEmpDesignation); + } + } + }); + + binding.etEmployeeCodeforHistory.setOnEditorActionListener((v, actionId, event) -> { + if (actionId == EditorInfo.IME_ACTION_DONE) { + // Your action on done + if (Objects.requireNonNull(binding.etEmployeeCodeforHistory.getText()).toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter Employee/Legacy Code"); + } else { + ///API call + getLeaveHistory(binding); + CommonFunctions.dismissKeyboard(binding.getRoot()); + } + return true; + } + return false; + }); + + binding.etEmployeeCodeforHistory.setDrawableClickListener(target -> { + if (Objects.requireNonNull(target) == DrawableClickListener.DrawablePosition.RIGHT) { + if (Objects.requireNonNull(binding.etEmployeeCodeforHistory.getText()).toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter Employee/Legacy Code"); + } else { + ///API call + getLeaveHistory(binding); + CommonFunctions.dismissKeyboard(binding.getRoot()); + } + } + }); + + binding.rlFromDateInfo.setOnClickListener(v -> { + if (binding.radioBFullday.isChecked() || binding.radioHalfDay.isChecked()) { + c = Calendar.getInstance(); + mYear = c.get(Calendar.YEAR); + mMonth = c.get(Calendar.MONTH); + mDay = c.get(Calendar.DAY_OF_MONTH); + // Launch Date Picker Dialog + dpd = new DatePickerDialog(context, (view, year, monthOfYear, dayOfMonth) -> { + String month_of_year = "", start_day_Of_Month = ""; + if ((monthOfYear + 1) < 10) { + month_of_year = "0" + (monthOfYear + 1); + } else { + month_of_year = String.valueOf(monthOfYear + 1); + } + if ((dayOfMonth) < 10) { + start_day_Of_Month = "0" + dayOfMonth; + } else { + start_day_Of_Month = String.valueOf(dayOfMonth); + } + String cmp_date = month_of_year + "/" + start_day_Of_Month + "/" + year; + binding.tvFromDate.setText(cmp_date); + binding.tvToDate.setText(""); + if (binding.radioHalfDay.isChecked()) { + binding.tvToDate.setText(cmp_date); + } + }, mYear, mMonth, mDay); + Calendar calendar = Calendar.getInstance(); + dpd.getDatePicker().setMinDate(calendar.getTimeInMillis() - 1000); + calendar = Calendar.getInstance(); + calendar.add(Calendar.MONTH, 2); + dpd.getDatePicker().setMaxDate(calendar.getTimeInMillis()); + dpd.show(); + } + }); + + binding.rlToDateInfo.setOnClickListener(v -> { + if (binding.radioBFullday.isChecked() && !binding.tvFromDate.getText().toString().isEmpty()) { + c = Calendar.getInstance(); + mYear = c.get(Calendar.YEAR); + mMonth = c.get(Calendar.MONTH); + mDay = c.get(Calendar.DAY_OF_MONTH); + dpd = new DatePickerDialog(context, (view, year, monthOfYear, dayOfMonth) -> { + try { + String month_of_year = "", day_Of_Month = ""; + if ((monthOfYear + 1) < 10) { + month_of_year = "0" + (monthOfYear + 1); + } else { + month_of_year = String.valueOf(monthOfYear + 1); + } + if ((dayOfMonth) < 10) { + day_Of_Month = "0" + dayOfMonth; + } else { + day_Of_Month = String.valueOf(dayOfMonth); + } + + binding.tvToDate.setText(month_of_year + "/" + day_Of_Month + "/" + year); + + } catch (Exception e) { + e.fillInStackTrace(); + } + }, mYear, mMonth, mDay); + String[] fromDate = binding.tvFromDate.getText().toString().split("/"); + Calendar calendar = Calendar.getInstance(); + calendar.set(Integer.parseInt(fromDate[2]), Integer.parseInt(fromDate[0]) - 1, Integer.parseInt(fromDate[1])); + dpd.getDatePicker().setMinDate(calendar.getTimeInMillis()); + calendar = Calendar.getInstance(); + calendar.set(Integer.parseInt(fromDate[2]), Integer.parseInt(fromDate[0]) + 1, Integer.parseInt(fromDate[1])); + dpd.getDatePicker().setMaxDate(calendar.getTimeInMillis()); + dpd.show(); + } + }); + } + + @SuppressLint("SetTextI18n") + @Override + protected void onStart() { + super.onStart(); + setCancelable(false); + if (leaveSpin.getSelectedItem().equals("Mark Leave")) { + binding.tvDialogTitle.setText("Apply For Leave"); + binding.btnSubmit.setVisibility(View.VISIBLE); + binding.rlApplyLeaveDetail.setVisibility(View.VISIBLE); + binding.rlLeaveHistory.setVisibility(View.GONE); + } else { + binding.tvDialogTitle.setText("Leave History"); + binding.btnSubmit.setVisibility(View.GONE); + binding.rlApplyLeaveDetail.setVisibility(View.GONE); + binding.rlLeaveHistory.setVisibility(View.VISIBLE); + } + + binding.radioBFullday.setOnCheckedChangeListener((buttonView, isChecked) -> { + if (isChecked) { + binding.radioHalfDay.setChecked(false); + binding.radioBFullday.setChecked(true); + binding.tvFromDateInfo.setText("Date From"); + binding.rlToDateInfo.setEnabled(true); + binding.tvFromDate.setText(""); + binding.tvToDate.setText(""); + binding.tvTodatePlaceholder.setTextColor(ContextCompat.getColor(context, R.color.black)); + } + }); + + binding.radioHalfDay.setOnCheckedChangeListener((buttonView, isChecked) -> { + if (isChecked) { + binding.radioHalfDay.setChecked(true); + binding.radioBFullday.setChecked(false); + binding.tvFromDateInfo.setText("Select Date"); + binding.rlToDateInfo.setEnabled(false); + binding.tvFromDate.setText(""); + binding.tvToDate.setText(""); + binding.tvTodatePlaceholder.setTextColor(ContextCompat.getColor(context, R.color.gray)); + } + }); + binding.btnSubmit.setOnClickListener(v -> { + if (tbameSearch == null && binding.tvEmpCode.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter Employee/Legacy Code"); + } else if (!binding.radioBFullday.isChecked() && !binding.radioHalfDay.isChecked()) { + AlertandMessages.showToastMsg(context, "Please Select Leave Type(Full/Half day)"); + } else if (!binding.radioHalfDay.isChecked() && binding.radioBFullday.isChecked() && binding.tvFromDate.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Select Date From"); + } else if (!binding.radioHalfDay.isChecked() && binding.radioBFullday.isChecked() && binding.tvToDate.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Select Date to"); + } else if (!binding.radioBFullday.isChecked() && binding.radioHalfDay.isChecked() && binding.tvFromDate.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Select Date"); + } else if (Objects.requireNonNull(binding.edtapplyForleaveReason.getText()).toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter Reason"); + } else { + if (CommonFunctions.checkNetIsAvailable(context)) { + submitLeaveRequest(tbameSearch.getEmpId().toString(), + binding.radioBFullday.isChecked() ? binding.radioBFullday.getText().toString() + : binding.radioHalfDay.getText().toString(), + binding.tvFromDate.getText().toString(), binding.tvToDate.getText().toString(), + binding.edtapplyForleaveReason.getText().toString()); + } else { + AlertandMessages.showToastMsg(context, getString(R.string.nonetwork)); + } + } + }); + } + } + + private void submitLeaveRequest(String empId, String leaveType, String date_from, String date_to, String leaveReason) { + ProgressDialog pd = null; + try { + pd = new ProgressDialog(context); + pd.setTitle("Applying Leave Request"); + pd.setMessage("Please wait....."); + pd.show(); + JSONObject json = new JSONObject().put("EmpId", empId) + .put("LeaveType", leaveType).put("FromDate", date_from).put("ToDate", leaveType.equals("Half Day") ? date_from : date_to) + .put("Reason", leaveReason).put("UserId", ""); + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), json.toString()); + Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS) + .writeTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build()).addConverterFactory(GsonConverterFactory.create()).build(); + ProgressDialog finalPd = pd; + adapter.create(PostApi.class).LeaveRequest(jsonData).enqueue(new Callback() { + @Override + public void onResponse(@NonNull Call call, @NonNull Response response) { + String responseBody = response.body(); + String data = null; + if (responseBody != null && response.isSuccessful()) { + try { + data = response.body(); + assert data != null; + if (!data.equals("") && !data.contains("No Data")) { + Common common = new Gson().fromJson(data, Common.class); + if (common != null && common.getLeaveRequest().size() > 0) { + assert common.getLeaveRequest().get(0).getResult() != null; + if (common.getLeaveRequest().get(0).getResult().equalsIgnoreCase(CommonString.KEY_SUCCESS)) { + if (finalPd.isShowing()) finalPd.dismiss(); + showAlert(customDialogLeave, "Leave request applied successfully."); + } else { + if (finalPd.isShowing()) finalPd.dismiss(); + showAlert(customDialogLeave, common.getLeaveRequest().get(0).getResult()); + } + } else { + if (finalPd.isShowing()) finalPd.dismiss(); + AlertandMessages.showToastMsg(context, getString(R.string.something_went_wrong)); + } + } else { + if (finalPd.isShowing()) finalPd.dismiss(); + AlertandMessages.showToastMsg(context, getString(R.string.something_went_wrong)); + } + if (finalPd.isShowing()) finalPd.dismiss(); + } catch (Exception e) { + if (finalPd.isShowing()) finalPd.dismiss(); + AlertandMessages.showToastMsg(context, "Error in data.Please try again..."); + } + } else { + if (finalPd.isShowing()) finalPd.dismiss(); + AlertandMessages.showToastMsg(context, "Error in Data,Please try again..."); + } + } + + @Override + public void onFailure(@NonNull Call call, @NonNull Throwable t) { + if (finalPd.isShowing()) finalPd.dismiss(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE); + } + }); + } catch (Exception ignored) { + if (pd != null && pd.isShowing()) pd.dismiss(); + } + + } + + private void showAlert(CustomDialogLeaveApply customDialogLeave, String str) { + try { + AlertDialog.Builder builder = new AlertDialog.Builder(context); + builder.setTitle(getString(R.string.parinaam)); + builder.setMessage(str).setCancelable(false) + .setPositiveButton(android.R.string.ok, (dialog, id) -> { + if (str.equals("Leave request applied successfully.")) { + if (leaveSpin != null) leaveSpin.setSelection(0); + if (customDialogLeave != null) customDialogLeave.cancel(); + } else dialog.dismiss(); + }); + AlertDialog alert = builder.create(); + alert.show(); + } catch (Exception e) { + e.fillInStackTrace(); + } + } + + private void getLeaveHistory(DialogApplyLeaveBinding binding) { + ProgressDialog pd = null; + try { + pd = new ProgressDialog(context); + pd.setTitle("Processing"); + pd.setMessage("Please wait....."); + pd.show(); + JSONObject json = new JSONObject().put("Downloadtype", "TBAME_LeaveHistory") + .put("Username", "").put("Param1", Objects.requireNonNull(binding.etEmployeeCodeforHistory.getText()).toString()).put("Param2", ""); + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), json.toString()); + Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS) + .writeTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build()).addConverterFactory(GsonConverterFactory.create()).build(); + ProgressDialog finalPd = pd; + adapter.create(PostApi.class).getDownloadAll(jsonData).enqueue(new Callback() { + @Override + public void onResponse(@NonNull Call call, @NonNull Response response) { + String responseBody = response.body(); + String data = null; + if (responseBody != null && response.isSuccessful()) { + try { + data = response.body(); + assert data != null; + if (!data.equals("") && !data.contains("No Data")) { + Common common = new Gson().fromJson(data, Common.class); + if (common != null && !common.getTBAMELeaveHistory().isEmpty()) { + runOnUiThread(() -> { + binding.tvEmpNameHistory.setText(CommonFunctions.capitalizeFirstLetter(common.getTBAMELeaveHistory().get(0).getName())); + binding.tvEmpDesignationHistory.setText(common.getTBAMELeaveHistory().get(0).getDesignation()); + binding.tvEmpCodeHistory.setText(common.getTBAMELeaveHistory().get(0).getEmpCode()); + binding.recyclerLeaveDetail.setAdapter(new LeaveDetailAdapter(context, common.getTBAMELeaveHistory())); + binding.recyclerLeaveDetail.setLayoutManager(new LinearLayoutManager(context)); + binding.rlLeaveDetailItem.setVisibility(View.VISIBLE); + }); + } + } else { + runOnUiThread(() -> { + binding.tvEmpNameHistory.setText(""); + binding.tvEmpCodeHistory.setText(""); + binding.tvEmpDesignationHistory.setText(""); + binding.rlLeaveDetailItem.setVisibility(View.GONE); + }); + AlertandMessages.showToastMsg(context, "No Leave history found for this employee . Please check Employee code and re-sync"); + } + if (finalPd.isShowing()) finalPd.dismiss(); + } catch (Exception e) { + runOnUiThread(() -> { + binding.tvEmpNameHistory.setText(""); + binding.tvEmpCodeHistory.setText(""); + binding.tvEmpDesignationHistory.setText(""); + binding.rlLeaveDetailItem.setVisibility(View.GONE); + }); + if (finalPd.isShowing()) finalPd.dismiss(); + AlertandMessages.showAlert((Activity) context, "Error in Leave history data.", true); + } + } else { + runOnUiThread(() -> { + binding.tvEmpNameHistory.setText(""); + binding.tvEmpCodeHistory.setText(""); + binding.tvEmpDesignationHistory.setText(""); + binding.rlLeaveDetailItem.setVisibility(View.GONE); + }); + if (finalPd.isShowing()) finalPd.dismiss(); + AlertandMessages.showAlert((Activity) context, "Error in downloading Data,Please try again... ", true); + } + } + + @Override + public void onFailure(@NonNull Call call, @NonNull Throwable t) { + runOnUiThread(() -> { + binding.tvEmpNameHistory.setText(""); + binding.tvEmpCodeHistory.setText(""); + binding.tvEmpDesignationHistory.setText(""); + binding.rlLeaveDetailItem.setVisibility(View.GONE); + }); + if (finalPd.isShowing()) finalPd.dismiss(); + AlertandMessages.showAlert((Activity) context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE, true); + } + }); + } catch (Exception ignored) { + if (pd != null && pd.isShowing()) pd.dismiss(); + } + } + + private void getEmployeeDetails(String empId, TextView tvEmpName, TextView tvEmpId, TextView empDesignation) { + ProgressDialog pd = null; + try { + pd = new ProgressDialog(context); + pd.setTitle("Processing"); + pd.setMessage("Please wait....."); + pd.show(); + JSONObject json = new JSONObject().put("Downloadtype", "TBAME_Search").put("Username", "").put("Param1", empId) + .put("Param2", ""); + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), json.toString()); + Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS) + .writeTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build()).addConverterFactory(GsonConverterFactory.create()).build(); + ProgressDialog finalPd = pd; + adapter.create(PostApi.class).getDownloadAll(jsonData).enqueue(new Callback() { + @Override + public void onResponse(@NonNull Call call, @NonNull Response response) { + String responseBody = response.body(); + String data = null; + if (responseBody != null && response.isSuccessful()) { + try { + data = response.body(); + assert data != null; + if (!data.equals("") && !data.contains("No Data")) { + Common common = new Gson().fromJson(data, Common.class); + if (common != null && common.getTBAMESearch().size() > 0) { + tbameSearch = common.getTBAMESearch().get(0); + runOnUiThread(() -> { + tvEmpName.setText(common.getTBAMESearch().get(0).getName()); + tvEmpId.setText(common.getTBAMESearch().get(0).getEmpCode()); + empDesignation.setText(common.getTBAMESearch().get(0).getDesignation()); + }); + } else { + tbameSearch = null; + runOnUiThread(() -> { + tvEmpName.setText(""); + tvEmpId.setText(""); + empDesignation.setText(""); + }); + AlertandMessages.showToastMsg(context, "Employee Detail not available. Please check Employee/Legacy code and re-sync"); + } + } else { + tbameSearch = null; + runOnUiThread(() -> { + tvEmpName.setText(""); + tvEmpId.setText(""); + empDesignation.setText(""); + }); + AlertandMessages.showToastMsg(context, "Employee Detail not available. Please check Employee/Legacy code and re-sync"); + } + if (finalPd.isShowing()) finalPd.dismiss(); + } catch (Exception e) { + tbameSearch = null; + runOnUiThread(() -> { + tvEmpName.setText(""); + tvEmpId.setText(""); + empDesignation.setText(""); + }); + if (finalPd.isShowing()) finalPd.dismiss(); + AlertandMessages.showToastMsg(context, "Error in data. " + e.getMessage()); + } + } else { + tbameSearch = null; + runOnUiThread(() -> { + tvEmpName.setText(""); + tvEmpId.setText(""); + empDesignation.setText(""); + }); + if (finalPd.isShowing()) finalPd.dismiss(); + AlertandMessages.showToastMsg(context, "Error in downloading Data,Please try again... "); + } + } + + @Override + public void onFailure(@NonNull Call call, @NonNull Throwable t) { + tbameSearch = null; + runOnUiThread(() -> { + tvEmpName.setText(""); + tvEmpId.setText(""); + empDesignation.setText(""); + }); + if (finalPd.isShowing()) finalPd.dismiss(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE); + } + }); + } catch (Exception ignored) { + if (pd != null && pd.isShowing()) pd.dismiss(); + } + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/Database/Lorealba_Database.java b/app/src/main/java/com/cpm/lorealbaautomation/Database/Lorealba_Database.java new file mode 100644 index 0000000..9b3cee5 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/Database/Lorealba_Database.java @@ -0,0 +1,15314 @@ +package com.cpm.lorealbaautomation.Database; + +import android.annotation.SuppressLint; +import android.content.ContentValues; +import android.content.Context; +import android.database.Cursor; +import android.database.SQLException; +import android.database.sqlite.SQLiteDatabase; +import android.database.sqlite.SQLiteOpenHelper; +import android.util.Log; + +import com.google.gson.Gson; +import com.google.gson.reflect.TypeToken; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.gettersetter.AuditDataGetterSetter; +import com.cpm.lorealbaautomation.gettersetter.BaTenureDetail; +import com.cpm.lorealbaautomation.gettersetter.GeotaggingBeans; +import com.cpm.lorealbaautomation.gettersetter.LoginGetterSetter; +import com.cpm.lorealbaautomation.gettersetter.MasterCompetitionOffer; +import com.cpm.lorealbaautomation.gettersetter.MasterCompetitionOfferSaleRange; +import com.cpm.lorealbaautomation.gettersetter.SaleableGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.AppDashboardTVA; +import com.cpm.lorealbaautomation.gsonGetterSetter.AppDashboardTVADrillDown; +import com.cpm.lorealbaautomation.gsonGetterSetter.BASurveyGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.BaListGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.DamagePreviousPending; +import com.cpm.lorealbaautomation.gsonGetterSetter.DamageReturnToDistributor; +import com.cpm.lorealbaautomation.gsonGetterSetter.GroomingGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.InvoiceGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.InwardSalesPO; +import com.cpm.lorealbaautomation.gsonGetterSetter.JCPGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.JourneyPlan; +import com.cpm.lorealbaautomation.gsonGetterSetter.MEMEAuditQuestion; +import com.cpm.lorealbaautomation.gsonGetterSetter.MEMEAuditQuestionUploadstatus; +import com.cpm.lorealbaautomation.gsonGetterSetter.MappingAppRestrictedKPI; +import com.cpm.lorealbaautomation.gsonGetterSetter.MappingCounterGroupBrand; +import com.cpm.lorealbaautomation.gsonGetterSetter.MappingVisibility; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterAgeLimit; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterBAProfile; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterBAProfileGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterCompetitionOfferGet; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterCompetitionOfferSet; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterCompetitionProductType; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterCompetitionPromoType; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterCompetitonBrandWiseNuance; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterInvoiceType; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterInvoiceTypeGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterBreak; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterLeaveType; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterLook; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterNonStockReason; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterNonStockReasonGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterNonVisibility; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterNonVisibilityGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterPosm; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterPromoOffer; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterPromotion; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterPromotionGetEntityItem; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterPromotionGetExclusionList; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterPromotionGetProductCatalog; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterPromotionGetProductGroup; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterPromotionSetEntityItem; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterPromotionSetExclusionList; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterPromotionSetProductCatalog; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterPromotionSetProductGroup; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterRetailExcellence; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterReturnReason; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterSkinType; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterProfile; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterProfileGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterProfileQuestion; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterProfileQuestionGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterSourcesOfSale; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterSurvey; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterSurveyUploadstatus; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterTermsCondition; +import com.cpm.lorealbaautomation.gsonGetterSetter.NotificationData; +import com.cpm.lorealbaautomation.gsonGetterSetter.ProductMaster; +import com.cpm.lorealbaautomation.gsonGetterSetter.ReportDamageStockHistory; +import com.cpm.lorealbaautomation.gsonGetterSetter.ReportMESale; +import com.cpm.lorealbaautomation.gsonGetterSetter.ReportMTDWorkingCounterME; +import com.cpm.lorealbaautomation.gsonGetterSetter.ReportProductGroupWiseSalesValue; +import com.cpm.lorealbaautomation.gsonGetterSetter.ReportSalesDateWise; +import com.cpm.lorealbaautomation.gsonGetterSetter.ReportSalesDetail; +import com.cpm.lorealbaautomation.gsonGetterSetter.ReportSalesL3MValue; +import com.cpm.lorealbaautomation.gsonGetterSetter.ResponseResult; +import com.cpm.lorealbaautomation.gsonGetterSetter.ServerTime; +import com.cpm.lorealbaautomation.gsonGetterSetter.ServerTimeGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.StockSummaryCheck; +import com.cpm.lorealbaautomation.gsonGetterSetter.TCounterInvoice; +import com.cpm.lorealbaautomation.gsonGetterSetter.TCounterInvoiceGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.TLeaveLedger; +import com.cpm.lorealbaautomation.gsonGetterSetter.TStockSummary; +import com.cpm.lorealbaautomation.gsonGetterSetter.TStockSummaryGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.T_LeaveRequest; +import com.cpm.lorealbaautomation.gsonGetterSetter.TableStructureGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.batbasale.BATBAPromoSale; +import com.cpm.lorealbaautomation.gsonGetterSetter.batbasale.BATBASale; +import com.cpm.lorealbaautomation.gsonGetterSetter.countervolune.ReportConterValue; +import com.cpm.lorealbaautomation.gsonGetterSetter.countervolune.ReportConterValueDetail; +import com.cpm.lorealbaautomation.gsonGetterSetter.countervolune.ReportCounterVolume; +import com.cpm.lorealbaautomation.gsonGetterSetter.countervolune.ReportCounterVolumeDetail; +import com.cpm.lorealbaautomation.gsonGetterSetter.inwordDetail.ReportCounterInwardStock; +import com.cpm.lorealbaautomation.gsonGetterSetter.inwordDetail.ReportCounterInwardStockDetail; +import com.cpm.lorealbaautomation.gsonGetterSetter.leaves.MasterHoliday; +import com.cpm.lorealbaautomation.gsonGetterSetter.leaves.TLeaveLedgerSummary; +import com.cpm.lorealbaautomation.gsonGetterSetter.leaves.TLeaveRequestDetail; +import com.cpm.lorealbaautomation.gsonGetterSetter.stockledger.ReportCounterStockLedger; +import com.cpm.lorealbaautomation.gsonGetterSetter.stockledger.ReportCounterStockLedgerDetail; +import com.cpm.lorealbaautomation.gsonGetterSetter.testerreports.ReportTesterCounter; +import com.cpm.lorealbaautomation.gsonGetterSetter.testerreports.TesterCounter; +import com.cpm.lorealbaautomation.reportGetterSetter.AppDashboardIncentive; +import com.cpm.lorealbaautomation.reportGetterSetter.AppDashboardLeaderBoard; +import com.cpm.lorealbaautomation.reportGetterSetter.ReportAttendanceDetail; +import com.cpm.lorealbaautomation.reportGetterSetter.ReportAttendanceSummary; +import com.cpm.lorealbaautomation.reportGetterSetter.ReportAvgBillValue; +import com.cpm.lorealbaautomation.reportGetterSetter.ReportAvgLinPerBill; +import com.cpm.lorealbaautomation.reportGetterSetter.ReportAvgTransactionPerDay; +import com.cpm.lorealbaautomation.reportGetterSetter.ReportAvgUnitsPerBill; +import com.cpm.lorealbaautomation.reportGetterSetter.ReportBAAvailability; +import com.cpm.lorealbaautomation.reportGetterSetter.ReportInwardStockSummary; +import com.cpm.lorealbaautomation.reportGetterSetter.ReportSalesValue; +import com.cpm.lorealbaautomation.reportGetterSetter.ReportSellingPrice; +import com.cpm.lorealbaautomation.reportGetterSetter.ReportTop10Value; +import com.cpm.lorealbaautomation.reportGetterSetter.ReportTop10Volume; +import com.cpm.lorealbaautomation.reports.dailyTva.DailyTVA; +import com.cpm.lorealbaautomation.reports.offtakemodels.L3MOffTakeCounter; +import com.cpm.lorealbaautomation.reports.offtakemodels.L3MOffTakeNuance; +import com.cpm.lorealbaautomation.reports.offtakemodels.L3MOffTakeSubAxe; +import com.cpm.lorealbaautomation.reports.offtakemodels.OffTakeData; +import com.cpm.lorealbaautomation.reports.offtakemodels.SalesGrowthCounter; +import com.cpm.lorealbaautomation.reports.offtakemodels.SalesGrowthSubAxe; +import com.cpm.lorealbaautomation.reports.testerdetails.ReportTesterCounterDetail; +import com.prolificinteractive.materialcalendarview.CalendarDay; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Objects; + +/** + * /** + * Created by jeevanp on 15-12-2017. + */ + +public class Lorealba_Database extends SQLiteOpenHelper { + public static final String DATABASE_NAME = CommonString.KEY_DB_NAME; + public static final int DATABASE_VERSION = CommonString.KEY_DB_NAME_iD; + private SQLiteDatabase db; + Context context; + + public Lorealba_Database(Context context) { + super(context, DATABASE_NAME, null, DATABASE_VERSION); + this.context = context; + } + + public void open() { + try { + db = this.getWritableDatabase(); + } catch (Exception e) { + e.fillInStackTrace(); + } + } + + @Override + public void onCreate(SQLiteDatabase db) { + try { + //jeevan + db.execSQL(CommonString.CREATE_TABLE_COMP_OFFERS); + db.execSQL(CommonString.CREATE_TABLE_User_Login); + db.execSQL(CommonString.CREATE_TABLE_COVERAGE_DATA); + db.execSQL(CommonString.CREATE_TABLE_COUNTER_IMAGE_DATA); + db.execSQL(CommonString.CREATE_TABLE_GROOMED_IMAGE_DATA); + db.execSQL(CommonString.CREATE_TABLE_FOCUS_PRODUCT_OPENINGHEADER_DATA); + db.execSQL(CommonString.CREATE_TABLE_FIRST_TIME_STOCK_DATA); + db.execSQL(CommonString.CREATE_TABLE_NOTIFICATION_DATA); + db.execSQL(CommonString.Create_Table_Sale_Tracking_Header_Data); + db.execSQL(CommonString.Create_Table_Sale_Tracking); + db.execSQL(CommonString.Create_Table_Applyed_Promotion); + db.execSQL(CommonString.Create_Table_PromoApplyeidOnProduct); + db.execSQL(CommonString.Create_Table_Consumer_Return); + db.execSQL(CommonString.Create_Table_Consumer_Return_Replace_Product); + + db.execSQL(CommonString.Create_Table_Leave_Management); + db.execSQL(CommonString.Create_Table_Break_Management); + db.execSQL(CommonString.Create_Table_Consumer_Return_Header_Data); + db.execSQL(CommonString.Create_Table_Makeover_Capture); + + db.execSQL(CommonString.Create_Table_ME_QUIZ); + db.execSQL(CommonString.Create_Table_ME_QUIZ_MULTI_ANSWER); + db.execSQL(CommonString.Create_Table_Temp_Consumer_Sale); + db.execSQL(CommonString.Create_Table_Temp_Temp_Promo_AplyDefinition); + db.execSQL(CommonString.Create_Table_Temp_Temp_Promo_AplyDefinitionfor_and); + db.execSQL(CommonString.CREATE_TABLE_RETURNTO_DISTRIBUTOR_DATA); + db.execSQL(CommonString.Create_Table_Temp_Image); + db.execSQL(CommonString.Create_Table_Temp_Sale); + db.execSQL(CommonString.CREATE_TABLE_NOTIFICATION_USER); + //---------------------- + db.execSQL(CommonString.CREATE_TABLE_TESTER_HEADER_DATA); + db.execSQL(CommonString.CREATE_TABLE_FIRST_TIME_TESTER_DATA); + db.execSQL(CommonString.CREATE_TABLE_SAMPLE_HEADER_DATA); + db.execSQL(CommonString.CREATE_TABLE_FIRST_TIME_SAMPLE_DATA); + db.execSQL(CommonString.CREATE_TABLE_DAMAGED_HEADER_DATA); + db.execSQL(CommonString.CREATE_TABLE_FIRST_TIME_DAMAGED_DATA); + db.execSQL(CommonString.CREATE_TABLE_SUGGESTED_STOCK_HEADER_DATA); + db.execSQL(CommonString.CREATE_TABLE_FIRST_TIME_SUGGESTED_STOCK_DATA); + //usk + db.execSQL(CommonString.CREATE_TABLE_VIISBILITY_DATA); + db.execSQL(CommonString.CREATE_TABLE_AUDIT_DATA_SAVE); + db.execSQL(CommonString.CREATE_TABLE_COUNTER_PROFILE_SAVE); + db.execSQL(CommonString.CREATE_TABLE_BA_PROFILE_DATAE_SAVE); + // neeraj + db.execSQL(CommonString.CREATE_TABLE_INWARD_STOCK_CHILD_DATA); + db.execSQL(CommonString.CREATE_TABLE_INWARD_STOCK_HEADER_DATA); + db.execSQL(CommonString.CREATE_TABLE_INWARD_STOCK_TRANSACTION); + db.execSQL(CommonString.CREATE_TABLE_AUDIT_DATA_SAVE); + db.execSQL(CommonString.CREATE_TABLE_MANUAL_INWARD_TRANSACTION); + //YSY + db.execSQL(CommonString.CREATE_TABLE_GWP_HEADER_DATA); + db.execSQL(CommonString.CREATE_TABLE_FIRST_TIME_GWP_DATA); + db.execSQL(CommonString.CREATE_TABLE_TRANSACTION_DATA); + db.execSQL(CommonString.CREATE_TABLE_BA_SURVEY_CHILD_DATA); + db.execSQL(CommonString.CREATE_TABLE_BA_SURVEY_HEADER_DATA); + db.execSQL(CommonString.CREATE_TABLE_COUNTER_SURVEY_CHILD_DATA); + db.execSQL(CommonString.CREATE_TABLE_COUNTER_SURVEY_HEADER_DATA); + db.execSQL(CommonString.CREATE_TABLE_TRANSACTION_WISE_DATA); + db.execSQL(CommonString.Create_Table_Skin_Genius_Table); + db.execSQL(CommonString.Create_Table_Open_Skin_Genius_Table); + db.execSQL(CommonString.Create_Table_Open_Mabelline_Table); + db.execSQL(CommonString.Create_Table_Temp_Promotion_OffSameProduct); + // + db.execSQL(CommonString.CREATE_TABLE_STORE_STOCK_CHILD_ME_SALE_DATA); + db.execSQL(CommonString.CREATE_TABLE_INSERT_HEADER_ME_SALE_DATA); + db.execSQL(CommonString.Create_Table_Retail_Excellence_Header); + db.execSQL(CommonString.Create_Table_Retail_Excellence_Child); + db.execSQL(CommonString.CREATE_TABLE_STORE_GEOTAGGING); + } catch (SQLException e) { + e.fillInStackTrace(); + } + } + + public void deleteSpecificStoreData() { + try { + if (!db.isOpen()) open(); + + db.delete(CommonString.TABLE_BA_SURVEY_CHILD_DATA, null, null); + db.delete(CommonString.TABLE_BA_SURVEY_HEADER_DATA, null, null); + db.delete(CommonString.TABLE_COUNTER_SURVEY_CHILD_DATA, null, null); + db.delete(CommonString.TABLE_COUNTER_SURVEY_HEADER_DATA, null, null); + db.delete(CommonString.TABLE_INSERT_HEADER_STOCK_DATA, null, null); + db.delete(CommonString.TABLE_STORE_STOCK_CHILD_DATA, null, null); + db.delete(CommonString.TABLE_COUNTER_IMAGE_DATA, null, null); + db.delete(CommonString.TABLE_GROOMED_IMAGE_DATA, null, null); + db.delete(CommonString.TABLE_COVERAGE_DATA, null, null); + db.delete(CommonString.TABLE_TRANSACTION_DATA, null, null); + db.delete(CommonString.TABLE_TRANSACTION_WISE_MASTER_TABLE, null, null); + db.delete(CommonString.TABLE_RETURNTO_DISTRIBUTOR_DATA, null, null); + db.delete(CommonString.TABLE_INSERT_HEADER_TESTER_DATA, null, null); + db.delete(CommonString.TABLE_TESTER_CHILD_DATA, null, null); + db.delete(CommonString.TABLE_INSERT_HEADER_SAMPLE_DATA, null, null); + db.delete(CommonString.TABLE_SAMPLE_CHILD_DATA, null, null); + db.delete(CommonString.TABLE_INSERT_HEADER_DAMAGED_DATA, null, null); + db.delete(CommonString.TABLE_DAMAGED_CHILD_DATA, null, null); + db.delete(CommonString.Table_visibilisty, null, null); + db.delete(CommonString.TABLE_AUDIT_DATA_SAVE, null, null); + db.delete(CommonString.Table_Consumer_Return, null, null); + db.delete(CommonString.Table_Consumer_Return_Replace_Product, null, null); + db.delete(CommonString.Table_Leave_Management, null, null); + db.delete(CommonString.Table_Break_Management, null, null); + db.delete(CommonString.TABLE_INSERT_INWARD_STOCK_TRANSACTION, null, null); + db.delete(CommonString.TABLE_COUNTER_PROFILE_DATA, null, null); + db.delete(CommonString.TABLE_INSERT_MANUAL_INWARD_TRANSACTION, null, null); + db.delete(CommonString.Table_Sale_Tracking_Header_Data, null, null); + db.delete(CommonString.Table_Makeover_Capture, null, null); + db.delete(CommonString.Table_Sale_Tracking, null, null); + db.delete(CommonString.Table_Applyeid_Promotion, null, null); + db.delete(CommonString.Table_PromoApplyeidOnProduct, null, null); + db.delete(CommonString.Table_Consumer_Return_Header_Data, null, null); + db.delete(CommonString.Table_ME_QUIZ, null, null); + db.delete(CommonString.Table_ME_QUIZ_MULTI_ANSWER, null, null); + db.delete(CommonString.Table_Skin_Genius_Table, null, null); + db.delete(CommonString.Table_Open_Skin_Genius_Table, null, null); + db.delete(CommonString.Table_Open_Maybelline_Table, null, null); + db.delete(CommonString.TABLE_COMP_OFFERS, null, null); + db.delete(CommonString.TABLE_INSERT_HEADER_ME_SALE_DATA, null, null); + db.delete(CommonString.TABLE_STORE_STOCK_CHILD_ME_SALE_DATA, null, null); + db.delete(CommonString.Table_Retail_Excellence_Header, null, null); + db.delete(CommonString.Table_Retail_Excellence_Child, null, null); + db.delete(CommonString.TABLE_STORE_GEOTAGGING, null, null); + } catch (Exception e) { + e.fillInStackTrace(); + } + } + + public void deleteNotificationTableafterOneWeek() { + try { + if (!db.isOpen()) { + open(); + } + db.delete(CommonString.TABLE_NOTIFICATION_USER, null, null); + db.delete(CommonString.TABLE_NOTIFICATION_DATA, null, null); + + } catch (Exception e) { + e.fillInStackTrace(); + } + } + + @Override + public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { + } + + public int createtable(String sqltext) { + try { + if (!db.isOpen()) { + open(); + } + db.execSQL(sqltext); + return 1; + } catch (Exception ex) { + ex.fillInStackTrace(); + return 0; + } + } + + + public boolean insertJCPData(JCPGetterSetter data) { + db.delete("Mapping_JourneyPlan", null, null); + List jcpList = data.getJourneyPlan(); + ContentValues values = new ContentValues(); + try { + if (jcpList.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < jcpList.size(); i++) { + values.put("StoreId", jcpList.get(i).getStoreId()); + values.put("CounterId", jcpList.get(i).getCounterId()); + values.put("EmpId", jcpList.get(i).getEmpId()); + values.put("ChainId", jcpList.get(i).getChainId()); + values.put("ChainName", jcpList.get(i).getChainName()); + values.put("StoreName", jcpList.get(i).getStoreName()); + values.put("Address", jcpList.get(i).getAddress()); + values.put("Location", jcpList.get(i).getLocation()); + values.put("Landmark", jcpList.get(i).getLandmark()); + values.put("CityId", jcpList.get(i).getCityId()); + values.put("CityName", jcpList.get(i).getCityName()); + values.put("CounterName", jcpList.get(i).getCounterName()); + values.put("IMEI", jcpList.get(i).getIMEI()); + values.put("ChannelId", jcpList.get(i).getChannelId()); + values.put("ChannelName", jcpList.get(i).getChannelName()); + values.put("StoreTypeId", jcpList.get(i).getStoreTypeId()); + values.put("StoreTypeName", jcpList.get(i).getStoreTypeName()); + values.put("ClassId", jcpList.get(i).getClassId()); + values.put("ClassName", jcpList.get(i).getClassName()); + values.put("CounterGroupId", jcpList.get(i).getCounterGroupId()); + values.put("CounterUploadStatus", jcpList.get(i).getCounterUploadStatus()); + values.put("BAUploadStatus", jcpList.get(i).getBAUploadStatus()); + values.put("MID", jcpList.get(i).getMID()); + values.put("BID", jcpList.get(i).getBID()); + values.put("RefImage", jcpList.get(i).getRefImage()); + values.put("ProfileImage1", jcpList.get(i).getProfileImage1()); + values.put("ProfileImage2", jcpList.get(i).getProfileImage2()); + values.put("CounterLength", jcpList.get(i).getCounterlength()); + values.put("CounterWidth", jcpList.get(i).getCounterwidth()); + values.put("SetUpDate", jcpList.get(i).getSetupDate()); + values.put("VisitDate", jcpList.get(i).getVisitDate()); + values.put("UserId", jcpList.get(i).getUserId().toLowerCase()); + + values.put("Latitude", jcpList.get(i).getLatitude()); + values.put("Longitude", jcpList.get(i).getLongitude()); + values.put("GeoTag", jcpList.get(i).getGeoTag()); + values.put("GeoFencingRadius", jcpList.get(i).getGeoFencingRadius()); + values.put("GeoFencingAllow", jcpList.get(i).getGeoFencingAllow()); + + if (!db.isOpen()) { + open(); + } + long id = db.insert("Mapping_JourneyPlan", null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ex.fillInStackTrace(); + ////////test("Exception in Jcp", ex.toString()); + return false; + } + } + + + public boolean insertBalistData(JCPGetterSetter data) { + db.delete("BA_List", null, null); + List baList = data.getBAList(); + ContentValues values = new ContentValues(); + try { + if (baList.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < baList.size(); i++) { + values.put("EmpId", baList.get(i).getEmpId()); + values.put("UserName", baList.get(i).getUserName().toLowerCase()); + values.put("DesignationId", baList.get(i).getDesignationId()); + values.put("DesignationName", baList.get(i).getDesignationName()); + values.put("VisitDate", baList.get(i).getVisitDate()); + values.put("ProfilePath", baList.get(i).getProfilePath()); + values.put("Profile_Pic", baList.get(i).getProfilePic()); + values.put("CounterId", baList.get(i).getCounterId()); + + long id = db.insert("BA_List", null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + // do ALL your inserts here + db.setTransactionSuccessful(); + db.endTransaction(); + ex.fillInStackTrace(); + ////////test("Exception in Jcp", ex.toString()); + return false; + } + } + + + public boolean insertmappingcountergroupBrand(JCPGetterSetter data) { + db.delete("Mapping_CounterGroup_Brand", null, null); + List baList = data.getMappingCounterGroupBrand(); + ContentValues values = new ContentValues(); + try { + if (baList.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < baList.size(); i++) { + values.put("CounterGroupId", baList.get(i).getCounterGroupId()); + values.put("BrandId", baList.get(i).getBrandId()); + + long id = db.insert("Mapping_CounterGroup_Brand", null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + ex.fillInStackTrace(); + // do ALL your inserts here + db.setTransactionSuccessful(); + db.endTransaction(); + ////////test("Exception in Jcp", ex.toString()); + return false; + } + } + + public long delete_table_data(String table_name) { + long l = 0; + try { + if (!db.isOpen()) { + open(); + } + l = db.delete(table_name, null, null); + } catch (Exception e) { + e.fillInStackTrace(); + } + return l; + } + + + public boolean insertproductmasterdata(TableStructureGetterSetter data) { + db.delete("Product_Master", null, null); + List productList = data.getProductMaster(); + ContentValues values = new ContentValues(); + try { + db.beginTransaction(); + if (productList.isEmpty()) { + return false; + } + for (ProductMaster productMaster : productList) { + values.put("ProductId", productMaster.getProductId()); + values.put("LorealCode", productMaster.getLorealCode().trim()); + values.put("ProductName", productMaster.getProductName().trim()); + + values.put("NuanceId", productMaster.getNuanceId()); + values.put("NuanceName", productMaster.getNuanceName().trim()); + values.put("SubAxeId", productMaster.getSubAxeId()); + values.put("SubAxeName", productMaster.getSubAxeName().trim()); + values.put("AxeId", productMaster.getAxeId()); + values.put("AxeName", productMaster.getAxeName().trim()); + values.put("ReferenceId", productMaster.getReferenceId()); + values.put("ReferenceName", productMaster.getReferenceName().trim()); + values.put("SubBrandId", productMaster.getSubBrandId()); + values.put("SubBrandName", productMaster.getSubBrandName().trim()); + values.put("BrandId", productMaster.getBrandId()); + values.put("BrandName", productMaster.getBrandName().trim()); + values.put("SignatureId", productMaster.getSignatureId()); + values.put("SignatureName", productMaster.getSignatureName().trim()); + values.put("EanCode", productMaster.getEanCode().trim()); + values.put("Mrp", productMaster.getMrp()); + values.put("ProductType", productMaster.getProductType().trim()); + values.put("VisitDate", productMaster.getVisit_date()); + + if (!db.isOpen()) { + open(); + } + long id = db.insert("Product_Master", null, values); + if (id == -1) { + throw new Exception(); + } + } + + // do ALL your inserts here + db.setTransactionSuccessful(); + db.endTransaction(); + return true; + } catch (Exception ex) { + ex.fillInStackTrace(); + // do ALL your inserts here + db.setTransactionSuccessful(); + db.endTransaction(); + ////////test("Exception in Jcp", ex.toString()); + return false; + } + } + + + public boolean insertmappingvisibility(TableStructureGetterSetter data) { + db.delete("Mapping_Visibility", null, null); + List productList = data.getMappingVisibility(); + ContentValues values = new ContentValues(); + try { + if (productList.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < productList.size(); i++) { + values.put("CounterId", productList.get(i).getCounterId()); + values.put("PosmId", productList.get(i).getPosmId()); + + if (!db.isOpen()) { + open(); + } + long id = db.insert("Mapping_Visibility", null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + ex.fillInStackTrace(); + // do ALL your inserts here + db.setTransactionSuccessful(); + db.endTransaction(); + ////////test("Exception in Jcp", ex.toString()); + return false; + } + } + + public boolean insertmappingposmdata(TableStructureGetterSetter data) { + db.delete("Master_Posm", null, null); + List productList = data.getMasterPosm(); + ContentValues values = new ContentValues(); + try { + if (productList.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < productList.size(); i++) { + values.put("Posm", productList.get(i).getPosm()); + values.put("PosmId", productList.get(i).getPosmId()); + values.put("PosmTypeId", productList.get(i).getPosmTypeId()); + values.put("RefImage", productList.get(i).getRefImage()); + + long id = db.insert("Master_Posm", null, values); + if (id == -1) { + throw new Exception(); + } + } + // do ALL your inserts here + closeDb(); + return true; + } catch (Exception ex) { + // do ALL your inserts here + db.setTransactionSuccessful(); + db.endTransaction(); + ex.fillInStackTrace(); + ////////test("Exception in Jcp", ex.toString()); + return false; + } + } + + + public ArrayList getsku_fromproductusing_eancode(String ean_code, boolean for_sale_flag, String visit_date, String counterId, String userType) { + ////////test("Fetching", "Storedata--------------->Start<------------"); + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + String table = CommonString.T_StockSummary, additionalQueryMe = "", additionalQueryMe2 = "", getData = "(s.SaleableBalance - ifnull(dm.DamageQty,0)) as SaleableBalance"; + if (userType != null && userType.equalsIgnoreCase(CommonString.TAG_FROM_ME)) { + additionalQueryMe2 = "UNION ALL Select T1.PRODUCT_ID AS ProductId , SUM(T1.QUANTITY) AS DamageQty FROM SALE_TRACKING_TABLE T1" + " INNER JOIN SALE_TRACKING_HEADER_TABLE T2 ON T2.RECCEPT_COUNT=T1.RECCEPT_COUNT WHERE T2.COUNTER_ID =" + counterId + " AND T2.Visit_Date='" + visit_date + "' AND T1.INVOICE_TYPE='Saleable'" + " AND T1.RIGHTNAME='ME' GROUP BY T1.PRODUCT_ID UNION ALL select S.PROMO_PRODUCT_ID AS ProductId ," + " SUM(S.PROMO_PRODUCT_QTY) AS DamageQty from APPLYED_PROMOTION_TABLE S INNER JOIN SALE_TRACKING_HEADER_TABLE S1 ON S.RECCEPT_COUNT=S1.RECCEPT_COUNT Where S.PROMO_TYPE ='Product'" + " AND S.COUNTER_ID =" + counterId + " AND S1.VISIT_DATE = '" + visit_date + "' AND S.RIGHTNAME='ME' GROUP BY S.PROMO_PRODUCT_ID "; + + + getData = "((s.SaleableBalance + ifnull(tempsale.TempSale,0) ) - ifnull(dm.DamageQty,0)) as SaleableBalance"; + additionalQueryMe = " left join (select ProductId, case when (Select count(*) from (Select CounterId, ProductId," + "sum(TempQty) as TempQty from ( Select T2.COUNTER_ID AS CounterId, T1.PRODUCT_ID AS ProductId , SUM(T1.QUANTITY) AS TempQty FROM SALE_TRACKING_TABLE T1" + " INNER JOIN SALE_TRACKING_HEADER_TABLE T2 ON T2.RECCEPT_COUNT=T1.RECCEPT_COUNT WHERE T2.COUNTER_ID =" + counterId + " AND T2.Visit_Date='" + visit_date + "' AND T1.INVOICE_TYPE='Saleable'" + " AND T1.RIGHTNAME !='ME' GROUP BY T1.PRODUCT_ID" + " UNION ALL select S.COUNTER_ID as CounterId," + " S.PROMO_PRODUCT_ID AS ProductId , SUM(S.PROMO_PRODUCT_QTY) AS TempQty from APPLYED_PROMOTION_TABLE S INNER JOIN SALE_TRACKING_HEADER_TABLE S1" + " ON S.RECCEPT_COUNT=S1.RECCEPT_COUNT Where S.PROMO_TYPE ='Product' AND S.COUNTER_ID =" + counterId + " AND S1.VISIT_DATE = '" + visit_date + "'" + " AND S.RIGHTNAME !='ME' GROUP BY S.PROMO_PRODUCT_ID)as t Group by CounterId, ProductId)" + " c where c.ProductId = t.Productid)>0 then (Select TempQty from (Select CounterId, ProductId," + "sum(TempQty) as TempQty from ( Select T2.COUNTER_ID AS CounterId, T1.PRODUCT_ID AS ProductId , SUM(T1.QUANTITY) AS TempQty FROM SALE_TRACKING_TABLE T1" + " INNER JOIN SALE_TRACKING_HEADER_TABLE T2 ON T2.RECCEPT_COUNT=T1.RECCEPT_COUNT WHERE T2.COUNTER_ID =" + counterId + " AND T2.Visit_Date='" + visit_date + "' AND T1.INVOICE_TYPE='Saleable'" + " AND T1.RIGHTNAME !='ME' AND T2.POS_SALE_FLAG='1' GROUP BY T1.PRODUCT_ID" + " UNION ALL select S.COUNTER_ID as CounterId," + " S.PROMO_PRODUCT_ID AS ProductId , SUM(S.PROMO_PRODUCT_QTY) AS TempQty from APPLYED_PROMOTION_TABLE S INNER JOIN SALE_TRACKING_HEADER_TABLE S1" + " ON S.RECCEPT_COUNT=S1.RECCEPT_COUNT Where S.PROMO_TYPE ='Product' AND S.COUNTER_ID =" + counterId + " AND S1.VISIT_DATE = '" + visit_date + "'" + " AND S.RIGHTNAME !='ME' AND S1.POS_SALE_FLAG ='1' GROUP BY S.PROMO_PRODUCT_ID)as t Group by CounterId, ProductId" + " ) c where c.productId = t.Productid) else (" + + + "Select sum(QtySold)as QtySold from (select SaleQty as QtySold from Report_BA_TBASale s where s.ProductId = t.ProductId and s.CounterId=" + counterId + " and VisitDate='" + visit_date + "'" + "UNION all select SaleQty as QtySold from Report_BA_TBAPromoSale s where s.ProductId = t.ProductId and s.CounterId=" + counterId + " and VisitDate='" + visit_date + "')" + + + ") end as TempSale" + " from T_StockSummary t) as tempsale on s.ProductId=tempsale.ProductId"; + } + String query = "select distinct ProductName,ProductId,EanCode,Mrp,ProductType from Product_Master where EanCode='" + ean_code + "'"; + if (for_sale_flag) { + query = "Select distinct s.ProductId as ProductId," + getData + "," + "pm.ProductName as ProductName,pm.EanCode as EanCode,pm.Mrp as Mrp,pm.ProductType as ProductType" + " from Product_Master pm inner join " + table + " s on pm.ProductId=s.ProductId Left join" + " (Select CounterId, ProductId, sum(DamageQty) as DamageQty from" + " (select T.COUNTER_ID as CounterId, T.ProductId, T.Stock as DamageQty from TABLE_TRANSACTION_DATA T INNER JOIN" + " DR_TABLE_TRANSACTION_WISE_MASTER M ON T.MASTER_TRANSACTION_ID = M.MASTER_TRANSACTION_ID" + " where T.STOCK_TYPE='DAMAGE' AND T.Visit_Date ='" + visit_date + "' and T.COUNTER_ID =" + counterId + " Union All" + " SELECT CounterId, ProductId, DamageQty from Damage_PreviousPending Where CounterId =" + counterId + " and Verify ='Pending'" + additionalQueryMe2 + ") as t" + " Group by CounterId, ProductId) as dm " + " on s.ProductId = dm.ProductId" + additionalQueryMe + " where pm.EanCode='" + ean_code + "' and SaleableBalance >0"; + } + + dbcursor = db.rawQuery(query, null); + + //test("query", query); + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + ProductMaster sb = new ProductMaster(); + sb.setProductName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ProductName"))); + sb.setProductId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("ProductId"))); + sb.setEanCode(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EanCode"))); + sb.setMrp(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("Mrp"))); + sb.setProductType(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ProductType"))); + + list.add(sb); + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list; + } + } catch (Exception e) { + ////////test("Exception ", "when fetching opening stock!!!!!!!!!!!" + e.toString()); + return list; + } + + ////////test("Fetching ", "opening stock---------------------->Stop<-----------"); + return list; + } + + + public ArrayList getsku_fromproductusing_eancodefor_return(String ean_code) { + ////////test("Fetching", "Storedata--------------->Start<------------"); + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + dbcursor = db.rawQuery("select distinct pm.ProductName as ProductName,pm.ProductId as ProductId,pm.EanCode as EanCode" + ",pm.Mrp as Mrp,pm.ProductType as ProductType from Product_Master pm " + "inner join T_StockSummary ts on ts.ProductId=pm.ProductId where pm.EanCode='" + ean_code + "'", null); + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + ProductMaster sb = new ProductMaster(); + sb.setProductName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ProductName"))); + sb.setProductId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("ProductId"))); + sb.setEanCode(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EanCode"))); + sb.setMrp(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("Mrp"))); + sb.setProductType(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ProductType"))); + list.add(sb); + dbcursor.moveToNext(); + } + dbcursor.close(); + return list; + } + } catch (Exception e) { + ////////test("Exception ", "when fetching opening stock!!!!!!!!!!!" + e.toString()); + return list; + } + ////////test("Fetching ", "opening stock---------------------->Stop<-----------"); + return list; + } + + + public ArrayList getStoreData(String date, String user_Id, String counterId) { + ArrayList list = new ArrayList(); + Cursor dbcursor = null; + + try { + if (user_Id != null) { + dbcursor = db.rawQuery("SELECT * FROM Mapping_JourneyPlan WHERE VisitDate ='" + date + "'and UserId='" + user_Id + "' and CounterId = " + counterId, null); + } else { + dbcursor = db.rawQuery("SELECT * FROM Mapping_JourneyPlan WHERE VisitDate ='" + date + "'", null); + } + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + JourneyPlan sb = new JourneyPlan(); + sb.setStoreId((dbcursor.getInt(dbcursor.getColumnIndexOrThrow("StoreId")))); + sb.setCounterId((dbcursor.getInt(dbcursor.getColumnIndexOrThrow("CounterId")))); + sb.setEmpId((dbcursor.getInt(dbcursor.getColumnIndexOrThrow("EmpId")))); + sb.setChainId((dbcursor.getInt(dbcursor.getColumnIndexOrThrow("ChainId")))); + sb.setChainName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ChainName"))); + sb.setStoreName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("StoreName"))); + sb.setAddress((dbcursor.getString(dbcursor.getColumnIndexOrThrow("Address")))); + sb.setLocation((dbcursor.getString(dbcursor.getColumnIndexOrThrow("Location")))); + sb.setLandmark(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Landmark"))); + sb.setCityId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("CityId"))); + sb.setCityName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("CityName"))); + sb.setCounterName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("CounterName"))); + sb.setIMEI(dbcursor.getString(dbcursor.getColumnIndexOrThrow("IMEI"))); + sb.setChannelId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("ChannelId"))); + sb.setChannelName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ChannelName"))); + sb.setStoreTypeId((dbcursor.getInt(dbcursor.getColumnIndexOrThrow("StoreTypeId")))); + sb.setStoreTypeName((dbcursor.getString(dbcursor.getColumnIndexOrThrow("StoreTypeName")))); + sb.setClassId((dbcursor.getInt(dbcursor.getColumnIndexOrThrow("ClassId")))); + sb.setClassName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ClassName"))); + sb.setCounterGroupId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("CounterGroupId"))); + sb.setCounterUploadStatus(dbcursor.getString(dbcursor.getColumnIndexOrThrow("CounterUploadStatus"))); + sb.setBAUploadStatus((dbcursor.getString(dbcursor.getColumnIndexOrThrow("BAUploadStatus")))); + sb.setMID(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("MID"))); + sb.setBID(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("BID"))); + sb.setRefImage(dbcursor.getString(dbcursor.getColumnIndexOrThrow("RefImage"))); + sb.setProfileImage1(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ProfileImage1"))); + sb.setProfileImage2(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ProfileImage2"))); + sb.setCounterlength(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("CounterLength"))); + sb.setCounterwidth(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("CounterWidth"))); + sb.setSetupDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SetUpDate"))); + sb.setVisitDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("VisitDate"))); + + sb.setLatitude(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("Latitude"))); + sb.setLongitude(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("Longitude"))); + sb.setGeoTag(dbcursor.getString(dbcursor.getColumnIndexOrThrow("GeoTag"))); + sb.setGeoFencingRadius(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("GeoFencingRadius"))); + sb.setGeoFencingAllow(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("GeoFencingAllow"))); + + + list.add(sb); + dbcursor.moveToNext(); + } + dbcursor.close(); + return list; + } + + } catch (Exception e) { + ////////test("Exception get JCP!", e.toString()); + return list; + } + + + return list; + } + + //jeevan nmjnmn, + public ArrayList getsalesTrackingByUserMobile(int reciept_count, String mobile_no, String visite_date, String counterId, String user_Id) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + + dbcursor = db.rawQuery("Select distinct SH.SOURCEOFSALES as SOURCEOFSALES,SH.SKIN_GENIUS as SKIN_GENIUS,SH.MAYBELLINE_VTO" + " as MAYBELLINE_VTO," + " SH.USER_ID as USER_ID, ST.PRODUCT_ID as PRODUCT_ID," + "ST.PRODUCT as PRODUCT,ST.QUANTITY as QUANTITY,ST.PRODUCT_RATE as PRODUCT_RATE," + "ST.TOTAL_AMOUNT as TOTAL_AMOUNT,ST.EAN_CODE as EAN_CODE,ST.DISCOUNT as DISCOUNT,ST.DISCOUNTED_VALUE as DISCOUNTED_VALUE" + ",ST.ACTUAL_PRICE as ACTUAL_PRICE,ST.SKU_TYPE as SKU_TYPE,ST.INVOICE_TYPE as INVOICE_TYPE," + "SH.POS_SALE_FLAG as POS_SALE_FLAG,SH.TERMCONDITION_FLAG as TERMCONDITION_FLAG,SH.CONSUMER_NOSALE_IMG as CONSUMER_NOSALE_IMG," + "SH.PER_TIMING as PER_TIMING,SH.RECCEPT_COUNT as RECCEPT_COUNT,SH.STORE_NAME as STORE_NAME,SH.STORE_ADDRESS as STORE_ADDRESS," + "SH.BUYER_NAME as BUYER_NAME,SH.CONTACT_NUMBER as CONTACT_NUMBER,SH.EMAIL_ID as EMAIL_ID," + "SH.AGE as AGE,SH.SKIN_TYPE as SKIN_TYPE,SH.DEMO_GIVEN as DEMO_GIVEN,SH.PRODUCT_SOLD as PRODUCT_SOLD,SH.UPLOAD_STATUS as UPLOAD_STATUS," + "SH.GENDER as GENDER,ST.PROMOTION as PROMOTION,ST.PROMOTION_ID as PROMOTION_ID,ST.PROMOTION_FLAG as PROMOTION_FLAG,ST.PROMO_TYPE as PROMO_TYPE" + " FROM SALE_TRACKING_TABLE ST INNER JOIN SALE_TRACKING_HEADER_TABLE SH ON SH.RECCEPT_COUNT=ST.RECCEPT_COUNT where SH.CONTACT_NUMBER='" + mobile_no + "'" + "and SH.Visit_Date ='" + visite_date + "' and SH.RECCEPT_COUNT=" + reciept_count + " and SH.COUNTER_ID =" + counterId + " and SH.USER_ID ='" + user_Id + "'", null); + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + InvoiceGetterSetter sale = new InvoiceGetterSetter(); + sale.setPos_sale_flag(dbcursor.getString(dbcursor.getColumnIndexOrThrow("POS_SALE_FLAG")).equals("1")); + sale.setPromo_flag(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PROMOTION_FLAG")).equals("1")); + sale.setSourceofSales(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SOURCEOFSALES"))); + sale.setUserName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("USER_ID"))); + sale.setStr_termcondition(dbcursor.getString(dbcursor.getColumnIndexOrThrow("TERMCONDITION_FLAG"))); + sale.setConsumer_no_saleImg(dbcursor.getString(dbcursor.getColumnIndexOrThrow("CONSUMER_NOSALE_IMG"))); + sale.setPercheasing_tym(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PER_TIMING"))); + sale.setReccept_count(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("RECCEPT_COUNT"))); + sale.setStore_name(dbcursor.getString(dbcursor.getColumnIndexOrThrow("STORE_NAME"))); + sale.setStore_address(dbcursor.getString(dbcursor.getColumnIndexOrThrow("STORE_ADDRESS"))); + sale.setCustomer_name(dbcursor.getString(dbcursor.getColumnIndexOrThrow("BUYER_NAME"))); + sale.setMobile_no(dbcursor.getString(dbcursor.getColumnIndexOrThrow("CONTACT_NUMBER"))); + sale.setConsumer_email_Id(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EMAIL_ID"))); + sale.setConsumer_age(dbcursor.getString(dbcursor.getColumnIndexOrThrow("AGE"))); + sale.setConsumer_skinType(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SKIN_TYPE"))); + sale.setDemo_given_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("DEMO_GIVEN"))); + sale.setProduct_sold_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PRODUCT_SOLD"))); + sale.setStr_upload_status(dbcursor.getString(dbcursor.getColumnIndexOrThrow("UPLOAD_STATUS"))); + sale.setCustomer_gender(dbcursor.getString(dbcursor.getColumnIndexOrThrow("GENDER"))); + sale.setProduct_Id(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PRODUCT_ID"))); + sale.setProduct(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PRODUCT"))); + sale.setQuantity(dbcursor.getString(dbcursor.getColumnIndexOrThrow("QUANTITY"))); + sale.setProduct_rate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PRODUCT_RATE"))); + sale.setTotal_amount(dbcursor.getString(dbcursor.getColumnIndexOrThrow("TOTAL_AMOUNT"))); + sale.setScan_ean_code_or_enterd_ean_code(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EAN_CODE"))); + sale.setDiscount(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("DISCOUNT"))); + sale.setDiscounted_value(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("DISCOUNTED_VALUE"))); + sale.setActual_price_per_product(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("ACTUAL_PRICE"))); + sale.setSkuType(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SKU_TYPE"))); + sale.setStr_invoiceType(dbcursor.getString(dbcursor.getColumnIndexOrThrow("INVOICE_TYPE"))); + sale.setPromotion_name(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PROMOTION"))); + sale.setPromotion_Id(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PROMOTION_ID"))); + sale.setPromo_type(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PROMO_TYPE"))); + sale.setSkin_genius_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SKIN_GENIUS"))); + sale.setMaybelline_vto_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("MAYBELLINE_VTO"))); + if (sale.isPromo_flag()) { + if (!db.isOpen()) open(); + sale.setApplyiedproductList(getproductsapplyeidOnpromo(reciept_count, mobile_no, visite_date, counterId, user_Id, sale.getPromotion_Id())); + } + list.add(sale); + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list; + } + + } catch (Exception e) { + ////////test("Exception Brands", e.toString()); + return list; + } + + return list; + } + + + public ArrayList getproductsapplyeidOnpromo(int reciept_count, String mobile_no, String visite_date, String counterId, String user_Id, String promoId) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + if (promoId.isEmpty()) { + dbcursor = db.rawQuery("SELECT Distinct t1.DISCOUNT as DISCOUNT ,t1.RECCEPT_COUNT as RECCEPT_COUNT,t1.PROMO_TYPE as" + " PROMO_TYPE,t1.PROMOTION_FLAG as PROMOTION_FLAG" + ",t1.PROMOTION as PROMOTION,t1.PROMOTION_ID as PROMOTION_ID," + "t1.PRODUCT_ID as PRODUCT_ID,t1.PRODUCT as PRODUCT,t1.EAN_CODE as EAN_CODE,t1.PRODUCT_QTY as PRODUCT_QTY," + "t1.MRP as MRP FROM DR_PROMOAPPLYED_PRODUCT t1 inner join SALE_TRACKING_HEADER_TABLE t2 on t2.RECCEPT_COUNT=t1.RECCEPT_COUNT" + " where t2.CONTACT_NUMBER='" + mobile_no + "' and t1.Visit_Date ='" + visite_date + "' and t1.RECCEPT_COUNT=" + reciept_count + " and t1.COUNTER_ID =" + counterId + " and t2.USER_ID ='" + user_Id + "' And t1.PROMOTION_FLAG = 1", null); + + } else { + dbcursor = db.rawQuery("SELECT Distinct t1.DISCOUNT as DISCOUNT, t1.RECCEPT_COUNT as RECCEPT_COUNT,t1.PROMO_TYPE as" + " PROMO_TYPE,t1.PROMOTION_FLAG as PROMOTION_FLAG" + ",t1.PROMOTION as PROMOTION,t1.PROMOTION_ID as PROMOTION_ID," + "t1.PRODUCT_ID as PRODUCT_ID,t1.PRODUCT as PRODUCT,t1.EAN_CODE as EAN_CODE,t1.PRODUCT_QTY as PRODUCT_QTY," + "t1.MRP as MRP FROM DR_PROMOAPPLYED_PRODUCT t1 inner join SALE_TRACKING_HEADER_TABLE t2 on t2.RECCEPT_COUNT=t1.RECCEPT_COUNT" + " where t2.CONTACT_NUMBER='" + mobile_no + "' and t1.Visit_Date ='" + visite_date + "' and t1.RECCEPT_COUNT=" + reciept_count + " AND t1.PROMOTION_ID =" + promoId + " AND t1.COUNTER_ID =" + counterId + " and t2.USER_ID ='" + user_Id + "' And t1.PROMOTION_FLAG = 1", null); + + } + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + InvoiceGetterSetter sale = new InvoiceGetterSetter(); + sale.setPromo_flag(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PROMOTION_FLAG")).equals("1")); + sale.setReccept_count(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("RECCEPT_COUNT"))); + sale.setPromo_type(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PROMO_TYPE"))); + sale.setPromotion_name(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PROMOTION"))); + sale.setPromotion_Id(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PROMOTION_ID"))); + sale.setProduct_Id(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PRODUCT_ID"))); + sale.setProduct(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PRODUCT"))); + sale.setScan_ean_code_or_enterd_ean_code(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EAN_CODE"))); + sale.setQuantity(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PRODUCT_QTY"))); + sale.setProduct_rate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("MRP"))); + sale.setDiscounted_value_productwise(dbcursor.getString(dbcursor.getColumnIndexOrThrow("DISCOUNT"))); + list.add(sale); + dbcursor.moveToNext(); + } + dbcursor.close(); + return list; + } + + } catch (Exception e) { + ////////test("Exception Brands", e.toString()); + return list; + } + + return list; + } + + + public ArrayList getapplyeid_promotion(int reciept_count, String mobile_no, String visite_date, String counterId, String user_Id) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + dbcursor = db.rawQuery("SELECT t1.RECCEPT_COUNT as RECCEPT_COUNT,t1.PROMO_TYPE as PROMO_TYPE,t1.PROMOTION_FLAG as PROMOTION_FLAG" + ",t1.PROMOTION as PROMOTION,t1.PROMOTION_ID as PROMOTION_ID," + "t1.PROMO_PRODUCT_ID as PROMO_PRODUCT_ID,t1.PROMO_PRODUCT as PROMO_PRODUCT,t1.EAN_CODE as EAN_CODE,t1.PROMO_PRODUCT_QTY as PROMO_PRODUCT_QTY," + "t1.PROMO_PRODUCT_MRP as PROMO_PRODUCT_MRP,t1.PROMO_DISCOUNT as PROMO_DISCOUNT" + " FROM APPLYED_PROMOTION_TABLE t1 inner join SALE_TRACKING_HEADER_TABLE t2 on t2.RECCEPT_COUNT=t1.RECCEPT_COUNT" + " where t2.CONTACT_NUMBER='" + mobile_no + "' and t1.Visit_Date ='" + visite_date + "' and t1.RECCEPT_COUNT=" + reciept_count + " and t1.COUNTER_ID =" + counterId + " and t2.USER_ID ='" + user_Id + "'", null); + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + InvoiceGetterSetter sale = new InvoiceGetterSetter(); + sale.setPromo_flag(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PROMOTION_FLAG")).equals("1")); + sale.setReccept_count(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("RECCEPT_COUNT"))); + sale.setPromo_type(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PROMO_TYPE"))); + sale.setPromotion_name(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PROMOTION"))); + sale.setPromotion_Id(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PROMOTION_ID"))); + sale.setProduct_Id(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PROMO_PRODUCT_ID"))); + sale.setProduct(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PROMO_PRODUCT"))); + sale.setScan_ean_code_or_enterd_ean_code(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EAN_CODE"))); + sale.setQuantity(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PROMO_PRODUCT_QTY"))); + sale.setProduct_rate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PROMO_PRODUCT_MRP"))); + sale.setDiscounted_value(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("PROMO_DISCOUNT"))); + if (sale.isPromo_flag()) { + sale.setApplyiedproductList(getproductsapplyeidOnpromo(reciept_count, mobile_no, visite_date, counterId, user_Id, sale.getPromotion_Id())); + } + list.add(sale); + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list; + } + + } catch (Exception e) { + ////////test("Exception Brands", e.toString()); + return list; + } + + return list; + } + + + public ArrayList getsalestrackingListusing_group(String CounterId, String visite_date, String user_Id, String userType) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + if (user_Id == null) { + dbcursor = db.rawQuery("select T1.*, ifnull (T2.DISCOUNT,0) as DISCOUNT, ifnull (T3.DISCOUNT,0) as DISCOUNTOffProduct ," + "ifnull(T2.DISCOUNT,0) + ifnull(T3.DISCOUNT,0) as finalDiscount FROM " + "(select m.USER_ID, m.DEMO_GIVEN,m.SKIN_GENIUS,m.MAYBELLINE_VTO,m.PRODUCT_SOLD, m.RECCEPT_COUNT, m.BUYER_NAME," + " m.CONTACT_NUMBER,m.SOURCEOFSALES,m.UPLOAD_STATUS," + "IFNULL(sum(t.QUANTITY),0) as QUANTITY, IFNULL(sum(t.QUANTITY*t.PRODUCT_RATE),0) AS TOTAL_AMOUNT,m.POS_SALE_FLAG " + "from SALE_TRACKING_HEADER_TABLE m LEFT join SALE_TRACKING_TABLE t on m.RECCEPT_COUNT = t.RECCEPT_COUNT " + "WHERE M.Visit_Date ='" + visite_date + "'and m.COUNTER_ID=" + CounterId + " And m." + CommonString.KEY_USER_TYPE + " ='" + userType + "'" + " GROUP BY m.RECCEPT_COUNT, m.BUYER_NAME, m.CONTACT_NUMBER) AS T1 " + "LEFT JOIN(select t.RECCEPT_COUNT, ifnull (sum(t.PRODUCT),0) AS DISCOUNT from SALE_TRACKING_HEADER_TABLE m LEFT join SALE_TRACKING_TABLE t" + " on m.RECCEPT_COUNT = t.RECCEPT_COUNT " + "WHERE M.Visit_Date ='" + visite_date + "'and m.COUNTER_ID=" + CounterId + " And t." + CommonString.KEY_USER_TYPE + " ='" + userType + "'" + " AND t.PRODUCT_ID = 0 AND (t.PROMO_TYPE='OffWorth' OR t.PROMO_TYPE='OffAdditionalProduct'OR t.PROMO_TYPE='ValueOffAdditionalProduct'" + " OR t.PROMO_TYPE='Worth' OR t.PROMO_TYPE='OffSameProduct' OR t.PROMO_TYPE='WorthWithProduct')" + "GROUP BY m.RECCEPT_COUNT, m.BUYER_NAME, m.CONTACT_NUMBER) AS T2 ON T1.RECCEPT_COUNT = T2.RECCEPT_COUNT" + " LEFT JOIN(select t.RECCEPT_COUNT, ifnull (sum(t.SKU_TYPE),0) AS DISCOUNT from " + "SALE_TRACKING_HEADER_TABLE m LEFT join SALE_TRACKING_TABLE t " + "on m.RECCEPT_COUNT = t.RECCEPT_COUNT WHERE M.Visit_Date ='" + visite_date + "'and m.COUNTER_ID=" + CounterId + " And m." + CommonString.KEY_USER_TYPE + " ='" + userType + "'" + " and (t.PROMO_TYPE='OffWorth' OR t.PROMO_TYPE='Worth' OR t.PROMO_TYPE='OffAdditionalProduct'" + " OR t.PROMO_TYPE='ValueOffAdditionalProduct' OR t.PROMO_TYPE='OffSameProduct' OR t.PROMO_TYPE='WorthWithProduct')" + " GROUP BY m.RECCEPT_COUNT,m.BUYER_NAME, m.CONTACT_NUMBER) AS T3 ON T1.RECCEPT_COUNT = T3.RECCEPT_COUNT", null); + } else { + dbcursor = db.rawQuery("SELECT T1.*, ifnull (T2.DISCOUNT,0) as DISCOUNT, ifnull (T3.DISCOUNT,0) as DISCOUNTOffProduct ," + "ifnull(T2.DISCOUNT,0) + ifnull(T3.DISCOUNT,0) as finalDiscount FROM " + "(select m.USER_ID, m.DEMO_GIVEN,m.PRODUCT_SOLD,m.SKIN_GENIUS,m.MAYBELLINE_VTO, m.RECCEPT_COUNT, m.BUYER_NAME," + " m.CONTACT_NUMBER,m.SOURCEOFSALES,m.UPLOAD_STATUS," + "IFNULL(sum(t.QUANTITY),0) as QUANTITY, IFNULL(sum(t.QUANTITY*t.PRODUCT_RATE),0) AS TOTAL_AMOUNT,m.POS_SALE_FLAG " + "from SALE_TRACKING_HEADER_TABLE m LEFT join SALE_TRACKING_TABLE t on m.RECCEPT_COUNT = t.RECCEPT_COUNT " + "WHERE M.Visit_Date ='" + visite_date + "' and m.COUNTER_ID=" + CounterId + " And m." + CommonString.KEY_USER_TYPE + " ='" + userType + "'" + " GROUP BY m.RECCEPT_COUNT, m.BUYER_NAME, m.CONTACT_NUMBER) AS T1 " + "LEFT JOIN(select t.RECCEPT_COUNT, ifnull (sum(t.PRODUCT),0) AS DISCOUNT from SALE_TRACKING_HEADER_TABLE m LEFT join" + " SALE_TRACKING_TABLE t on m.RECCEPT_COUNT = t.RECCEPT_COUNT " + "WHERE M.Visit_Date ='" + visite_date + "' and m.COUNTER_ID=" + CounterId + " And m." + CommonString.KEY_USER_TYPE + " ='" + userType + "'" + " AND t.PRODUCT_ID =0 AND (t.PROMO_TYPE='OffWorth' OR t.PROMO_TYPE='OffAdditionalProduct'OR" + " t.PROMO_TYPE='ValueOffAdditionalProduct' OR t.PROMO_TYPE='Worth' OR t.PROMO_TYPE='OffSameProduct' OR t.PROMO_TYPE='WorthWithProduct') and m.USER_ID='" + user_Id + "'" + "GROUP BY m.RECCEPT_COUNT, m.BUYER_NAME, m.CONTACT_NUMBER) AS T2 ON T1.RECCEPT_COUNT = T2.RECCEPT_COUNT" + " LEFT JOIN(select t.RECCEPT_COUNT, ifnull (sum(t.SKU_TYPE),0) AS DISCOUNT from " + "SALE_TRACKING_HEADER_TABLE m LEFT join SALE_TRACKING_TABLE t " + "on m.RECCEPT_COUNT = t.RECCEPT_COUNT WHERE M.Visit_Date ='" + visite_date + "' and m.COUNTER_ID=" + CounterId + " And m." + CommonString.KEY_USER_TYPE + " ='" + userType + "'" + " and (t.PROMO_TYPE='OffWorth' OR t.PROMO_TYPE='Worth' OR t.PROMO_TYPE='OffAdditionalProduct' OR t.PROMO_TYPE='ValueOffAdditionalProduct' OR t.PROMO_TYPE='OffSameProduct' OR t.PROMO_TYPE='WorthWithProduct')" + " and m.USER_ID='" + user_Id + "'" + " GROUP BY m.RECCEPT_COUNT,m.BUYER_NAME, m.CONTACT_NUMBER) AS T3 ON T1.RECCEPT_COUNT = T3.RECCEPT_COUNT", null); + } + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + InvoiceGetterSetter sale = new InvoiceGetterSetter(); + sale.setUserName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("USER_ID"))); + sale.setMobile_no(dbcursor.getString(dbcursor.getColumnIndexOrThrow("CONTACT_NUMBER"))); + sale.setTotal_amount(dbcursor.getString(dbcursor.getColumnIndexOrThrow("TOTAL_AMOUNT"))); + sale.setCustomer_name(dbcursor.getString(dbcursor.getColumnIndexOrThrow("BUYER_NAME"))); + sale.setQuantity(dbcursor.getString(dbcursor.getColumnIndexOrThrow("QUANTITY"))); + sale.setReccept_count(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("RECCEPT_COUNT"))); + sale.setDemo_given_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("DEMO_GIVEN"))); + sale.setProduct_sold_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PRODUCT_SOLD"))); + sale.setSkin_genius_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SKIN_GENIUS"))); + sale.setMaybelline_vto_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("MAYBELLINE_VTO"))); + sale.setAplyieddiscountedprice(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("finalDiscount"))); + sale.setSourceofSales(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SOURCEOFSALES"))); + sale.setStr_upload_status(dbcursor.getString(dbcursor.getColumnIndexOrThrow("UPLOAD_STATUS"))); + sale.setPos_sale_flag("1".equalsIgnoreCase(dbcursor.getString(dbcursor.getColumnIndexOrThrow("POS_SALE_FLAG")))); + list.add(sale); + dbcursor.moveToNext(); + } + dbcursor.close(); + return list; + } + } catch (Exception e) { + ////////test("Exception Brands", e.toString()); + return list; + } + return list; + } + + public ArrayList getstock_check_axeandsub_axe(String counterGroup_Id) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + dbcursor = db.rawQuery("select distinct SubAxeName from Product_Master", null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + ProductMaster sb = new ProductMaster(); + sb.setSubAxeName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SubAxeName"))); + list.add(sb); + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list; + } + } catch (Exception e) { + + return list; + } + + return list; + } + + + public ArrayList getsub_brand_name(String counterGroup_Id, String column_name, boolean GWPFlag) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + if (GWPFlag) { + dbcursor = db.rawQuery("select distinct " + column_name + " from Product_Master where ProductType ='GWP'", null); + } else { + dbcursor = db.rawQuery("select distinct " + column_name + " from Product_Master where ProductType ='Normal'", null); + } + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + ProductMaster sb = new ProductMaster(); + sb.setBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow(column_name))); + list.add(sb); + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list; + } + } catch (Exception e) { + + return list; + } + + return list; + } + + + public ArrayList getbrand_wise_sku_fromStockData(String SubAxeName, String AxeName, String BrandName, String counterGroup_Id) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + dbcursor = db.rawQuery("select * from Product_Master Where AxeName=\"" + AxeName + "\" and SubAxeName=\"" + SubAxeName + "\" and BrandName=\"" + BrandName + "\"", null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + ProductMaster sb = new ProductMaster(); + sb.setProductName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ProductName"))); + sb.setProductId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("ProductId"))); + sb.setEanCode(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EanCode"))); + sb.setMrp(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("Mrp"))); + sb.setStock(0); + + list.add(sb); + dbcursor.moveToNext(); + } + dbcursor.close(); + return list; + } + } catch (Exception e) { + + return list; + } + + return list; + } + + + public boolean insertInwordSalesPoData(TableStructureGetterSetter nonWorkingdata) { + db.delete("InwardSales_PO", null, null); + ContentValues values = new ContentValues(); + List data = nonWorkingdata.getInwardSalesPO(); + try { + if (data.isEmpty()) { + return false; + } + + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("CounterCode", data.get(i).getCounterCode()); + values.put("CounterId", data.get(i).getCounterId()); + values.put("GrnDate", data.get(i).getGrnDate()); + values.put("GrnRefNo", data.get(i).getGrnRefNo()); + values.put("GrnType", data.get(i).getGrnType()); + values.put("MRP", data.get(i).getMRP()); + values.put("ProductCode", data.get(i).getProductCode()); + values.put("ProductId", data.get(i).getProductId()); + values.put("QTY", data.get(i).getQTY()); + values.put("StoreCode", data.get(i).getStoreCode()); + values.put("StoreId", data.get(i).getStoreId()); + values.put("UOM", data.get(i).getUOM()); + values.put("ProductName", data.get(i).getProductName()); + + long id = db.insert("InwardSales_PO", null, values); + if (id == -1) { + throw new Exception(); + } + } + // do ALL your inserts here + closeDb(); + return true; + } catch (Exception ex) { + // do ALL your inserts here + db.setTransactionSuccessful(); + db.endTransaction(); + ex.fillInStackTrace(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + + public long insertNotificationData(String title, String body, String path, String visited_date, String type, String counter_id) { + long id = 0; + ContentValues values = new ContentValues(); + try { + db.beginTransaction(); + values.put(CommonString.KEY_BODY, body); + values.put(CommonString.KEY_TITLE, title); + values.put(CommonString.KEY_COUNTER_ID, counter_id); + values.put(CommonString.KEY_VISIT_DATE, visited_date); + values.put(CommonString.KEY_PATH, path); + values.put(CommonString.KEY_TYPE, type); + values.put(CommonString.KEY_READ_STATUS, "0"); + id = db.insert(CommonString.TABLE_NOTIFICATION_DATA, null, values); + closeDb(); + } catch (Exception ex) { + closeDb(); + ////////test("Database Exception ", ex.toString()); + return 0; + } + return id; + } + + private void closeDb() { + // do ALL your inserts here + db.setTransactionSuccessful(); + db.endTransaction(); + } + + public long insertnotification_users(String userId, String visit_date, String counter_id, String keyId) { + db.delete(CommonString.TABLE_NOTIFICATION_USER, CommonString.KEY_ID + "='" + keyId + "'and " + CommonString.KEY_USER_ID + "='" + userId + "'", null); + long id = 0; + ContentValues values = new ContentValues(); + try { + db.beginTransaction(); + values.put(CommonString.KEY_COUNTER_ID, counter_id); + values.put(CommonString.KEY_VISIT_DATE, visit_date); + values.put(CommonString.KEY_USER_ID, userId); + values.put(CommonString.KEY_ID, keyId); + id = db.insert(CommonString.TABLE_NOTIFICATION_USER, null, values); + closeDb(); + } catch (Exception ex) { + closeDb(); + ////////test("Database Exception ", ex.toString()); + return 0; + } + return id; + } + + public ArrayList getNotificationList() { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + dbcursor = db.rawQuery("Select * from " + CommonString.TABLE_NOTIFICATION_DATA + " order by " + CommonString.KEY_ID + " desc ", null); + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + NotificationData notifyData = new NotificationData(); + notifyData.setId(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_ID))); + notifyData.setBody(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_BODY))); + notifyData.setPath(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_PATH))); + notifyData.setTitle(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_TITLE))); + notifyData.setVisited_date(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_VISIT_DATE))); + notifyData.setType(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_TYPE))); + notifyData.setRead_status(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_READ_STATUS))); + list.add(notifyData); + dbcursor.moveToNext(); + } + dbcursor.close(); + return list; + } + + } catch (Exception e) { + ////////test("Exception Brands", e.toString()); + return list; + } + return list; + } + + + public InvoiceGetterSetter getcst_countandtotal_sale_value(String visit_date, String counterId, String userId, String userType) { + InvoiceGetterSetter sb = new InvoiceGetterSetter(); + Cursor dbcursor = null; + try { + if (userId == null) { + dbcursor = db.rawQuery("select count(RECCEPT_COUNT) as TotalCustomer, sum(TOTAL_AMOUNT) as TOTAL_AMOUNT from " + "(select m.RECCEPT_COUNT as RECCEPT_COUNT, m.BUYER_NAME as BUYER_NAME, m.CONTACT_NUMBER as CONTACT_NUMBER, IFNULL(sum(t.QUANTITY*t.PRODUCT_RATE),0) " + "AS TOTAL_AMOUNT from SALE_TRACKING_HEADER_TABLE m LEFT join SALE_TRACKING_TABLE t on m.RECCEPT_COUNT = t.RECCEPT_COUNT " + "WHERE M.Visit_Date ='" + visit_date + "' and M.COUNTER_ID=" + counterId + " and m.POS_SALE_FLAG='1'" + " And m." + CommonString.KEY_USER_TYPE + " ='" + userType + "'" + " GROUP BY m.RECCEPT_COUNT, m.BUYER_NAME, m.CONTACT_NUMBER, m.POS_SALE_FLAG) as t", null); + + } else { + dbcursor = db.rawQuery("select count(RECCEPT_COUNT) as TotalCustomer, sum(TOTAL_AMOUNT) as TOTAL_AMOUNT from " + "(select m.RECCEPT_COUNT as RECCEPT_COUNT, m.BUYER_NAME as BUYER_NAME, m.CONTACT_NUMBER as CONTACT_NUMBER, IFNULL(sum(t.QUANTITY*t.PRODUCT_RATE),0) " + "AS TOTAL_AMOUNT from SALE_TRACKING_HEADER_TABLE m LEFT join SALE_TRACKING_TABLE t on m.RECCEPT_COUNT = t.RECCEPT_COUNT " + "WHERE M.Visit_Date ='" + visit_date + "' and M.COUNTER_ID=" + counterId + " and M.USER_ID='" + userId + "' and m.POS_SALE_FLAG='1'" + " And m." + CommonString.KEY_USER_TYPE + " ='" + userType + "'" + " GROUP BY m.RECCEPT_COUNT, m.BUYER_NAME, m.CONTACT_NUMBER, m.POS_SALE_FLAG) as t", null); + } + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + sb.setTotal_amount(dbcursor.getString(dbcursor.getColumnIndexOrThrow("TOTAL_AMOUNT"))); + sb.setCst_count(dbcursor.getString(dbcursor.getColumnIndexOrThrow("TotalCustomer"))); + dbcursor.moveToNext(); + } + + dbcursor.close(); + return sb; + } + } catch (Exception e) { + return sb; + } + + return sb; + } + + public ArrayList getcst_totaldiscount(String visit_date, String counterId, String userId, String userType) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + if (userId == null) { + dbcursor = db.rawQuery(" select sum (ifnull (DISCOUNT,0)) as DISCOUNT from (" + " select Ifnull (sum(t.PRODUCT),0) AS DISCOUNT from SALE_TRACKING_HEADER_TABLE m LEFT join SALE_TRACKING_TABLE t on" + " m.RECCEPT_COUNT = t.RECCEPT_COUNT " + " WHERE m.Visit_Date ='" + visit_date + "'and m.COUNTER_ID=" + counterId + " And m." + CommonString.KEY_USER_TYPE + " ='" + userType + "'" + " and m.POS_SALE_FLAG='1'and t.PRODUCT_ID =0 AND" + " (t.PROMO_TYPE='OffWorth' OR t.PROMO_TYPE='Worth' OR t.PROMO_TYPE='OffAdditionalProduct' OR t.PROMO_TYPE='ValueOffAdditionalProduct' OR t.PROMO_TYPE='OffSameProduct' OR t.PROMO_TYPE='WorthWithProduct')" + " GROUP BY m.RECCEPT_COUNT, m.BUYER_NAME, m.CONTACT_NUMBER " + "union all select Ifnull (sum(t.SKU_TYPE),0) AS DISCOUNT from SALE_TRACKING_HEADER_TABLE m LEFT join SALE_TRACKING_TABLE t" + " on m.RECCEPT_COUNT = t.RECCEPT_COUNT " + " WHERE m.Visit_Date ='" + visit_date + "'and m.COUNTER_ID=" + counterId + " And m." + CommonString.KEY_USER_TYPE + " ='" + userType + "'" + " and m.POS_SALE_FLAG='1' AND" + " (t.PROMO_TYPE='OffWorth' OR t.PROMO_TYPE='Worth' OR t.PROMO_TYPE='OffAdditionalProduct' OR t.PROMO_TYPE='ValueOffAdditionalProduct' OR t.PROMO_TYPE='OffSameProduct' OR t.PROMO_TYPE='WorthWithProduct')" + " GROUP BY m.RECCEPT_COUNT, m.BUYER_NAME, m.CONTACT_NUMBER)", null); + + } else { + dbcursor = db.rawQuery(" select sum (ifnull (DISCOUNT,0)) as DISCOUNT from (" + " select Ifnull (sum(t.PRODUCT),0) AS DISCOUNT from SALE_TRACKING_HEADER_TABLE m LEFT join SALE_TRACKING_TABLE t" + " on m.RECCEPT_COUNT = t.RECCEPT_COUNT " + " WHERE m.Visit_Date ='" + visit_date + "'and m.COUNTER_ID=" + counterId + " And m." + CommonString.KEY_USER_TYPE + " ='" + userType + "'" + " and m.POS_SALE_FLAG='1' and " + "t.PRODUCT_ID =0 AND (t.PROMO_TYPE='OffWorth' OR t.PROMO_TYPE='OffAdditionalProduct' OR t.PROMO_TYPE='ValueOffAdditionalProduct' OR t.PROMO_TYPE='Worth' OR t.PROMO_TYPE='OffSameProduct' OR t.PROMO_TYPE='WorthWithProduct') and m.USER_ID='" + userId + "'GROUP BY m.RECCEPT_COUNT, m.BUYER_NAME, m.CONTACT_NUMBER " + "union all select Ifnull (sum(t.SKU_TYPE),0) AS DISCOUNT from SALE_TRACKING_HEADER_TABLE m LEFT join SALE_TRACKING_TABLE t" + " on m.RECCEPT_COUNT = t.RECCEPT_COUNT " + " WHERE m.Visit_Date ='" + visit_date + "' and m.COUNTER_ID=" + counterId + " And m." + CommonString.KEY_USER_TYPE + " ='" + userType + "'" + " and m.POS_SALE_FLAG='1' AND" + " (t.PROMO_TYPE='OffWorth' OR t.PROMO_TYPE='Worth' OR t.PROMO_TYPE='OffAdditionalProduct' OR t.PROMO_TYPE='ValueOffAdditionalProduct' OR t.PROMO_TYPE='OffSameProduct' OR t.PROMO_TYPE='WorthWithProduct')" + " and m.USER_ID='" + userId + "' GROUP BY m.RECCEPT_COUNT, m.BUYER_NAME, m.CONTACT_NUMBER)", null); + + } + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + InvoiceGetterSetter sb = new InvoiceGetterSetter(); + sb.setAplyieddiscountedprice(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("DISCOUNT"))); + list.add(sb); + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list; + } + } catch (Exception e) { + return list; + } + + return list; + } + + + public long insertcounteruserdata(String counter_id, String user_id, String visit_date, JourneyPlan counterimg_object, String userType) { + db.delete(CommonString.TABLE_COUNTER_IMAGE_DATA, CommonString.KEY_VISIT_DATE + "<>'" + visit_date + "'", null); + long id = 0; + ContentValues values = new ContentValues(); + try { + db.beginTransaction(); + values.put(CommonString.KEY_COUNTER_ID, counter_id); + values.put(CommonString.KEY_USER_ID, user_id); + values.put(CommonString.KEY_VISIT_DATE, visit_date); + values.put(CommonString.KEY_USER_TYPE, userType); + values.put("Pre_Setup_Img_One", counterimg_object.getPresetup_img_one_str()); + values.put("Pre_Setup_Img_Two", counterimg_object.getPresetup_img_two_str()); + values.put("Post_Setup_Img_One", counterimg_object.getPostsetup_img_one_str()); + values.put("Post_Setup_Img_Two", counterimg_object.getPostsetup_img_two_str()); + + values.put("Counter_Img_One", counterimg_object.getCounter_img_onefor_ba()); + values.put("Counter_Img_Two", counterimg_object.getCounter_img_two_for_ba()); + values.put("UNIQUE_CODE", counterimg_object.getTransId()); + values.put("UPLOAD_STATUS", CommonString.KEY_N); + + id = db.insert(CommonString.TABLE_COUNTER_IMAGE_DATA, null, values); + closeDb(); + } catch (Exception ex) { + closeDb(); + ////////test("Database Exception ", ex.toString()); + return 0; + } + return id; + } + + public long inseetgroomingdata(String counter_id, String user_id, String visit_date, GroomingGetterSetter groomedObject) { + db.delete(CommonString.TABLE_GROOMED_IMAGE_DATA, CommonString.KEY_VISIT_DATE + "<>'" + visit_date + "'", null); + long id = 0; + ContentValues values = new ContentValues(); + try { + db.beginTransaction(); + values.put(CommonString.KEY_COUNTER_ID, counter_id); + values.put(CommonString.KEY_USER_ID, user_id); + values.put(CommonString.KEY_VISIT_DATE, visit_date); + values.put("Mornning_groomed_img", groomedObject.getMorning_groom_img_str()); + values.put("Mornning_groomed_time", groomedObject.getMorning_groom_time_str()); + values.put("Noon_groomed_img", groomedObject.getNoon_groom_img_str()); + values.put("Noon_groomed_time", groomedObject.getNoon_groom_time_str()); + + values.put("Evening_groomed_img", groomedObject.getEvenning_groom_img_str()); + values.put("Evening_groomed_time", groomedObject.getEvenning_groom_time_str()); + values.put("UPLOAD_STATUS", groomedObject.getUpload_status()); + values.put("UNIQUE_CODE", groomedObject.getTransId()); + + id = db.insert(CommonString.TABLE_GROOMED_IMAGE_DATA, null, values); + closeDb(); + } catch (Exception ex) { + closeDb(); + ////////test("Database Exception ", ex.toString()); + return 0; + } + + return id; + } + + public GroomingGetterSetter getinserted_groomingdata(String counter_Id, String user_name, String visit_date) { + GroomingGetterSetter sb = new GroomingGetterSetter(); + Cursor dbcursor = null; + try { + dbcursor = db.rawQuery("Select * from " + CommonString.TABLE_GROOMED_IMAGE_DATA + " where COUNTER_ID=" + counter_Id + " And " + CommonString.KEY_USER_ID + "='" + user_name + "'And Visit_Date='" + visit_date + "'", null); + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + sb.setMorning_groom_img_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Mornning_groomed_img"))); + sb.setMorning_groom_time_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Mornning_groomed_time"))); + sb.setNoon_groom_img_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Noon_groomed_img"))); + sb.setNoon_groom_time_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Noon_groomed_time"))); + sb.setEvenning_groom_img_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Evening_groomed_img"))); + sb.setEvenning_groom_time_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Evening_groomed_time"))); + sb.setVisit_date(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_VISIT_DATE))); + + dbcursor.moveToNext(); + } + dbcursor.close(); + return sb; + } + } catch (Exception e) { + + return sb; + } + + return sb; + } + + + public ArrayList getgroomingdata(String counter_Id, String visit_date, boolean previous_date) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + + if (previous_date) { + dbcursor = db.rawQuery("Select * from " + CommonString.TABLE_GROOMED_IMAGE_DATA + " where COUNTER_ID=" + counter_Id + " And Visit_Date <>'" + visit_date + "' and UPLOAD_STATUS='N'", null); + + } else { + dbcursor = db.rawQuery("Select * from " + CommonString.TABLE_GROOMED_IMAGE_DATA + " where COUNTER_ID=" + counter_Id + " And Visit_Date='" + visit_date + "' and UPLOAD_STATUS='N'", null); + + } + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + GroomingGetterSetter sb = new GroomingGetterSetter(); + sb.setMorning_groom_img_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Mornning_groomed_img"))); + sb.setMorning_groom_time_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Mornning_groomed_time"))); + sb.setNoon_groom_img_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Noon_groomed_img"))); + sb.setNoon_groom_time_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Noon_groomed_time"))); + sb.setEvenning_groom_img_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Evening_groomed_img"))); + sb.setEvenning_groom_time_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Evening_groomed_time"))); + sb.setVisit_date(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_VISIT_DATE))); + sb.setUser_Id(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_USER_ID))); + list.add(sb); + + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list; + } + + } catch (Exception e) { + return list; + } + + return list; + } + + public ArrayList getBa(String visitDate, String counterId) { + + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + + dbcursor = db.rawQuery("SELECT * FROM BA_List WHERE VisitDate ='" + visitDate + "' and CounterId <>" + counterId + "", null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + BaListGetterSetter ch = new BaListGetterSetter(); + ch.setEmpId(Integer.valueOf(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EmpId")))); + ch.setUserName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("UserName"))); + ch.setVisitDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("VisitDate"))); + ch.setDesignationId(Integer.valueOf(dbcursor.getString(dbcursor.getColumnIndexOrThrow("DesignationId")))); + list.add(ch); + dbcursor.moveToNext(); + } + dbcursor.close(); + return list; + } + } catch (Exception e) { + return list; + } + return list; + } + + + public ArrayList getBAListAllData(String visitDate, String counterId) { + + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + + dbcursor = db.rawQuery("SELECT * FROM BA_List WHERE VisitDate ='" + visitDate + "' and CounterId =" + counterId + "", null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + BaListGetterSetter ch = new BaListGetterSetter(); + ch.setEmpId(Integer.valueOf(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EmpId")))); + ch.setUserName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("UserName"))); + ch.setVisitDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("VisitDate"))); + ch.setDesignationId(Integer.valueOf(dbcursor.getString(dbcursor.getColumnIndexOrThrow("DesignationId")))); + list.add(ch); + dbcursor.moveToNext(); + } + dbcursor.close(); + return list; + } + } catch (Exception e) { + return list; + } + return list; + } + + public ArrayList getBAListData(String userType, String counterId) { + + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + dbcursor = db.rawQuery("SELECT * FROM BA_List WHERE DesignationName ='" + userType + "' and CounterId=" + counterId + "", null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + BaListGetterSetter ch = new BaListGetterSetter(); + ch.setEmpId(Integer.valueOf(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EmpId")))); + ch.setUserName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("UserName"))); + ch.setVisitDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("VisitDate"))); + ch.setDesignationId(Integer.valueOf(dbcursor.getString(dbcursor.getColumnIndexOrThrow("DesignationId")))); + list.add(ch); + dbcursor.moveToNext(); + } + dbcursor.close(); + return list; + } + } catch (Exception e) { + + return list; + } + + return list; + } + + public long insertLoginData(LoginGetterSetter loginGetterSetter) { + db.delete(CommonString.TABLE_User_Login, "USER_ID='" + loginGetterSetter.getUserId() + "'", null); + ContentValues values = new ContentValues(); + long l = 0; + try { + db.beginTransaction(); + values.put("USER_ID", loginGetterSetter.getUserId().toLowerCase()); + values.put(CommonString.KEY_VISIT_DATE, loginGetterSetter.getVisitDate()); + values.put(CommonString.KEY_PASSWORD, loginGetterSetter.getPassword()); + values.put(CommonString.KEY_MPIN, loginGetterSetter.getMpin()); + ///jp_changes insert login tyme + values.put(CommonString.KEY_USER_LOGINTIME, loginGetterSetter.getUserLoginTym()); + values.put(CommonString.KEY_USER_TYPE, loginGetterSetter.getUserType()); + values.put(CommonString.KEY_USER_Checkout, loginGetterSetter.getUser_checkout()); + values.put(CommonString.KEY_IMAGE, ""); + l = db.insert(CommonString.TABLE_User_Login, null, values); + + closeDb(); + } catch (Exception ex) { + closeDb(); + ex.fillInStackTrace(); + } + + return l; + } + + public long updateVisitDateLoginData(String userId, String visit_date) { + long l = 0; + try { + ContentValues values = new ContentValues(); + values.put(CommonString.KEY_VISIT_DATE, visit_date); + values.put(CommonString.KEY_IMAGE, ""); + values.put(CommonString.KEY_USER_Checkout, "0"); + if (!db.isOpen()) { + open(); + } + l = db.update("User_login", values, "USER_ID='" + userId + "'", null); + + } catch (Exception e) { + e.fillInStackTrace(); + } + + return l; + } + + public long updateLoginTym(String userId, String visit_date, String loginTym) { + long l = 0; + try { + ContentValues values = new ContentValues(); + values.put(CommonString.KEY_VISIT_DATE, visit_date); + values.put(CommonString.KEY_USER_LOGINTIME, loginTym); + values.put(CommonString.KEY_USER_Checkout, "0"); + if (!db.isOpen()) { + open(); + } + l = db.update("User_login", values, "USER_ID='" + userId + "'", null); + } catch (Exception e) { + e.fillInStackTrace(); + } + + return l; + } + + public ArrayList getAxeNSubAxe(String counterGroup_Id, String column_name, String brandName, String axeName) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + if (brandName == null) { + dbcursor = db.rawQuery("select distinct " + column_name + " from Product_Master", null); + } else if (column_name.equals("SubAxeName") && axeName != null) { + dbcursor = db.rawQuery("select distinct " + column_name + " from Product_Master where AxeName ='" + axeName + "'", null); + } else { + dbcursor = db.rawQuery("select distinct " + column_name + " from Product_Master where BrandName =\"" + brandName + "\"", null); + } + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + ProductMaster sb = new ProductMaster(); + sb.setBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow(column_name))); + list.add(sb); + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list; + } + } catch (Exception e) { + + return list; + } + return list; + } + + // + public long insertMESaleCapturedData(String visit_date, HashMap> data, List save_listDataHeader, String uploadstatus, String counterId, String unique_code, String username) { + db.delete(CommonString.TABLE_INSERT_HEADER_ME_SALE_DATA, null, null); + db.delete(CommonString.TABLE_STORE_STOCK_CHILD_ME_SALE_DATA, null, null); + ContentValues values = new ContentValues(); + ContentValues values1 = new ContentValues(); + long lf = 0, l = 0; + try { + db.beginTransaction(); + for (int i = 0; i < save_listDataHeader.size(); i++) { + values.put("AxeName", save_listDataHeader.get(i).getSubBrandName()); + values.put("BrandName", save_listDataHeader.get(i).getBrandName()); + values.put("UploadStatus", uploadstatus); + values.put("UNIQUE_CODE", unique_code); + values.put("USER_ID", username); + values.put(CommonString.KEY_VISIT_DATE, visit_date); + values.put(CommonString.KEY_COUNTER_ID, counterId); + values.put("SubAxeName", save_listDataHeader.get(i).getSubAxeName()); + values.put("SignatureName", save_listDataHeader.get(i).getSignatureName()); + values.put("NuanceName", save_listDataHeader.get(i).getNuanceName()); + values.put("ImagePath", save_listDataHeader.get(i).getImagePath()); + lf = db.insert(CommonString.TABLE_INSERT_HEADER_ME_SALE_DATA, null, values); + for (int j = 0; j < data.get(save_listDataHeader.get(i)).size(); j++) { + values1.put(CommonString.KEY_COMMON_ID, l); + values1.put("USER_ID", username); + values1.put("STOCK", data.get(save_listDataHeader.get(i)).get(j).getStock()); + values1.put("STOCK_RECEIVED", data.get(save_listDataHeader.get(i)).get(j).getStock()); + values1.put("STOCK_RECEIVED", data.get(save_listDataHeader.get(i)).get(j).getStock()); + values1.put("ImagePath", save_listDataHeader.get(i).getImagePath()); + values1.put("UploadStatus", uploadstatus); + values1.put("UNIQUE_CODE", unique_code); + values1.put(CommonString.KEY_VISIT_DATE, visit_date); + values1.put(CommonString.KEY_COUNTER_ID, counterId); + values1.put("AxeName", save_listDataHeader.get(i).getSubBrandName()); + values1.put("NuanceName", save_listDataHeader.get(i).getNuanceName()); + values1.put("SubAxeName", save_listDataHeader.get(i).getSubAxeName()); + values1.put("ProductName", data.get(save_listDataHeader.get(i)).get(j).getProductName()); + values1.put("ProductId", data.get(save_listDataHeader.get(i)).get(j).getProductId()); + values1.put("EanCode", data.get(save_listDataHeader.get(i)).get(j).getEanCode()); + values1.put("Mrp", data.get(save_listDataHeader.get(i)).get(j).getMrp()); + values1.put("SignatureName", data.get(save_listDataHeader.get(i)).get(j).getSignatureName()); + values1.put("BrandName", data.get(save_listDataHeader.get(i)).get(j).getBrandName()); + values1.put("SubBrandName", data.get(save_listDataHeader.get(i)).get(j).getSubBrandName()); + values1.put("ReferenceName", data.get(save_listDataHeader.get(i)).get(j).getReferenceName()); + l = db.insert(CommonString.TABLE_STORE_STOCK_CHILD_ME_SALE_DATA, null, values1); + } + } + closeDb(); + } catch (Exception ex) { + ex.fillInStackTrace(); + closeDb(); + } + return l; + } + + + //Insert Stock data + public void insertStockCapturedData(String visit_date, HashMap> data, List save_listDataHeader, boolean completeFlag, String counterId) { + db.delete(CommonString.TABLE_INSERT_HEADER_STOCK_DATA, null, null); + db.delete(CommonString.TABLE_STORE_STOCK_CHILD_DATA, null, null); + ContentValues values = new ContentValues(); + TStockSummary stockObj; + try { + db.beginTransaction(); + for (int i = 0; i < save_listDataHeader.size(); i++) { + values.put("AxeName", save_listDataHeader.get(i).getSubBrandName()); + values.put("BrandName", save_listDataHeader.get(i).getBrandName()); + values.put(CommonString.KEY_VISIT_DATE, visit_date); + values.put(CommonString.KEY_COUNTER_ID, counterId); + values.put("SubAxeName", save_listDataHeader.get(i).getSubAxeName()); + values.put("SignatureName", save_listDataHeader.get(i).getSignatureName()); + values.put("NuanceName", save_listDataHeader.get(i).getNuanceName()); + values.put("ImagePath", save_listDataHeader.get(i).getImagePath()); + long l = db.insert(CommonString.TABLE_INSERT_HEADER_STOCK_DATA, null, values); + for (int j = 0; j < data.get(save_listDataHeader.get(i)).size(); j++) { + int stock = data.get(save_listDataHeader.get(i)).get(j).getStock(); + if (completeFlag && stock == -1) { + stock = 0; + } + + if (!db.isOpen()) { + open(); + } + // getting product details from TStockSummary Table + boolean stockFlag = isTStockSummaryProductFilled(data.get(save_listDataHeader.get(i)).get(j).getProductId()); + if (stockFlag) { + // set stock to product + updateTStockData(stock, CommonString.SALEABLE, data.get(save_listDataHeader.get(i)).get(j).getProductId(), completeFlag, visit_date); + } else { + stockObj = getStockSummaryStatus(visit_date); + if (stockObj != null) { + insertTStockSummaryData(stockObj, data.get(save_listDataHeader.get(i)).get(j).getProductId(), counterId, CommonString.SALEABLE, stock, completeFlag, visit_date); + } + } + } + } + db.setTransactionSuccessful(); + db.endTransaction(); + } catch (Exception ex) { + ex.fillInStackTrace(); + closeDb(); + } + } + + //get Stock header inserted data + public ArrayList getlistAllData(String visitDate, String user_name) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + dbcursor = db.rawQuery("Select * from User_login where USER_ID='" + user_name + "'", null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + LoginGetterSetter ch = new LoginGetterSetter(); + ch.setUserId(dbcursor.getString(dbcursor.getColumnIndexOrThrow("USER_ID"))); + ch.setImg(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_IMAGE))); + ch.setUserType(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_USER_TYPE))); + ch.setMpin(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_MPIN))); + ch.setVisitDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_VISIT_DATE))); + ch.setPassword(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_PASSWORD))); + ch.setUser_checkout(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_USER_Checkout))); + list.add(ch); + dbcursor.moveToNext(); + } + dbcursor.close(); + return list; + } + } catch (Exception e) { + return list; + } + return list; + } + + + //Insert Tester data + public void insertTesterCapturedData(String visit_date, HashMap> data, List save_listDataHeader, boolean completeFlag, String counterId) { + db.delete(CommonString.TABLE_INSERT_HEADER_TESTER_DATA, null, null); + db.delete(CommonString.TABLE_TESTER_CHILD_DATA, null, null); + ContentValues values = new ContentValues(); + + try { + db.beginTransaction(); + for (int i = 0; i < save_listDataHeader.size(); i++) { + values.put("AxeName", save_listDataHeader.get(i).getSubBrandName()); + values.put("BrandName", save_listDataHeader.get(i).getBrandName()); + values.put(CommonString.KEY_VISIT_DATE, visit_date); + values.put(CommonString.KEY_COUNTER_ID, counterId); + values.put("SubAxeName", save_listDataHeader.get(i).getSubAxeName()); + values.put("SignatureName", save_listDataHeader.get(i).getSignatureName()); + values.put("ImagePath", save_listDataHeader.get(i).getImagePath()); + values.put("NuanceName", save_listDataHeader.get(i).getNuanceName()); + long l = db.insert(CommonString.TABLE_INSERT_HEADER_TESTER_DATA, null, values); + for (int j = 0; j < data.get(save_listDataHeader.get(i)).size(); j++) { + if (db.isOpen()) { + } else { + open(); + } + // getting product details from TStockSummary Table + boolean stockFlag = isTStockSummaryProductFilled(data.get(save_listDataHeader.get(i)).get(j).getProductId()); + if (stockFlag) { + // set stock to product + updateTStockData(data.get(save_listDataHeader.get(i)).get(j).getStock(), CommonString.TESTER, data.get(save_listDataHeader.get(i)).get(j).getProductId(), completeFlag, visit_date); + } else { + if (db.isOpen()) { + } else { + open(); + } + TStockSummary stockObj; + stockObj = getStockSummaryStatus(visit_date); + if (stockObj != null) { + insertTStockSummaryData(stockObj, data.get(save_listDataHeader.get(i)).get(j).getProductId(), counterId, CommonString.TESTER, data.get(save_listDataHeader.get(i)).get(j).getStock(), completeFlag, visit_date); + } + } + } + } + + db.setTransactionSuccessful(); + db.endTransaction(); + } catch (Exception ex) { + ex.fillInStackTrace(); + } + } + + //get Tester header inserted data + public ArrayList getTesterHeaderInsertedData(String visitDate, boolean filledregularstock) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + + if (filledregularstock) { + dbcursor = db.rawQuery("select distinct t1.AxeName as AxeName,t1.SubAxeName as SubAxeName,t1.BrandName as BrandName," + "t1.SignatureName as SignatureName,t1.NuanceName as NuanceName,t1.ImagePath as ImagePath from DR_TESTER_HEADER_DATA t1 " + "inner join Product_Master t2 on t1.NuanceName= t2.NuanceName and t1.SubAxeName=t2.SubAxeName " + "Inner Join T_StockSummary TS ON t1.NuanceName= t2.NuanceName and t1.SubAxeName=t2.SubAxeName and TS.ProductId = t2.ProductId where TS.TesterBalance >'0' and t1.Visit_Date ='" + visitDate + "'", null); + + } else { + dbcursor = db.rawQuery("select * from " + CommonString.TABLE_INSERT_HEADER_TESTER_DATA + " where Visit_Date ='" + visitDate + "'", null); + } + + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + ProductMaster sb = new ProductMaster(); + + sb.setSubBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("AxeName"))); + sb.setSubAxeName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SubAxeName"))); + sb.setBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("BrandName"))); + sb.setSignatureName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SignatureName"))); + sb.setNuanceName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("NuanceName"))); + sb.setImagePath(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ImagePath"))); + + list.add(sb); + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list; + } + } catch (Exception e) { + + return list; + } + + return list; + } + + //Insert Sample Data + public void insertSampleCapturedData(String visit_date, HashMap> data, List save_listDataHeader, boolean completeFlag, String counterId) { + db.delete(CommonString.TABLE_INSERT_HEADER_SAMPLE_DATA, null, null); + db.delete(CommonString.TABLE_SAMPLE_CHILD_DATA, null, null); + ContentValues values = new ContentValues(); + try { + db.beginTransaction(); + if (!db.isOpen()) { + open(); + } + for (int i = 0; i < save_listDataHeader.size(); i++) { + values.put("AxeName", save_listDataHeader.get(i).getSubBrandName()); + values.put("BrandName", save_listDataHeader.get(i).getBrandName()); + values.put(CommonString.KEY_VISIT_DATE, visit_date); + values.put(CommonString.KEY_COUNTER_ID, counterId); + values.put("SubAxeName", save_listDataHeader.get(i).getSubAxeName()); + values.put("SignatureName", save_listDataHeader.get(i).getSignatureName()); + values.put("NuanceName", save_listDataHeader.get(i).getNuanceName()); + values.put("ImagePath", save_listDataHeader.get(i).getImagePath()); + long l = db.insert(CommonString.TABLE_INSERT_HEADER_SAMPLE_DATA, null, values); + for (int j = 0; j < data.get(save_listDataHeader.get(i)).size(); j++) { + if (!db.isOpen()) { + open(); + } + // getting product details from TStockSummary Table + boolean stockFlag = isTStockSummaryProductFilled(data.get(save_listDataHeader.get(i)).get(j).getProductId()); + if (stockFlag) { + // set stock to product + updateTStockData(data.get(save_listDataHeader.get(i)).get(j).getStock(), CommonString.SAMPLE, data.get(save_listDataHeader.get(i)).get(j).getProductId(), completeFlag, visit_date); + } else { + if (!db.isOpen()) { + open(); + } + TStockSummary stockObj; + stockObj = getStockSummaryStatus(visit_date); + if (stockObj != null) { + insertTStockSummaryData(stockObj, data.get(save_listDataHeader.get(i)).get(j).getProductId(), counterId, CommonString.SAMPLE, data.get(save_listDataHeader.get(i)).get(j).getStock(), completeFlag, visit_date); + } + } + } + } + db.setTransactionSuccessful(); + db.endTransaction(); + } catch (Exception ex) { + ex.fillInStackTrace(); + + } + } + + //get Sample header inserted data + public ArrayList getSampleHeaderInsertedData(String visitDate, String counterId, boolean regularstock) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + if (regularstock) { + dbcursor = db.rawQuery("select distinct t1.AxeName as AxeName,t1.SubAxeName as SubAxeName,t1.BrandName as BrandName," + "t1.SignatureName as SignatureName,t1.NuanceName as NuanceName,t1.ImagePath as ImagePath from DR_SAMPLE_HEADER_DATA t1 " + "inner join Product_Master t2 on t1.NuanceName= t2.NuanceName and t1.SubAxeName=t2.SubAxeName " + "Inner Join T_StockSummary TS ON t1.NuanceName= t2.NuanceName and t1.SubAxeName=t2.SubAxeName and TS.ProductId = t2.ProductId where TS.SampleBalance >'0' and t1.Visit_Date ='" + visitDate + "'and t1.COUNTER_ID='" + counterId + "'", null); + + } else { + dbcursor = db.rawQuery("select * from " + CommonString.TABLE_INSERT_HEADER_SAMPLE_DATA + " where Visit_Date ='" + visitDate + "'and COUNTER_ID='" + counterId + "'", null); + } + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + ProductMaster sb = new ProductMaster(); + sb.setSubBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("AxeName"))); + sb.setSubAxeName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SubAxeName"))); + sb.setBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("BrandName"))); + sb.setSignatureName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SignatureName"))); + sb.setNuanceName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("NuanceName"))); + sb.setImagePath(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ImagePath"))); + list.add(sb); + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list; + } + } catch (Exception e) { + + return list; + } + + return list; + } + + //Insert Damaged Data + public long insertDamagedCapturedData(String visit_date, String counterId, HashMap> data, List save_listDataHeader) { + db.delete(CommonString.TABLE_INSERT_HEADER_DAMAGED_DATA, null, null); + db.delete(CommonString.TABLE_DAMAGED_CHILD_DATA, null, null); + ContentValues values1 = new ContentValues(); + long l = 0; + try { + db.beginTransaction(); + for (int i = 0; i < save_listDataHeader.size(); i++) { + for (int j = 0; j < data.get(save_listDataHeader.get(i)).size(); j++) { + + values1.put("AxeName", save_listDataHeader.get(i).getSubBrandName()); + values1.put("BrandName", save_listDataHeader.get(i).getBrandName()); + values1.put(CommonString.KEY_VISIT_DATE, visit_date); + values1.put(CommonString.KEY_COUNTER_ID, counterId); + values1.put("SubAxeName", save_listDataHeader.get(i).getReferenceName()); + values1.put("ProductName", data.get(save_listDataHeader.get(i)).get(j).getProductName()); + values1.put("ProductId", data.get(save_listDataHeader.get(i)).get(j).getProductId()); + values1.put("STOCK", data.get(save_listDataHeader.get(i)).get(j).getStock()); + values1.put("Mrp", data.get(save_listDataHeader.get(i)).get(j).getMrp()); + values1.put("STOCK_RECEIVED", data.get(save_listDataHeader.get(i)).get(j).getStock_receive()); + values1.put("ImagePath", data.get(save_listDataHeader.get(i)).get(j).getImagePath()); + l = db.insert(CommonString.TABLE_DAMAGED_CHILD_DATA, null, values1); + } + } + closeDb(); + } catch (Exception ex) { + closeDb(); + ex.fillInStackTrace(); + } + + return l; + } + + + //Insert Suggested Stock Data + public void insertSuggestedStockCapturedData(String visit_date, HashMap> data, List save_listDataHeader) { + db.delete(CommonString.TABLE_INSERT_HEADER_SUGGESTED_STOCK_DATA, null, null); + db.delete(CommonString.TABLE_SUGGESTED_STOCK_CHILD_DATA, null, null); + + ContentValues values = new ContentValues(); + ContentValues values1 = new ContentValues(); + + try { + db.beginTransaction(); + for (int i = 0; i < save_listDataHeader.size(); i++) { + values.put("AxeName", save_listDataHeader.get(i).getAxeName()); + values.put("BrandName", save_listDataHeader.get(i).getBrandName()); + values.put(CommonString.KEY_VISIT_DATE, visit_date); + values.put("SubAxeName", save_listDataHeader.get(i).getSubAxeName()); + values.put("ImagePath", save_listDataHeader.get(i).getImagePath()); + long l = db.insert(CommonString.TABLE_INSERT_HEADER_SUGGESTED_STOCK_DATA, null, values); + for (int j = 0; j < data.get(save_listDataHeader.get(i)).size(); j++) { + values1.put("Common_Id", (int) l); + values1.put("AxeName", save_listDataHeader.get(i).getAxeName()); + values1.put("BrandName", save_listDataHeader.get(i).getBrandName()); + values1.put(CommonString.KEY_VISIT_DATE, visit_date); + values1.put("SubAxeName", save_listDataHeader.get(i).getSubAxeName()); + values1.put("ProductName", data.get(save_listDataHeader.get(i)).get(j).getProductName()); + values1.put("ProductId", data.get(save_listDataHeader.get(i)).get(j).getProductId()); + values1.put("STOCK", data.get(save_listDataHeader.get(i)).get(j).getStock()); + values1.put("Mrp", data.get(save_listDataHeader.get(i)).get(j).getMrp()); + values1.put("STOCK_RECEIVED", data.get(save_listDataHeader.get(i)).get(j).getStock_receive()); + + db.insert(CommonString.TABLE_SUGGESTED_STOCK_CHILD_DATA, null, values1); + } + } + closeDb(); + } catch (Exception ex) { + closeDb(); + ex.fillInStackTrace(); + } + } + + //get Suggested Stock header inserted data + public ArrayList getSuggestedStockHeaderInsertedData(String visitDate) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + dbcursor = db.rawQuery("select * from " + CommonString.TABLE_INSERT_HEADER_SUGGESTED_STOCK_DATA + " where Visit_Date ='" + visitDate + "'", null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + ProductMaster sb = new ProductMaster(); + + sb.setAxeName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("AxeName"))); + sb.setSubAxeName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SubAxeName"))); + sb.setBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("BrandName"))); + sb.setImagePath(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ImagePath"))); + + list.add(sb); + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list; + } + } catch (Exception e) { + + return list; + } + + return list; + } + + + //get Child Suggested data + public ArrayList getSuggestedInsertedData(String axeName, String subAxeName, String brandName) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + + dbcursor = db.rawQuery("SELECT * from " + CommonString.TABLE_SUGGESTED_STOCK_CHILD_DATA + " where SubAxeName =\"" + subAxeName + "\" AND AxeName=\"" + axeName + "\" AND BrandName=\"" + brandName + "\"", null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + ProductMaster sb = new ProductMaster(); + sb.setProductName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ProductName"))); + sb.setProductId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("ProductId"))); + sb.setStock(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("STOCK"))); + sb.setMrp(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("Mrp"))); + + + list.add(sb); + dbcursor.moveToNext(); + } + dbcursor.close(); + return list; + } + } catch (Exception e) { + return list; + } + + return list; + } + + public boolean insertTCounterInvoiceData(TCounterInvoiceGetterSetter cst) { + db.delete("T_CounterInvoice", null, null); + ContentValues values = new ContentValues(); + List data = cst.getTCounterInvoice(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("InvId", data.get(i).getInvId()); + values.put("CounterId", data.get(i).getCounterId()); + values.put("InvoiceNo", data.get(i).getInvoiceNo().trim()); + values.put("InvoiceDate", data.get(i).getInvoiceDate()); + values.put("ProductId", data.get(i).getProductId()); + values.put("Qty", data.get(i).getQty()); + values.put("Amount", data.get(i).getAmount()); + values.put("InvoiceType", data.get(i).getInvoiceType().trim()); + values.put("CounterConfirm", data.get(i).getCounterConfirm()); + values.put("InvoiceStatus", data.get(i).getInvoiceStatus()); + values.put("VisitDate", data.get(i).getVisitDate()); + values.put("ActualQty", data.get(i).getActualQty()); + values.put("ReasonId", data.get(i).getReasonId()); + values.put("TranId", data.get(i).getTranId()); + + if (!db.isOpen()) open(); + + long id = db.insert("T_CounterInvoice", null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ex.fillInStackTrace(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + + public boolean insertTStockSummaryData(TStockSummaryGetterSetter cst, String counterId, String date) { + db.delete("T_StockSummary", null, null); + ContentValues values = new ContentValues(); + List data = cst.gettStockSummary(); + try { + + if (data.isEmpty()) { + return false; + } + + ArrayList sumcheck = getStockSummaryCheck(counterId, date); + if (!sumcheck.isEmpty()) { + int totallinecount = sumcheck.get(0).getTotalLine(); + int data_size = data.size(); + if (totallinecount != data_size) { + delete_table_data("T_StockSummary"); + throw new Exception(); + } + } + db.beginTransaction(); + if (!data.isEmpty()) { + for (TStockSummary tStockSummary : data) { + values = new ContentValues(); + values.put("Id", tStockSummary.getId()); + values.put("CounterId", tStockSummary.getCounterId()); + values.put("ProductId", tStockSummary.getProductId()); + values.put("SaleableIn", tStockSummary.getSaleableIn()); + values.put("SaleableOut", tStockSummary.getSaleableOut()); + values.put("SaleableDamage", tStockSummary.getSaleableDamage()); + values.put("SaleableBalance", tStockSummary.getSaleableBalance()); + values.put("TesterIn", tStockSummary.getTesterIn()); + values.put("TesterOut", tStockSummary.getTesterOut()); + values.put("TesterDamage", tStockSummary.getTesterDamage()); + values.put("TesterBalance", tStockSummary.getTesterBalance()); + values.put("SampleIn", tStockSummary.getSampleIn()); + values.put("SampleOut", tStockSummary.getSampleOut()); + values.put("SampleDamage", tStockSummary.getSampleDamage()); + values.put("SampleBalance", tStockSummary.getSampleBalance()); + values.put("GwpIn", tStockSummary.getGwpIn()); + values.put("GwpOut", tStockSummary.getGwpOut()); + values.put("GwpDamage", tStockSummary.getGwpDamage()); + values.put("GwpBalance", tStockSummary.getGwpBalance()); + values.put("SaleableStatus", tStockSummary.getSaleableStatus().trim()); + values.put("TesterStatus", tStockSummary.getTesterStatus().trim()); + values.put("SampleStatus", tStockSummary.getSampleStatus().trim()); + values.put("GwpStatus", tStockSummary.getGwpStatus().trim()); + values.put("VisitDate", tStockSummary.getVisitDate()); + if (!db.isOpen()) { + open(); + } + long l = db.insert("T_StockSummary", null, values); + if (l == -1) { + throw new Exception(); + } + + } + + if (isTStockTotalLine(date, counterId, "T_StockSummary") != data.size()) { + delete_table_data("T_StockSummary"); + throw new Exception(); + } + } + // do ALL your inserts here + db.setTransactionSuccessful(); + db.endTransaction(); + + return true; + } catch (Exception ex) { + ex.fillInStackTrace(); + db.setTransactionSuccessful(); + db.endTransaction(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + + public long updateLoginData(String userId, String new_password, boolean flag) { + long l = 0; + try { + if (db.isOpen()) { + } else { + open(); + } + ContentValues values = new ContentValues(); + if (flag) { + values.put(CommonString.KEY_PASSWORD, new_password); + } else { + values.put(CommonString.KEY_USER_Checkout, "1"); + } + + l = db.update("User_login", values, "USER_ID='" + userId + "'", null); + } catch (Exception e) { + e.fillInStackTrace(); + } + + return l; + } + + public ArrayList getVisibility_inserted_data(String counterId, String visit_date, String transId, boolean manual_upload) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + if (manual_upload) { + dbcursor = db.rawQuery("Select distinct pt.UUID_ID as UUID_ID, Pt.Posm as Posm,Pt.PosmId as PosmId,Pt.PosmTypeId as PosmTypeId," + "Pt.RefImage as RefImage,Pt.Resion as Resion,Pt.Resion_id as Resion_id,pt.User_Id as User_Id," + "Pt.VISIBILITY_EXIST as VISIBILITY_EXIST,Pt.VISIBILITY_IMG as VISIBILITY_IMG from VISIBILITY_TABLE Pt Inner Join Master_Posm Pm " + "On Pt.PosmId=Pm.PosmId where Pt.COUNTER_ID='" + counterId + "' and " + CommonString.KEY_UUID + "='" + transId + "'and " + CommonString.KEY_STATUS + " ='N'", null); + + } else { + + dbcursor = db.rawQuery("Select distinct pt.UUID_ID as UUID_ID, Pt.Posm as Posm,Pt.PosmId as PosmId,Pt.PosmTypeId as PosmTypeId," + "Pt.RefImage as RefImage,Pt.Resion as Resion,Pt.Resion_id as Resion_id,pt.User_Id as User_Id," + "Pt.VISIBILITY_EXIST as VISIBILITY_EXIST,Pt.VISIBILITY_IMG as VISIBILITY_IMG from VISIBILITY_TABLE Pt Inner Join Master_Posm Pm " + "On Pt.PosmId=Pm.PosmId where Pt.COUNTER_ID='" + counterId + "' and " + CommonString.KEY_VISIT_DATE + "='" + visit_date + "'", null); + } + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + MasterPosm sale = new MasterPosm(); + + sale.setPosm(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Posm"))); + sale.setPosmTypeId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("PosmId"))); + sale.setPromotion_exists_state(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PosmTypeId"))); + sale.setRefImage(dbcursor.getString(dbcursor.getColumnIndexOrThrow("RefImage"))); + sale.setPromotion_currect_ans(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Resion"))); + sale.setPromotion_currect_ans_Id(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Resion_id"))); + sale.setPromotion_exists_state(dbcursor.getString(dbcursor.getColumnIndexOrThrow("VISIBILITY_EXIST"))); + sale.setPromotion_img(dbcursor.getString(dbcursor.getColumnIndexOrThrow("VISIBILITY_IMG"))); + sale.setTransId(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_UUID))); + sale.setUserId(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_USER_ID))); + + list.add(sale); + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list; + } + + } catch (Exception e) { + + return list; + } + return list; + } + + public ArrayList getVisibility_master_data(String counterId) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + + dbcursor = db.rawQuery("SELECT MP.PosmId as PosmId,MP.Posm as Posm,MP.PosmTypeId as PosmTypeId,MP.RefImage as RefImage FROM Master_Posm MP inner join Mapping_Visibility MV ON MV.PosmId=MP.PosmId where MV.CounterId='" + counterId + "'", null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + + MasterPosm sale = new MasterPosm(); + sale.setPosm(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Posm"))); + sale.setPosmId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("PosmId"))); + sale.setPosmTypeId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("PosmTypeId"))); + sale.setRefImage(dbcursor.getString(dbcursor.getColumnIndexOrThrow("RefImage"))); + + sale.setPromotion_exists_state(""); + sale.setPromotion_img(""); + sale.setPromotion_currect_ans(""); + sale.setPromotion_currect_ans_Id("0"); + + list.add(sale); + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list; + } + + } catch (Exception e) { + + return list; + } + return list; + } + + public boolean insertMasterNonVisibilityData(MasterNonVisibilityGetterSetter cst) { + db.delete("Master_NonVisibility", null, null); + ContentValues values = new ContentValues(); + List data = cst.getMasterNonVisibility(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("Reason", data.get(i).getReason()); + values.put("ReasonId", data.get(i).getReasonId()); + long id = db.insert("Master_NonVisibility", null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ex.fillInStackTrace(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + public ArrayList getnon_promotion_reasonList() { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + dbcursor = db.rawQuery("Select * from Master_NonVisibility", null); + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + MasterNonVisibility sale = new MasterNonVisibility(); + sale.setReason(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Reason"))); + sale.setReasonId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("ReasonId"))); + list.add(sale); + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list; + } + + } catch (Exception e) { + return list; + } + return list; + } + + public long insertVisibility_data(String userId, String counterId, String visit_date, ArrayList visibilitylist, String uuid_ID) { + db.delete(CommonString.Table_visibilisty, null, null); + db.delete(CommonString.TABLE_TRANSACTION_WISE_MASTER_TABLE, CommonString.KEY_VISIT_DATE + "<>'" + visit_date + "'", null); + ContentValues values = new ContentValues(); + ContentValues finalvalues = new ContentValues(); + long l = 0, masterreturn = 0; + try { + db.beginTransaction(); + finalvalues.put(CommonString.KEY_UUID, uuid_ID); + finalvalues.put(CommonString.KEY_USER_ID, userId); + finalvalues.put(CommonString.KEY_COUNTER_ID, counterId); + finalvalues.put(CommonString.KEY_VISIT_DATE, visit_date); + finalvalues.put(CommonString.KEY_STOCK_TYPE, CommonString.VISIBILITY); + finalvalues.put(CommonString.KEY_ENTRY_TYPE, CommonString.KEY_REGULAR); + finalvalues.put(CommonString.KEY_STATUS, CommonString.KEY_N); + + masterreturn = db.insert(CommonString.TABLE_TRANSACTION_WISE_MASTER_TABLE, null, finalvalues); + + for (int k = 0; k < visibilitylist.size(); k++) { + values.put(CommonString.KEY_UUID, uuid_ID); + values.put(CommonString.KEY_MASTER_TRANSACTION_ID, masterreturn); + values.put(CommonString.KEY_STATUS, CommonString.KEY_N); + values.put(CommonString.KEY_COUNTER_ID, counterId); + values.put(CommonString.KEY_VISIT_DATE, visit_date); + values.put(CommonString.KEY_USER_ID, userId); + values.put("Posm", visibilitylist.get(k).getPosm()); + values.put("PosmId", visibilitylist.get(k).getPosmId()); + values.put("PosmTypeId", visibilitylist.get(k).getPosmTypeId()); + values.put("RefImage", visibilitylist.get(k).getRefImage()); + values.put("Resion", visibilitylist.get(k).getPromotion_currect_ans()); + values.put("Resion_id", visibilitylist.get(k).getPromotion_currect_ans_Id()); + values.put("VISIBILITY_EXIST", visibilitylist.get(k).getPromotion_exists_state()); + values.put("VISIBILITY_IMG", visibilitylist.get(k).getPromotion_img()); + + l = db.insert(CommonString.Table_visibilisty, null, values); + } + closeDb(); + } catch (Exception ex) { + closeDb(); + ////////test("Database Exception", ex.toString()); + } + return l; + } + + public long insertCompOffers(String userId, String counterId, String visit_date, ArrayList compOffers, String uuid_ID) { + long l = 0, masterreturn = 0; + Gson gson = new Gson(); + try { + db.delete(CommonString.TABLE_COMP_OFFERS, CommonString.KEY_VISIT_DATE + "<>'" + visit_date + "'", null); + db.delete(CommonString.TABLE_TRANSACTION_WISE_MASTER_TABLE, CommonString.KEY_VISIT_DATE + "<>'" + visit_date + "'", null); + ContentValues values = new ContentValues(); + ContentValues finalvalues = new ContentValues(); + + db.beginTransaction(); + finalvalues.put(CommonString.KEY_UUID, uuid_ID); + finalvalues.put(CommonString.KEY_USER_ID, userId); + finalvalues.put(CommonString.KEY_COUNTER_ID, counterId); + finalvalues.put(CommonString.KEY_VISIT_DATE, visit_date); + finalvalues.put(CommonString.KEY_STOCK_TYPE, CommonString.COMP_OFFERS); + finalvalues.put(CommonString.KEY_ENTRY_TYPE, CommonString.KEY_REGULAR); + finalvalues.put(CommonString.KEY_STATUS, CommonString.KEY_N); + + masterreturn = db.insert(CommonString.TABLE_TRANSACTION_WISE_MASTER_TABLE, null, finalvalues); + + for (int k = 0; k < compOffers.size(); k++) { + values.put(CommonString.KEY_UUID, uuid_ID); + values.put(CommonString.KEY_MASTER_TRANSACTION_ID, masterreturn); + values.put(CommonString.KEY_STATUS, CommonString.KEY_N); + values.put(CommonString.KEY_COUNTER_ID, counterId); + values.put(CommonString.KEY_VISIT_DATE, visit_date); + values.put(CommonString.KEY_USER_ID, userId); + values.put("PRESENT", compOffers.get(k).getPresent_str()); + values.put("DATA_FOR_MONTH", compOffers.get(k).getDateOfMonth()); + values.put("COMPANY", compOffers.get(k).getCompetitionBrand()); + values.put("COMPANY_ID", compOffers.get(k).getCompetitionBrandId()); + values.put("NUANCE", compOffers.get(k).getCompetitionNuance()); + values.put("NUANCE_ID", compOffers.get(k).getCompetitionNuanceId()); + values.put("PROMOTYPE", compOffers.get(k).getPromoType()); + values.put("PROMOTYPE_ID", compOffers.get(k).getPromoTypeId()); + values.put("NUM_COUNTER", compOffers.get(k).getCounter()); + values.put("NO_OF_BA", compOffers.get(k).getNoOfBa()); + values.put("SALE_RANGE", compOffers.get(k).getSaleRange()); + values.put("COMP_OFFER", compOffers.get(k).getPromoType()); + values.put("COMP_OFFER_ID", compOffers.get(k).getPromoTypeId()); + values.put("COMP_BUY_TYPE", compOffers.get(k).getBuyType()); + values.put("COMP_BUY_TYPE_ID", compOffers.get(k).getBuyTypeId()); + values.put("COMP_BUY_TYPE_INPUT_ID", compOffers.get(k).getBuyTypeInputId()); + values.put("COMP_BUY_TYPE_INPUT", compOffers.get(k).getBuyTypeInput()); + values.put("COMP_GET_TYPE_INPUT_ID", compOffers.get(k).getGetTypeInputId()); + values.put("COMP_GET_TYPE_INPUT", compOffers.get(k).getGetTypeInput()); + values.put("COMP_NEW_LAUNCH_MRP", compOffers.get(k).getNewLaunchMrp()); + values.put("COMPOFFERSET_QTY", compOffers.get(k).getBuyQuantity()); + values.put("COMPOFFERSET", compOffers.get(k).getCompOfferset()); + values.put("COMPOFFERSET_ID", compOffers.get(k).getCompOffersetId()); + values.put("COMPOFFERGET_QTY", compOffers.get(k).getGetQuantity()); + values.put("COMPOFFERGET", compOffers.get(k).getCompOfferGet()); + values.put("COMPOFFERGET_ID", compOffers.get(k).getCompOfferGetId()); + values.put("FROM_DATE", compOffers.get(k).getFromDate()); + values.put("TO_DATE", compOffers.get(k).getToDate()); + values.put("PRODUCTTYPE", compOffers.get(k).getProductType()); + values.put("PRODUCTTYPE_ID", compOffers.get(k).getProductTypeId()); + values.put("PROMO_DETAILS", compOffers.get(k).getCompPromDetail()); + values.put("PROMO_IMG", compOffers.get(k).getCompOfferImg()); + values.put("AVG_TARGET", compOffers.get(k).getAvgtarget()); + values.put("AVG_OFFTAKE", compOffers.get(k).getAvgOfftake()); + values.put("TVA_PER", compOffers.get(k).getTvapercent()); + values.put("GWP_AVAILABLE", compOffers.get(k).getGwpAvailable()); + values.put("GWP_IMAGE", compOffers.get(k).getGwpImage()); + String baInfoJson = gson.toJson(compOffers.get(k).getBaTenureDetailList()); + values.put("BA_INFO_LIST", baInfoJson); + l = db.insert(CommonString.TABLE_COMP_OFFERS, null, values); + } + closeDb(); + } catch (Exception ex) { + closeDb(); + ////////test("Database Exception", ex.toString()); + } + + return l; + } + + public ArrayList getInsertedCompOffers(String visit_date, String counterId, String transId, boolean upload) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + if (upload) { + dbcursor = db.rawQuery("SELECT * FROM " + CommonString.TABLE_COMP_OFFERS + " WHERE " + CommonString.KEY_COUNTER_ID + "='" + counterId + "' AND " + CommonString.KEY_VISIT_DATE + "='" + visit_date + "'AND " + CommonString.KEY_UUID + "='" + transId + "'and " + CommonString.KEY_STATUS + " ='N'", null); + } else { + dbcursor = db.rawQuery("SELECT * FROM " + CommonString.TABLE_COMP_OFFERS + " WHERE " + CommonString.KEY_VISIT_DATE + "='" + visit_date + "' AND " + CommonString.KEY_COUNTER_ID + "='" + counterId + "'", null); + } + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + MasterCompetitonBrandWiseNuance sb = new MasterCompetitonBrandWiseNuance(); + sb.setKeyId(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_ID))); + sb.setuUId(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_UUID))); + sb.setStatus(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_STATUS))); + sb.set_userId(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_USER_ID))); + sb.setPresent_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PRESENT"))); + sb.setDateOfMonth(dbcursor.getString(dbcursor.getColumnIndexOrThrow("DATA_FOR_MONTH"))); + sb.setCompetitionBrand(dbcursor.getString(dbcursor.getColumnIndexOrThrow("COMPANY"))); + sb.setCompetitionBrandId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("COMPANY_ID"))); + sb.setCompetitionNuance(dbcursor.getString(dbcursor.getColumnIndexOrThrow("NUANCE"))); + sb.setCompetitionNuanceId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("NUANCE_ID"))); + sb.setPromoType(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PROMOTYPE"))); + sb.setPromoTypeId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("PROMOTYPE_ID"))); + sb.setCounter(dbcursor.getString(dbcursor.getColumnIndexOrThrow("NUM_COUNTER"))); + sb.setNoOfBa(dbcursor.getString(dbcursor.getColumnIndexOrThrow("NO_OF_BA"))); + sb.setSaleRange(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SALE_RANGE"))); + sb.setBuyType(dbcursor.getString(dbcursor.getColumnIndexOrThrow("COMP_BUY_TYPE"))); + sb.setBuyTypeId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("COMP_BUY_TYPE_ID"))); + sb.setBuyTypeInput(dbcursor.getString(dbcursor.getColumnIndexOrThrow("COMP_BUY_TYPE_INPUT"))); + sb.setBuyTypeInputId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("COMP_BUY_TYPE_INPUT_ID"))); + sb.setGetTypeInput(dbcursor.getString(dbcursor.getColumnIndexOrThrow("COMP_GET_TYPE_INPUT"))); + sb.setGetTypeInputId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("COMP_GET_TYPE_INPUT_ID"))); + sb.setNewLaunchMrp(dbcursor.getString(dbcursor.getColumnIndexOrThrow("COMP_NEW_LAUNCH_MRP"))); + sb.setCompOfferGet(dbcursor.getString(dbcursor.getColumnIndexOrThrow("COMPOFFERGET"))); + sb.setCompOfferGetId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("COMPOFFERGET_ID"))); + sb.setCompOfferset(dbcursor.getString(dbcursor.getColumnIndexOrThrow("COMPOFFERSET"))); + sb.setCompOffersetId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("COMPOFFERSET_ID"))); + sb.setProductType(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PRODUCTTYPE"))); + sb.setProductTypeId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("PRODUCTTYPE_ID"))); + sb.setFromDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("FROM_DATE"))); + sb.setToDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("TO_DATE"))); + sb.setCompPromDetail(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PROMO_DETAILS"))); + sb.setCompOfferImg(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PROMO_IMG"))); + sb.setBuyQuantity(dbcursor.getString(dbcursor.getColumnIndexOrThrow("COMPOFFERSET_QTY"))); + sb.setGetQuantity(dbcursor.getString(dbcursor.getColumnIndexOrThrow("COMPOFFERGET_QTY"))); + sb.setAvgtarget(dbcursor.getString(dbcursor.getColumnIndexOrThrow("AVG_TARGET"))); + sb.setAvgOfftake(dbcursor.getString(dbcursor.getColumnIndexOrThrow("AVG_OFFTAKE"))); + sb.setTvapercent(dbcursor.getString(dbcursor.getColumnIndexOrThrow("TVA_PER"))); + sb.setGwpAvailable(dbcursor.getString(dbcursor.getColumnIndexOrThrow("GWP_AVAILABLE"))); + sb.setGwpImage(dbcursor.getString(dbcursor.getColumnIndexOrThrow("GWP_IMAGE"))); + String baInfoJson = dbcursor.getString(dbcursor.getColumnIndexOrThrow("BA_INFO_LIST")); + Type type = new TypeToken>() { + }.getType(); + List baInfoList = new Gson().fromJson(baInfoJson, type); + sb.setBaTenureDetailList(baInfoList); + list.add(sb); + dbcursor.moveToNext(); + } + dbcursor.close(); + return list; + } + } catch (Exception e) { + ////////test("Exception", " when fetching Primary Visibility !!!!!!!!!!! " + e.toString()); + return list; + } + ////////test("Fetching", " opening stock---------------------->Stop<-----------"); + return list; + } + + // neeraj db changes added + public ArrayList getInwardStockData(String counter_id, String visit_date) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + String day = "", month = "", year = "", final_date = ""; + try { + + dbcursor = db.rawQuery(" select InvoiceNo, InvoiceDate,InvoiceStatus, InvoiceType, sum(CounterConfirm) as ApprovedLine," + + " count(ProductId) as NoofLine, sum(Amount) as FinalAmount from " + + "(select InvoiceNo, Qty, Amount, InvoiceType, InvoiceDate,InvoiceStatus, ProductId, " + + "case when (CounterConfirm + localConfirm)>0 then 1 else 0 end as CounterConfirm from " + + "(select d.InvId, d.CounterId, d.InvoiceNo, d.InvoiceDate,d.InvoiceStatus, d.ProductId, d.Qty, d.Amount," + + " d.InvoiceType, d.CounterConfirm, t.InvId ," + + " case when t.InvId is null then 0 else 1 end as localConfirm from T_CounterInvoice d" + + " Left join DR_INWARD_STOCK_TRANSACTION t on d.InvId = t.InvId" + + " Inner join Product_Master Pm on d.ProductId = Pm.ProductId where d.CounterId = '" + counter_id + + "' and d.VisitDate = '" + visit_date + "'" + " )as t) as t group by InvoiceNo, InvoiceDate, InvoiceType order by InvoiceDate desc ", null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + TCounterInvoice sb = new TCounterInvoice(); + sb.setInvoiceNo(dbcursor.getString(dbcursor.getColumnIndexOrThrow("InvoiceNo"))); + sb.setInvoiceType(dbcursor.getString(dbcursor.getColumnIndexOrThrow("InvoiceType"))); + String invoiceStatus = dbcursor.getString(dbcursor.getColumnIndexOrThrow("InvoiceStatus")); + String[] date_format = dbcursor.getString(dbcursor.getColumnIndexOrThrow("InvoiceDate")).split("-"); + year = date_format[0]; + month = date_format[1]; + day = date_format[2]; + final_date = month + "-" + day + "-" + year; + sb.setInvoiceDate(final_date); + sb.setApproved_line(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ApprovedLine"))); + sb.setInvoiceStatus(invoiceStatus != null && invoiceStatus.equals("0") ? false : true); + sb.setNo_ofLine(dbcursor.getString(dbcursor.getColumnIndexOrThrow("NoofLine"))); + sb.setFinalAmount(dbcursor.getString(dbcursor.getColumnIndexOrThrow("FinalAmount"))); + sb.setUpload_status(""); + sb.setSource(""); + list.add(sb); + dbcursor.moveToNext(); + } + dbcursor.close(); + return list; + } + } catch (Exception e) { + return list; + } + + return list; + } + + // neeraj code commited + public boolean insertServerTimeData(ServerTimeGetterSetter cst) { + db.delete("ServerTime", null, null); + ContentValues values = new ContentValues(); + List data = cst.getServerTime(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("ServerDate", data.get(i).getServerDate()); + values.put("ServerTime", data.get(i).getServerTime()); + long id = db.insert("ServerTime", null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ex.fillInStackTrace(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + + public boolean insertTStockSummaryCheck(ServerTimeGetterSetter cst) { + db.delete("StockSummary_Check", null, null); + ContentValues values = new ContentValues(); + List data = cst.getStockSummaryCheck(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("CounterId", data.get(i).getCounterId()); + values.put("TotalLine", data.get(i).getTotalLine()); + values.put("TotalStock", data.get(i).getTotalStock()); + values.put("VisitDate", data.get(i).getVisitDate()); + + if (!db.isOpen()) { + open(); + } + + long id = db.insert("StockSummary_Check", null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ex.fillInStackTrace(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + + public ArrayList getStockSummaryCheck(String counterId, String visit_date) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + + try { + + dbcursor = db.rawQuery("Select distinct TotalLine,TotalStock from StockSummary_Check where CounterId =" + counterId + " And VisitDate='" + visit_date + "'", null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + StockSummaryCheck sb = new StockSummaryCheck(); + + sb.setTotalLine(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("TotalLine"))); + sb.setTotalStock(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("TotalStock"))); + + list.add(sb); + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list; + } + } catch (Exception e) { + + return list; + } + + return list; + } + + + public long insert_makeover_capture(String user_Id, String visit_date, String store_Cd, InvoiceGetterSetter makeover_object) { + db.delete(CommonString.Table_Makeover_Capture, CommonString.KEY_VISIT_DATE + "<>'" + visit_date + "'", null); + ContentValues values = new ContentValues(); + long l = 0; + try { + db.beginTransaction(); + values.put("USER_ID", user_Id); + values.put(CommonString.KEY_MASTER_TRANSACTION_ID, 0); + values.put(CommonString.KEY_COUNTER_ID, store_Cd); + values.put(CommonString.KEY_VISIT_DATE, visit_date); + + values.put("UNIQUE_CODE", makeover_object.getUnique_code()); + values.put("BUYER_NAME", makeover_object.getCustomer_name()); + values.put("CONTACT_NUMBER", makeover_object.getMobile_no()); + values.put("EMAIL_ID", makeover_object.getConsumer_email_Id()); + values.put("AGE", makeover_object.getConsumer_age()); + values.put("SKIN_TYPE", makeover_object.getConsumer_skinType()); + values.put("LOOk", makeover_object.getLook_creater_str()); + values.put("GENDER", makeover_object.getCustomer_gender()); + values.put("BEFORE_MAKEOVER_IMG", makeover_object.getBefore_makeover_img()); + values.put("AFTER_MAKEOVER_IMG", makeover_object.getAfter_makeover_img()); + values.put("FEEDBACK", makeover_object.getCst_feed_back_value()); + values.put("UPLOAD_STATUS", makeover_object.getStr_upload_status()); + values.put("TERMCONDITION_FLAG", makeover_object.getStr_termcondition()); + values.put("POS_SALE_FLAG", makeover_object.isPos_sale_flag()); + + l = db.insert(CommonString.Table_Makeover_Capture, null, values); + closeDb(); + } catch (Exception ex) { + closeDb(); + ////////test("Database Exception", ex.toString()); + } + + return l; + } + + public long update_makeover_capture(String counterId, String visit_date, String user_Id, InvoiceGetterSetter makeover_object) { + db.delete(CommonString.TABLE_TRANSACTION_WISE_MASTER_TABLE, CommonString.KEY_VISIT_DATE + " <>'" + visit_date + "'", null); + ContentValues values = new ContentValues(); + ContentValues valuesmasterT = new ContentValues(); + long l = 0, masterreturn = 0; + try { + db.beginTransaction(); + valuesmasterT.put(CommonString.KEY_UUID, makeover_object.getUnique_code()); + valuesmasterT.put(CommonString.KEY_USER_ID, user_Id); + valuesmasterT.put(CommonString.KEY_COUNTER_ID, counterId); + valuesmasterT.put(CommonString.KEY_VISIT_DATE, visit_date); + valuesmasterT.put(CommonString.KEY_STOCK_TYPE, CommonString.MAKEOVER_CAPTURE); + valuesmasterT.put(CommonString.KEY_ENTRY_TYPE, CommonString.KEY_REGULAR); + valuesmasterT.put(CommonString.KEY_STATUS, CommonString.KEY_N); + + masterreturn = db.insert(CommonString.TABLE_TRANSACTION_WISE_MASTER_TABLE, null, valuesmasterT); + + if (masterreturn > 0) { + values.put(CommonString.KEY_MASTER_TRANSACTION_ID, masterreturn); + values.put("UNIQUE_CODE", makeover_object.getUnique_code()); + values.put("BUYER_NAME", makeover_object.getCustomer_name()); + values.put("CONTACT_NUMBER", makeover_object.getMobile_no()); + values.put("EMAIL_ID", makeover_object.getConsumer_email_Id()); + values.put("AGE", makeover_object.getConsumer_age()); + values.put("SKIN_TYPE", makeover_object.getConsumer_skinType()); + values.put("LOOk", makeover_object.getLook_creater_str()); + values.put("GENDER", makeover_object.getCustomer_gender()); + values.put("BEFORE_MAKEOVER_IMG", makeover_object.getBefore_makeover_img()); + values.put("AFTER_MAKEOVER_IMG", makeover_object.getAfter_makeover_img()); + values.put("FEEDBACK", makeover_object.getCst_feed_back_value()); + values.put("UPLOAD_STATUS", makeover_object.getStr_upload_status()); + values.put("TERMCONDITION_FLAG", makeover_object.getStr_termcondition()); + + if (makeover_object.isPos_sale_flag()) { + values.put("POS_SALE_FLAG", "1"); + } else { + values.put("POS_SALE_FLAG", "0"); + + } + + if (!db.isOpen()) { + open(); + } + l = db.update(CommonString.Table_Makeover_Capture, values, CommonString.KEY_COUNTER_ID + "='" + counterId + "' AND " + CommonString.KEY_VISIT_DATE + " ='" + visit_date + "'AND USER_ID='" + user_Id + "'and " + CommonString.KEY_ID + "='" + makeover_object.getReccept_count() + "'", null); + + } + closeDb(); + } catch (Exception e) { + closeDb(); + e.fillInStackTrace(); + } + return l; + } + + + ///jeevanp + public long deleteconsumersale(String visit_date, int reciept_count, String user_id) { + long l = 0; + try { + if (!db.isOpen()) { + open(); + } + + String whereClause = CommonString.KEY_RECCEPT_NUMBER + "='" + reciept_count + "' and " + CommonString.KEY_VISIT_DATE + "='" + visit_date + "'and USER_ID='" + user_id + "'"; + l = db.delete(CommonString.Table_Sale_Tracking, whereClause, null); + l = db.delete(CommonString.Table_Sale_Tracking_Header_Data, whereClause, null); + l = db.delete(CommonString.Table_Applyeid_Promotion, whereClause, null); + l = db.delete(CommonString.Table_PromoApplyeidOnProduct, whereClause, null); + } catch (Exception e) { + e.fillInStackTrace(); + } + + return l; + } + + public long delete_sale(String visit_date, int reciept_count, String user_id) { + long l = 0; + try { + if (!db.isOpen()) { + open(); + } + + l = db.delete(CommonString.Table_Sale_Tracking, CommonString.KEY_RECCEPT_NUMBER + "='" + String.valueOf(reciept_count) + "' and " + CommonString.KEY_VISIT_DATE + "='" + visit_date + "'and USER_ID='" + user_id + "'", null); + + } catch (Exception e) { + e.fillInStackTrace(); + } + return l; + } + + public ArrayList get_inwrad_stock_header_data(String invoiceNo, String type, String counterId) { + ArrayList list1 = new ArrayList<>(); + Cursor dbcursor = null; + try { + + dbcursor = db.rawQuery("select distinct Pm.SubAxeName as SubAxeName,Pm.SignatureName as SignatureName,Pm.BrandName as BrandName," + "Pm.SubBrandName as SubBrandName,Pm.ReferenceName as ReferenceName from T_CounterInvoice as ci " + "inner join Product_Master Pm on ci.ProductId = Pm.ProductId where ci.InvoiceNo ='" + invoiceNo + "' and ci.InvoiceType ='" + type + "' And ci.CounterId=" + counterId + "", null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + ProductMaster sb = new ProductMaster(); + sb.setSubBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SubBrandName"))); + sb.setReferenceName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ReferenceName"))); + sb.setBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("BrandName"))); + sb.setSignatureName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SignatureName"))); + sb.setSubAxeName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SubAxeName"))); + + list1.add(sb); + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list1; + } + } catch (Exception e) { + + return list1; + } + + return list1; + } + + + public ArrayList get_inward_stock_child_product_data(String referenceName, String brandName, String subBrandName, String signatureName, String invoice_no, String type, String counterId) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + + String qury = "Select Distinct pm.ProductName as ProductName,pm.ProductId as ProductId,pm.EanCode as EanCode,pm.Mrp as Mrp,tc.InvId as InvId," + "(ifnull(tc.Qty,0))as InvoiceQty," + "tc.CounterConfirm as CounterConfirm,tc.InvoiceStatus as InvoiceStatus,(ifnull(tc.ActualQty,0))as ActualQty," + "(ifnull(tc.ReasonId,0))as ReasonId,ifnull(tc.TranId,'')as" + + " TranId From Product_Master" + " pm inner join T_CounterInvoice tc on pm.ProductId=tc.ProductId" + + " Where pm.SignatureName =trim(\"" + signatureName + "\") AND pm.BrandName=trim(\"" + brandName + "\") AND" + + " pm.SubBrandName =trim(\"" + subBrandName + "\") AND pm.ReferenceName =trim(\"" + + referenceName + "\") AND tc.InvoiceNo=trim('" + invoice_no + "') And " + "tc.CounterId=" + counterId + + " AND tc.InvoiceType='" + type + "' and tc. InvId not in(SELECT InvId From DR_INWARD_STOCK_CHILD_DATA Where" + + " SignatureName =trim(\"" + signatureName + "\") AND BrandName=trim(\"" + brandName + "\") And COUNTER_ID=" + counterId + + " AND SubBrandName =trim(\"" + subBrandName + "\") AND ReferenceName =trim(\"" + referenceName + "\") AND InvoiceNo=trim('" + + invoice_no + "')" + " AND InvoiceType=trim('" + type + "'))" + " UNION" + + " Select Distinct pm.ProductName as ProductName,pm.ProductId as ProductId,pm.EanCode as EanCode,pm.Mrp as Mrp,tc.InvId as InvId," + + "(ifnull(tc.Invoice_Qty,0))as InvoiceQty," + + " tc.Sku_Confirmation_Check as CounterConfirm,tc.Invoice_Status as InvoiceStatus,(ifnull(tc.Actual_Qty,0))as ActualQty," + + "(ifnull(tc.REASON_ID,0))as ReasonId," + "ifnull((SELECT Transaction_Id FROM DR_INWARD_STOCK_TRANSACTION Where InvoiceNo='" + + invoice_no + "' and ProductId=tc.ProductId and InvId=tc.InvId),'')as TranId From Product_Master" + + " pm inner join DR_INWARD_STOCK_CHILD_DATA tc on pm.ProductId=tc.ProductId Where" + + " pm.SignatureName =trim(\"" + signatureName + "\") AND pm.BrandName=trim(\"" + brandName + "\") AND" + + " pm.SubBrandName =trim(\"" + subBrandName + "\") AND pm.ReferenceName =trim(\"" + referenceName + "\") AND" + + " tc.InvoiceNo=trim('" + invoice_no + "') AND tc.InvoiceType=trim('" + type + "') And tc.COUNTER_ID=" + counterId + ""; + + dbcursor = db.rawQuery(qury, null); + +/* + dbcursor = db.rawQuery("select distinct Pm.ProductName,Pm.ProductId,Pm.EanCode,ci.Qty,Pm.Mrp," + + "ci.InvId,ci.CounterConfirm,ci.InvoiceStatus,ci.ActualQty,ci.ReasonId,ci.TranId from T_CounterInvoice as ci" + + " inner join Product_Master Pm on ci.ProductId = Pm.ProductId " + + " where Pm.SignatureName =\"" + signatureName + "\" AND Pm.BrandName=\"" + brandName + + "\" AND Pm.SubBrandName =\"" + subBrandName + "\" AND Pm.ReferenceName =\"" + referenceName + "\" " + + " AND ci.InvoiceNo='" + invoice_no + "' AND ci.InvoiceType='" + type + "'", null); +*/ + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + ProductMaster sb = new ProductMaster(); + sb.setInvId(dbcursor.getString(dbcursor.getColumnIndexOrThrow("InvId"))); + sb.setProductName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ProductName"))); + sb.setProductId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("ProductId"))); + sb.setEanCode(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EanCode"))); + sb.setInvoice_Status(dbcursor.getString(dbcursor.getColumnIndexOrThrow("InvoiceStatus"))); + String checkVal1 = dbcursor.getString(dbcursor.getColumnIndexOrThrow("CounterConfirm")); + sb.setConsumer_qty(dbcursor.getString(dbcursor.getColumnIndexOrThrow("InvoiceQty"))); + int consumer = (dbcursor.getInt(dbcursor.getColumnIndexOrThrow("ActualQty"))); + if (consumer == 0 && checkVal1 != null && !checkVal1.equals("") && checkVal1.equals("0")) { + sb.setActualQty(dbcursor.getString(dbcursor.getColumnIndexOrThrow("InvoiceQty"))); + } else { + sb.setActualQty(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ActualQty"))); + } + + sb.setReasonId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("ReasonId"))); + sb.setTransaction_Id(dbcursor.getString(dbcursor.getColumnIndexOrThrow("TranId"))); + sb.setMrp(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("Mrp"))); + if (checkVal1 != null && !checkVal1.equals("") && checkVal1.equals("0")) { + sb.setConfirmChecked(false); + } else { + sb.setConfirmChecked(true); + } + + list.add(sb); + dbcursor.moveToNext(); + } + dbcursor.close(); + return list; + } + + } catch (Exception e) { + + return list; + } + + return list; + } + + + public ArrayList getAgeLimitMasterData() { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + + dbcursor = db.rawQuery("select distinct AgeLimit from Master_AgeLimit", null); + + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + MasterAgeLimit sb = new MasterAgeLimit(); + sb.setAgeLimit(dbcursor.getString(dbcursor.getColumnIndexOrThrow("AgeLimit"))); + list.add(sb); + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list; + } + } catch (Exception e) { + + return list; + } + return list; + } + + + public ArrayList getsourceofsales() { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + + dbcursor = db.rawQuery("select distinct SourcesOfSale from Master_SourcesOfSales", null); + + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + MasterSourcesOfSale sb = new MasterSourcesOfSale(); + sb.setSourcesOfSale(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SourcesOfSale"))); + list.add(sb); + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list; + } + } catch (Exception e) { + + return list; + } + return list; + } + + + public ArrayList getskinTypeMaster() { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + + dbcursor = db.rawQuery("select distinct SkinType from Master_SkinType", null); + + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + MasterSkinType sb = new MasterSkinType(); + sb.setSkinType(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SkinType"))); + list.add(sb); + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list; + } + } catch (Exception e) { + + return list; + } + return list; + } + + public boolean insertSkinTypeMaster(TableStructureGetterSetter cst) { + db.delete("Master_SkinType", null, null); + ContentValues values = new ContentValues(); + List data = cst.getMasterSkinType(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("SkinType", data.get(i).getSkinType()); + long id = db.insert("Master_SkinType", null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + ex.fillInStackTrace(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + + public String getStatus(String columnName, String counterId) { + String status = null; + Cursor dbcursor = null; + try { + if (columnName != null && columnName.equalsIgnoreCase(CommonString.KEY_GwpStatus)) { + dbcursor = db.rawQuery("select distinct t1.GwpStatus as GwpStatus from T_StockSummary t1 INNER JOIN Product_Master t2 on t1.ProductId=t2.ProductId where t1.GwpStatus<>''and t1.CounterId=" + counterId + " and t2.ProductType='GWP'", null); + + } else { + dbcursor = db.rawQuery("select distinct t1." + columnName + " from T_StockSummary t1 INNER JOIN Product_Master t2 on t1.ProductId=t2.ProductId where t1." + columnName + "<>''and t1.CounterId=" + counterId + " and t2.ProductType='Normal'", null); + } + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + + status = dbcursor.getString(dbcursor.getColumnIndexOrThrow(columnName)); + + dbcursor.moveToNext(); + } + + dbcursor.close(); + return status; + } + } catch (Exception e) { + + return status; + } + + return status; + } + + + // neeraj database + public boolean insertNonStockReasonData(MasterNonStockReasonGetterSetter nonWorkingdata) { + db.delete("Master_NonStockReason", null, null); + ContentValues values = new ContentValues(); + List data = nonWorkingdata.getMasterNonStockReason(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + + values.put("ReasonId", data.get(i).getReasonId()); + values.put("Reason", data.get(i).getReason()); + values.put("Applicable", data.get(i).getApplicable()); + + long id = db.insert("Master_NonStockReason", null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ex.fillInStackTrace(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + public ArrayList getReasonData(boolean stockcheck_flag) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + if (stockcheck_flag) { + dbcursor = db.rawQuery("select * from Master_NonStockReason where Applicable=1", null); + } else { + dbcursor = db.rawQuery("select * from Master_NonStockReason", null); + } + + MasterNonStockReason sb1 = new MasterNonStockReason(); + sb1.setReason("- Select Reason -"); + sb1.setReasonId(0); + list.add(sb1); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + MasterNonStockReason sb = new MasterNonStockReason(); + sb.setReason(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Reason"))); + sb.setReasonId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("ReasonId"))); + list.add(sb); + dbcursor.moveToNext(); + } + dbcursor.close(); + return list; + } + } catch (Exception e) { + return list; + } + return list; + } + + public boolean insertMasterProfile(MasterProfileGetterSetter cst) { + db.delete("Master_Profile", null, null); + ContentValues values = new ContentValues(); + List data = cst.getMasterProfile(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("Email", data.get(i).getEmail()); + values.put("FullName", data.get(i).getFullName()); + values.put("Supervisor", data.get(i).getSupervisor()); + values.put("Gender", data.get(i).getGender()); + values.put("dob", data.get(i).getDob()); + values.put("Current_BPgrade", data.get(i).getCurrentBPgrade()); + values.put("Mobile", data.get(i).getMobile()); + values.put("InstragramAddress", data.get(i).getInstragramAddress()); + values.put("Profile_Pic", data.get(i).getProfilePic()); + values.put("Address", data.get(i).getAddress()); + values.put("EmpCode", data.get(i).getEmpCode()); + values.put("UserId", data.get(i).getUserId().toLowerCase()); + values.put("VisitDate", data.get(i).getViisitDate()); + + long id = db.insert("Master_Profile", null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ex.fillInStackTrace(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + public boolean insertMasterProfileQuestion(MasterProfileQuestionGetterSetter cst) { + db.delete("Master_ProfileQuestion", null, null); + ContentValues values = new ContentValues(); + List data = cst.getMasterProfileQuestion(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("Answer", data.get(i).getAnswer()); + values.put("AnswerId", data.get(i).getAnswerId()); + values.put("Category", data.get(i).getCategory()); + values.put("CategoryId", data.get(i).getCategoryId()); + values.put("Question", data.get(i).getQuestion()); + values.put("QuestionId", data.get(i).getQuestionId()); + values.put("QuestionType", data.get(i).getQuestionType()); + values.put("BA", data.get(i).getBA()); + values.put("TBA", data.get(i).getTBA()); + values.put("ME", data.get(i).getME()); + + long id = db.insert("Master_ProfileQuestion", null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ex.fillInStackTrace(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + public ArrayList getBAProfileListAllData(String userId, String visit_date) { + + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + + dbcursor = db.rawQuery("SELECT * FROM Master_Profile WHERE UserId ='" + userId + "' AND VisitDate='" + visit_date + "'", null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + MasterProfile ch = new MasterProfile(); + + ch.setEmail(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Email"))); + ch.setFullName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("FullName"))); + ch.setSupervisor(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Supervisor"))); + ch.setGender(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Gender"))); + ch.setDob(dbcursor.getString(dbcursor.getColumnIndexOrThrow("dob"))); + ch.setCurrentBPgrade(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Current_BPgrade"))); + ch.setMobile(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Mobile"))); + ch.setInstragramAddress(dbcursor.getString(dbcursor.getColumnIndexOrThrow("InstragramAddress"))); + ch.setProfilePic(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Profile_Pic"))); + ch.setAddress(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Address"))); + ch.setEmpCode(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EmpCode"))); + ch.setUserId(dbcursor.getString(dbcursor.getColumnIndexOrThrow("UserId"))); + ch.setViisitDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("VisitDate"))); + + list.add(ch); + dbcursor.moveToNext(); + } + dbcursor.close(); + return list; + } + } catch (Exception e) { + return list; + } + return list; + } + + + public long saveAuditQuestionAnswerData(HashMap> data, ArrayList save_listDataHeader, String userId, String visit_date) { + db.delete(CommonString.TABLE_AUDIT_DATA_SAVE, CommonString.KEY_USER_ID + "='" + userId + "' AND Visit_Date='" + visit_date + "'", null); + long id = 0; + ContentValues values = new ContentValues(); + try { + + try { + db.beginTransaction(); + for (int i = 0; i < save_listDataHeader.size(); i++) { + + for (int j = 0; j < data.get(save_listDataHeader.get(i)).size(); j++) { + values.put("User_Id", userId); + values.put(CommonString.KEY_STATUS, CommonString.KEY_N); + values.put("QUESTION_ID", data.get(save_listDataHeader.get(i)).get(j).getQUESTION_ID()); + values.put("QUESTION", data.get(save_listDataHeader.get(i)).get(j).getQUESTION()); + values.put("ANSWER_ID", data.get(save_listDataHeader.get(i)).get(j).getANSWER_ID()); + values.put("ANSWER_TYPE", data.get(save_listDataHeader.get(i)).get(j).getANSWER_TYPE()); + values.put("CATEGORY_ID", save_listDataHeader.get(i).getCategoryId()); + values.put("VISIT_DATE", visit_date); + + if (data.get(save_listDataHeader.get(i)).get(j).getANSWER_TYPE().equalsIgnoreCase("Multi selection")) { + for (int m = 0; m < data.get(save_listDataHeader.get(i)).get(j).getSelectedSamplingData().size(); m++) { + String txt = ""; + int count = 0; + if (data.get(save_listDataHeader.get(i)).get(j).getSelectedSamplingData().size() > 0) { + for (int k = 0; k < data.get(save_listDataHeader.get(i)).get(j).getSelectedSamplingData().size(); k++) { + if (data.get(save_listDataHeader.get(i)).get(j).getSelectedSamplingData().get(k).isSelected()) { + if (count == 0) { + txt = data.get(save_listDataHeader.get(i)).get(j).getSelectedSamplingData().get(k).getName(); + } else { + txt = txt + " , " + data.get(save_listDataHeader.get(i)).get(j).getSelectedSamplingData().get(k).getName(); + } + + count++; + } + } + values.put("ANSWER", txt); + } + } + + } else { + + values.put("ANSWER", data.get(save_listDataHeader.get(i)).get(j).getANSWER()); + } + + values.put("OTHERS_TVALUE", data.get(save_listDataHeader.get(i)).get(j).getSpin_others_for_edt()); + + id = db.insert(CommonString.TABLE_AUDIT_DATA_SAVE, null, values); + + } + } + + closeDb(); + } catch (Exception ex) { + closeDb(); + ////////test("Database Exception", " while Insert Posm Master Data " + ex.toString()); + } + + return id; + } catch (Exception ex) { + return 0; + } + } + + + public ArrayList getAuditQuestionCategoryData(String userType) { + Cursor cursordata = null; + ArrayList auditData = new ArrayList<>(); + try { + if (userType.trim().equalsIgnoreCase("BA")) { + cursordata = db.rawQuery("select distinct CategoryId,Category from Master_ProfileQuestion where BA='1'", null); + } else if (userType.trim().equalsIgnoreCase("TBA")) { + cursordata = db.rawQuery("select distinct CategoryId,Category from Master_ProfileQuestion where TBA='1'", null); + } else if (userType.trim().equalsIgnoreCase("ME")) { + cursordata = db.rawQuery("select distinct CategoryId,Category from Master_ProfileQuestion where ME='1'", null); + } + + if (cursordata != null) { + cursordata.moveToFirst(); + while (!cursordata.isAfterLast()) { + MasterProfileQuestion sb = new MasterProfileQuestion(); + sb.setCategoryId(cursordata.getInt(cursordata.getColumnIndexOrThrow("CategoryId"))); + sb.setCategory(cursordata.getString(cursordata.getColumnIndexOrThrow("Category"))); + auditData.add(sb); + cursordata.moveToNext(); + } + cursordata.close(); + } + + } catch (Exception ex) { + ex.fillInStackTrace(); + } + + return auditData; + + } + + + public ArrayList getAfterSaveAuditQuestionAnswerData(String userId, String categodyId) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + + try { + if (categodyId == null) { + dbcursor = db.rawQuery("Select * " + "From " + CommonString.TABLE_AUDIT_DATA_SAVE + " where User_Id='" + userId + "'", null); + + } else { + dbcursor = db.rawQuery("Select * " + "From " + CommonString.TABLE_AUDIT_DATA_SAVE + " where User_Id='" + userId + "' AND CATEGORY_ID ='" + categodyId + "'", null); + + } + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + AuditDataGetterSetter sb = new AuditDataGetterSetter(); + sb.setQUESTION_ID(dbcursor.getString(dbcursor.getColumnIndexOrThrow("QUESTION_ID"))); + sb.setQUESTION(dbcursor.getString(dbcursor.getColumnIndexOrThrow("QUESTION"))); + sb.setANSWER_ID(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ANSWER_ID"))); + sb.setANSWER(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ANSWER"))); + sb.setMENU_ID(dbcursor.getString(dbcursor.getColumnIndexOrThrow("CATEGORY_ID"))); + sb.setANSWER_TYPE(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ANSWER_TYPE"))); + sb.setSpin_others_for_edt(dbcursor.getString(dbcursor.getColumnIndexOrThrow("OTHERS_TVALUE"))); + + list.add(sb); + dbcursor.moveToNext(); + } + dbcursor.close(); + return list; + } + } catch (Exception e) { + + return list; + } + return list; + } + + public ArrayList getAuditCategoryWise(int categoryId) { + Cursor cursordata = null; + + ArrayList auditData = new ArrayList<>(); + try { + + cursordata = db.rawQuery("select distinct QuestionId,Question, QuestionType FROM Master_ProfileQuestion " + "where CategoryId ='" + categoryId + "'", null); + + if (cursordata != null) { + cursordata.moveToFirst(); + while (!cursordata.isAfterLast()) { + AuditDataGetterSetter sb = new AuditDataGetterSetter(); + sb.setQUESTION(cursordata.getString(cursordata.getColumnIndexOrThrow("Question"))); + sb.setQUESTION_ID(cursordata.getString(cursordata.getColumnIndexOrThrow("QuestionId"))); + sb.setANSWER_TYPE(cursordata.getString(cursordata.getColumnIndexOrThrow("QuestionType"))); + sb.setKEYACCOUNT_ID("0"); + + auditData.add(sb); + cursordata.moveToNext(); + } + cursordata.close(); + } + + } catch (Exception ex) { + + } + return auditData; + } + + public ArrayList getAuditAnswerData(AuditDataGetterSetter auditGetSet, String select) { + + ArrayList list = new ArrayList<>(); + if (auditGetSet.getANSWER_TYPE().equalsIgnoreCase("Single selection")) { + AuditDataGetterSetter sb1 = new AuditDataGetterSetter(); + sb1.setANSWER_ID("0"); + sb1.setANSWER(select); + list.add(0, sb1); + } else if (auditGetSet.getANSWER_TYPE().equalsIgnoreCase("Text")) { + AuditDataGetterSetter sb1 = new AuditDataGetterSetter(); + sb1.setANSWER_ID("0"); + sb1.setANSWER(""); + list.add(0, sb1); + } + + Cursor dbcursor = null; + + try { + + dbcursor = db.rawQuery("select distinct QuestionType,AnswerId,Answer FROM Master_ProfileQuestion where QuestionId =" + auditGetSet.getQUESTION_ID() + "", null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + AuditDataGetterSetter sb = new AuditDataGetterSetter(); + + sb.setANSWER_ID(dbcursor.getString(dbcursor.getColumnIndexOrThrow("AnswerId"))); + sb.setANSWER(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Answer"))); + + list.add(sb); + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list; + } + } catch (Exception e) { + ////////test("Exception", " answer " + e.toString()); + return list; + } + ////////test("Fetching", " audit answer-->Stop<-"); + return list; + } + + + ///jp work + public ArrayList getproduct_masterlist(String invoice_type, String visit_date, String counterId, String userType) { + ////////test("Fetching", "Storedata--------------->Start<------------"); + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + String table = CommonString.T_StockSummary, additionalQueryMe2 = "", additionalQueryMe = " Where SaleableBalance >0", getData = "(s.SaleableBalance - ifnull(dm.DamageQty,0)) as SaleableBalance"; + if (userType != null && userType.equalsIgnoreCase(CommonString.TAG_FROM_ME)) { + additionalQueryMe2 = "UNION ALL Select T1.PRODUCT_ID AS ProductId , SUM(T1.QUANTITY) AS DamageQty FROM SALE_TRACKING_TABLE T1" + " INNER JOIN SALE_TRACKING_HEADER_TABLE T2 ON T2.RECCEPT_COUNT=T1.RECCEPT_COUNT WHERE T2.COUNTER_ID =" + counterId + " AND T2.Visit_Date='" + visit_date + "' AND T1.INVOICE_TYPE='Saleable'" + " AND T1.RIGHTNAME='ME' GROUP BY T1.PRODUCT_ID UNION ALL select S.PROMO_PRODUCT_ID AS ProductId ," + " SUM(S.PROMO_PRODUCT_QTY) AS DamageQty from APPLYED_PROMOTION_TABLE S INNER JOIN SALE_TRACKING_HEADER_TABLE S1 ON S.RECCEPT_COUNT=S1.RECCEPT_COUNT Where S.PROMO_TYPE ='Product'" + " AND S.COUNTER_ID =" + counterId + " AND S1.VISIT_DATE = '" + visit_date + "' AND S.RIGHTNAME='ME' GROUP BY S.PROMO_PRODUCT_ID "; + + getData = "((s.SaleableBalance + ifnull(tempsale.TempSale,0) ) - ifnull(dm.DamageQty,0)) as SaleableBalance"; + additionalQueryMe = " left join (select ProductId, case when (Select count(*) from (Select CounterId, ProductId," + "sum(TempQty) as TempQty from ( Select T2.COUNTER_ID AS CounterId, T1.PRODUCT_ID AS ProductId , SUM(T1.QUANTITY) AS TempQty FROM SALE_TRACKING_TABLE T1" + " INNER JOIN SALE_TRACKING_HEADER_TABLE T2 ON T2.RECCEPT_COUNT=T1.RECCEPT_COUNT WHERE T2.COUNTER_ID =" + counterId + " AND T2.Visit_Date='" + visit_date + "' AND T1.INVOICE_TYPE='Saleable'" + " AND T1.RIGHTNAME !='ME' GROUP BY T1.PRODUCT_ID" + " UNION ALL select S.COUNTER_ID as CounterId," + " S.PROMO_PRODUCT_ID AS ProductId , SUM(S.PROMO_PRODUCT_QTY) AS TempQty from APPLYED_PROMOTION_TABLE S INNER JOIN SALE_TRACKING_HEADER_TABLE S1" + " ON S.RECCEPT_COUNT=S1.RECCEPT_COUNT Where S.PROMO_TYPE ='Product' AND S.COUNTER_ID =" + counterId + " AND S1.VISIT_DATE = '" + visit_date + "'" + " AND S.RIGHTNAME !='ME' GROUP BY S.PROMO_PRODUCT_ID)as t Group by CounterId, ProductId)" + " c where c.ProductId = t.Productid)>0 then (Select TempQty from (Select CounterId, ProductId," + "sum(TempQty) as TempQty from ( Select T2.COUNTER_ID AS CounterId, T1.PRODUCT_ID AS ProductId , SUM(T1.QUANTITY) AS TempQty FROM SALE_TRACKING_TABLE T1" + " INNER JOIN SALE_TRACKING_HEADER_TABLE T2 ON T2.RECCEPT_COUNT=T1.RECCEPT_COUNT WHERE T2.COUNTER_ID =" + counterId + " AND T2.Visit_Date='" + visit_date + "' AND T1.INVOICE_TYPE='Saleable'" + " AND T1.RIGHTNAME !='ME' AND T2.POS_SALE_FLAG='1' GROUP BY T1.PRODUCT_ID" + " UNION ALL select S.COUNTER_ID as CounterId," + " S.PROMO_PRODUCT_ID AS ProductId , SUM(S.PROMO_PRODUCT_QTY) AS TempQty from APPLYED_PROMOTION_TABLE S INNER JOIN SALE_TRACKING_HEADER_TABLE S1" + " ON S.RECCEPT_COUNT=S1.RECCEPT_COUNT Where S.PROMO_TYPE ='Product' AND S.COUNTER_ID =" + counterId + " AND S1.VISIT_DATE = '" + visit_date + "'" + " AND S.RIGHTNAME !='ME' AND S1.POS_SALE_FLAG ='1' GROUP BY S.PROMO_PRODUCT_ID)as t Group by CounterId, ProductId" + " ) c where c.productId = t.Productid) else (" + "Select sum(QtySold)as QtySold from (select SaleQty as QtySold from Report_BA_TBASale s where s.ProductId = t.ProductId and s.CounterId=" + counterId + " and VisitDate='" + visit_date + "'" + "UNION all select SaleQty as QtySold from Report_BA_TBAPromoSale s where s.ProductId = t.ProductId and s.CounterId=" + counterId + " and VisitDate='" + visit_date + "')" + ") end as TempSale" + " from T_StockSummary t) as tempsale on s.ProductId=tempsale.ProductId"; + } + if (invoice_type != null && invoice_type.trim().equalsIgnoreCase("Sample")) { + dbcursor = db.rawQuery("select distinct ProductName,pm.ProductId as ProductId,ReferenceId,ReferenceName," + "SubBrandId,SubBrandName," + "BrandId,BrandName,Mrp,EanCode,ProductType from Product_Master pm inner join " + table + " ts" + " on ts.ProductId=pm.ProductId where SampleBalance>0", null); + } else if (invoice_type != null && invoice_type.equalsIgnoreCase("GWP")) { + dbcursor = db.rawQuery("select distinct ProductName,pm.ProductId as ProductId,ReferenceId,ReferenceName," + "SubBrandId,SubBrandName,BrandId," + "BrandName,Mrp,EanCode,ProductType from Product_Master pm inner join " + table + " ts" + " on ts.ProductId=pm.ProductId where GwpBalance>0", null); + } else if (invoice_type != null && invoice_type.trim().equalsIgnoreCase("T_StockSummary")) { + dbcursor = db.rawQuery("select distinct pm.ProductName as ProductName,pm.ProductId as ProductId,pm.ReferenceId as ReferenceId," + "pm.ReferenceName as ReferenceName,pm.SubBrandId as SubBrandId,pm.SubBrandName as SubBrandName,pm.BrandId as BrandId," + "pm.BrandName as BrandName,pm.Mrp as Mrp,pm.EanCode as EanCode,pm.ProductType as ProductType from Product_Master pm" + " left join (Select s.ProductId," + getData + " from " + table + " s Left join (Select ProductId, sum(DamageQty) as DamageQty" + " from (select T.ProductId, T.Stock as DamageQty from TABLE_TRANSACTION_DATA T INNER JOIN DR_TABLE_TRANSACTION_WISE_MASTER M" + " ON T.MASTER_TRANSACTION_ID = M.MASTER_TRANSACTION_ID where T.STOCK_TYPE='DAMAGE' AND T.Visit_Date ='" + visit_date + "' and T.COUNTER_ID ='" + counterId + "'" + " Union All SELECT ProductId, DamageQty from Damage_PreviousPending Where CounterId ='" + counterId + "' and Verify ='Pending'" + additionalQueryMe2 + ") as t Group by ProductId) as dm" + " on s.ProductId = dm.ProductId Left Join (Select ProductId, sum(ReturnQty) as ReturnQty from" + " (select ProductId, ReturnQty from Damage_ReturnToDistributor" + " WHERE CounterId='" + counterId + "'and VERIFY ='Pending' Union All select ProductId, STOCK as ReturnQty from TABLE_RETURNTO_DISTRIBUTOR" + " WHERE Visit_Date='" + visit_date + "' AND COUNTER_ID='" + counterId + "') as" + " t Group by ProductId ) as rd on trim(s.ProductId) = trim(rd.ProductId) and s.CounterId ='" + counterId + "' " + additionalQueryMe + ") as TS ON TS.ProductId = pm.ProductId where TS.SaleableBalance >0 ", null); + + } else { + dbcursor = db.rawQuery("select distinct ProductName,ProductId,ReferenceId," + "ReferenceName,SubBrandId,SubBrandName," + "BrandId,BrandName" + ",Mrp,EanCode,ProductType from Product_Master", null); + } + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + ProductMaster sb = new ProductMaster(); + sb.setProductName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ProductName"))); + sb.setProductId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("ProductId"))); + sb.setReferenceId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("ReferenceId"))); + sb.setReferenceName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ReferenceName"))); + sb.setSubBrandId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("SubBrandId"))); + sb.setSubBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SubBrandName"))); + sb.setBrandId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("BrandId"))); + sb.setBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("BrandName"))); + sb.setMrp(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("Mrp"))); + sb.setEanCode(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EanCode"))); + sb.setProductType(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ProductType"))); + list.add(sb); + dbcursor.moveToNext(); + } + dbcursor.close(); + return list; + } + } catch (Exception e) { + ////////test("Exception ", "when fetching opening stock!!!!!!!!!!!" + e.toString()); + return list; + } + ////////test("Fetching ", "opening stock---------------------->Stop<-----------"); + return list; + } + + public ArrayList getproductdata_dialog(String column_name, String column_name_Id, boolean flag_for_filtr_stocksm, String stock_summary_balance, String visit_date, String counterId, String userType) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + String table = CommonString.T_StockSummary, additionalQueryMe = " Where SaleableBalance >0", additionalQueryMe2 = "", getData = "(s.SaleableBalance - ifnull(dm.DamageQty,0)) as SaleableBalance"; + if (userType != null && userType.equalsIgnoreCase(CommonString.TAG_FROM_ME)) { + additionalQueryMe2 = "UNION ALL Select T1.PRODUCT_ID AS ProductId , SUM(T1.QUANTITY) AS DamageQty FROM SALE_TRACKING_TABLE T1" + " INNER JOIN SALE_TRACKING_HEADER_TABLE T2 ON T2.RECCEPT_COUNT=T1.RECCEPT_COUNT WHERE T2.COUNTER_ID =" + counterId + " AND T2.Visit_Date='" + visit_date + "' AND T1.INVOICE_TYPE='Saleable'" + " AND T1.RIGHTNAME='ME' GROUP BY T1.PRODUCT_ID UNION ALL select S.PROMO_PRODUCT_ID AS ProductId ," + " SUM(S.PROMO_PRODUCT_QTY) AS DamageQty from APPLYED_PROMOTION_TABLE S INNER JOIN SALE_TRACKING_HEADER_TABLE S1 ON S.RECCEPT_COUNT=S1.RECCEPT_COUNT Where S.PROMO_TYPE ='Product'" + " AND S.COUNTER_ID =" + counterId + " AND S1.VISIT_DATE = '" + visit_date + "' AND S.RIGHTNAME='ME' GROUP BY S.PROMO_PRODUCT_ID "; + + getData = "((s.SaleableBalance + ifnull(tempsale.TempSale,0) ) - ifnull(dm.DamageQty,0)) as SaleableBalance"; + additionalQueryMe = " left join (select ProductId, case when (Select count(*) from (Select CounterId, ProductId," + "sum(TempQty) as TempQty from ( Select T2.COUNTER_ID AS CounterId, T1.PRODUCT_ID AS ProductId , SUM(T1.QUANTITY) AS TempQty FROM SALE_TRACKING_TABLE T1" + " INNER JOIN SALE_TRACKING_HEADER_TABLE T2 ON T2.RECCEPT_COUNT=T1.RECCEPT_COUNT WHERE T2.COUNTER_ID =" + counterId + " AND T2.Visit_Date='" + visit_date + "' AND T1.INVOICE_TYPE='Saleable'" + " AND T1.RIGHTNAME !='ME' GROUP BY T1.PRODUCT_ID" + " UNION ALL select S.COUNTER_ID as CounterId," + " S.PROMO_PRODUCT_ID AS ProductId , SUM(S.PROMO_PRODUCT_QTY) AS TempQty from APPLYED_PROMOTION_TABLE S INNER JOIN SALE_TRACKING_HEADER_TABLE S1" + " ON S.RECCEPT_COUNT=S1.RECCEPT_COUNT Where S.PROMO_TYPE ='Product' AND S.COUNTER_ID =" + counterId + " AND S1.VISIT_DATE = '" + visit_date + "'" + " AND S.RIGHTNAME !='ME' GROUP BY S.PROMO_PRODUCT_ID)as t Group by CounterId, ProductId)" + " c where c.ProductId = t.Productid)>0 then (Select TempQty from (Select CounterId, ProductId," + "sum(TempQty) as TempQty from ( Select T2.COUNTER_ID AS CounterId, T1.PRODUCT_ID AS ProductId , SUM(T1.QUANTITY) AS TempQty FROM SALE_TRACKING_TABLE T1" + " INNER JOIN SALE_TRACKING_HEADER_TABLE T2 ON T2.RECCEPT_COUNT=T1.RECCEPT_COUNT WHERE T2.COUNTER_ID =" + counterId + " AND T2.Visit_Date='" + visit_date + "' AND T1.INVOICE_TYPE='Saleable'" + " AND T1.RIGHTNAME !='ME' AND T2.POS_SALE_FLAG='1' GROUP BY T1.PRODUCT_ID" + " UNION ALL select S.COUNTER_ID as CounterId," + " S.PROMO_PRODUCT_ID AS ProductId , SUM(S.PROMO_PRODUCT_QTY) AS TempQty from APPLYED_PROMOTION_TABLE S INNER JOIN SALE_TRACKING_HEADER_TABLE S1" + " ON S.RECCEPT_COUNT=S1.RECCEPT_COUNT Where S.PROMO_TYPE ='Product' AND S.COUNTER_ID =" + counterId + " AND S1.VISIT_DATE = '" + visit_date + "'" + " AND S.RIGHTNAME !='ME' AND S1.POS_SALE_FLAG ='1' GROUP BY S.PROMO_PRODUCT_ID)as t Group by CounterId, ProductId" + " ) c where c.productId = t.Productid) else (" + "Select sum(QtySold)as QtySold from (select SaleQty as QtySold from Report_BA_TBASale s where s.ProductId = t.ProductId and s.CounterId=" + counterId + " and VisitDate='" + visit_date + "'" + "UNION all select SaleQty as QtySold from Report_BA_TBAPromoSale s where s.ProductId = t.ProductId and s.CounterId=" + counterId + " and VisitDate='" + visit_date + "')" + ") end as TempSale" + " from T_StockSummary t) as tempsale on s.ProductId=tempsale.ProductId"; + } + + if (flag_for_filtr_stocksm) { + dbcursor = db.rawQuery("Select distinct " + column_name + "," + column_name_Id + " from Product_Master pm inner join " + table + " ts on ts.ProductId=pm.ProductId where " + stock_summary_balance + ">0", null); + } else { + dbcursor = db.rawQuery("select distinct pm." + column_name + ",pm." + column_name_Id + " from Product_Master pm" + " left join (Select s.ProductId," + getData + " from " + table + " s Left join (Select ProductId, sum(DamageQty) as DamageQty" + " from (select T.ProductId, T.Stock as DamageQty from TABLE_TRANSACTION_DATA T INNER JOIN DR_TABLE_TRANSACTION_WISE_MASTER M" + " ON T.MASTER_TRANSACTION_ID = M.MASTER_TRANSACTION_ID where T.STOCK_TYPE=trim('DAMAGE') AND T.Visit_Date ='" + visit_date + "' and T.COUNTER_ID ='" + counterId + "'" + " Union All SELECT ProductId, DamageQty from Damage_PreviousPending Where CounterId ='" + counterId + "' and Verify ='Pending'" + additionalQueryMe2 + ") as t Group by ProductId) as dm" + " on s.ProductId = dm.ProductId Left Join (Select ProductId, sum(ReturnQty) as ReturnQty from (select ProductId, ReturnQty from Damage_ReturnToDistributor" + " WHERE CounterId='" + counterId + "'and VERIFY ='Pending' Union All select ProductId, STOCK as ReturnQty from TABLE_RETURNTO_DISTRIBUTOR WHERE Visit_Date='" + visit_date + "' AND COUNTER_ID='" + counterId + "') as" + " t Group by ProductId ) as rd on trim(s.ProductId) = trim(rd.ProductId) and s.CounterId ='" + counterId + "'" + additionalQueryMe + ") as TS ON TS.ProductId = pm.ProductId where TS.SaleableBalance >0 ", null); + } + + //test("Query2---", dbcursor.toString()); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + ProductMaster sb = new ProductMaster(); + sb.setBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow(column_name))); + sb.setBrandId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(column_name_Id))); + list.add(sb); + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list; + } + } catch (Exception e) { + + return list; + } + + return list; + } + + public ArrayList getproductdata_formanual_inwarddialog(String column_name, String column_name_Id) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + + dbcursor = db.rawQuery("select distinct " + column_name + "," + column_name_Id + " from Product_Master", null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + ProductMaster sb = new ProductMaster(); + sb.setBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow(column_name))); + sb.setBrandId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(column_name_Id))); + list.add(sb); + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list; + } + } catch (Exception e) { + + return list; + } + + return list; + } + + + public ArrayList getproductdata_dialogfor_return(String column_name, String column_name_Id, boolean flag_for_filtr_stocksm, String stock_summary_balance) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + + dbcursor = db.rawQuery("select distinct " + column_name + "," + column_name_Id + " from Product_Master pm inner join T_StockSummary ts on ts.ProductId=pm.ProductId", null); + + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + ProductMaster sb = new ProductMaster(); + sb.setBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow(column_name))); + sb.setBrandId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(column_name_Id))); + list.add(sb); + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list; + } + } catch (Exception e) { + + return list; + } + + return list; + } + + public ArrayList getsub_brand_using_brand_Id(String dialog_brand_Id, String column_name, String column_Id, String value_get_column_name, String invoice_type, String visit_date, String counterId, boolean consumersale_flag, String userType) { + ////////test("Fetching", "Storedata--------------->Start<------------"); + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + String table = CommonString.T_StockSummary, additionalQueryMe = " Where SaleableBalance >0", additionalQueryMe2 = "", getData = "(s.SaleableBalance - ifnull(dm.DamageQty,0)) as SaleableBalance"; + if (userType != null && userType.equalsIgnoreCase(CommonString.TAG_FROM_ME)) { + additionalQueryMe2 = "UNION ALL Select T1.PRODUCT_ID AS ProductId , SUM(T1.QUANTITY) AS DamageQty FROM SALE_TRACKING_TABLE T1" + " INNER JOIN SALE_TRACKING_HEADER_TABLE T2 ON T2.RECCEPT_COUNT=T1.RECCEPT_COUNT WHERE T2.COUNTER_ID =" + counterId + " AND T2.Visit_Date='" + visit_date + "' AND T1.INVOICE_TYPE='Saleable'" + " AND T1.RIGHTNAME='ME' GROUP BY T1.PRODUCT_ID UNION ALL select S.PROMO_PRODUCT_ID AS ProductId ," + " SUM(S.PROMO_PRODUCT_QTY) AS DamageQty from APPLYED_PROMOTION_TABLE S INNER JOIN SALE_TRACKING_HEADER_TABLE S1 ON S.RECCEPT_COUNT=S1.RECCEPT_COUNT Where S.PROMO_TYPE ='Product'" + " AND S.COUNTER_ID =" + counterId + " AND S1.VISIT_DATE = '" + visit_date + "' AND S.RIGHTNAME='ME' GROUP BY S.PROMO_PRODUCT_ID "; + + + getData = "((s.SaleableBalance + ifnull(tempsale.TempSale,0) ) - ifnull(dm.DamageQty,0)) as SaleableBalance"; + additionalQueryMe = " left join (select ProductId, case when (Select count(*) from (Select CounterId, ProductId," + "sum(TempQty) as TempQty from ( Select T2.COUNTER_ID AS CounterId, T1.PRODUCT_ID AS ProductId , SUM(T1.QUANTITY) AS TempQty FROM SALE_TRACKING_TABLE T1" + " INNER JOIN SALE_TRACKING_HEADER_TABLE T2 ON T2.RECCEPT_COUNT=T1.RECCEPT_COUNT WHERE T2.COUNTER_ID =" + counterId + " AND T2.Visit_Date='" + visit_date + "' AND T1.INVOICE_TYPE='Saleable'" + " AND T1.RIGHTNAME !='ME' GROUP BY T1.PRODUCT_ID" + " UNION ALL select S.COUNTER_ID as CounterId," + " S.PROMO_PRODUCT_ID AS ProductId , SUM(S.PROMO_PRODUCT_QTY) AS TempQty from APPLYED_PROMOTION_TABLE S INNER JOIN SALE_TRACKING_HEADER_TABLE S1" + " ON S.RECCEPT_COUNT=S1.RECCEPT_COUNT Where S.PROMO_TYPE ='Product' AND S.COUNTER_ID =" + counterId + " AND S1.VISIT_DATE = '" + visit_date + "'" + " AND S.RIGHTNAME !='ME' GROUP BY S.PROMO_PRODUCT_ID)as t Group by CounterId, ProductId)" + " c where c.ProductId = t.Productid)>0 then (Select TempQty from (Select CounterId, ProductId," + "sum(TempQty) as TempQty from ( Select T2.COUNTER_ID AS CounterId, T1.PRODUCT_ID AS ProductId , SUM(T1.QUANTITY) AS TempQty FROM SALE_TRACKING_TABLE T1" + " INNER JOIN SALE_TRACKING_HEADER_TABLE T2 ON T2.RECCEPT_COUNT=T1.RECCEPT_COUNT WHERE T2.COUNTER_ID =" + counterId + " AND T2.Visit_Date='" + visit_date + "' AND T1.INVOICE_TYPE='Saleable'" + " AND T1.RIGHTNAME !='ME' AND T2.POS_SALE_FLAG='1' GROUP BY T1.PRODUCT_ID" + " UNION ALL select S.COUNTER_ID as CounterId," + " S.PROMO_PRODUCT_ID AS ProductId , SUM(S.PROMO_PRODUCT_QTY) AS TempQty from APPLYED_PROMOTION_TABLE S INNER JOIN SALE_TRACKING_HEADER_TABLE S1" + " ON S.RECCEPT_COUNT=S1.RECCEPT_COUNT Where S.PROMO_TYPE ='Product' AND S.COUNTER_ID =" + counterId + " AND S1.VISIT_DATE = '" + visit_date + "'" + " AND S.RIGHTNAME !='ME' AND S1.POS_SALE_FLAG ='1' GROUP BY S.PROMO_PRODUCT_ID)as t Group by CounterId, ProductId" + " ) c where c.productId = t.Productid) else (" + "Select sum(QtySold)as QtySold from (select SaleQty as QtySold from Report_BA_TBASale s where s.ProductId = t.ProductId and s.CounterId=" + counterId + " and VisitDate='" + visit_date + "'" + "UNION all select SaleQty as QtySold from Report_BA_TBAPromoSale s where s.ProductId = t.ProductId and s.CounterId=" + counterId + " and VisitDate='" + visit_date + "')" + ") end as TempSale" + " from T_StockSummary t) as tempsale on s.ProductId=tempsale.ProductId"; + } + if (invoice_type != null && invoice_type.trim().equalsIgnoreCase("Sample")) { + dbcursor = db.rawQuery("select distinct " + column_name + "," + column_Id + " from Product_Master pm inner join " + table + " ts on ts.ProductId=pm.ProductId where " + value_get_column_name + "=\"" + dialog_brand_Id + "\"" + " and SampleBalance>0", null); + } else if (invoice_type != null && invoice_type.trim().equalsIgnoreCase("GWP")) { + dbcursor = db.rawQuery("select distinct " + column_name + "," + column_Id + " from Product_Master pm inner join " + table + " ts on ts.ProductId=pm.ProductId where " + value_get_column_name + "=\"" + dialog_brand_Id + "\"" + " and GwpBalance>0", null); + } else if (value_get_column_name == null && dialog_brand_Id.isEmpty()) { + if (consumersale_flag) { + dbcursor = db.rawQuery("select distinct pm." + column_name + ",pm." + column_Id + " from Product_Master pm" + " left join (Select s.ProductId," + getData + " from " + table + " s Left join (Select ProductId, sum(DamageQty) as DamageQty" + " from (select T.ProductId, T.Stock as DamageQty from TABLE_TRANSACTION_DATA T INNER JOIN DR_TABLE_TRANSACTION_WISE_MASTER M" + " ON T.MASTER_TRANSACTION_ID = M.MASTER_TRANSACTION_ID where T.STOCK_TYPE='DAMAGE' AND T.Visit_Date ='" + visit_date + "' and T.COUNTER_ID ='" + counterId + "'" + " Union All SELECT ProductId, DamageQty from Damage_PreviousPending Where CounterId ='" + counterId + "' and Verify ='Pending'" + additionalQueryMe2 + ") as t Group by ProductId) as dm" + " on s.ProductId = dm.ProductId Left Join (Select ProductId, sum(ReturnQty) as ReturnQty from (select ProductId, ReturnQty from Damage_ReturnToDistributor" + " WHERE CounterId='" + counterId + "'and VERIFY ='Pending' Union All select ProductId, STOCK as ReturnQty from TABLE_RETURNTO_DISTRIBUTOR WHERE Visit_Date='" + visit_date + "' AND COUNTER_ID='" + counterId + "') as" + " t Group by ProductId ) as rd on trim(s.ProductId) = trim(rd.ProductId) and s.CounterId ='" + counterId + "' " + additionalQueryMe + " ) as TS ON TS.ProductId = pm.ProductId where TS.SaleableBalance >0 ", null); + + } else { + dbcursor = db.rawQuery("select distinct " + column_name + "," + column_Id + " from Product_Master", null); + } + + } else { + if (consumersale_flag) { + dbcursor = db.rawQuery("select distinct pm." + column_name + ",pm." + column_Id + " from Product_Master pm" + " left join (Select s.ProductId," + getData + " from " + table + " s Left join (Select ProductId, sum(DamageQty) as DamageQty" + " from (select T.ProductId, T.Stock as DamageQty from TABLE_TRANSACTION_DATA T INNER JOIN DR_TABLE_TRANSACTION_WISE_MASTER M" + " ON T.MASTER_TRANSACTION_ID = M.MASTER_TRANSACTION_ID where T.STOCK_TYPE='DAMAGE' AND T.Visit_Date ='" + visit_date + "' and T.COUNTER_ID ='" + counterId + "'" + " Union All SELECT ProductId, DamageQty from Damage_PreviousPending Where CounterId ='" + counterId + "' and Verify ='Pending'" + additionalQueryMe2 + ") as t Group by ProductId) as dm" + " on s.ProductId = dm.ProductId Left Join (Select ProductId, sum(ReturnQty) as ReturnQty from (select ProductId, ReturnQty from Damage_ReturnToDistributor" + " WHERE CounterId='" + counterId + "'and VERIFY ='Pending' Union All select ProductId, STOCK as ReturnQty from TABLE_RETURNTO_DISTRIBUTOR WHERE Visit_Date='" + visit_date + "' AND COUNTER_ID='" + counterId + "') as" + " t Group by ProductId ) as rd on trim(s.ProductId) = trim(rd.ProductId) and s.CounterId ='" + counterId + "'" + additionalQueryMe + " ) as TS ON TS.ProductId = pm.ProductId where TS.SaleableBalance >0 and pm." + value_get_column_name + " =\"" + dialog_brand_Id + "\"", null); + + } else { + dbcursor = db.rawQuery("select distinct " + column_name + "," + column_Id + " from Product_Master where " + value_get_column_name + " =\"" + dialog_brand_Id + "\"", null); + + } + } + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + ProductMaster sb = new ProductMaster(); + sb.setBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow(column_name))); + sb.setBrandId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(column_Id))); + list.add(sb); + dbcursor.moveToNext(); + } + dbcursor.close(); + return list; + } + } catch (Exception e) { + ////////test("Exception ", "when fetching opening stock!!!!!!!!!!!" + e.toString()); + return list; + } + ////////test("Fetching ", "opening stock---------------------->Stop<-----------"); + return list; + } + + + public ArrayList getSubBrandOrReference(String counterGroup_Id, String column_name, String signatureName, String brandName, String subBrand, boolean GWPFlag) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + String productType = "Normal"; + if (GWPFlag) { + productType = "GWP"; + } + + if (signatureName == null) { + dbcursor = db.rawQuery("select distinct " + column_name + " from Product_Master where ProductType ='" + productType + "'", null); + } else if (column_name != null && column_name.trim().equalsIgnoreCase("ReferenceName") && subBrand != null) { + dbcursor = db.rawQuery("select distinct " + column_name + " from Product_Master where" + " SubBrandName =trim(\"" + subBrand + "\") and ProductType =trim('" + productType + "')", null); + } else if (brandName != null) { + dbcursor = db.rawQuery("select distinct " + column_name + " from Product_Master where" + " BrandName =trim(\"" + brandName + "\") and ProductType =trim('" + productType + "')", null); + } else { + dbcursor = db.rawQuery("select distinct " + column_name + " from Product_Master " + "where SignatureName =trim(\"" + signatureName + "\") and ProductType =trim('" + productType + "')", null); + } + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + ProductMaster sb = new ProductMaster(); + sb.setBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow(column_name))); + list.add(sb); + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list; + } + } catch (Exception e) { + + return list; + } + return list; + } + + + //get Signature Brand Sub Brand and Reference + public ArrayList getbrand_wise_sku_fromproduct(String brand_Id, String stock_summary_balance, String visit_date, String counterId, String userType) { + ////////test("Fetching", "Storedata--------------->Start<------------"); + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + String table = CommonString.T_StockSummary, additionalQueryMe = " Where SaleableBalance >0", additionalQueryMe2 = "", getData = "(s.SaleableBalance - ifnull(dm.DamageQty,0)) as SaleableBalance"; + if (userType != null && userType.equalsIgnoreCase(CommonString.TAG_FROM_ME)) { + additionalQueryMe2 = "UNION ALL Select T1.PRODUCT_ID AS ProductId , SUM(T1.QUANTITY) AS DamageQty FROM SALE_TRACKING_TABLE T1" + " INNER JOIN SALE_TRACKING_HEADER_TABLE T2 ON T2.RECCEPT_COUNT=T1.RECCEPT_COUNT WHERE T2.COUNTER_ID =" + counterId + " AND T2.Visit_Date='" + visit_date + "' AND T1.INVOICE_TYPE='Saleable'" + " AND T1.RIGHTNAME='ME' GROUP BY T1.PRODUCT_ID UNION ALL select S.PROMO_PRODUCT_ID AS ProductId ," + " SUM(S.PROMO_PRODUCT_QTY) AS DamageQty from APPLYED_PROMOTION_TABLE S INNER JOIN SALE_TRACKING_HEADER_TABLE S1 ON S.RECCEPT_COUNT=S1.RECCEPT_COUNT Where S.PROMO_TYPE ='Product'" + " AND S.COUNTER_ID =" + counterId + " AND S1.VISIT_DATE = '" + visit_date + "' AND S.RIGHTNAME='ME' GROUP BY S.PROMO_PRODUCT_ID "; + + + getData = "((s.SaleableBalance + ifnull(tempsale.TempSale,0) ) - ifnull(dm.DamageQty,0)) as SaleableBalance"; + additionalQueryMe = " left join (select ProductId, case when (Select count(*) from (Select CounterId, ProductId," + "sum(TempQty) as TempQty from ( Select T2.COUNTER_ID AS CounterId, T1.PRODUCT_ID AS ProductId , SUM(T1.QUANTITY) AS TempQty FROM SALE_TRACKING_TABLE T1" + " INNER JOIN SALE_TRACKING_HEADER_TABLE T2 ON T2.RECCEPT_COUNT=T1.RECCEPT_COUNT WHERE T2.COUNTER_ID =" + counterId + " AND T2.Visit_Date='" + visit_date + "' AND T1.INVOICE_TYPE='Saleable'" + " AND T1.RIGHTNAME !='ME' GROUP BY T1.PRODUCT_ID" + " UNION ALL select S.COUNTER_ID as CounterId," + " S.PROMO_PRODUCT_ID AS ProductId , SUM(S.PROMO_PRODUCT_QTY) AS TempQty from APPLYED_PROMOTION_TABLE S INNER JOIN SALE_TRACKING_HEADER_TABLE S1" + " ON S.RECCEPT_COUNT=S1.RECCEPT_COUNT Where S.PROMO_TYPE ='Product' AND S.COUNTER_ID =" + counterId + " AND S1.VISIT_DATE = '" + visit_date + "'" + " AND S.RIGHTNAME !='ME' GROUP BY S.PROMO_PRODUCT_ID)as t Group by CounterId, ProductId)" + " c where c.ProductId = t.Productid)>0 then (Select TempQty from (Select CounterId, ProductId," + "sum(TempQty) as TempQty from ( Select T2.COUNTER_ID AS CounterId, T1.PRODUCT_ID AS ProductId , SUM(T1.QUANTITY) AS TempQty FROM SALE_TRACKING_TABLE T1" + " INNER JOIN SALE_TRACKING_HEADER_TABLE T2 ON T2.RECCEPT_COUNT=T1.RECCEPT_COUNT WHERE T2.COUNTER_ID =" + counterId + " AND T2.Visit_Date='" + visit_date + "' AND T1.INVOICE_TYPE='Saleable'" + " AND T1.RIGHTNAME !='ME' AND T2.POS_SALE_FLAG='1' GROUP BY T1.PRODUCT_ID" + " UNION ALL select S.COUNTER_ID as CounterId," + " S.PROMO_PRODUCT_ID AS ProductId , SUM(S.PROMO_PRODUCT_QTY) AS TempQty from APPLYED_PROMOTION_TABLE S INNER JOIN SALE_TRACKING_HEADER_TABLE S1" + " ON S.RECCEPT_COUNT=S1.RECCEPT_COUNT Where S.PROMO_TYPE ='Product' AND S.COUNTER_ID =" + counterId + " AND S1.VISIT_DATE = '" + visit_date + "'" + " AND S.RIGHTNAME !='ME' AND S1.POS_SALE_FLAG ='1' GROUP BY S.PROMO_PRODUCT_ID)as t Group by CounterId, ProductId" + " ) c where c.productId = t.Productid) else (" + "Select sum(QtySold)as QtySold from (select SaleQty as QtySold from Report_BA_TBASale s where s.ProductId = t.ProductId and s.CounterId=" + counterId + " and VisitDate='" + visit_date + "'" + "UNION all select SaleQty as QtySold from Report_BA_TBAPromoSale s where s.ProductId = t.ProductId and s.CounterId=" + counterId + " and VisitDate='" + visit_date + "')" + ") end as TempSale" + " from T_StockSummary t) as tempsale on s.ProductId=tempsale.ProductId"; + } + if (stock_summary_balance != null && brand_Id == null) { + dbcursor = db.rawQuery(" select distinct ProductName,pm.ProductId as ProductId,EanCode,Mrp,LorealCode,ProductType from Product_Master pm inner join " + table + " ts on ts.ProductId=pm.ProductId where " + stock_summary_balance + ">0", null); + } else if (stock_summary_balance == null && brand_Id == null) { + dbcursor = db.rawQuery("select distinct pm.ProductName as ProductName,pm.ProductId as ProductId,pm.LorealCode as" + " LorealCode,pm.Mrp as Mrp," + "pm.EanCode as EanCode,pm.ProductType as ProductType from Product_Master pm" + " left join (Select s.ProductId," + getData + " from " + table + " s Left join (Select ProductId, sum(DamageQty) as DamageQty" + " from (select T.ProductId, T.Stock as DamageQty from TABLE_TRANSACTION_DATA T " + "INNER JOIN DR_TABLE_TRANSACTION_WISE_MASTER M" + " ON T.MASTER_TRANSACTION_ID = M.MASTER_TRANSACTION_ID where T.STOCK_TYPE='DAMAGE' AND T.Visit_Date ='" + visit_date + "' and T.COUNTER_ID ='" + counterId + "'" + " Union All SELECT ProductId, DamageQty from Damage_PreviousPending Where CounterId ='" + counterId + "' and Verify ='Pending'" + additionalQueryMe2 + ") as t Group by ProductId) as dm" + " on s.ProductId = dm.ProductId Left Join (Select ProductId, sum(ReturnQty) as ReturnQty " + "from (select ProductId, ReturnQty from Damage_ReturnToDistributor" + " WHERE CounterId='" + counterId + "'and VERIFY ='Pending' Union All select ProductId, " + "STOCK as ReturnQty from TABLE_RETURNTO_DISTRIBUTOR WHERE Visit_Date='" + visit_date + "' AND COUNTER_ID='" + counterId + "') as" + " t Group by ProductId ) as rd on trim(s.ProductId) = trim(rd.ProductId) and s.CounterId ='" + counterId + "'" + additionalQueryMe + ") as TS ON TS.ProductId = pm.ProductId where TS.SaleableBalance >0 ", null); + + } else { + dbcursor = db.rawQuery("select distinct ProductName,ProductId,EanCode,Mrp,LorealCode,ProductType " + "from Product_Master where BrandId='" + brand_Id + "'", null); + } + //test("query3--", dbcursor.toString()); + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + ProductMaster sb = new ProductMaster(); + sb.setProductName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ProductName"))); + sb.setProductId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("ProductId"))); + sb.setEanCode(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EanCode"))); + sb.setMrp(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("Mrp"))); + sb.setLorealCode(dbcursor.getString(dbcursor.getColumnIndexOrThrow("LorealCode"))); + sb.setProductType(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ProductType"))); + list.add(sb); + dbcursor.moveToNext(); + } + dbcursor.close(); + return list; + } + } catch (Exception e) { + ////////test("Exception ", "when fetching opening stock!!!!!!!!!!!" + e.toString()); + return list; + } + ////////test("Fetching ", "opening stock---------------------->Stop<-----------"); + return list; + } + + public ArrayList getbrand_wise_sku_fromproductformanual() { + ////////test("Fetching", "Storedata--------------->Start<------------"); + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + dbcursor = db.rawQuery("select distinct ProductName,ProductId,EanCode,Mrp,LorealCode,ProductType from Product_Master", null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + ProductMaster sb = new ProductMaster(); + sb.setProductName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ProductName"))); + sb.setProductId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("ProductId"))); + sb.setEanCode(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EanCode"))); + sb.setMrp(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("Mrp"))); + sb.setLorealCode(dbcursor.getString(dbcursor.getColumnIndexOrThrow("LorealCode"))); + sb.setProductType(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ProductType"))); + list.add(sb); + dbcursor.moveToNext(); + } + dbcursor.close(); + return list; + } + } catch (Exception e) { + ////////test("Exception ", "when fetching opening stock!!!!!!!!!!!" + e.toString()); + return list; + } + ////////test("Fetching ", "opening stock---------------------->Stop<-----------"); + return list; + } + + + public ArrayList getbrand_wise_sku_fromproductfor_return() { + ////////test("Fetching", "Storedata--------------->Start<------------"); + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + + dbcursor = db.rawQuery("select distinct pm.ProductName as ProductName,pm.ProductId as ProductId,pm.EanCode as EanCode,pm.Mrp as Mrp," + "pm.LorealCode as LorealCode,pm.ProductType as ProductType from Product_Master pm inner join T_StockSummary ts on ts.ProductId=pm.ProductId", null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + ProductMaster sb = new ProductMaster(); + sb.setProductName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ProductName"))); + sb.setProductId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("ProductId"))); + sb.setEanCode(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EanCode"))); + sb.setMrp(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("Mrp"))); + sb.setLorealCode(dbcursor.getString(dbcursor.getColumnIndexOrThrow("LorealCode"))); + sb.setProductType(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ProductType"))); + list.add(sb); + dbcursor.moveToNext(); + } + dbcursor.close(); + return list; + } + } catch (Exception e) { + ////////test("Exception ", "when fetching opening stock!!!!!!!!!!!" + e.toString()); + return list; + } + ////////test("Fetching ", "opening stock---------------------->Stop<-----------"); + return list; + } + + + public boolean insert_return_reason(MasterProfileQuestionGetterSetter cst) { + db.delete("Master_ReturnReason", null, null); + ContentValues values = new ContentValues(); + List data = cst.getMasterReturnReason(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("ReasonId", data.get(i).getReasonId()); + values.put("Reason", data.get(i).getReason()); + + long id = db.insert("Master_ReturnReason", null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ex.fillInStackTrace(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + public ArrayList getreturn_reasonList() { + ////////test("Fetching", "Storedata--------------->Start<------------"); + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + dbcursor = db.rawQuery("select distinct ReasonId,Reason from Master_ReturnReason", null); + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + MasterReturnReason sb = new MasterReturnReason(); + + sb.setReasonId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("ReasonId"))); + sb.setReason(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Reason"))); + + list.add(sb); + dbcursor.moveToNext(); + } + dbcursor.close(); + return list; + } + } catch (Exception e) { + ////////test("Exception ", "when fetching opening stock!!!!!!!!!!!" + e.toString()); + return list; + } + ////////test("Fetching ", "opening stock---------------------->Stop<-----------"); + return list; + } + + public boolean inserterm_condition(MasterProfileQuestionGetterSetter cst) { + db.delete("Master_TermsCondition", null, null); + ContentValues values = new ContentValues(); + List data = cst.getMasterTermsCondition(); + try { + if (data.isEmpty()) { + return false; + } + + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + + values.put("TermsCondition", data.get(i).getTermsCondition()); + + long id = db.insert("Master_TermsCondition", null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ex.fillInStackTrace(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + public MasterTermsCondition getterm_and_condition() { + ////////test("Fetching", "Storedata--------------->Start<------------"); + MasterTermsCondition list = new MasterTermsCondition(); + Cursor dbcursor = null; + try { + dbcursor = db.rawQuery("select distinct TermsCondition from Master_TermsCondition", null); + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + + list.setTermsCondition(dbcursor.getString(dbcursor.getColumnIndexOrThrow("TermsCondition"))); + + dbcursor.moveToNext(); + } + dbcursor.close(); + return list; + } + } catch (Exception e) { + ////////test("Exception ", "when fetching opening stock!!!!!!!!!!!" + e.toString()); + return list; + } + ////////test("Fetching ", "opening stock---------------------->Stop<-----------"); + return list; + } + + public ArrayList getconsumerReturndataformDb(String storeid, String visite_date, String user_Id) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + + dbcursor = db.rawQuery("SELECT * from " + CommonString.Table_Consumer_Return + " WHERE " + CommonString.KEY_VISIT_DATE + "='" + visite_date + "'AND " + CommonString.KEY_COUNTER_ID + "='" + storeid + "' and USER_ID='" + user_Id + "'", null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + InvoiceGetterSetter sale = new InvoiceGetterSetter(); + sale.setCustomer_name(dbcursor.getString(dbcursor.getColumnIndexOrThrow("BUYER_NAME"))); + sale.setConsumer_return_bill_no(dbcursor.getString(dbcursor.getColumnIndexOrThrow("BILL_NO"))); + sale.setMobile_no(dbcursor.getString(dbcursor.getColumnIndexOrThrow("CONTACT_NUMBER"))); + sale.setProduct_Id(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PRODUCT_ID"))); + sale.setProduct(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PRODUCT"))); + sale.setQuantity(dbcursor.getString(dbcursor.getColumnIndexOrThrow("QUANTITY"))); + sale.setProduct_rate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PRODUCT_RATE"))); + sale.setTotal_amount(dbcursor.getString(dbcursor.getColumnIndexOrThrow("TOTAL_PRICE"))); + sale.setCustomer_gender(dbcursor.getString(dbcursor.getColumnIndexOrThrow("GENDER"))); + sale.setScan_ean_code_or_enterd_ean_code(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EAN_CODE"))); + sale.setCon_return_reason_Id(dbcursor.getString(dbcursor.getColumnIndexOrThrow("REASON_ID"))); + sale.setCon_return_reason(dbcursor.getString(dbcursor.getColumnIndexOrThrow("REASON"))); + sale.setUnique_code(dbcursor.getString(dbcursor.getColumnIndexOrThrow("UNIQUE_CODE"))); + sale.setStore_name(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_STORE_NAME))); + sale.setStore_address(dbcursor.getString(dbcursor.getColumnIndexOrThrow("STORE_ADDRESS"))); + list.add(sale); + + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list; + } + + } catch (Exception e) { + ////////test("Exception Brands", e.toString()); + return list; + } + return list; + } + + public boolean insertInvoiceTypeMasterData(MasterInvoiceTypeGetterSetter cst) { + db.delete("Master_InvoiceType", null, null); + ContentValues values = new ContentValues(); + List data = cst.getMasterInvoiceType(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("InvoiceType", data.get(i).getInvoiceType().trim()); + + long id = db.insert("Master_InvoiceType", null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ex.fillInStackTrace(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + + private long updateInvoiceStatus(String invoiceNo, boolean newproductInward) { + long l = 0; + try { + if (!db.isOpen()) open(); + ContentValues values = new ContentValues(); + values.put(CommonString.KEY_INVOICE_STATUS, "1"); + l = db.update(CommonString.TABLE_INSERT_INWARD_STOCK_TRANSACTION, values, CommonString.KEY_INVOICE_NUMBER + " ='" + invoiceNo + "' AND " + CommonString.KEY_NEW_PRODUCT + "= " + (newproductInward ? 1 : 0), null); + } catch (Exception e) { + e.fillInStackTrace(); + } + return l; + } + + public ProductMaster getInwardStockCheckTransactionData(Integer productId, String invId, String invoiceNo) { + Cursor dbcursor = null; + ProductMaster sb = null; + try { + + dbcursor = db.rawQuery("SELECT * FROM " + CommonString.TABLE_INSERT_INWARD_STOCK_TRANSACTION + " WHERE " + CommonString.KEY_INVOICE_ID + " ='" + invId + "'AND " + CommonString.KEY_INVOICE_NUMBER + " ='" + invoiceNo + "' AND " + CommonString.KEY_ProductId + " =" + productId, null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + sb = new ProductMaster(); + sb.setTransaction_Id(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_TRANSACTION_ID))); + dbcursor.moveToNext(); + } + + dbcursor.close(); + return sb; + } + } catch (Exception e) { + + return sb; + } + + return sb; + } + + + public ArrayList get_inward_sub_brand_name(String column_name, String invoiceNo, String type) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + dbcursor = db.rawQuery("select distinct Pm." + column_name + " from T_CounterInvoice as ci inner join Product_Master Pm on ci.ProductId = Pm.ProductId " + "where ci.InvoiceNo ='" + invoiceNo + "' and ci.InvoiceType ='" + type + "'", null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + ProductMaster sb = new ProductMaster(); + sb.setBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow(column_name))); + list.add(sb); + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list; + } + } catch (Exception e) { + + return list; + } + + return list; + } + + + public ArrayList getInwardSubBrandOrReference(String column_name, String signatureName, String brandName, String subBrand, String invoiceNo, String type) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + + if (signatureName == null) { + dbcursor = db.rawQuery("select distinct p." + column_name + " from Product_Master p inner join " + "T_CounterInvoice t on p.ProductId = t.ProductId WHERE t.InvoiceNo = '" + invoiceNo + "' and t.InvoiceType = '" + type + "'", null); + } else if (column_name != null && column_name.trim().equalsIgnoreCase("ReferenceName") && subBrand != null) { + dbcursor = db.rawQuery("select distinct p." + column_name + " from Product_Master p inner join " + "T_CounterInvoice t on p.ProductId = t.ProductId WHERE p.SubBrandName =trim(\"" + subBrand + "\") and t.InvoiceNo = '" + invoiceNo + "' and t.InvoiceType =trim('" + type + "')", null); + } else if (brandName != null) { + dbcursor = db.rawQuery("select distinct p." + column_name + " from Product_Master p inner join " + "T_CounterInvoice t on p.ProductId = t.ProductId WHERE p.BrandName =trim(\"" + brandName + "\") and t.InvoiceNo =trim('" + invoiceNo + "')" + " and t.InvoiceType =trim('" + type + "')", null); + } else { + dbcursor = db.rawQuery("select distinct p." + column_name + " from Product_Master p inner join " + "T_CounterInvoice t on p.ProductId = t.ProductId WHERE p.SignatureName =trim(\"" + signatureName + "\") and " + " t.InvoiceNo =trim('" + invoiceNo + "') and t.InvoiceType =trim('" + type + "')", null); + } + + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + ProductMaster sb = new ProductMaster(); + sb.setBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow(column_name))); + list.add(sb); + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list; + } + } catch (Exception e) { + + return list; + } + return list; + } + + public boolean insertLeaveRequest(MasterProfileQuestionGetterSetter cst) { + db.delete("T_LeaveRequest", null, null); + ContentValues values = new ContentValues(); + List data = cst.gettLeaveRequestList(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + + values.put("Id", data.get(i).getId()); + values.put("RequestDate", data.get(i).getRequestDate()); + values.put("UserId", data.get(i).getUserId().toLowerCase()); + values.put("FromDate", data.get(i).getFromDate()); + values.put("ToDate", data.get(i).getToDate()); + values.put("LeaveStatus", data.get(i).getLeaveStatus()); + values.put("LeaveType", data.get(i).getLeaveType()); + values.put("LeaveTypeDesc", data.get(i).getLeaveTypeDesc()); + + long id = db.insert("T_LeaveRequest", null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ex.fillInStackTrace(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + + public long insertNewInwardProductStockData(String visit_date, HashMap> data, List save_listDataHeader, String invoiceNo, String type, String invDate, String counter_id, String username, String source, String transactionId, boolean checked_checkbox_flag) { + long id = 0, id2 = 0, masterreturn = 0; + db.delete(CommonString.TABLE_INSERT_INWARD_STOCK_HEADER_DATA, CommonString.KEY_INVOICE_NUMBER + "='" + invoiceNo + "' AND " + CommonString.KEY_COUNTER_ID + "='" + counter_id + "' AND " + CommonString.KEY_INVOICE_TYPE + " ='" + type + "'", null); + db.delete(CommonString.TABLE_INSERT_INWARD_STOCK_CHILD_DATA, CommonString.KEY_INVOICE_NUMBER + "='" + invoiceNo + "' AND " + CommonString.KEY_COUNTER_ID + "='" + counter_id + "' AND " + CommonString.KEY_INVOICE_TYPE + " = '" + type + "'", null); + db.delete(CommonString.TABLE_TRANSACTION_WISE_MASTER_TABLE, CommonString.KEY_VISIT_DATE + " <>'" + visit_date + "'", null); + db.delete(CommonString.TABLE_INSERT_INWARD_STOCK_TRANSACTION, CommonString.KEY_VISIT_DATE + " <>'" + visit_date + "'", null); + ContentValues values; + ContentValues values1; + ContentValues valuesmasterT; + ContentValues values2; + ProductMaster transactionList; + TStockSummary stockObj; + try { + db.beginTransaction(); + if (save_listDataHeader.size() > 0) { + if (checked_checkbox_flag) { + valuesmasterT = new ContentValues(); + valuesmasterT.put(CommonString.KEY_UUID, transactionId); + valuesmasterT.put(CommonString.KEY_USER_ID, username); + valuesmasterT.put(CommonString.KEY_COUNTER_ID, counter_id); + valuesmasterT.put(CommonString.KEY_VISIT_DATE, visit_date); + valuesmasterT.put(CommonString.KEY_STOCK_TYPE, CommonString.INWARD_DMS_NEW_SKU); + valuesmasterT.put(CommonString.KEY_ENTRY_TYPE, CommonString.KEY_REGULAR); + valuesmasterT.put(CommonString.KEY_STATUS, CommonString.KEY_N); + + if (!db.isOpen()) open(); + + masterreturn = db.insert(CommonString.TABLE_TRANSACTION_WISE_MASTER_TABLE, null, valuesmasterT); + } + for (int i = 0; i < save_listDataHeader.size(); i++) { + values = new ContentValues(); + values.put("SubBrandName", save_listDataHeader.get(i).getSubBrandName()); + values.put("BrandName", save_listDataHeader.get(i).getBrandName()); + values.put("SignatureName", save_listDataHeader.get(i).getSignatureName()); + values.put("ReferenceName", save_listDataHeader.get(i).getReferenceName()); + values.put("SubAxeName", save_listDataHeader.get(i).getSubAxeName()); + values.put(CommonString.KEY_VISIT_DATE, visit_date); + values.put(CommonString.KEY_COUNTER_ID, counter_id); + values.put(CommonString.KEY_USER_ID, username); + values.put(CommonString.KEY_INVOICE_NUMBER, invoiceNo); + values.put(CommonString.KEY_INVOICE_DATE, invDate); + values.put(CommonString.KEY_INVOICE_TYPE, type); + + if (!db.isOpen()) open(); + + long l = db.insert(CommonString.TABLE_INSERT_INWARD_STOCK_HEADER_DATA, null, values); + + for (int j = 0; j < data.get(save_listDataHeader.get(i)).size(); j++) { + values1 = new ContentValues(); + values1.put(CommonString.KEY_COMMON_ID, (int) l); + values1.put("SubBrandName", save_listDataHeader.get(i).getSubBrandName()); + values1.put("BrandName", save_listDataHeader.get(i).getBrandName()); + values1.put("SignatureName", save_listDataHeader.get(i).getSignatureName()); + values1.put("ReferenceName", save_listDataHeader.get(i).getReferenceName()); + values1.put("SubAxeName", save_listDataHeader.get(i).getSubAxeName()); + values1.put(CommonString.KEY_VISIT_DATE, visit_date); + values1.put(CommonString.KEY_SKU_CONFIRMATION_CHECK, data.get(save_listDataHeader.get(i)).get(j).isConfirmChecked()); + values1.put(CommonString.KEY_COUNTER_ID, counter_id); + values1.put(CommonString.KEY_USER_ID, username); + values1.put(CommonString.KEY_INVOICE_NUMBER, invoiceNo); + values1.put(CommonString.KEY_INVOICE_TYPE, type); + values1.put(CommonString.KEY_INVOICE_ID, Objects.requireNonNull(data.get(save_listDataHeader.get(i))).get(j).getInvId()); + values1.put(CommonString.KEY_Product, data.get(save_listDataHeader.get(i)).get(j).getProductName()); + values1.put(CommonString.KEY_ProductId, data.get(save_listDataHeader.get(i)).get(j).getProductId()); + values1.put(CommonString.KEY_INVOICE_QTY, data.get(save_listDataHeader.get(i)).get(j).getConsumer_qty()); + values1.put(CommonString.KEY_MRP, data.get(save_listDataHeader.get(i)).get(j).getMrp()); + values1.put(CommonString.KEY_ACTUAL_QTY, data.get(save_listDataHeader.get(i)).get(j).getActualQty()); + values1.put(CommonString.KEY_REASON_ID, data.get(save_listDataHeader.get(i)).get(j).getReasonId()); + values1.put(CommonString.KEY_INVOICE_STATUS, save_listDataHeader.get(i).getInvoice_Status()); + + transactionList = getInwardStockCheckTransactionData(data.get(save_listDataHeader.get(i)).get(j).getProductId(), data.get(save_listDataHeader.get(i)).get(j).getInvId(), invoiceNo); + stockObj = getTStockSummaryProductDetails(data.get(save_listDataHeader.get(i)).get(j).getProductId()); + + if (transactionList == null && data.get(save_listDataHeader.get(i)).get(j).isConfirmChecked() && masterreturn > 0 && stockObj == null) { + values2 = new ContentValues(); + values2.put(CommonString.KEY_MASTER_TRANSACTION_ID, masterreturn); + values2.put(CommonString.KEY_VISIT_DATE, visit_date); + values2.put(CommonString.KEY_SKU_CONFIRMATION_CHECK, data.get(save_listDataHeader.get(i)).get(j).isConfirmChecked()); + values2.put(CommonString.KEY_COUNTER_ID, counter_id); + values2.put(CommonString.KEY_USER_ID, username); + values2.put(CommonString.KEY_INVOICE_NUMBER, invoiceNo); + values2.put(CommonString.KEY_INVOICE_DATE, invDate); + values2.put(CommonString.KEY_INVOICE_TYPE, type); + values2.put(CommonString.KEY_SOURCE, source); + values2.put(CommonString.KEY_UPLOAD_STATUS, CommonString.KEY_N); + values2.put(CommonString.KEY_INVOICE_ID, data.get(save_listDataHeader.get(i)).get(j).getInvId()); + values2.put(CommonString.KEY_ProductId, data.get(save_listDataHeader.get(i)).get(j).getProductId()); + values2.put(CommonString.KEY_INVOICE_QTY, data.get(save_listDataHeader.get(i)).get(j).getConsumer_qty()); + values2.put(CommonString.KEY_MRP, data.get(save_listDataHeader.get(i)).get(j).getMrp()); + values2.put(CommonString.KEY_ACTUAL_QTY, data.get(save_listDataHeader.get(i)).get(j).getActualQty()); + values2.put(CommonString.KEY_REASON_ID, data.get(save_listDataHeader.get(i)).get(j).getReasonId()); + + if (save_listDataHeader.get(i).getInvoice_Status().equals("1")) { + values2.put(CommonString.KEY_INVOICE_STATUS, "1"); + ///For Update Invoice Status if Confirmed invoice + if (!db.isOpen()) open(); + updateInvoiceStatus(invoiceNo, true); + } else { + values2.put(CommonString.KEY_INVOICE_STATUS, save_listDataHeader.get(i).getInvoice_Status()); + } + values2.put(CommonString.KEY_TRANSACTION_ID, transactionId); + values2.put(CommonString.KEY_NEW_PRODUCT, 1); + if (!db.isOpen()) open(); + stockObj = getStockSummaryStatus(visit_date); + if (stockObj != null) { + //Insert New Data comming + insertTStockSummaryManualData(stockObj, data.get(save_listDataHeader.get(i)).get(j).getProductId(), counter_id, type, data.get(save_listDataHeader.get(i)).get(j).getActualQty()); + } + + // only for damaged stock + int ReasonId = data.get(save_listDataHeader.get(i)).get(j).getReasonId(); + if (ReasonId == 2 && type.trim().equalsIgnoreCase("Sellable")) { + ///change by jp Updated Damage Stock QTY from T_StockSummery + int damageStockQty = Integer.parseInt(data.get(save_listDataHeader.get(i)).get(j).getActualQty()); + updateStockSummaryDamageValue(data.get(save_listDataHeader.get(i)).get(j).getProductId(), damageStockQty, counter_id); + } + if (!db.isOpen()) open(); + id2 = db.insert(CommonString.TABLE_INSERT_INWARD_STOCK_TRANSACTION, null, values2); + if (id2 > 0) { + //updated counter invoice Confirm status using Invoice Id + updateT_CounterInvoiceConfirmCounter(data.get(save_listDataHeader.get(i)).get(j).getInvId(), data.get(save_listDataHeader.get(i)).get(j).getProductId()); + } + } + if (!db.isOpen()) open(); + id = db.insert(CommonString.TABLE_INSERT_INWARD_STOCK_CHILD_DATA, null, values1); + } + } + } + closeDb(); + if (id > 0) { + return id; + } else { + return 0; + } + + } catch (Exception ex) { + closeDb(); + ////////test("Database Exception ", ex.toString()); + return 0; + } + } + + + public long insertInwardStockData(String visit_date, HashMap> data, List save_listDataHeader, String invoiceNo, String type, String invDate, String counter_id, String username, String source, String transactionId, boolean checked_checkbox_flag) { + long id = 0, id2 = 0, masterreturn = 0; + db.delete(CommonString.TABLE_INSERT_INWARD_STOCK_HEADER_DATA, CommonString.KEY_INVOICE_NUMBER + "='" + invoiceNo + "' AND " + CommonString.KEY_COUNTER_ID + "='" + counter_id + "' AND " + CommonString.KEY_INVOICE_TYPE + " ='" + type + "'", null); + db.delete(CommonString.TABLE_INSERT_INWARD_STOCK_CHILD_DATA, CommonString.KEY_INVOICE_NUMBER + "='" + invoiceNo + "' AND " + CommonString.KEY_COUNTER_ID + "='" + counter_id + "' AND " + CommonString.KEY_INVOICE_TYPE + " = '" + type + "'", null); + db.delete(CommonString.TABLE_TRANSACTION_WISE_MASTER_TABLE, CommonString.KEY_VISIT_DATE + " <>'" + visit_date + "'", null); + db.delete(CommonString.TABLE_INSERT_INWARD_STOCK_TRANSACTION, CommonString.KEY_VISIT_DATE + " <>'" + visit_date + "'", null); + ContentValues values; + ContentValues values1; + ContentValues valuesmasterT; + ContentValues values2; + ProductMaster transactionList; + TStockSummary stockObj; + + try { + db.beginTransaction(); + if (save_listDataHeader.size() > 0) { + if (checked_checkbox_flag) { + valuesmasterT = new ContentValues(); + valuesmasterT.put(CommonString.KEY_UUID, transactionId); + valuesmasterT.put(CommonString.KEY_USER_ID, username); + valuesmasterT.put(CommonString.KEY_COUNTER_ID, counter_id); + valuesmasterT.put(CommonString.KEY_VISIT_DATE, visit_date); + valuesmasterT.put(CommonString.KEY_STOCK_TYPE, CommonString.INWARD_DMS); + valuesmasterT.put(CommonString.KEY_ENTRY_TYPE, CommonString.KEY_REGULAR); + valuesmasterT.put(CommonString.KEY_STATUS, CommonString.KEY_N); + if (!db.isOpen()) open(); + masterreturn = db.insert(CommonString.TABLE_TRANSACTION_WISE_MASTER_TABLE, null, valuesmasterT); + } + for (int i = 0; i < save_listDataHeader.size(); i++) { + values = new ContentValues(); + values.put("SubBrandName", save_listDataHeader.get(i).getSubBrandName()); + values.put("BrandName", save_listDataHeader.get(i).getBrandName()); + values.put("SignatureName", save_listDataHeader.get(i).getSignatureName()); + values.put("ReferenceName", save_listDataHeader.get(i).getReferenceName()); + values.put("SubAxeName", save_listDataHeader.get(i).getSubAxeName()); + values.put(CommonString.KEY_VISIT_DATE, visit_date); + values.put(CommonString.KEY_COUNTER_ID, counter_id); + values.put(CommonString.KEY_USER_ID, username); + values.put(CommonString.KEY_INVOICE_NUMBER, invoiceNo); + values.put(CommonString.KEY_INVOICE_DATE, invDate); + values.put(CommonString.KEY_INVOICE_TYPE, type); + + if (!db.isOpen()) open(); + long l = db.insert(CommonString.TABLE_INSERT_INWARD_STOCK_HEADER_DATA, null, values); + + if (data.get(save_listDataHeader.get(i)).size() > 0) { + for (int j = 0; j < data.get(save_listDataHeader.get(i)).size(); j++) { + values1 = new ContentValues(); + values1.put(CommonString.KEY_COMMON_ID, (int) l); + values1.put("SubBrandName", save_listDataHeader.get(i).getSubBrandName()); + values1.put("BrandName", save_listDataHeader.get(i).getBrandName()); + values1.put("SignatureName", save_listDataHeader.get(i).getSignatureName()); + values1.put("ReferenceName", save_listDataHeader.get(i).getReferenceName()); + values1.put("SubAxeName", save_listDataHeader.get(i).getSubAxeName()); + values1.put(CommonString.KEY_VISIT_DATE, visit_date); + values1.put(CommonString.KEY_COUNTER_ID, counter_id); + values1.put(CommonString.KEY_USER_ID, username); + values1.put(CommonString.KEY_INVOICE_NUMBER, invoiceNo); + values1.put(CommonString.KEY_INVOICE_TYPE, type); + values1.put(CommonString.KEY_SKU_CONFIRMATION_CHECK, data.get(save_listDataHeader.get(i)).get(j).isConfirmChecked()); + values1.put(CommonString.KEY_INVOICE_ID, data.get(save_listDataHeader.get(i)).get(j).getInvId()); + values1.put(CommonString.KEY_Product, data.get(save_listDataHeader.get(i)).get(j).getProductName()); + values1.put(CommonString.KEY_ProductId, data.get(save_listDataHeader.get(i)).get(j).getProductId()); + values1.put(CommonString.KEY_INVOICE_QTY, data.get(save_listDataHeader.get(i)).get(j).getConsumer_qty()); + values1.put(CommonString.KEY_MRP, data.get(save_listDataHeader.get(i)).get(j).getMrp()); + values1.put(CommonString.KEY_ACTUAL_QTY, data.get(save_listDataHeader.get(i)).get(j).getActualQty()); + values1.put(CommonString.KEY_REASON_ID, data.get(save_listDataHeader.get(i)).get(j).getReasonId()); + values1.put(CommonString.KEY_INVOICE_STATUS, save_listDataHeader.get(i).getInvoice_Status()); + + if (!db.isOpen()) open(); + transactionList = getInwardStockCheckTransactionData(data.get(save_listDataHeader.get(i)).get(j).getProductId(), data.get(save_listDataHeader.get(i)).get(j).getInvId(), invoiceNo); + stockObj = getTStockSummaryProductDetails(data.get(save_listDataHeader.get(i)).get(j).getProductId()); + if (transactionList == null && data.get(save_listDataHeader.get(i)).get(j).isConfirmChecked() && masterreturn > 0 && stockObj != null && stockObj.getProductId() != null) { + values2 = new ContentValues(); + values2.put(CommonString.KEY_MASTER_TRANSACTION_ID, masterreturn); + values2.put(CommonString.KEY_VISIT_DATE, visit_date); + values2.put(CommonString.KEY_SKU_CONFIRMATION_CHECK, data.get(save_listDataHeader.get(i)).get(j).isConfirmChecked()); + values2.put(CommonString.KEY_COUNTER_ID, counter_id); + values2.put(CommonString.KEY_USER_ID, username); + values2.put(CommonString.KEY_INVOICE_NUMBER, invoiceNo); + values2.put(CommonString.KEY_INVOICE_DATE, invDate); + values2.put(CommonString.KEY_INVOICE_TYPE, type); + values2.put(CommonString.KEY_SOURCE, source); + values2.put(CommonString.KEY_UPLOAD_STATUS, CommonString.KEY_N); + + values2.put(CommonString.KEY_INVOICE_ID, data.get(save_listDataHeader.get(i)).get(j).getInvId()); + values2.put(CommonString.KEY_ProductId, data.get(save_listDataHeader.get(i)).get(j).getProductId()); + values2.put(CommonString.KEY_INVOICE_QTY, data.get(save_listDataHeader.get(i)).get(j).getConsumer_qty()); + values2.put(CommonString.KEY_MRP, data.get(save_listDataHeader.get(i)).get(j).getMrp()); + values2.put(CommonString.KEY_ACTUAL_QTY, data.get(save_listDataHeader.get(i)).get(j).getActualQty()); + values2.put(CommonString.KEY_REASON_ID, data.get(save_listDataHeader.get(i)).get(j).getReasonId()); + // only for damaged stock + if (data.get(save_listDataHeader.get(i)).get(j).getReasonId() == 2 && type != null && type.trim().equalsIgnoreCase("Sellable")) { + ///change by jp Updated Damage Stock QTY from T_StockSummery + int damageStockQty = Integer.parseInt(data.get(save_listDataHeader.get(i)).get(j).getActualQty()); + if (!db.isOpen()) open(); + updateStockSummaryDamageValue(data.get(save_listDataHeader.get(i)).get(j).getProductId(), damageStockQty, counter_id); + } + if (save_listDataHeader.get(i).getInvoice_Status().equals("1")) { + values2.put(CommonString.KEY_INVOICE_STATUS, "1"); + ///For Update Invoice Status if Confirmed invoice + updateInvoiceStatus(invoiceNo, false); + } else { + values2.put(CommonString.KEY_INVOICE_STATUS, save_listDataHeader.get(i).getInvoice_Status()); + } + values2.put(CommonString.KEY_TRANSACTION_ID, transactionId); + values2.put(CommonString.KEY_NEW_PRODUCT, 0); + // if stockObj is not null means product exist in stock summary table data then update value in TStockSummary + updateStockSummaryData(stockObj, type, data.get(save_listDataHeader.get(i)).get(j).getActualQty(), visit_date); + if (!db.isOpen()) open(); + id2 = db.insert(CommonString.TABLE_INSERT_INWARD_STOCK_TRANSACTION, null, values2); + if (id2 > 0) { + updateT_CounterInvoiceConfirmCounter(data.get(save_listDataHeader.get(i)).get(j).getInvId(), data.get(save_listDataHeader.get(i)).get(j).getProductId()); + } + } + if (!db.isOpen()) open(); + id = db.insert(CommonString.TABLE_INSERT_INWARD_STOCK_CHILD_DATA, null, values1); + } + } + } + } + closeDb(); + if (id > 0) { + return id; + } else { + return 0; + } + + } catch (Exception ex) { + closeDb(); + ////////test("Database Exception ", ex.toString()); + return 0; + } + } + + + public boolean insert_leave_status(MasterProfileQuestionGetterSetter cst) { + db.delete("T_LeaveLedger", null, null); + ContentValues values = new ContentValues(); + List data = cst.getTLeaveLedger(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("UserId", data.get(i).getUserId().toLowerCase()); + values.put("TotalLeave", data.get(i).getTotalLeave()); + values.put("LeaveTaken", data.get(i).getLeaveTaken()); + values.put("BalanceLeave", data.get(i).getBalanceLeave()); + + long id = db.insert("T_LeaveLedger", null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ex.fillInStackTrace(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + public ArrayList getleave_balance_status(String user_Id) { + ////////test("Fetching", "Storedata--------------->Start<------------"); + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + dbcursor = db.rawQuery("select distinct TotalLeave,LeaveTaken,BalanceLeave from T_LeaveLedger where UserId='" + user_Id + "'", null); + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + TLeaveLedger sb = new TLeaveLedger(); + sb.setTotalLeave(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("TotalLeave"))); + sb.setLeaveTaken(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("LeaveTaken"))); + sb.setBalanceLeave(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("BalanceLeave"))); + + list.add(sb); + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list; + } + } catch (Exception e) { + ////////test("Exception ", "when fetching opening stock!!!!!!!!!!!" + e.toString()); + return list; + } + ////////test("Fetching ", "opening stock---------------------->Stop<-----------"); + return list; + } + + public long insert_leave_management_data(String user_Id, String visit_date, String store_Cd, T_LeaveRequest invoiceList) { + db.delete(CommonString.Table_Leave_Management, CommonString.KEY_VISIT_DATE + "<>'" + visit_date + "'", null); + db.delete(CommonString.TABLE_TRANSACTION_WISE_MASTER_TABLE, CommonString.KEY_VISIT_DATE + "<>'" + visit_date + "'", null); + ContentValues values = new ContentValues(); + ContentValues finalvalues = new ContentValues(); + long l = 0, masterreturn = 0; + try { + db.beginTransaction(); + finalvalues.put(CommonString.KEY_UUID, invoiceList.getTransId()); + finalvalues.put(CommonString.KEY_USER_ID, user_Id); + finalvalues.put(CommonString.KEY_COUNTER_ID, store_Cd); + finalvalues.put(CommonString.KEY_VISIT_DATE, visit_date); + finalvalues.put(CommonString.KEY_STOCK_TYPE, CommonString.LEAVE_MANAGEMENT); + finalvalues.put(CommonString.KEY_ENTRY_TYPE, CommonString.KEY_REGULAR); + finalvalues.put(CommonString.KEY_STATUS, CommonString.KEY_N); + + masterreturn = db.insert(CommonString.TABLE_TRANSACTION_WISE_MASTER_TABLE, null, finalvalues); + + values.put("USER_ID", user_Id); + values.put("UNIQUE_CODE", invoiceList.getTransId()); + values.put(CommonString.KEY_COUNTER_ID, store_Cd); + values.put(CommonString.KEY_MASTER_TRANSACTION_ID, masterreturn); + values.put(CommonString.KEY_VISIT_DATE, visit_date); + values.put("Request_Date", invoiceList.getRequestDate()); + values.put("From_Date", invoiceList.getFromDate()); + values.put("Upload_From_Date", invoiceList.getUpload_start_date_str()); + values.put("To_Date", invoiceList.getToDate()); + values.put("Upload_To_Date", invoiceList.getUpload_end_date_str()); + values.put("LeaveReason", invoiceList.getLeave_reason()); + values.put("Leave_Status", invoiceList.getLeaveStatus()); + values.put("One_Day_Leave", invoiceList.getOne_day_leave_str()); + values.put("UPLOAD_STATUS", CommonString.KEY_N); + values.put("LeaveType", invoiceList.getStr_leaveType()); + values.put("LeaveTypeId", invoiceList.getStr_leaveTypeId()); + + l = db.insert(CommonString.Table_Leave_Management, null, values); + closeDb(); + } catch (Exception ex) { + closeDb(); + ////////test("Database Exception", ex.toString()); + } + + return l; + } + + public boolean insert_master_break(MasterProfileQuestionGetterSetter cst) { + db.delete("Master_Break", null, null); + ContentValues values = new ContentValues(); + List data = cst.getMasterBreak(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("BreakId", data.get(i).getBreakId()); + values.put("BreakType", data.get(i).getBreakType()); + + long id = db.insert("Master_Break", null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ex.fillInStackTrace(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + public ArrayList getmasterBreak() { + ////////test("Fetching", "Storedata--------------->Start<------------"); + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + dbcursor = db.rawQuery("select distinct BreakId,BreakType from Master_Break", null); + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + + MasterBreak sb = new MasterBreak(); + sb.setBreakId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("BreakId"))); + sb.setBreakType(dbcursor.getString(dbcursor.getColumnIndexOrThrow("BreakType"))); + + list.add(sb); + dbcursor.moveToNext(); + } + dbcursor.close(); + return list; + } + } catch (Exception e) { + ////////test("Exception ", "when fetching opening stock!!!!!!!!!!!" + e.toString()); + return list; + } + + ////////test("Fetching ", "opening stock---------------------->Stop<-----------"); + return list; + } + + public long insertBreakManagement(String user_Id, String visit_date, String counterId, MasterBreak breakObject) { + db.delete(CommonString.Table_Break_Management, CommonString.KEY_VISIT_DATE + "<>'" + visit_date + "'", null); + ContentValues values = new ContentValues(); + + long l = 0; + + try { + db.beginTransaction(); + values.put("USER_ID", user_Id); + values.put(CommonString.KEY_COUNTER_ID, counterId); + values.put(CommonString.KEY_VISIT_DATE, visit_date); + values.put("LoginTym", breakObject.getLoginTym()); + values.put("BreakType", breakObject.getBreakType()); + values.put("BreakId", breakObject.getBreakId()); + values.put("StartTym", breakObject.getStartTym()); + values.put("EndTym", breakObject.getEndTym()); + values.put("TotalDuration", breakObject.getTotalDuration()); + values.put("UPLOAD_STATUS", breakObject.getUpload_status()); + values.put("UNIQUE_CODE", breakObject.getTransId()); + values.put(CommonString.KEY_MASTER_TRANSACTION_ID, 0); + + l = db.insert(CommonString.Table_Break_Management, null, values); + closeDb(); + } catch (Exception ex) { + closeDb(); + ////////test("Database Exception", ex.toString()); + } + + return l; + } + + + public long update_break_management(String counterId, String visit_date, String user_Id, MasterBreak breakObject) { + ContentValues values = new ContentValues(); + ContentValues finalvalues = new ContentValues(); + long l = 0, masterreturn = 0; + try { + + if (!db.isOpen()) open(); + db.beginTransaction(); + finalvalues.put(CommonString.KEY_UUID, breakObject.getTransId()); + finalvalues.put(CommonString.KEY_USER_ID, user_Id); + finalvalues.put(CommonString.KEY_COUNTER_ID, counterId); + finalvalues.put(CommonString.KEY_VISIT_DATE, visit_date); + finalvalues.put(CommonString.KEY_STOCK_TYPE, CommonString.BREAK_MANAGEMENT); + finalvalues.put(CommonString.KEY_ENTRY_TYPE, CommonString.KEY_REGULAR); + finalvalues.put(CommonString.KEY_STATUS, CommonString.KEY_N); + + masterreturn = db.insert(CommonString.TABLE_TRANSACTION_WISE_MASTER_TABLE, null, finalvalues); + if (masterreturn > 0) { + values.put(CommonString.KEY_MASTER_TRANSACTION_ID, masterreturn); + values.put("EndTym", breakObject.getEndTym()); + values.put("TotalDuration", breakObject.getTotalDuration()); + values.put("UNIQUE_CODE", breakObject.getTransId()); + values.put("UPLOAD_STATUS", CommonString.KEY_N); + + l = db.update(CommonString.Table_Break_Management, values, CommonString.KEY_COUNTER_ID + "='" + counterId + "' AND " + CommonString.KEY_VISIT_DATE + " ='" + visit_date + "'AND USER_ID='" + user_Id + "'and " + CommonString.KEY_ID + "='" + breakObject.getKeyId() + "'", null); + } + closeDb(); + } catch (Exception e) { + e.fillInStackTrace(); + closeDb(); + } + return l; + } + + public ArrayList getBreakManagementList(String storeid, String visite_date, String user_Id, String upload_status) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + if (upload_status != null && user_Id == null) { + dbcursor = db.rawQuery("SELECT * from " + CommonString.Table_Break_Management + " WHERE " + CommonString.KEY_VISIT_DATE + "='" + visite_date + "'AND " + CommonString.KEY_COUNTER_ID + "='" + storeid + "'and UPLOAD_STATUS='N'", null); + + } else if (upload_status != null) { + dbcursor = db.rawQuery("SELECT * from " + CommonString.Table_Break_Management + " WHERE " + CommonString.KEY_VISIT_DATE + "='" + visite_date + "'AND " + CommonString.KEY_COUNTER_ID + "='" + storeid + "' and USER_ID='" + user_Id + "'and UPLOAD_STATUS='N'", null); + + } else { + dbcursor = db.rawQuery("SELECT * from " + CommonString.Table_Break_Management + " WHERE " + CommonString.KEY_VISIT_DATE + "='" + visite_date + "'AND " + CommonString.KEY_COUNTER_ID + "='" + storeid + "' and USER_ID='" + user_Id + "'", null); + } + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + MasterBreak sale = new MasterBreak(); + + sale.setLoginTym(dbcursor.getString(dbcursor.getColumnIndexOrThrow("LoginTym"))); + sale.setBreakType(dbcursor.getString(dbcursor.getColumnIndexOrThrow("BreakType"))); + sale.setBreakId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("BreakId"))); + sale.setStartTym(dbcursor.getString(dbcursor.getColumnIndexOrThrow("StartTym"))); + sale.setEndTym(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EndTym"))); + sale.setTotalDuration(dbcursor.getString(dbcursor.getColumnIndexOrThrow("TotalDuration"))); + sale.setTransId(dbcursor.getString(dbcursor.getColumnIndexOrThrow("UNIQUE_CODE"))); + sale.setUpload_status(dbcursor.getString(dbcursor.getColumnIndexOrThrow("UPLOAD_STATUS"))); + sale.setKeyId(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_ID))); + sale.setUserId(dbcursor.getString(dbcursor.getColumnIndexOrThrow("USER_ID"))); + + list.add(sale); + + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list; + } + + } catch (Exception e) { + ////////test("Exception Brands", e.toString()); + return list; + } + return list; + } + + //get Signature Brand Sub Brand and Reference + public ArrayList getStockSignatureBrandSubBrandReference(String counterGroup_Id, boolean gwp_flag, boolean regularstock, String columnName) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + if (regularstock) { + if (gwp_flag) { + dbcursor = db.rawQuery("select distinct SignatureName,BrandName,SubBrandName,ReferenceName from Product_Master p inner join T_StockSummary TS ON TS.ProductId = p.ProductId where TS." + columnName + " >0 and p.ProductType='GWP'", null); + + } else { + dbcursor = db.rawQuery("select distinct SignatureName,BrandName,SubBrandName,ReferenceName from Product_Master p inner join T_StockSummary TS ON TS.ProductId = p.ProductId where TS." + columnName + " > 0 and p.ProductType='Normal'", null); + } + } else { + if (gwp_flag) { + dbcursor = db.rawQuery("select distinct SignatureName,BrandName,SubBrandName,ReferenceName from Product_Master where ProductType='GWP'", null); + + } else { + dbcursor = db.rawQuery("select distinct SignatureName,BrandName,SubBrandName,ReferenceName from Product_Master where ProductType='Normal'", null); + } + } + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + ProductMaster sb = new ProductMaster(); + + //sb.setAxeName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("AxeName"))); + sb.setSignatureName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SignatureName"))); + sb.setSubBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SubBrandName"))); + //sb.setSubAxeName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SubAxeName"))); + sb.setReferenceName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ReferenceName"))); + sb.setBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("BrandName"))); + + list.add(sb); + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list; + } + } catch (Exception e) { + + return list; + } + + return list; + } + + public ArrayList getMESaleSignatureBrandSubBrandReference(String counterGroup_Id, boolean gwp_flag, boolean regularstock, String columnName) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + if (regularstock) { + dbcursor = db.rawQuery("select distinct SignatureName,BrandName,SubBrandName,ReferenceName from Product_Master p inner join T_StockSummary TS ON TS.ProductId = p.ProductId where p.ProductType='Normal'", null); + } else { + dbcursor = db.rawQuery("select distinct SignatureName,BrandName,SubBrandName,ReferenceName from Product_Master where ProductType='Normal'", null); + } + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + ProductMaster sb = new ProductMaster(); + + //sb.setAxeName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("AxeName"))); + sb.setSignatureName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SignatureName"))); + sb.setSubBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SubBrandName"))); + //sb.setSubAxeName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SubAxeName"))); + sb.setReferenceName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ReferenceName"))); + sb.setBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("BrandName"))); + + list.add(sb); + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list; + } + } catch (Exception e) { + + return list; + } + + return list; + } + + public ArrayList getStockSignatureBrandSubBrandReferenceforfilled(String counterGroup_Id, String activity_name) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + + if (activity_name != null && !activity_name.equals("") && activity_name.equalsIgnoreCase("StockCheck")) { + dbcursor = db.rawQuery("select distinct SignatureName,BrandName,SubBrandName,ReferenceName from Product_Master p inner join T_StockSummary TS" + " ON TS.ProductId = p.ProductId where TS.SaleableBalance >0 and p.ProductType='Normal'", null); + + } else { + + dbcursor = db.rawQuery("select distinct SignatureName,BrandName,SubBrandName,ReferenceName from Product_Master p inner join T_StockSummary TS" + " ON TS.ProductId = p.ProductId where TS.TesterBalance >0 and p.ProductType='Normal'", null); + } + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + ProductMaster sb = new ProductMaster(); + + //sb.setAxeName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("AxeName"))); + sb.setSignatureName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SignatureName"))); + sb.setSubBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SubBrandName"))); + //sb.setSubAxeName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SubAxeName"))); + sb.setReferenceName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ReferenceName"))); + sb.setBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("BrandName"))); + + list.add(sb); + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list; + } + } catch (Exception e) { + + return list; + } + + return list; + } + + + //get Signature Brand Sub Brand and Reference + public ArrayList getGWPSignatureBrandSubBrandReference(boolean regular_flag, String counterId, String visit_date) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + if (regular_flag) { + dbcursor = db.rawQuery("select distinct SignatureName,BrandName,SubBrandName,ReferenceName,AxeName,SubAxeName from Product_Master p inner join" + " (Select s.ProductId, (s.GwpBalance - ifnull(dm.DamageQty,0)) as GwpBalance" + " from T_StockSummary s Left join" + " (Select CounterId, ProductId, sum(DamageQty) as DamageQty from (" + " Select T2.COUNTER_ID AS CounterId, T1.PRODUCT_ID AS ProductId , SUM(T1.QUANTITY) AS DamageQty FROM SALE_TRACKING_TABLE T1 INNER JOIN SALE_TRACKING_HEADER_TABLE T2 ON" + " T2.RECCEPT_COUNT=T1.RECCEPT_COUNT " + " WHERE T2.COUNTER_ID =" + counterId + " AND T2.Visit_Date='" + visit_date + "' AND T2.POS_SALE_FLAG='0' AND T1.INVOICE_TYPE='GWP' GROUP BY T1.PRODUCT_ID" + " UNION ALL" + " select S.COUNTER_ID,S.PROMO_PRODUCT_ID AS PRODUCT_ID,SUM(S.PROMO_PRODUCT_QTY) AS QUANTITY from APPLYED_PROMOTION_TABLE S INNER JOIN SALE_TRACKING_HEADER_TABLE S1" + " ON S.RECCEPT_COUNT=S1.RECCEPT_COUNT" + " Where S.PROMO_TYPE ='Gift' AND S.COUNTER_ID =" + counterId + " AND S1.VISIT_DATE = '" + visit_date + "' AND S1.POS_SALE_FLAG ='0'" + " GROUP BY S.PROMO_PRODUCT_ID) as t" + " Group by CounterId, ProductId) as dm on s.ProductId = dm.ProductId)" + " as TS ON TS.ProductId = p.ProductId where TS.GwpBalance >0 and p.ProductType='GWP'", null); + + } else { + dbcursor = db.rawQuery("select distinct SignatureName,BrandName,SubBrandName,ReferenceName, AxeName,SubAxeName from Product_Master where ProductType = 'GWP'", null); + } + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + ProductMaster sb = new ProductMaster(); + + sb.setAxeName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("AxeName"))); + sb.setSignatureName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SignatureName"))); + sb.setSubBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SubBrandName"))); + sb.setSubAxeName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SubAxeName"))); + sb.setReferenceName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ReferenceName"))); + sb.setBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("BrandName"))); + + list.add(sb); + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list; + } + } catch (Exception e) { + + return list; + } + + return list; + } + + //get stock child default data + public ArrayList getDefaultGWPOnSignatureData(String SubBrandName, String ReferenceName, String BrandName, String columnBalance, boolean regularstock, String visit_date, String counterId) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + + if (regularstock) { + dbcursor = db.rawQuery("select distinct p.ProductId as ProductId,p.ProductName as ProductName,p.EanCode as EanCode, p.Mrp as Mrp, TS." + columnBalance + " from" + " Product_Master p left JOIN(Select s.ProductId,(s." + columnBalance + " - ifnull(dm.DamageQty,0)) as " + columnBalance + " from T_StockSummary s Left join" + " (Select CounterId, ProductId, sum(DamageQty) as DamageQty from (" + " Select T2.COUNTER_ID AS CounterId,T1.PRODUCT_ID AS ProductId,SUM(T1.QUANTITY) AS DamageQty FROM SALE_TRACKING_TABLE T1" + " INNER JOIN SALE_TRACKING_HEADER_TABLE T2 ON" + " T2.RECCEPT_COUNT=T1.RECCEPT_COUNT WHERE T2.COUNTER_ID =" + counterId + " AND T2.Visit_Date='" + visit_date + "' AND T2.POS_SALE_FLAG='0'" + " AND T1.INVOICE_TYPE='GWP' GROUP BY T1.PRODUCT_ID UNION ALL" + " select S.COUNTER_ID, S.PROMO_PRODUCT_ID AS PRODUCT_ID ,SUM(S.PROMO_PRODUCT_QTY) AS QUANTITY from APPLYED_PROMOTION_TABLE S" + " INNER JOIN SALE_TRACKING_HEADER_TABLE S1" + " ON S.RECCEPT_COUNT=S1.RECCEPT_COUNT Where S.PROMO_TYPE ='Gift' AND S.COUNTER_ID =" + counterId + " AND S1.VISIT_DATE = '" + visit_date + "' AND S1.POS_SALE_FLAG ='0' GROUP BY S.PROMO_PRODUCT_ID) as t Group by CounterId, ProductId) as dm on s.ProductId = dm.ProductId) as" + " TS ON TS.ProductId = p.ProductId" + " Where p.SubBrandName=trim(\"" + SubBrandName + "\") AND p.ReferenceName=trim(\"" + ReferenceName + "\")" + " AND BrandName=trim(\"" + BrandName + "\") AND p.ProductType =trim('GWP')and TS." + columnBalance + " >0", null); + } else { + dbcursor = db.rawQuery("select p.ProductId, as ProductId p.ProductName as ProductName, p.EanCode as EanCode, p.Mrp as Mrp, TS." + columnBalance + " from Product_Master p " + "LEFT JOIN T_StockSummary TS ON TS.ProductId = p.ProductId " + "Where p.SubBrandName=trim(\"" + SubBrandName + "\") AND p.ReferenceName=trim(\"" + ReferenceName + "\")" + " AND BrandName=trim(\"" + BrandName + "\") AND p.ProductType ='GWP'", null); + + } + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + ProductMaster sb = new ProductMaster(); + sb.setProductName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ProductName"))); + sb.setProductId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("ProductId"))); + sb.setEanCode(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EanCode"))); + sb.setMrp(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("Mrp"))); + sb.setStock_receive(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(columnBalance))); + sb.setStock(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(columnBalance))); + + list.add(sb); + dbcursor.moveToNext(); + } + dbcursor.close(); + return list; + } + } catch (Exception e) { + + return list; + } + + return list; + } + + + public boolean insertAgeLimitMaster(TableStructureGetterSetter cst) { + db.delete("Master_AgeLimit", null, null); + ContentValues values = new ContentValues(); + List data = cst.getMasterAgeLimit(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("AgeLimit", data.get(i).getAgeLimit()); + long id = db.insert("Master_AgeLimit", null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ex.fillInStackTrace(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + //usk + public long insertCounterProfiledata(String counter_id, String user_id, String user_type, String visit_date, JourneyPlan counterimg_object, String status, String uuid_ID) { + db.delete(CommonString.TABLE_COUNTER_PROFILE_DATA, CommonString.KEY_VISIT_DATE + "<>'" + visit_date + "'", null); + db.delete(CommonString.TABLE_COUNTER_PROFILE_DATA, "COUNTER_ID" + "='" + counter_id + "' And Visit_Date='" + visit_date + "'", null); + long id = 0; + ContentValues values = new ContentValues(); + + try { + db.beginTransaction(); + values.put(CommonString.KEY_UUID, uuid_ID); + values.put("COUNTER_ID", counter_id); + values.put(CommonString.KEY_STATUS, status); + values.put(CommonString.KEY_USER_ID, user_id); + values.put(CommonString.KEY_USER_TYPE, user_type); + values.put(CommonString.KEY_VISIT_DATE, visit_date); + values.put("IMAGE1", counterimg_object.getProfileImage1()); + values.put("IMAGE2", counterimg_object.getProfileImage2()); + values.put("HIGHT", counterimg_object.getCounterlength()); + values.put("WIDTH", counterimg_object.getCounterwidth()); + values.put("SETUP_DATE", counterimg_object.getSetupDate()); + values.put("COUNTER_AGEING", counterimg_object.getStoreName()); + if (!db.isOpen()) { + open(); + } + id = db.insert(CommonString.TABLE_COUNTER_PROFILE_DATA, null, values); + closeDb(); + } catch (Exception ex) { + closeDb(); + ////////test("Database Exception ", ex.toString()); + return 0; + } + + return id; + } + + public long insertBaProfiledata(String counter_id, String user_id, String user_type, String visit_date, MasterProfile ba_object) { + db.delete(CommonString.TABLE_BA_PROFILE_DATA, CommonString.KEY_VISIT_DATE + "<>'" + visit_date + "'", null); + db.delete(CommonString.TABLE_BA_PROFILE_DATA, "COUNTER_ID" + "='" + counter_id + "' And User_Id='" + user_id + "' And Visit_Date='" + visit_date + "'", null); + long id = 0; + ContentValues values = new ContentValues(); + try { + db.beginTransaction(); + values.put(CommonString.KEY_STATUS, CommonString.KEY_N); + values.put("COUNTER_ID", counter_id); + values.put(CommonString.KEY_USER_ID, user_id); + values.put(CommonString.KEY_USER_TYPE, user_type); + values.put(CommonString.KEY_VISIT_DATE, visit_date); + values.put("ADDRESS", ba_object.getAddress()); + values.put("DOB", ba_object.getDob()); + values.put("MOBILE_NO", ba_object.getMobile()); + values.put("EMAIL_ADDRESS", ba_object.getEmail()); + values.put("INSTAGRAM_ADDRESS", ba_object.getInstragramAddress()); + values.put("PROFILE_IMAGE", ba_object.getProfilePic()); + values.put("LANDMARK", ba_object.getLandmark()); + values.put("LOCATION", ba_object.getLocation()); + + id = db.insert(CommonString.TABLE_BA_PROFILE_DATA, null, values); + closeDb(); + } catch (Exception ex) { + closeDb(); + ////////test("Database Exception ", ex.toString()); + return 0; + } + + return id; + } + + + public MasterProfile getBaProfileData(String userId, String visit_date, boolean flag) { + MasterProfile sb = new MasterProfile(); + Cursor dbcursor = null; + try { + if (flag) { + dbcursor = db.rawQuery("SELECT * FROM BA_PROFILE_DATA WHERE Visit_Date='" + visit_date + "'and STATUS='N'", null); + } else { + dbcursor = db.rawQuery("SELECT * FROM BA_PROFILE_DATA WHERE User_Id ='" + userId + "' AND Visit_Date='" + visit_date + "'", null); + } + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + sb.setUserId((dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_USER_ID)))); + sb.setViisitDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_VISIT_DATE))); + sb.setAddress(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ADDRESS"))); + sb.setDob(dbcursor.getString(dbcursor.getColumnIndexOrThrow("DOB"))); + sb.setMobile(dbcursor.getString(dbcursor.getColumnIndexOrThrow("MOBILE_NO"))); + sb.setEmail(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EMAIL_ADDRESS"))); + sb.setInstragramAddress(dbcursor.getString(dbcursor.getColumnIndexOrThrow("INSTAGRAM_ADDRESS"))); + sb.setProfilePic(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PROFILE_IMAGE"))); + sb.setLandmark(dbcursor.getString(dbcursor.getColumnIndexOrThrow("LANDMARK"))); + sb.setLocation(dbcursor.getString(dbcursor.getColumnIndexOrThrow("LOCATION"))); + sb.setUpload_status(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_STATUS))); + + dbcursor.moveToNext(); + } + dbcursor.close(); + return sb; + } + + } catch (Exception e) { + ////////test("Exception get JCP!", e.toString()); + return sb; + } + + return sb; + } + + + public ArrayList getBaProfileListData(String visit_date, String counterId, boolean previous_date) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + + if (previous_date) { + dbcursor = db.rawQuery("SELECT * FROM BA_PROFILE_DATA WHERE Visit_Date <>'" + visit_date + "'and " + CommonString.KEY_COUNTER_ID + "=" + counterId + " and STATUS='N'", null); + + } else { + dbcursor = db.rawQuery("SELECT * FROM BA_PROFILE_DATA WHERE Visit_Date='" + visit_date + "'and " + CommonString.KEY_COUNTER_ID + "=" + counterId + " and STATUS='N'", null); + + } + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + MasterProfile sb = new MasterProfile(); + sb.setUserId((dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_USER_ID)))); + sb.setViisitDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_VISIT_DATE))); + sb.setAddress(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ADDRESS"))); + sb.setDob(dbcursor.getString(dbcursor.getColumnIndexOrThrow("DOB"))); + sb.setMobile(dbcursor.getString(dbcursor.getColumnIndexOrThrow("MOBILE_NO"))); + sb.setEmail(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EMAIL_ADDRESS"))); + sb.setInstragramAddress(dbcursor.getString(dbcursor.getColumnIndexOrThrow("INSTAGRAM_ADDRESS"))); + sb.setProfilePic(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PROFILE_IMAGE"))); + sb.setLandmark(dbcursor.getString(dbcursor.getColumnIndexOrThrow("LANDMARK"))); + sb.setLocation(dbcursor.getString(dbcursor.getColumnIndexOrThrow("LOCATION"))); + sb.setUpload_status(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_STATUS))); + list.add(sb); + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list; + } + + } catch (Exception e) { + ////////test("Exception get JCP!", e.toString()); + return list; + } + return list; + } + + public JourneyPlan getCounterProfileData(String userId, String visit_date, String counterId, boolean flag) { + JourneyPlan sb = new JourneyPlan(); + Cursor dbcursor = null; + try { + if (userId == null && flag) { + dbcursor = db.rawQuery("SELECT * FROM COUNTER_PROFILE_DATA WHERE COUNTER_ID ='" + counterId + "' AND Visit_Date='" + visit_date + "'", null); + } else { + dbcursor = db.rawQuery("SELECT * FROM COUNTER_PROFILE_DATA WHERE User_Id ='" + userId + "' AND Visit_Date='" + visit_date + "'AND COUNTER_ID='" + counterId + "'", null); + + } + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + sb.setUserId((dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_USER_ID)))); + sb.setVisitDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_VISIT_DATE))); + sb.setProfileImage1(dbcursor.getString(dbcursor.getColumnIndexOrThrow("IMAGE1"))); + sb.setProfileImage2(dbcursor.getString(dbcursor.getColumnIndexOrThrow("IMAGE2"))); + sb.setCounterlength(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("HIGHT"))); + sb.setCounterwidth(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("WIDTH"))); + sb.setSetupDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SETUP_DATE"))); + sb.setStoreName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("COUNTER_AGEING"))); + sb.setTransId(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_UUID))); + + dbcursor.moveToNext(); + } + + dbcursor.close(); + return sb; + } + + } catch (Exception e) { + ////////test("Exception get JCP!", e.toString()); + return sb; + } + + return sb; + } + + + public ArrayList getCounterProfileListData(String visit_date, String counterId, boolean previous_date) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + + if (previous_date) { + dbcursor = db.rawQuery("SELECT * FROM COUNTER_PROFILE_DATA WHERE COUNTER_ID ='" + counterId + "' AND Visit_Date <>'" + visit_date + "' and STATUS='N'", null); + } else { + dbcursor = db.rawQuery("SELECT * FROM COUNTER_PROFILE_DATA WHERE COUNTER_ID ='" + counterId + "' AND Visit_Date='" + visit_date + "' and STATUS='N'", null); + } + + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + JourneyPlan sb = new JourneyPlan(); + sb.setUserId((dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_USER_ID)))); + sb.setVisitDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_VISIT_DATE))); + sb.setProfileImage1(dbcursor.getString(dbcursor.getColumnIndexOrThrow("IMAGE1"))); + sb.setProfileImage2(dbcursor.getString(dbcursor.getColumnIndexOrThrow("IMAGE2"))); + sb.setCounterlength(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("HIGHT"))); + sb.setCounterwidth(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("WIDTH"))); + sb.setSetupDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SETUP_DATE"))); + sb.setStoreName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("COUNTER_AGEING"))); + list.add(sb); + dbcursor.moveToNext(); + } + dbcursor.close(); + return list; + } + + } catch (Exception e) { + ////////test("Exception get JCP!", e.toString()); + return list; + } + + return list; + } + + public long insertmanualinwardinDraft(ArrayList selected_list, String invoice_status, String invoice_id, String counter_confirm, String draft_status, String counter_id, String username, String invoiceNo, String invoiceType, String invDate, String source, String visit_date, String invoice_img) { + db.delete(CommonString.TABLE_INSERT_MANUAL_INWARD_TRANSACTION, CommonString.KEY_VISIT_DATE + "<>'" + visit_date + "'", null); + db.delete(CommonString.TABLE_INSERT_MANUAL_INWARD_TRANSACTION, CommonString.KEY_VISIT_DATE + "='" + visit_date + "' AND " + CommonString.KEY_COUNTER_ID + "=" + counter_id + " AND " + CommonString.KEY_INVOICE_NUMBER + "='" + invoiceNo + "' AND " + CommonString.KEY_INVOICE_ID + "='" + invoice_id + "'", null); + + ContentValues values2 = new ContentValues(); + long id = 0; + try { + + db.beginTransaction(); + for (int j = 0; j < selected_list.size(); j++) { + values2 = new ContentValues(); + values2.put(CommonString.KEY_VISIT_DATE, visit_date); + values2.put(CommonString.KEY_COUNTER_ID, counter_id); + values2.put(CommonString.KEY_USER_ID, username); + values2.put(CommonString.KEY_INVOICE_NUMBER, invoiceNo); + values2.put(CommonString.KEY_INVOICE_DATE, invDate); + values2.put(CommonString.KEY_INVOICE_TYPE, invoiceType); + values2.put(CommonString.KEY_INVOICE_ID, invoice_id); + values2.put(CommonString.KEY_INVOICE_IMG, invoice_img); + values2.put(CommonString.KEY_Product, selected_list.get(j).getProduct()); + values2.put(CommonString.KEY_ProductId, selected_list.get(j).getProduct_Id()); + values2.put(CommonString.KEY_INVOICE_QTY, selected_list.get(j).getQuantity()); + values2.put(CommonString.KEY_MRP, selected_list.get(j).getProduct_rate()); + values2.put(CommonString.KEY_ACTUAL_QTY, selected_list.get(j).getActualQty()); + //Total amount + int totalAmount = Integer.parseInt(selected_list.get(j).getActualQty()) * Integer.parseInt(selected_list.get(j).getProduct_rate()); + values2.put(CommonString.KEY_TOTAL_AMOUNT, totalAmount); + values2.put(CommonString.KEY_REASON_ID, selected_list.get(j).getReasonId()); + values2.put(CommonString.KEY_COUNTER_CONFIRM, counter_confirm); + values2.put(CommonString.KEY_DRAFT_STATUS, draft_status); + values2.put(CommonString.KEY_VIEW_MODE, "-1"); + values2.put(CommonString.KEY_SOURCE, source); + values2.put(CommonString.KEY_SKU_CONFIRMATION_CHECK, selected_list.get(j).isConfirmChecked()); + values2.put(CommonString.KEY_UPLOAD_STATUS, CommonString.KEY_N); + values2.put(CommonString.KEY_TRANSACTION_ID, ""); + values2.put(CommonString.KEY_MASTER_TRANSACTION_ID, 0); + values2.put(CommonString.KEY_INVOICE_STATUS, invoice_status); + values2.put(CommonString.KEY_NEW_PRODUCT, 0); + id = db.insert(CommonString.TABLE_INSERT_MANUAL_INWARD_TRANSACTION, null, values2); + } + + closeDb(); + + if (id > 0) { + return id; + } else { + return 0; + } + } catch (Exception ex) { + closeDb(); + ////////test("Database Exception ", ex.toString()); + return 0; + } + } + + + public long deletemanualinwardbyInvoiceid(String counter_id, String visit_date, String invoiceNo, String invoiceType) { + long l = 0; + + try { + l = db.delete(CommonString.TABLE_INSERT_MANUAL_INWARD_TRANSACTION, CommonString.KEY_VISIT_DATE + "='" + visit_date + "' AND " + CommonString.KEY_COUNTER_ID + "=" + counter_id + " AND " + CommonString.KEY_INVOICE_NUMBER + "='" + invoiceNo + "' AND " + CommonString.KEY_INVOICE_TYPE + "='" + invoiceType + "'", null); + } catch (Exception e) { + e.fillInStackTrace(); + } + return l; + + } + + + public long insertManualInwardStockData(ArrayList selected_list, String counter_id, String username, String invoiceNo, String invoiceType, String invDate, String visit_date, String invoice_img, String transactionId, boolean newinwardproduct) { + db.delete(CommonString.TABLE_TRANSACTION_WISE_MASTER_TABLE, CommonString.KEY_VISIT_DATE + " <>'" + visit_date + "'", null); + db.delete(CommonString.TABLE_INSERT_MANUAL_INWARD_TRANSACTION, CommonString.KEY_VISIT_DATE + "<>'" + visit_date + "'", null); + long id = 0, masterreturn = 0; + ContentValues values2; + ContentValues values1; + String invoice_status = "1", invoiceId = "0", counter_confirm = "1", draft_status = "1", source = "Manual"; + int totalAmount = 0; + try { + + db.beginTransaction(); + values1 = new ContentValues(); + values1.put(CommonString.KEY_UUID, transactionId); + values1.put(CommonString.KEY_USER_ID, username); + values1.put(CommonString.KEY_COUNTER_ID, counter_id); + values1.put(CommonString.KEY_VISIT_DATE, visit_date); + if (newinwardproduct) { + values1.put(CommonString.KEY_STOCK_TYPE, CommonString.MANUALINWARD_DMS_NEWPRODUCT); + } else { + values1.put(CommonString.KEY_STOCK_TYPE, CommonString.MANUALINWARD_DMS); + } + values1.put(CommonString.KEY_ENTRY_TYPE, CommonString.KEY_REGULAR); + values1.put(CommonString.KEY_STATUS, CommonString.KEY_N); + masterreturn = db.insert(CommonString.TABLE_TRANSACTION_WISE_MASTER_TABLE, null, values1); + if (masterreturn > 0) { + for (int j = 0; j < selected_list.size(); j++) { + values2 = new ContentValues(); + values2.put(CommonString.KEY_UPLOAD_STATUS, CommonString.KEY_N); + values2.put(CommonString.KEY_TRANSACTION_ID, transactionId); + values2.put(CommonString.KEY_MASTER_TRANSACTION_ID, masterreturn); + values2.put(CommonString.KEY_VISIT_DATE, visit_date); + values2.put(CommonString.KEY_COUNTER_ID, counter_id); + values2.put(CommonString.KEY_USER_ID, username); + values2.put(CommonString.KEY_INVOICE_NUMBER, invoiceNo); + values2.put(CommonString.KEY_INVOICE_DATE, invDate); + values2.put(CommonString.KEY_INVOICE_TYPE, invoiceType); + values2.put(CommonString.KEY_INVOICE_ID, invoiceId); + values2.put(CommonString.KEY_INVOICE_IMG, invoice_img); + values2.put(CommonString.KEY_COUNTER_CONFIRM, counter_confirm); + values2.put(CommonString.KEY_DRAFT_STATUS, draft_status); + values2.put(CommonString.KEY_VIEW_MODE, "-1"); + values2.put(CommonString.KEY_SOURCE, source); + values2.put(CommonString.KEY_INVOICE_STATUS, invoice_status); + + values2.put(CommonString.KEY_Product, selected_list.get(j).getProduct()); + values2.put(CommonString.KEY_ProductId, selected_list.get(j).getProduct_Id()); + values2.put(CommonString.KEY_INVOICE_QTY, selected_list.get(j).getQuantity()); + values2.put(CommonString.KEY_MRP, selected_list.get(j).getProduct_rate()); + values2.put(CommonString.KEY_ACTUAL_QTY, selected_list.get(j).getActualQty()); + totalAmount = Integer.parseInt(selected_list.get(j).getActualQty()) * Integer.parseInt(selected_list.get(j).getProduct_rate()); + values2.put(CommonString.KEY_TOTAL_AMOUNT, totalAmount); + values2.put(CommonString.KEY_REASON_ID, selected_list.get(j).getReasonId()); + values2.put(CommonString.KEY_SKU_CONFIRMATION_CHECK, selected_list.get(j).isConfirmChecked()); + if (newinwardproduct) { + values2.put(CommonString.KEY_NEW_PRODUCT, 1); + } else { + values2.put(CommonString.KEY_NEW_PRODUCT, 0); + } + if (!db.isOpen()) open(); + + id = db.insert(CommonString.TABLE_INSERT_MANUAL_INWARD_TRANSACTION, null, values2); + if (id > 0) { + if (!db.isOpen()) open(); + TStockSummary stockObj = getTStockSummaryProductDetails(Integer.parseInt(selected_list.get(j).getProduct_Id())); + if (stockObj != null) { + // if stockObj is not null means product exist in stock summary table data then update value in TStockSummary + updateStockSummaryData(stockObj, invoiceType, selected_list.get(j).getActualQty(), visit_date); + } else { + if (!db.isOpen()) open(); + stockObj = getStockSummaryStatus(visit_date); + if (stockObj.getId() != null) { + if (!db.isOpen()) open(); + insertTStockSummaryManualData(stockObj, Integer.parseInt(selected_list.get(j).getProduct_Id()), counter_id, invoiceType, selected_list.get(j).getActualQty()); + } + } + if (selected_list.get(j).getReasonId() == 2 && invoiceType.equalsIgnoreCase("Sellable")) { + int damageStockQty = Integer.parseInt(selected_list.get(j).getActualQty()); + updateStockSummaryDamageValue(Integer.parseInt(selected_list.get(j).getProduct_Id()), damageStockQty, counter_id); + } + } + } + } + + db.setTransactionSuccessful(); + db.endTransaction(); + if (id > 0) { + return id; + } else { + return 0; + } + } catch (Exception ex) { + ////////test("Database Exception ", ex.toString()); + return 0; + } + } + + + public ArrayList getManualInwardStockData(String counter_id, String visit_date) { + ArrayList list = new ArrayList<>(); + + Cursor dbcursor = null; + try { + + dbcursor = db.rawQuery("Select distinct " + CommonString.KEY_INVOICE_NUMBER + "," + CommonString.KEY_TRANSACTION_ID + "," + CommonString.KEY_UPLOAD_STATUS + "," + CommonString.KEY_INVOICE_TYPE + "," + CommonString.KEY_INVOICE_DATE + "," + CommonString.KEY_INVOICE_STATUS + "," + CommonString.KEY_SOURCE + "," + CommonString.KEY_COUNTER_CONFIRM + ",count(" + CommonString.KEY_ProductId + ") as NoofLine,sum(" + CommonString.KEY_TOTAL_AMOUNT + ") as FinalAmount , " + CommonString.KEY_INVOICE_IMG + " from " + CommonString.TABLE_INSERT_MANUAL_INWARD_TRANSACTION + " where " + CommonString.KEY_COUNTER_ID + " = '" + counter_id + "' and " + CommonString.KEY_VISIT_DATE + " = '" + visit_date + "' group by InvoiceNo order by InvoiceDate desc ", null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + TCounterInvoice sb = new TCounterInvoice(); + sb.setInvoiceNo(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_INVOICE_NUMBER))); + sb.setInvoiceDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_INVOICE_DATE))); + sb.setInvoiceType(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_INVOICE_TYPE))); + sb.setInvoice_img(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_INVOICE_IMG))); + String counterconfirm = dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_COUNTER_CONFIRM)); + String invoiceStatus = dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_INVOICE_STATUS)); + sb.setCounterConfirm(counterconfirm == null || counterconfirm.equals("0") ? false : true); + sb.setApproved_line(dbcursor.getString(dbcursor.getColumnIndexOrThrow("NoofLine"))); + sb.setInvoiceStatus(invoiceStatus == null || invoiceStatus.equals("0") ? false : true); + sb.setNo_ofLine(dbcursor.getString(dbcursor.getColumnIndexOrThrow("NoofLine"))); + sb.setFinalAmount(dbcursor.getString(dbcursor.getColumnIndexOrThrow("FinalAmount"))); + sb.setSource(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_SOURCE))); + sb.setTransactionId(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_TRANSACTION_ID))); + sb.setUpload_status(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_UPLOAD_STATUS))); + + list.add(sb); + dbcursor.moveToNext(); + } + dbcursor.close(); + return list; + } + } catch (Exception e) { + + return list; + } + return list; + } + + private String getinwardStockTransactionId(String invoiceNo, int product_id) { + Cursor dbcursor = null; + String transId = ""; + try { + dbcursor = db.rawQuery("select * from " + CommonString.TABLE_INSERT_INWARD_STOCK_TRANSACTION + " where " + CommonString.KEY_INVOICE_NUMBER + " = '" + invoiceNo + "' " + "and " + CommonString.KEY_ProductId + " =" + product_id + "", null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + ProductMaster sb = new ProductMaster(); + transId = dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_TRANSACTION_ID)); + dbcursor.moveToNext(); + } + dbcursor.close(); + return transId; + } + } catch (Exception e) { + + return transId; + } + + return transId; + } + + ///jp_update_getSaleable Stock + public ProductMaster getActualSaleableStock(String productId, String coulmn_name, String visit_date, String counterId, String userType) { + ProductMaster list = new ProductMaster(); + Cursor dbcursor = null; + String q1 = userType != null && userType.equalsIgnoreCase(CommonString.TAG_FROM_ME) ? " AND T1." + CommonString.KEY_USER_TYPE + "='" + CommonString.TAG_FROM_ME + "'" : " AND T1." + CommonString.KEY_USER_TYPE + "!='" + CommonString.TAG_FROM_ME + "' AND T2.POS_SALE_FLAG='0'"; + String q2 = userType != null && userType.equalsIgnoreCase(CommonString.TAG_FROM_ME) ? " AND S." + CommonString.KEY_USER_TYPE + "='" + CommonString.TAG_FROM_ME + "'" : " AND S." + CommonString.KEY_USER_TYPE + "!='" + CommonString.TAG_FROM_ME + "' AND S1.POS_SALE_FLAG ='0'"; + String additionQueryMe = "", getDataMe = "(s.SaleableBalance - ifnull(dm.DamageQty,0)) as SaleableBalance"; + try { + if (!db.isOpen()) { + open(); + } + String table = "T_StockSummary", query = ""; + if (userType != null && userType.equalsIgnoreCase(CommonString.TAG_FROM_ME)) { + getDataMe = "((s.SaleableBalance + ifnull(tempsale.TempSale,0) ) - ifnull(dm.DamageQty,0)) as SaleableBalance"; + additionQueryMe = " left join (select ProductId, case when (Select count(*) from (" + " Select CounterId, ProductId," + "sum(TempQty) as TempQty from ( Select T2.COUNTER_ID AS CounterId, T1.PRODUCT_ID AS ProductId , SUM(T1.QUANTITY) AS TempQty FROM SALE_TRACKING_TABLE T1" + " INNER JOIN SALE_TRACKING_HEADER_TABLE T2 ON T2.RECCEPT_COUNT=T1.RECCEPT_COUNT WHERE T2.COUNTER_ID =" + counterId + " AND T2.Visit_Date='" + visit_date + "' AND T1.INVOICE_TYPE='Saleable'" + " and T1.PRODUCT_ID=" + productId + " AND T1.RIGHTNAME !='ME' AND T1.POS_SALE_FLAG !=0 GROUP BY T1.PRODUCT_ID" + " UNION ALL select S.COUNTER_ID as CounterId," + " S.PROMO_PRODUCT_ID AS ProductId , SUM(S.PROMO_PRODUCT_QTY) AS TempQty from APPLYED_PROMOTION_TABLE S INNER JOIN SALE_TRACKING_HEADER_TABLE S1" + " ON S.RECCEPT_COUNT=S1.RECCEPT_COUNT Where S.PROMO_TYPE ='Product' AND S.COUNTER_ID =" + counterId + " AND S1.VISIT_DATE = '" + visit_date + "'" + "and S.PROMO_PRODUCT_ID=" + productId + " AND S.RIGHTNAME !='ME' AND S1.POS_SALE_FLAG !=0 GROUP BY S.PROMO_PRODUCT_ID)as t Group by CounterId, ProductId" + ")" + " c where c.ProductId = t.Productid)>0 then" + " (Select TempQty from (" + " Select CounterId, ProductId," + "sum(TempQty) as TempQty from ( Select T2.COUNTER_ID AS CounterId,T1.PRODUCT_ID AS ProductId,SUM(T1.QUANTITY) AS TempQty FROM SALE_TRACKING_TABLE T1" + " INNER JOIN SALE_TRACKING_HEADER_TABLE T2 ON T2.RECCEPT_COUNT=T1.RECCEPT_COUNT WHERE T2.COUNTER_ID =" + counterId + " AND T2.Visit_Date='" + visit_date + "' AND T1.INVOICE_TYPE='Saleable'" + " and T1.PRODUCT_ID=" + productId + " AND T1.RIGHTNAME !='ME' AND T1.POS_SALE_FLAG !=0 GROUP BY T1.PRODUCT_ID" + " UNION ALL select S.COUNTER_ID as CounterId," + " S.PROMO_PRODUCT_ID AS ProductId , SUM(S.PROMO_PRODUCT_QTY) AS TempQty from APPLYED_PROMOTION_TABLE S INNER JOIN SALE_TRACKING_HEADER_TABLE S1" + " ON S.RECCEPT_COUNT=S1.RECCEPT_COUNT Where S.PROMO_TYPE ='Product' AND S.COUNTER_ID =" + counterId + " AND S1.VISIT_DATE = '" + visit_date + "'" + "and S.PROMO_PRODUCT_ID=" + productId + " AND S.RIGHTNAME !='ME' AND S1.POS_SALE_FLAG !=0 GROUP BY S.PROMO_PRODUCT_ID)as t Group by CounterId, ProductId" + " ) c where c.productId = t.Productid) else (" + "Select sum(QtySold)as QtySold from (select SaleQty as QtySold from Report_BA_TBASale s where s.ProductId = t.ProductId and s.CounterId=" + counterId + " and VisitDate='" + visit_date + "'" + "UNION all select SaleQty as QtySold from Report_BA_TBAPromoSale s where s.ProductId = t.ProductId and s.CounterId=" + counterId + " and VisitDate='" + visit_date + "')" + ") end as TempSale" + " from T_StockSummary t) as tempsale on s.ProductId=tempsale.ProductId"; + } + + if (coulmn_name != null && coulmn_name.equalsIgnoreCase("GwpBalance")) { + query = "select distinct (ts.GwpBalance - ifnull(t.DamageQty,0)) as GwpBalance from Product_Master PM" + " inner join " + table + " ts on ts.ProductId= PM.ProductID Left join (Select CounterId, ProductId, sum(DamageQty) as DamageQty from (" + " Select T2.COUNTER_ID AS CounterId,T1.PRODUCT_ID AS ProductId,SUM(T1.QUANTITY) AS DamageQty FROM SALE_TRACKING_TABLE T1" + " INNER JOIN SALE_TRACKING_HEADER_TABLE T2 ON T2.RECCEPT_COUNT=T1.RECCEPT_COUNT" + " WHERE T2.COUNTER_ID =" + counterId + " AND T2.Visit_Date='" + visit_date + "'" + q1 + " AND T1.INVOICE_TYPE='GWP' and T1.PRODUCT_ID=" + productId + " GROUP BY T1.PRODUCT_ID" + " UNION ALL" + " select S.COUNTER_ID, S.PROMO_PRODUCT_ID AS PRODUCT_ID,SUM(S.PROMO_PRODUCT_QTY) AS QUANTITY from APPLYED_PROMOTION_TABLE S" + " INNER JOIN SALE_TRACKING_HEADER_TABLE S1 ON S.RECCEPT_COUNT=S1.RECCEPT_COUNT" + " Where S.PROMO_TYPE ='Gift' AND S.COUNTER_ID =" + counterId + " AND S1.VISIT_DATE ='" + visit_date + "' and S.PROMO_PRODUCT_ID=" + productId + q2 + " GROUP BY S.PROMO_PRODUCT_ID UNION ALL" + " SELECT COUNTER_ID as CounterId,ProductId,Quantity as DamageQty from Temp_Sale" + " where COUNTER_ID =" + counterId + " and Visit_Date = '" + visit_date + "' and Product_Type='GWP' and ProductId=" + productId + " GROUP By ProductId) as t Group by CounterId, ProductId" + " ) as t on PM.ProductId = t.ProductId" + + + " where ts.GwpBalance >0"; + } else if (coulmn_name != null && coulmn_name.equalsIgnoreCase("SampleBalance")) { + query = "select distinct " + coulmn_name + " from " + table + " where ProductId='" + productId + "'"; + } else { + query = " Select " + getDataMe + " from " + table + " s" + " Left join" + " (Select CounterId, ProductId, sum(DamageQty) as DamageQty from (" + " select T.COUNTER_ID as CounterId, T.ProductId, T.Stock as DamageQty from" + " TABLE_TRANSACTION_DATA T INNER JOIN DR_TABLE_TRANSACTION_WISE_MASTER M" + " ON T.MASTER_TRANSACTION_ID = M.MASTER_TRANSACTION_ID where T.STOCK_TYPE='DAMAGE'" + " AND T.Visit_Date ='" + visit_date + "' and T.COUNTER_ID =" + counterId + " and T.ProductId = " + productId + " Union All SELECT CounterId, ProductId, DamageQty from Damage_PreviousPending Where" + " CounterId =" + counterId + " and Verify ='Pending' and ProductId=" + productId + " UNION ALL" + " Select T2.COUNTER_ID AS CounterId, T1.PRODUCT_ID AS ProductId , SUM(T1.QUANTITY) AS DamageQty" + " FROM SALE_TRACKING_TABLE T1 INNER JOIN SALE_TRACKING_HEADER_TABLE T2 ON" + " T2.RECCEPT_COUNT=T1.RECCEPT_COUNT" + " WHERE T2.COUNTER_ID =" + counterId + " AND T2.Visit_Date='" + visit_date + "' AND T1.INVOICE_TYPE='Saleable'" + " and T1.PRODUCT_ID=" + productId + q1 + " GROUP BY T1.PRODUCT_ID UNION ALL" + " select S.COUNTER_ID as CounterId, S.PROMO_PRODUCT_ID AS ProductId , SUM(S.PROMO_PRODUCT_QTY) AS DamageQty" + " from APPLYED_PROMOTION_TABLE S INNER JOIN SALE_TRACKING_HEADER_TABLE S1" + " ON S.RECCEPT_COUNT=S1.RECCEPT_COUNT" + " Where S.PROMO_TYPE ='Product' AND S.COUNTER_ID = " + counterId + " AND S1.VISIT_DATE = '" + visit_date + "' and S.PROMO_PRODUCT_ID=" + productId + q2 + " GROUP BY S.PROMO_PRODUCT_ID) as" + " t Group by CounterId, ProductId) as dm on s.ProductId = dm.ProductId" + additionQueryMe + " where s.ProductId=" + productId; + } + + dbcursor = db.rawQuery(query, null); + + //test("Query--", query); + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + if (coulmn_name != null && coulmn_name.equalsIgnoreCase("SampleBalance") || coulmn_name != null && coulmn_name.equalsIgnoreCase("GwpBalance")) { + list.setStock(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(coulmn_name))); + } else { + list.setStock(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("SaleableBalance"))); + } + + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list; + } + } catch (Exception e) { + + return list; + } + + return list; + } + + public boolean insertReportSaleValue(MasterProfileQuestionGetterSetter cst) { + db.delete("Report_SalesValue", null, null); + ContentValues values = new ContentValues(); + List data = cst.getReportSalesValue(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("CounterId", data.get(i).getCounterId()); + values.put("KPI", data.get(i).getKPI()); + values.put("MTDTg", data.get(i).getMTDTg()); + values.put("MTDAch", data.get(i).getMTDAch()); + values.put("AchPer", data.get(i).getAchPer()); + values.put("Pending", data.get(i).getPending()); + values.put("RunRate", data.get(i).getRunRate()); + + long id = db.insert("Report_SalesValue", null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ex.fillInStackTrace(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + public boolean insertReportSaleDetails(MasterProfileQuestionGetterSetter cst, boolean me) { + String table = "Report_Sales_Detail"; + List data = cst.getReportSalesDetail(); + if (me) { + table = "Report_Sales_DetailME"; + data = cst.getReportSalesDetailMe(); + } + db.delete(table, null, null); + ContentValues values = new ContentValues(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("CounterId", data.get(i).getCounterId()); + values.put("ProductId", data.get(i).getProductId()); + values.put("Qty", data.get(i).getQty()); + values.put("SalesValue", data.get(i).getSalesValue()); + + long id = db.insert(table, null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ex.fillInStackTrace(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + + public boolean insertReportAvgTransationperDay(MasterProfileQuestionGetterSetter cst) { + db.delete("Report_AvgTransactionPerDay", null, null); + ContentValues values = new ContentValues(); + List data = cst.getReportAvgTransactionPerDay(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("CounterId", data.get(i).getCounterId()); + values.put("KPI", data.get(i).getKPI()); + values.put("MTDTg", data.get(i).getMTDTg()); + values.put("MTDAch", data.get(i).getMTDAch()); + values.put("AchPer", data.get(i).getAchPer()); + values.put("Pending", data.get(i).getPending()); + long id = db.insert("Report_AvgTransactionPerDay", null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ex.fillInStackTrace(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + + public boolean insertReportAvgBillUnit(MasterProfileQuestionGetterSetter cst) { + db.delete("Report_AvgBillValue", null, null); + ContentValues values = new ContentValues(); + List data = cst.getReportAvgBillValue(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("CounterId", data.get(i).getCounterId()); + values.put("KPI", data.get(i).getKPI()); + values.put("MTDTg", data.get(i).getMTDTg()); + values.put("MTDAch", data.get(i).getMTDAch()); + values.put("AchPer", data.get(i).getAchPer()); + values.put("Pending", data.get(i).getPending()); + long id = db.insert("Report_AvgBillValue", null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ex.fillInStackTrace(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + public boolean insertReportAvgPerBillDay(MasterProfileQuestionGetterSetter cst) { + db.delete("Report_AvgUnitsPerBill", null, null); + ContentValues values = new ContentValues(); + List data = cst.getReportAvgUnitsPerBill(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("CounterId", data.get(i).getCounterId()); + values.put("KPI", data.get(i).getKPI()); + values.put("MTDTg", data.get(i).getMTDTg()); + values.put("MTDAch", data.get(i).getMTDAch()); + values.put("AchPer", data.get(i).getAchPer()); + values.put("Pending", data.get(i).getPending()); + long id = db.insert("Report_AvgUnitsPerBill", null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + ex.fillInStackTrace(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + + public ArrayList getInvoiceTypeList() { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + dbcursor = db.rawQuery("select * from Master_InvoiceType", null); + + MasterInvoiceType sb1 = new MasterInvoiceType(); + sb1.setInvoiceType("- Select Invoice Type -"); + list.add(sb1); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + MasterInvoiceType sb = new MasterInvoiceType(); + sb.setInvoiceType(dbcursor.getString(dbcursor.getColumnIndexOrThrow("InvoiceType"))); + list.add(sb); + dbcursor.moveToNext(); + } + dbcursor.close(); + return list; + } + } catch (Exception e) { + return list; + } + return list; + } + + public long deleteTableWithLogin(String userName) { + long l = 0; + try { + l = db.delete("User_login", "USER_ID='" + userName + "'", null); + } catch (Exception e) { + e.fillInStackTrace(); + } + return l; + } + + + public ArrayList getInsertedManualStockData(String invNumber, String invType, String date) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + + dbcursor = db.rawQuery("SELECT * from " + CommonString.TABLE_INSERT_MANUAL_INWARD_TRANSACTION + " WHERE " + CommonString.KEY_INVOICE_NUMBER + "='" + invNumber + "' " + " AND " + CommonString.KEY_INVOICE_TYPE + "='" + invType + "' and " + CommonString.KEY_VISIT_DATE + "='" + date + "'", null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + InvoiceGetterSetter sale = new InvoiceGetterSetter(); + sale.setKeyId(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_ID))); + sale.setProduct_Id(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_ProductId))); + sale.setProduct(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_Product))); + sale.setQuantity(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_INVOICE_QTY))); + sale.setActualQty(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_ACTUAL_QTY))); + sale.setProduct_rate(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_MRP))); + sale.setViewMode(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_VIEW_MODE))); + sale.setInvoice_status(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_INVOICE_STATUS))); + sale.setReasonId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(CommonString.KEY_REASON_ID))); + sale.setDraft_status(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_DRAFT_STATUS))); + sale.setInvoice_img(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_INVOICE_IMG))); + list.add(sale); + + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list; + } + + } catch (Exception e) { + ////////test("Exception Brands", e.toString()); + return list; + } + return list; + } + + + public boolean insertReportAvgLinPerBill(MasterProfileQuestionGetterSetter cst) { + db.delete("Report_AvgLinPerBill", null, null); + ContentValues values = new ContentValues(); + List data = cst.getReportAvgLinPerBill(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("CounterId", data.get(i).getCounterId()); + values.put("KPI", data.get(i).getKPI()); + values.put("MTDTg", data.get(i).getMTDTg()); + values.put("MTDAch", data.get(i).getMTDAch()); + values.put("AchPer", data.get(i).getAchPer()); + values.put("Pending", data.get(i).getPending()); + long id = db.insert("Report_AvgLinPerBill", null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ex.fillInStackTrace(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + public boolean insertReportSelingPrice(MasterProfileQuestionGetterSetter cst) { + db.delete("Report_SellingPrice", null, null); + ContentValues values = new ContentValues(); + List data = cst.getReportSellingPrice(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("CounterId", data.get(i).getCounterId()); + values.put("KPI", data.get(i).getKPI()); + values.put("MTDTg", data.get(i).getMTDTg()); + values.put("MTDAch", data.get(i).getMTDAch()); + values.put("Pending", data.get(i).getPending()); + values.put("AchPer", data.get(i).getAchPer()); + long id = db.insert("Report_SellingPrice", null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ex.fillInStackTrace(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + public boolean insertReportTop10Volume(MasterProfileQuestionGetterSetter cst) { + db.delete("Report_Top10Volume", null, null); + ContentValues values = new ContentValues(); + List data = cst.getReportTop10Volume(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("CounterId", data.get(i).getCounterId()); + values.put("BrandName", data.get(i).getBrandName()); + values.put("SubBrandName", data.get(i).getSubBrandName()); + values.put("ReferenceName", data.get(i).getReferenceName()); + values.put("EanCode", data.get(i).getEanCode()); + values.put("ProductName", data.get(i).getProductName()); + values.put("MTDVolume", data.get(i).getMTDVolume()); + values.put("AvgPerDayVolume", data.get(i).getAvgPerDayVolume()); + long id = db.insert("Report_Top10Volume", null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ex.fillInStackTrace(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + + public boolean insertReportTop10Value(MasterProfileQuestionGetterSetter cst) { + db.delete("Report_Top10Value", null, null); + ContentValues values = new ContentValues(); + List data = cst.getReportTop10Value(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("CounterId", data.get(i).getCounterId()); + values.put("BrandName", data.get(i).getBrandName()); + values.put("SubBrandName", data.get(i).getSubBrandName()); + values.put("ReferenceName", data.get(i).getReferenceName()); + values.put("EanCode", data.get(i).getEanCode()); + values.put("ProductName", data.get(i).getProductName()); + values.put("MTDValue", data.get(i).getMTDValue()); + values.put("AvgPerDayValue", data.get(i).getAvgPerDayValue()); + long id = db.insert("Report_Top10Value", null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + ex.fillInStackTrace(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + public boolean insertMeSaleReport(MasterProfileQuestionGetterSetter cst) { + db.delete("Report_ME_Sale", null, null); + ContentValues values = new ContentValues(); + List data = cst.getReportMeSaleList(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("CounterCode", data.get(i).getCounterCode()); + values.put("CounterName", data.get(i).getCounterName()); + values.put("VisitDate", data.get(i).getVisitDate()); + values.put("TotalUnitSale", data.get(i).getTotalunitsale()); + values.put("TotalSale", data.get(i).getTotalsale()); + long id = db.insert("Report_ME_Sale", null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ex.fillInStackTrace(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + public ArrayList getDashboardReport(String CounterId) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + if (CounterId == null) { + dbcursor = db.rawQuery("Select *,0 as RunRate from Report_AvgBillValue " + " Union " + "Select *,0 as RunRate from Report_AvgLinPerBill " + " Union " + "Select *,0 as RunRate from Report_AvgTransactionPerDay " + " Union " + "Select *,0 as RunRate from Report_AvgUnitsPerBill " + " Union " + "Select *,0 as RunRate from Report_SellingPrice " + " Union " + "Select * from Report_SalesValue order by RunRate desc", null); + } else { + dbcursor = db.rawQuery("Select *,0 as RunRate from Report_AvgBillValue where CounterId='" + CounterId + "'" + " Union " + "Select *,0 as RunRate from Report_AvgLinPerBill where CounterId='" + CounterId + "'" + " Union " + "Select *,0 as RunRate from Report_AvgTransactionPerDay where CounterId='" + CounterId + "'" + " Union " + "Select *,0 as RunRate from Report_AvgUnitsPerBill where CounterId='" + CounterId + "'" + " Union " + "Select *,0 as RunRate from Report_SellingPrice where CounterId='" + CounterId + "'" + " Union " + "Select * from Report_SalesValue where CounterId='" + CounterId + "'order by RunRate desc", null); + + } + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + ReportAvgUnitsPerBill sb = new ReportAvgUnitsPerBill(); + sb.setKPI(dbcursor.getString(dbcursor.getColumnIndexOrThrow("KPI"))); + sb.setMTDTg(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("MTDTg"))); + sb.setMTDAch(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("MTDAch"))); + sb.setAchPer(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("AchPer"))); + sb.setPending(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("Pending"))); + sb.setRunRate(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("RunRate"))); + list.add(sb); + dbcursor.moveToNext(); + } + dbcursor.close(); + return list; + } + } catch (Exception e) { + return list; + } + return list; + } + + //Insert GWP data + public void insertGWPCapturedData(String visit_date, HashMap> data, List save_listDataHeader, boolean completeFlag, String counterId) { + db.delete(CommonString.TABLE_INSERT_HEADER_GWP_DATA, null, null); + db.delete(CommonString.TABLE_GWP_CHILD_DATA, null, null); + ContentValues values = new ContentValues(); + ContentValues values1 = new ContentValues(); + try { + db.beginTransaction(); + for (int i = 0; i < save_listDataHeader.size(); i++) { + values.put("AxeName", save_listDataHeader.get(i).getSubBrandName()); + values.put("BrandName", save_listDataHeader.get(i).getBrandName()); + values.put(CommonString.KEY_VISIT_DATE, visit_date); + values.put(CommonString.KEY_COUNTER_ID, counterId); + values.put("SubAxeName", save_listDataHeader.get(i).getReferenceName()); + values.put("SignatureName", save_listDataHeader.get(i).getSignatureName()); + long l = db.insert(CommonString.TABLE_INSERT_HEADER_GWP_DATA, null, values); + for (int j = 0; j < data.get(save_listDataHeader.get(i)).size(); j++) { + values1.put("Common_Id", (int) l); + values1.put(CommonString.KEY_COUNTER_ID, counterId); + values1.put("AxeName", save_listDataHeader.get(i).getSubBrandName()); + values1.put("BrandName", save_listDataHeader.get(i).getBrandName()); + values1.put(CommonString.KEY_VISIT_DATE, visit_date); + values1.put("SubAxeName", save_listDataHeader.get(i).getReferenceName()); + values1.put("ProductName", data.get(save_listDataHeader.get(i)).get(j).getProductName()); + values1.put("ProductId", data.get(save_listDataHeader.get(i)).get(j).getProductId()); + values1.put("STOCK", data.get(save_listDataHeader.get(i)).get(j).getStock()); + values1.put("Mrp", data.get(save_listDataHeader.get(i)).get(j).getMrp()); + values1.put("STOCK_RECEIVED", data.get(save_listDataHeader.get(i)).get(j).getStock_receive()); + values1.put("ImagePath", data.get(save_listDataHeader.get(i)).get(j).getImagePath()); + values1.put("REASON", data.get(save_listDataHeader.get(i)).get(j).getResion()); + if (!db.isOpen()) open(); + + boolean stockFlag = isTStockSummaryProductFilled(data.get(save_listDataHeader.get(i)).get(j).getProductId()); + if (stockFlag) { + // set stock to product + updateTStockData(data.get(save_listDataHeader.get(i)).get(j).getStock(), CommonString.GWP, data.get(save_listDataHeader.get(i)).get(j).getProductId(), completeFlag, visit_date); + } else { + if (!db.isOpen()) open(); + + TStockSummary stockObj; + stockObj = getStockSummaryStatus(visit_date); + if (stockObj != null) { + insertTStockSummaryData(stockObj, data.get(save_listDataHeader.get(i)).get(j).getProductId(), counterId, CommonString.GWP, data.get(save_listDataHeader.get(i)).get(j).getStock(), completeFlag, visit_date); + } + } + + db.insert(CommonString.TABLE_GWP_CHILD_DATA, null, values1); + } + } + closeDb(); + } catch (Exception ex) { + closeDb(); + ex.fillInStackTrace(); + } + } + + ///jp changes + public JourneyPlan getBIDfromJCP(String UserId, String CounterId) { + JourneyPlan sb = new JourneyPlan(); + Cursor dbcursor = null; + try { + if (UserId == null) { + dbcursor = db.rawQuery("SELECT distinct MID,BID,VisitDate from Mapping_JourneyPlan where CounterId=" + CounterId, null); + } else { + dbcursor = db.rawQuery("SELECT distinct MID,BID,VisitDate from Mapping_JourneyPlan where UserId='" + UserId + "' and CounterId=" + CounterId, null); + } + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + if (UserId == null) { + sb.setVisitDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("VisitDate"))); + sb.setMID(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("MID"))); + sb.setBID(0); + } else { + sb.setMID(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("MID"))); + sb.setBID(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("BID"))); + sb.setVisitDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("VisitDate"))); + } + + dbcursor.moveToNext(); + } + + dbcursor.close(); + return sb; + } + + } catch (Exception e) { + ////////test("Exception get JCP!", e.toString()); + return sb; + } + + return sb; + } + + //jeevan nmjnmn, + public long update_SaleTRacking(String counterId, String user_Id, String reciept_count) { + long l = 0; + try { + if (!db.isOpen()) { + open(); + } + ContentValues values = new ContentValues(); + values.put("UPLOAD_STATUS", CommonString.KEY_Y); + l = db.update(CommonString.Table_Sale_Tracking_Header_Data, values, CommonString.KEY_COUNTER_ID + "='" + counterId + "' AND USER_ID='" + user_Id + "' AND RECCEPT_COUNT='" + reciept_count + "'", null); + l = db.update(CommonString.Table_Sale_Tracking, values, CommonString.KEY_COUNTER_ID + "='" + counterId + "' AND USER_ID='" + user_Id + "' AND RECCEPT_COUNT='" + reciept_count + "'", null); + } catch (Exception e) { + e.fillInStackTrace(); + } + + return l; + } + + public long insert_consumer_sales_data(String user_Id, String visit_date, String counter_Id, String total_value, boolean pos_sale_flag, String UID_code, String termcondition_str, HashMap> data, List invoiceHeaderList, String demo_image, String userType) { + db.delete(CommonString.Table_Sale_Tracking, CommonString.KEY_VISIT_DATE + "<>'" + visit_date + "'", null); + db.delete(CommonString.Table_Applyeid_Promotion, CommonString.KEY_VISIT_DATE + "<>'" + visit_date + "'", null); + db.delete(CommonString.Table_Sale_Tracking_Header_Data, CommonString.KEY_VISIT_DATE + "<>'" + visit_date + "'", null); + db.delete(CommonString.TABLE_TRANSACTION_WISE_MASTER_TABLE, CommonString.KEY_VISIT_DATE + " <>'" + visit_date + "'", null); + db.delete(CommonString.Table_PromoApplyeidOnProduct, CommonString.KEY_VISIT_DATE + " <>'" + visit_date + "'", null); + + ContentValues finalvalues = new ContentValues(); + ContentValues promovalues = new ContentValues(); + ContentValues values4 = new ContentValues(); + ContentValues values = new ContentValues(); + ContentValues values1 = new ContentValues(); + long finalreturen = 0, masterreturn = 0, l3 = 0, header_return = 0; + try { + db.beginTransaction(); + if (pos_sale_flag && !invoiceHeaderList.isEmpty()) { + finalvalues.put(CommonString.KEY_UUID, UID_code); + finalvalues.put(CommonString.KEY_USER_ID, user_Id); + finalvalues.put(CommonString.KEY_COUNTER_ID, counter_Id); + finalvalues.put(CommonString.KEY_VISIT_DATE, visit_date); + finalvalues.put(CommonString.KEY_STOCK_TYPE, CommonString.CONSUMERSALE); + finalvalues.put(CommonString.KEY_ENTRY_TYPE, CommonString.KEY_REGULAR); + finalvalues.put(CommonString.KEY_STATUS, CommonString.KEY_N); + if (!db.isOpen()) open(); + + masterreturn = db.insert(CommonString.TABLE_TRANSACTION_WISE_MASTER_TABLE, null, finalvalues); + + } + + for (int i = 0; i < invoiceHeaderList.size(); i++) { + values.put("USER_ID", user_Id); + values.put("UNIQUE_CODE", UID_code); + values.put(CommonString.KEY_MASTER_TRANSACTION_ID, masterreturn); + values.put(CommonString.KEY_COUNTER_ID, counter_Id); + values.put(CommonString.KEY_VISIT_DATE, visit_date); + values.put("BUYER_NAME", invoiceHeaderList.get(i).getCustomer_name()); + values.put("CONTACT_NUMBER", invoiceHeaderList.get(i).getMobile_no()); + values.put("EMAIL_ID", invoiceHeaderList.get(i).getConsumer_email_Id()); + values.put("AGE", invoiceHeaderList.get(i).getConsumer_age()); + values.put("SKIN_TYPE", invoiceHeaderList.get(i).getConsumer_skinType()); + values.put("GENDER", invoiceHeaderList.get(i).getCustomer_gender()); + values.put("DEMO_GIVEN", invoiceHeaderList.get(i).getDemo_given_str()); + values.put("PRODUCT_SOLD", invoiceHeaderList.get(i).getProduct_sold_str()); + values.put("SKIN_GENIUS", invoiceHeaderList.get(i).getSkin_genius_str()); + values.put("MAYBELLINE_VTO", invoiceHeaderList.get(i).getMaybelline_vto_str()); + values.put("PER_TIMING", invoiceHeaderList.get(i).getPercheasing_tym()); + values.put(CommonString.KEY_STORE_NAME, invoiceHeaderList.get(i).getStore_name()); + values.put("STORE_ADDRESS", invoiceHeaderList.get(i).getStore_address()); + values.put("UPLOAD_STATUS", invoiceHeaderList.get(i).getStr_upload_status()); + values.put("CONSUMER_NOSALE_IMG", demo_image); + values.put("SOURCEOFSALES", invoiceHeaderList.get(i).getSourceofSales()); + if (pos_sale_flag) { + values.put("POS_SALE_FLAG", "1"); + } else { + values.put("POS_SALE_FLAG", "0"); + } + values.put("TERMCONDITION_FLAG", termcondition_str); + values.put(CommonString.KEY_USER_TYPE, userType); + if (!db.isOpen()) { + open(); + } + + header_return = db.insert(CommonString.Table_Sale_Tracking_Header_Data, null, values); + + if (invoiceHeaderList.get(i).getProduct_sold_str().trim().equalsIgnoreCase("Yes")) { + for (int j = 0; j < Objects.requireNonNull(data.get(invoiceHeaderList.get(i))).size(); j++) { + values1.put(CommonString.KEY_RECCEPT_NUMBER, (int) header_return); + values1.put(CommonString.KEY_MASTER_TRANSACTION_ID, masterreturn); + values1.put("USER_ID", user_Id); + if (pos_sale_flag) { + values1.put("POS_SALE_FLAG", "1"); + } else { + values1.put("POS_SALE_FLAG", "0"); + } + + values1.put("TOTAL_AMOUNT", total_value); + values1.put(CommonString.KEY_COUNTER_ID, counter_Id); + values1.put(CommonString.KEY_VISIT_DATE, visit_date); + values1.put("UNIQUE_CODE", UID_code); + values.put("CONSUMER_NOSALE_IMG", demo_image); + values.put("TERMCONDITION_FLAG", termcondition_str); + values1.put(CommonString.KEY_STORE_NAME, data.get(invoiceHeaderList.get(i)).get(j).getStore_name()); + values1.put("STORE_ADDRESS", data.get(invoiceHeaderList.get(i)).get(j).getStore_address()); + values1.put("EMAIL_ID", data.get(invoiceHeaderList.get(i)).get(j).getConsumer_email_Id()); + values1.put("AGE", data.get(invoiceHeaderList.get(i)).get(j).getConsumer_age()); + values1.put("SKIN_TYPE", data.get(invoiceHeaderList.get(i)).get(j).getConsumer_skinType()); + values1.put("DEMO_GIVEN", data.get(invoiceHeaderList.get(i)).get(j).getDemo_given_str()); + values1.put("PRODUCT_SOLD", data.get(invoiceHeaderList.get(i)).get(j).getProduct_sold_str()); + values1.put("SKIN_GENIUS", data.get(invoiceHeaderList.get(i)).get(j).getSkin_genius_str()); + values1.put("MAYBELLINE_VTO", data.get(invoiceHeaderList.get(i)).get(j).getMaybelline_vto_str()); + values1.put("SOURCEOFSALES", data.get(invoiceHeaderList.get(i)).get(j).getSourceofSales()); + + values1.put("BUYER_NAME", data.get(invoiceHeaderList.get(i)).get(j).getCustomer_name()); + values1.put("CONTACT_NUMBER", data.get(invoiceHeaderList.get(i)).get(j).getMobile_no()); + values1.put("PRODUCT_ID", data.get(invoiceHeaderList.get(i)).get(j).getProduct_Id()); + values1.put("PRODUCT", data.get(invoiceHeaderList.get(i)).get(j).getProduct()); + values1.put("SKU_TYPE", data.get(invoiceHeaderList.get(i)).get(j).getSkuType()); + values1.put("QUANTITY", data.get(invoiceHeaderList.get(i)).get(j).getQuantity()); + values1.put("PRODUCT_RATE", data.get(invoiceHeaderList.get(i)).get(j).getProduct_rate()); + values1.put("GENDER", data.get(invoiceHeaderList.get(i)).get(j).getCustomer_gender()); + values1.put("EAN_CODE", data.get(invoiceHeaderList.get(i)).get(j).getScan_ean_code_or_enterd_ean_code()); + values1.put("PER_TIMING", data.get(invoiceHeaderList.get(i)).get(j).getPercheasing_tym()); + values1.put("ACTUAL_PRICE", data.get(invoiceHeaderList.get(i)).get(j).getActual_price_per_product()); + values1.put("DISCOUNTED_VALUE", data.get(invoiceHeaderList.get(i)).get(j).getDiscounted_value()); + values1.put("UPLOAD_STATUS", data.get(invoiceHeaderList.get(i)).get(j).getStr_upload_status()); + values1.put("INVOICE_TYPE", data.get(invoiceHeaderList.get(i)).get(j).getStr_invoiceType()); + //////addd discount items + values1.put("PROMOTION", data.get(invoiceHeaderList.get(i)).get(j).getPromotion_name()); + values1.put("PROMOTION_ID", data.get(invoiceHeaderList.get(i)).get(j).getPromotion_Id()); + if (data.get(invoiceHeaderList.get(i)).get(j).isPromo_flag()) { + values1.put("PROMOTION_FLAG", 1); + } else { + values1.put("PROMOTION_FLAG", 0); + } + + values1.put("PROMO_TYPE", data.get(invoiceHeaderList.get(i)).get(j).getPromo_type().trim()); + ///update Sample,GWP, Saleable product--Not Promo------------ + if (pos_sale_flag && userType != null && !userType.equalsIgnoreCase(CommonString.TAG_FROM_ME)) { + InvoiceGetterSetter obj = data.get(invoiceHeaderList.get(i)).get(j); + if (!obj.isPromo_flag()) { + if (!db.isOpen()) { + open(); + } + update_tstock_summery_using_consumer_sales(counter_Id, obj.getProduct_Id(), obj.getQuantity(), obj.getStr_invoiceType()); + } + } + if (!db.isOpen()) { + open(); + } + values1.put(CommonString.KEY_USER_TYPE, userType); + finalreturen = db.insert(CommonString.Table_Sale_Tracking, null, values1); + //////for applyied promotion insert + if (Objects.requireNonNull(data.get(invoiceHeaderList.get(i))).get(j).isPromo_flag()) { + String promoType = data.get(invoiceHeaderList.get(i)).get(j).getPromo_type().trim(); + promovalues.put(CommonString.KEY_MASTER_TRANSACTION_ID, masterreturn); + promovalues.put(CommonString.KEY_RECCEPT_NUMBER, (int) header_return); + promovalues.put(CommonString.KEY_COUNTER_ID, counter_Id); + promovalues.put(CommonString.KEY_VISIT_DATE, visit_date); + promovalues.put("UNIQUE_CODE", UID_code); + promovalues.put("USER_ID", user_Id); + promovalues.put("PROMOTION_FLAG", 1); + promovalues.put("PROMO_TYPE", promoType); + promovalues.put("INVOICE_TYPE", data.get(invoiceHeaderList.get(i)).get(j).getStr_invoiceType()); + promovalues.put("PROMOTION", data.get(invoiceHeaderList.get(i)).get(j).getPromotion_name()); + promovalues.put("PROMOTION_ID", data.get(invoiceHeaderList.get(i)).get(j).getPromotion_Id()); + + if (promoType.equalsIgnoreCase("OffSameProduct")) { + promovalues.put("PROMO_PRODUCT_ID", 0); + promovalues.put("PROMO_PRODUCT", ""); + promovalues.put("EAN_CODE", ""); + promovalues.put("PROMO_PRODUCT_QTY", 0); + promovalues.put("PROMO_PRODUCT_MRP", 0); + promovalues.put("PROMO_DISCOUNT", data.get(invoiceHeaderList.get(i)).get(j).getProduct()); + } else if (promoType.equalsIgnoreCase("OffAdditionalProduct")) { + promovalues.put("PROMO_PRODUCT_ID", 0); + promovalues.put("PROMO_PRODUCT", ""); + promovalues.put("EAN_CODE", ""); + promovalues.put("PROMO_PRODUCT_QTY", 0); + promovalues.put("PROMO_PRODUCT_MRP", 0); + promovalues.put("PROMO_DISCOUNT", data.get(invoiceHeaderList.get(i)).get(j).getProduct()); + } else if (promoType.equalsIgnoreCase("ValueOffAdditionalProduct")) { + promovalues.put("PROMO_PRODUCT_ID", 0); + promovalues.put("PROMO_PRODUCT", ""); + promovalues.put("EAN_CODE", ""); + promovalues.put("PROMO_PRODUCT_QTY", 0); + promovalues.put("PROMO_PRODUCT_MRP", 0); + promovalues.put("PROMO_DISCOUNT", data.get(invoiceHeaderList.get(i)).get(j).getProduct()); + } else if (promoType.equalsIgnoreCase("OffWorth") || promoType.equalsIgnoreCase("WorthWithProduct")) { + promovalues.put("PROMO_PRODUCT_ID", 0); + promovalues.put("PROMO_PRODUCT", ""); + promovalues.put("EAN_CODE", ""); + promovalues.put("PROMO_PRODUCT_QTY", 0); + promovalues.put("PROMO_PRODUCT_MRP", 0); + promovalues.put("PROMO_DISCOUNT", data.get(invoiceHeaderList.get(i)).get(j).getProduct()); + + } else if (promoType.equalsIgnoreCase("OffProduct")) { + promovalues.put("PROMO_PRODUCT_ID", data.get(invoiceHeaderList.get(i)).get(j).getProduct_Id()); + promovalues.put("PROMO_PRODUCT", data.get(invoiceHeaderList.get(i)).get(j).getProduct()); + promovalues.put("EAN_CODE", data.get(invoiceHeaderList.get(i)).get(j).getScan_ean_code_or_enterd_ean_code()); + promovalues.put("PROMO_PRODUCT_QTY", data.get(invoiceHeaderList.get(i)).get(j).getQuantity()); + promovalues.put("PROMO_PRODUCT_MRP", data.get(invoiceHeaderList.get(i)).get(j).getProduct_rate()); + promovalues.put("PROMO_DISCOUNT", data.get(invoiceHeaderList.get(i)).get(j).getSkuType()); + + } else if (promoType.equalsIgnoreCase("Product")) { + promovalues.put("PROMO_PRODUCT_ID", data.get(invoiceHeaderList.get(i)).get(j).getProduct_Id()); + promovalues.put("PROMO_PRODUCT", data.get(invoiceHeaderList.get(i)).get(j).getProduct()); + promovalues.put("EAN_CODE", data.get(invoiceHeaderList.get(i)).get(j).getScan_ean_code_or_enterd_ean_code()); + promovalues.put("PROMO_PRODUCT_QTY", data.get(invoiceHeaderList.get(i)).get(j).getQuantity()); + promovalues.put("PROMO_PRODUCT_MRP", 0); + promovalues.put("PROMO_DISCOUNT", 0); + + } else if (promoType.equalsIgnoreCase("Worth")) { + promovalues.put("PROMO_PRODUCT_ID", 0); + promovalues.put("PROMO_PRODUCT", ""); + promovalues.put("EAN_CODE", ""); + promovalues.put("PROMO_PRODUCT_QTY", 0); + promovalues.put("PROMO_PRODUCT_MRP", 0); + promovalues.put("PROMO_DISCOUNT", data.get(invoiceHeaderList.get(i)).get(j).getProduct()); + + } else if (promoType.equalsIgnoreCase("Gift")) { + promovalues.put("PROMO_PRODUCT_ID", data.get(invoiceHeaderList.get(i)).get(j).getProduct_Id()); + promovalues.put("PROMO_PRODUCT", data.get(invoiceHeaderList.get(i)).get(j).getProduct()); + promovalues.put("EAN_CODE", data.get(invoiceHeaderList.get(i)).get(j).getScan_ean_code_or_enterd_ean_code()); + promovalues.put("PROMO_PRODUCT_QTY", data.get(invoiceHeaderList.get(i)).get(j).getQuantity()); + promovalues.put("PROMO_PRODUCT_MRP", 0); + promovalues.put("PROMO_DISCOUNT", 0); + } + + if (pos_sale_flag && userType != null && !userType.equalsIgnoreCase(CommonString.TAG_FROM_ME)) { + //------------------update product qty in T_Stock summery..---------// + InvoiceGetterSetter obj = data.get(invoiceHeaderList.get(i)).get(j); + if (obj.getPromo_type().equalsIgnoreCase("Product")) { + update_tstock_summery_using_promotion(counter_Id, obj.getProduct_Id(), obj.getQuantity(), true); + } else if (obj.getPromo_type().equalsIgnoreCase("Gift")) { + update_tstock_summery_using_promotion(counter_Id, obj.getProduct_Id(), obj.getQuantity(), false); + } else if (obj.getPromo_type().equalsIgnoreCase("OffProduct")) { + update_tstock_summery_using_promotion(counter_Id, obj.getProduct_Id(), obj.getQuantity(), true); + } + } + if (!db.isOpen()) { + open(); + } + promovalues.put(CommonString.KEY_USER_TYPE, userType); + l3 = db.insert(CommonString.Table_Applyeid_Promotion, null, promovalues); + ////insert promo applyed on Products + InvoiceGetterSetter obj = data.get(invoiceHeaderList.get(i)).get(j); + if (l3 > 0 && !obj.getApplyiedproductList().isEmpty()) { + values4 = new ContentValues(); + for (int d = 0; d < obj.getApplyiedproductList().size(); d++) { + values4.put(CommonString.KEY_COMMON_ID, l3); + values4.put(CommonString.KEY_MASTER_TRANSACTION_ID, masterreturn); + values4.put(CommonString.KEY_RECCEPT_NUMBER, (int) header_return); + values4.put(CommonString.KEY_COUNTER_ID, counter_Id); + values4.put(CommonString.KEY_VISIT_DATE, visit_date); + values4.put("UNIQUE_CODE", UID_code); + values4.put("USER_ID", user_Id); + values4.put("PROMOTION_FLAG", 1); + values4.put("PROMO_TYPE", promoType); + values4.put("INVOICE_TYPE", obj.getStr_invoiceType()); + values4.put("PROMOTION", obj.getPromotion_name()); + values4.put("PROMOTION_ID", obj.getPromotion_Id()); + values4.put("PRODUCT_ID", obj.getApplyiedproductList().get(d).getProduct_Id()); + values4.put("PRODUCT", obj.getApplyiedproductList().get(d).getProduct()); + values4.put("EAN_CODE", obj.getApplyiedproductList().get(d).getScan_ean_code_or_enterd_ean_code()); + values4.put("PRODUCT_QTY", obj.getApplyiedproductList().get(d).getQuantity()); + values4.put("MRP", obj.getApplyiedproductList().get(d).getProduct_rate()); + values4.put("DISCOUNT", obj.getApplyiedproductList().get(d).getDiscounted_value_productwise()); + if (!db.isOpen()) { + open(); + } + values4.put(CommonString.KEY_USER_TYPE, userType); + long l7 = db.insert(CommonString.Table_PromoApplyeidOnProduct, null, values4); + } + } + } + } + } + } + + if (finalreturen == 0 && header_return > 0) { + finalreturen = header_return; + } + db.setTransactionSuccessful(); + db.endTransaction(); + } catch (Exception ex) { + closeDb(); + ////////test("Database Exception", " while Insert Posm Master Data " + ex); + } + + return finalreturen; + } + + + public long insert_temp_sales_data(String visit_date, String counter_Id, ArrayList saleList) { + db.delete(CommonString.Table_Temp_Sale, null, null); + ContentValues values = new ContentValues(); + long l2 = 0; + try { + db.beginTransaction(); + for (int k = 0; k < saleList.size(); k++) { + values.put(CommonString.KEY_COUNTER_ID, counter_Id); + values.put(CommonString.KEY_VISIT_DATE, visit_date); + values.put("ProductId", saleList.get(k).getProduct_Id()); + values.put("Quantity", saleList.get(k).getQuantity()); + values.put("Product_Type", saleList.get(k).getStr_invoiceType()); + if (!db.isOpen()) open(); + l2 = db.insert(CommonString.Table_Temp_Sale, null, values); + } + closeDb(); + } catch (Exception ex) { + closeDb(); + ////////test("Database Exception", " while Insert Posm Master Data " + ex.toString()); + } + + return l2; + } + + public ArrayList getsaleTrackingHeaderData(String visite_date, String counterId, String user_Id, boolean flagfor_sale, boolean flagforuuid, String uuid_Id) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + if (flagforuuid) { + dbcursor = db.rawQuery("Select * FROM " + CommonString.Table_Sale_Tracking_Header_Data + " Where UNIQUE_CODE ='" + uuid_Id + "'", null); + } else { + if (flagfor_sale) { + dbcursor = db.rawQuery("Select * FROM " + CommonString.Table_Sale_Tracking_Header_Data + " Where " + CommonString.KEY_VISIT_DATE + " ='" + visite_date + "' and " + CommonString.KEY_COUNTER_ID + " ='" + counterId + "'and USER_ID ='" + user_Id + "' and UPLOAD_STATUS='N'", null); + } else if (user_Id == null) { + dbcursor = db.rawQuery("Select * FROM " + CommonString.Table_Sale_Tracking_Header_Data + " Where " + CommonString.KEY_VISIT_DATE + " ='" + visite_date + "' and " + CommonString.KEY_COUNTER_ID + " ='" + counterId + "' and POS_SALE_FLAG='1' and UPLOAD_STATUS='N'", null); + } else { + dbcursor = db.rawQuery("Select * FROM " + CommonString.Table_Sale_Tracking_Header_Data + " Where " + CommonString.KEY_VISIT_DATE + " ='" + visite_date + "' and " + CommonString.KEY_COUNTER_ID + " ='" + counterId + "'and USER_ID ='" + user_Id + "' and POS_SALE_FLAG='1' and UPLOAD_STATUS='N'", null); + } + } + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + InvoiceGetterSetter sale = new InvoiceGetterSetter(); + sale.setCustomer_name(dbcursor.getString(dbcursor.getColumnIndexOrThrow("BUYER_NAME"))); + sale.setMobile_no(dbcursor.getString(dbcursor.getColumnIndexOrThrow("CONTACT_NUMBER"))); + sale.setConsumer_email_Id(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EMAIL_ID"))); + sale.setConsumer_age(dbcursor.getString(dbcursor.getColumnIndexOrThrow("AGE"))); + sale.setConsumer_skinType(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SKIN_TYPE"))); + sale.setCustomer_gender(dbcursor.getString(dbcursor.getColumnIndexOrThrow("GENDER"))); + sale.setDemo_given_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("DEMO_GIVEN"))); + sale.setProduct_sold_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PRODUCT_SOLD"))); + sale.setSkin_genius_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SKIN_GENIUS"))); + sale.setMaybelline_vto_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("MAYBELLINE_VTO"))); + sale.setPercheasing_tym(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PER_TIMING"))); + sale.setReccept_count(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("RECCEPT_COUNT"))); + sale.setStr_upload_status(dbcursor.getString(dbcursor.getColumnIndexOrThrow("UPLOAD_STATUS"))); + sale.setUnique_code(dbcursor.getString(dbcursor.getColumnIndexOrThrow("UNIQUE_CODE"))); + sale.setStr_termcondition(dbcursor.getString(dbcursor.getColumnIndexOrThrow("TERMCONDITION_FLAG"))); + sale.setStrUserId(dbcursor.getString(dbcursor.getColumnIndexOrThrow("USER_ID"))); + sale.setConsumer_no_saleImg(dbcursor.getString(dbcursor.getColumnIndexOrThrow("CONSUMER_NOSALE_IMG"))); + sale.setSourceofSales(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SOURCEOFSALES"))); + sale.setVisit_date(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_VISIT_DATE))); + sale.setPos_sale_flag("1".equalsIgnoreCase(dbcursor.getString(dbcursor.getColumnIndexOrThrow("POS_SALE_FLAG")))); + sale.setUserType(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_USER_TYPE))); + list.add(sale); + dbcursor.moveToNext(); + } + dbcursor.close(); + return list; + } + + } catch (Exception e) { + ////////test("Exception Brands", e.toString()); + return list; + } + return list; + } + + public long updateCounterProfileStatus(String userId, String visit_date, String status) { + long l = 0; + try { + if (!db.isOpen()) { + open(); + } + ContentValues values = new ContentValues(); + values.put(CommonString.KEY_STATUS, status); + l = db.update(CommonString.TABLE_COUNTER_PROFILE_DATA, values, CommonString.KEY_USER_ID + " ='" + userId + "' AND " + CommonString.KEY_VISIT_DATE + " ='" + visit_date + "'", null); + } catch (Exception e) { + e.fillInStackTrace(); + } + return l; + } + + + public long updateBaProfileStatus(String userId, String visit_date, String status) { + long l = 0; + try { + ContentValues values = new ContentValues(); + values.put(CommonString.KEY_STATUS, status); + if (!db.isOpen()) { + open(); + } + l = db.update("BA_PROFILE_DATA", values, CommonString.KEY_USER_ID + " ='" + userId + "' AND " + CommonString.KEY_VISIT_DATE + " ='" + visit_date + "'", null); + } catch (Exception e) { + e.fillInStackTrace(); + } + return l; + } + + + public JourneyPlan getinserted_counter_images(String counterId, String visit_date) { + JourneyPlan list = new JourneyPlan(); + Cursor dbcursor = null; + + try { + + dbcursor = db.rawQuery("Select * FROM " + CommonString.TABLE_COUNTER_IMAGE_DATA + " where " + CommonString.KEY_VISIT_DATE + " ='" + visit_date + "' and " + CommonString.KEY_COUNTER_ID + " ='" + counterId + "'", null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + list.setPresetup_img_one_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Pre_Setup_Img_One"))); + list.setPresetup_img_two_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Pre_Setup_Img_Two"))); + list.setPostsetup_img_one_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Post_Setup_Img_One"))); + list.setPostsetup_img_two_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Post_Setup_Img_Two"))); + list.setCounter_img_onefor_ba(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Counter_Img_One"))); + list.setCounter_img_two_for_ba(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Counter_Img_Two"))); + dbcursor.moveToNext(); + } + dbcursor.close(); + return list; + } + } catch (Exception e) { + + return list; + } + return list; + } + + //jeevan nmjnmn, + public long update_CounterImage(String counterId, String user_Id, String visit_date, JourneyPlan counterimageObject) { + long l = 0; + try { + if (db.isOpen()) { + } else { + open(); + } + ContentValues values = new ContentValues(); + values.put("Pre_Setup_Img_One", counterimageObject.getPresetup_img_one_str()); + values.put("Pre_Setup_Img_Two", counterimageObject.getPresetup_img_two_str()); + values.put("Post_Setup_Img_One", counterimageObject.getPostsetup_img_one_str()); + values.put("Post_Setup_Img_Two", counterimageObject.getPostsetup_img_two_str()); + values.put("UNIQUE_CODE", counterimageObject.getTransId()); + l = db.update(CommonString.TABLE_COUNTER_IMAGE_DATA, values, CommonString.KEY_COUNTER_ID + "='" + counterId + "' AND USER_ID='" + user_Id + "' AND " + CommonString.KEY_VISIT_DATE + "='" + visit_date + "'", null); + } catch (Exception e) { + e.fillInStackTrace(); + } + + return l; + } + + public long update_Groomed_images(String counterId, String user_Id, String visit_date, GroomingGetterSetter groomedObject, String transId) { + long l = 0; + try { + if (!db.isOpen()) { + open(); + } + ContentValues values = new ContentValues(); + values.put("Mornning_groomed_img", groomedObject.getMorning_groom_img_str()); + values.put("Mornning_groomed_time", groomedObject.getMorning_groom_time_str()); + values.put("Noon_groomed_img", groomedObject.getNoon_groom_img_str()); + values.put("Noon_groomed_time", groomedObject.getNoon_groom_time_str()); + values.put("Evening_groomed_img", groomedObject.getEvenning_groom_img_str()); + values.put("Evening_groomed_time", groomedObject.getEvenning_groom_time_str()); + values.put("UNIQUE_CODE", transId); + + l = db.update(CommonString.TABLE_GROOMED_IMAGE_DATA, values, CommonString.KEY_COUNTER_ID + "='" + counterId + "' AND " + CommonString.KEY_USER_ID + "='" + user_Id + "' AND " + CommonString.KEY_VISIT_DATE + "='" + visit_date + "'", null); + + } catch (Exception e) { + e.fillInStackTrace(); + } + + return l; + } + + + ////jp get ba login tyme + public LoginGetterSetter get_baLoginTym(String visit_date, String userId) { + LoginGetterSetter sb = new LoginGetterSetter(); + Cursor dbcursor = null; + + try { + + dbcursor = db.rawQuery("Select * FROM User_login where " + CommonString.KEY_VISIT_DATE + "='" + visit_date + "'and USER_ID ='" + userId + "'", null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + sb.setUserLoginTym(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_USER_LOGINTIME))); + sb.setUserType(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_USER_TYPE))); + sb.setUser_checkout(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_USER_Checkout))); + dbcursor.moveToNext(); + } + dbcursor.close(); + return sb; + } + } catch (Exception e) { + + return sb; + } + return sb; + } + + public TStockSummary getTStockSummaryProductDetails(int productId) { + Cursor dbcursor = null; + TStockSummary sb = null; + try { + + dbcursor = db.rawQuery("SELECT * FROM T_StockSummary WHERE " + CommonString.KEY_ProductId + " =" + productId, null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + sb = new TStockSummary(); + sb.setProductId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(CommonString.KEY_ProductId))); + sb.setSaleableIn(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(CommonString.KEY_SALEABLE_IN))); + sb.setSaleableBalance(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(CommonString.KEY_SaleableBalance))); + sb.setTesterIn(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(CommonString.KEY_TESTER_IN))); + sb.setTesterBalance(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(CommonString.KEY_TesterBalance))); + sb.setSampleIn(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(CommonString.KEY_SAMPLE_IN))); + sb.setSampleBalance(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(CommonString.KEY_SampleBalance))); + sb.setGwpIn(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(CommonString.KEY_GWP_IN))); + sb.setGwpBalance(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(CommonString.KEY_GWP_BALANCE))); + sb.setVisitDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("VisitDate"))); + dbcursor.moveToNext(); + } + dbcursor.close(); + return sb; + } + } catch (Exception e) { + return sb; + } + return sb; + } + + public long updateStockSummaryData(TStockSummary stockObj, String type, String actualQty, String visit_date) { + long id = 0; + int saleableIn = 0, saleableBalance = 0, gwpIn = 0, gwpBalance = 0, sampleIn = 0, sampleBalance = 0, testerIn = 0, testerBalance = 0; + ContentValues values = new ContentValues(); + try { + values.put("VisitDate", visit_date); + if (type.equalsIgnoreCase("Sellable")) { + saleableIn = stockObj.getSaleableIn(); + saleableIn = saleableIn + Integer.parseInt(actualQty); + + saleableBalance = stockObj.getSaleableBalance(); + saleableBalance = saleableBalance + Integer.parseInt(actualQty); + + values.put(CommonString.KEY_SALEABLE_IN, saleableIn); + values.put(CommonString.KEY_SaleableBalance, saleableBalance); + } else if (type.equalsIgnoreCase("Sample")) { + sampleIn = stockObj.getSampleIn(); + sampleIn = sampleIn + Integer.parseInt(actualQty); + + sampleBalance = stockObj.getSampleBalance(); + sampleBalance = sampleBalance + Integer.parseInt(actualQty); + + values.put(CommonString.KEY_SAMPLE_IN, sampleIn); + values.put(CommonString.KEY_SampleBalance, sampleBalance); + } else if (type.equalsIgnoreCase("Tester")) { + testerIn = stockObj.getTesterIn(); + testerIn = testerIn + Integer.parseInt(actualQty); + + testerBalance = stockObj.getTesterBalance(); + testerBalance = testerBalance + Integer.parseInt(actualQty); + + values.put(CommonString.KEY_TESTER_IN, testerIn); + values.put(CommonString.KEY_TesterBalance, testerBalance); + } else { + gwpIn = stockObj.getGwpIn(); + gwpIn = gwpIn + Integer.parseInt(actualQty); + + gwpBalance = stockObj.getGwpBalance(); + gwpBalance = gwpBalance + Integer.parseInt(actualQty); + + values.put(CommonString.KEY_GWP_IN, gwpIn); + values.put(CommonString.KEY_GWP_BALANCE, gwpBalance); + } + if (!db.isOpen()) open(); + id = db.update(CommonString.T_StockSummary, values, CommonString.KEY_ProductId + "=" + stockObj.getProductId(), null); + } catch (Exception ex) { + return 0; + } + return id; + } + + + public TStockSummary getStockSummaryStatus(String visit_date) { + Cursor dbcursor = null; + TStockSummary tStockSummaryObj = null; + int id = 0; + try { + dbcursor = db.rawQuery("select distinct MAX(Id) as Id,SaleableStatus,TesterStatus,SampleStatus,GwpStatus,VisitDate from T_StockSummary", null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + tStockSummaryObj = new TStockSummary(); + if (dbcursor.getString(dbcursor.getColumnIndexOrThrow("Id")) == null) { + id = 1; + tStockSummaryObj.setId(id); + tStockSummaryObj.setSaleableStatus("Draft"); + tStockSummaryObj.setTesterStatus("Draft"); + tStockSummaryObj.setGwpStatus("Draft"); + tStockSummaryObj.setSampleStatus("Draft"); + tStockSummaryObj.setVisitDate(visit_date); + } else { + id = Integer.parseInt(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Id"))); + id = id + 1; + tStockSummaryObj.setId(id); + tStockSummaryObj.setSaleableStatus(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_SaleableStatus))); + tStockSummaryObj.setTesterStatus(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_TesterStatus))); + tStockSummaryObj.setGwpStatus(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_GwpStatus))); + tStockSummaryObj.setSampleStatus(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_SampleStatus))); + tStockSummaryObj.setVisitDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("VisitDate"))); + } + + dbcursor.moveToNext(); + } + + dbcursor.close(); + return tStockSummaryObj; + } + } catch (Exception e) { + + return tStockSummaryObj; + } + + return tStockSummaryObj; + } + + + public boolean insertTStockSummaryManualData(TStockSummary stockObj, Integer productId, String counter_id, String type, String actualQty) { + ContentValues values = new ContentValues(); + try { + db.beginTransaction(); + values.put("Id", stockObj.getId()); + values.put("CounterId", counter_id); + values.put("ProductId", productId); + + if (type.equalsIgnoreCase("Sellable")) { + values.put("SaleableIn", actualQty); + values.put("SaleableBalance", actualQty); + } else { + values.put("SaleableIn", 0); + values.put("SaleableBalance", 0); + } + + if (type.equalsIgnoreCase("Sample")) { + values.put("SampleIn", actualQty); + values.put("SampleBalance", actualQty); + } else { + values.put("SampleIn", 0); + values.put("SampleBalance", 0); + } + + if (type.equalsIgnoreCase("Tester")) { + values.put("TesterIn", actualQty); + values.put("TesterBalance", actualQty); + } else { + values.put("TesterIn", 0); + values.put("TesterBalance", 0); + } + + if (type.equalsIgnoreCase("Consumer Offer (PWP)")) { + values.put("GwpIn", actualQty); + values.put("GwpBalance", actualQty); + } else { + values.put("GwpIn", 0); + values.put("GwpBalance", 0); + } + + values.put("SaleableOut", 0); + values.put("SaleableDamage", 0); + values.put("TesterOut", 0); + values.put("TesterDamage", 0); + values.put("SampleOut", 0); + values.put("SampleDamage", 0); + values.put("GwpOut", 0); + values.put("GwpDamage", 0); + + values.put("SaleableStatus", stockObj.getSaleableStatus()); + values.put("TesterStatus", stockObj.getTesterStatus()); + values.put("SampleStatus", stockObj.getSampleStatus()); + values.put("GwpStatus", stockObj.getGwpStatus()); + values.put("VisitDate", stockObj.getVisitDate()); + + if (!db.isOpen()) open(); + + long id = db.insert("T_StockSummary", null, values); + if (id == -1) { + throw new Exception(); + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ex.fillInStackTrace(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + //get JCP is filled + public boolean isProductMasterFilled(String visit_date) { + boolean filled = false; + Cursor dbcursor = null; + try { + dbcursor = db.rawQuery("SELECT * FROM Product_Master where VisitDate ='" + visit_date + "'", null); + if (dbcursor != null) { + dbcursor.moveToFirst(); + int icount = dbcursor.getCount(); + dbcursor.close(); + if (icount > 0) { + filled = true; + } else { + filled = false; + } + + } + } catch (Exception e) { + ////////test("Exception--", e.toString()); + return filled; + } + + return filled; + } + + public boolean isCheck_Old_Product(String visit_date) { + boolean filled = false; + Cursor dbcursor = null; + try { + dbcursor = db.rawQuery("SELECT * FROM Product_Master where VisitDate <>'" + visit_date + "'", null); + if (dbcursor != null) { + dbcursor.moveToFirst(); + int icount = dbcursor.getCount(); + dbcursor.close(); + if (icount > 0) { + filled = true; + } else { + filled = false; + } + } + } catch (Exception e) { + ////////test("Exception--", e.toString()); + return filled; + } + return filled; + } + + + public boolean isTStockSummaryFilled(String visit_date) { + boolean filled = false; + Cursor dbcursor = null; + try { + dbcursor = db.rawQuery("select * from T_StockSummary where VisitDate ='" + visit_date + "'", null); + if (dbcursor != null) { + dbcursor.moveToFirst(); + int icount = dbcursor.getCount(); + dbcursor.close(); + if (icount > 0) { + filled = true; + } else { + filled = false; + } + } + } catch (Exception e) { + ////////test("Exception--", e.toString()); + return filled; + } + + return filled; + } + + public boolean isTStockCorrectedinsert(String visit_date, String counterId) { + boolean filled = false; + Cursor dbcursor = null; + try { + dbcursor = db.rawQuery("SELECT (ifnull(T4.TotLine,0) + ifnull(T4.TotalStock,0)) as StockStatus From" + " (select case when c.TotalLine = t.TotLine then 1 else 0 end as TotLine," + " case when c.TotalStock = t.TotValue then 1 else 0 end as TotalStock from" + " (SELECT * FROM StockSummary_Check Where VisitDate='" + visit_date + "' and CounterId=" + counterId + ") as c" + " INNER JOIN" + " (select counterId, count(*) as TotLIne, sum(SaleableBalance)as TotValue from T_StockSummary Where VisitDate='" + visit_date + "' and CounterId=" + counterId + " group by CounterId) AS t" + " ON c.CounterId = t.CounterId) as T4", null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + int icount = dbcursor.getInt(dbcursor.getColumnIndexOrThrow("StockStatus")); + if (icount == 2) { + filled = true; + break; + } else { + filled = false; + } + + dbcursor.moveToNext(); + } + dbcursor.close(); + } + } catch (Exception e) { + ////////test("Exception--", e.toString()); + + return filled; + } + + return filled; + } + + + public boolean isTStockt(String visit_date, String counterId) { + boolean filled = false; + Cursor dbcursor = null; + try { + + dbcursor = db.rawQuery("SELECT Count(*) As TotalLine FRom T_StockSummary Where VisitDate='" + visit_date + "' And CounterId=" + counterId + "", null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + int icount = dbcursor.getInt(dbcursor.getColumnIndexOrThrow("TotalLine")); + if (icount > 0) { + filled = true; + break; + } else { + filled = false; + } + + dbcursor.moveToNext(); + } + dbcursor.close(); + } + } catch (Exception e) { + ////////test("Exception--", e.toString()); + + return filled; + } + + return filled; + } + + public int isTStockTotalLine(String visit_date, String counterId, String table_name) { + int filled = 0; + Cursor dbcursor = null; + try { + + dbcursor = db.rawQuery("SELECT Count(*) As TotalLine FRom " + table_name + " Where VisitDate='" + visit_date + "' And CounterId=" + counterId + "", null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + int icount = dbcursor.getInt(dbcursor.getColumnIndexOrThrow("TotalLine")); + if (icount > 0) { + filled = icount; + break; + } else { + filled = 0; + } + + dbcursor.moveToNext(); + } + dbcursor.close(); + } + } catch (Exception e) { + ////////test("Exception--", e.toString()); + + return filled; + } + + return filled; + } + + public boolean isTStockSummeryCheckNoData(String visit_date, String counterId) { + boolean filled = false; + Cursor dbcursor = null; + try { + + dbcursor = db.rawQuery("SELECT Count(*) As TotalLine FRom StockSummary_Check Where VisitDate='" + visit_date + "' And CounterId=" + counterId + "", null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + int icount = dbcursor.getInt(dbcursor.getColumnIndexOrThrow("TotalLine")); + if (icount > 0) { + filled = true; + break; + } else { + filled = false; + } + + dbcursor.moveToNext(); + } + dbcursor.close(); + } + } catch (Exception e) { + ////////test("Exception--", e.toString()); + + return filled; + } + + return filled; + } + + + public boolean isCompOffersFilled(String visit_date, String counterId) { + boolean filled = false; + Cursor dbcursor = null; + try { + + dbcursor = db.rawQuery("SELECT Count(*) As TotalLine FROM " + CommonString.TABLE_COMP_OFFERS + " WHERE " + CommonString.KEY_VISIT_DATE + "='" + visit_date + "' AND " + CommonString.KEY_COUNTER_ID + "='" + counterId + "' AND " + CommonString.KEY_STATUS + "<>'N'", null); + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + int icount = dbcursor.getInt(dbcursor.getColumnIndexOrThrow("TotalLine")); + if (icount > 0) { + filled = true; + break; + } + + dbcursor.moveToNext(); + } + dbcursor.close(); + } + } catch (Exception e) { + ////////test("Exception--", e.toString()); + + return filled; + } + + return filled; + } + + public ArrayList getInsertedManualInwardStockData(String counter_id, String invoiceNo) { + ArrayList list = new ArrayList<>(); + + Cursor dbcursor = null; + try { + + dbcursor = db.rawQuery("select * from " + CommonString.TABLE_INSERT_MANUAL_INWARD_TRANSACTION + " where " + CommonString.KEY_COUNTER_ID + " = '" + counter_id + "' " + "and " + CommonString.KEY_INVOICE_NUMBER + " = '" + invoiceNo + "' ", null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + TCounterInvoice sb = new TCounterInvoice(); + sb.setInvoiceNo(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_INVOICE_NUMBER))); + list.add(sb); + dbcursor.moveToNext(); + } + dbcursor.close(); + return list; + } + } catch (Exception e) { + + return list; + } + return list; + } + + + public void update_tstock_summery_using_consumer_sales(String counterId, String product_Id, String productQty, String invoiceType) { + try { + if (!db.isOpen()) { + open(); + } + String table = CommonString.T_StockSummary; + + if (!invoiceType.isEmpty() && invoiceType.trim().equalsIgnoreCase("Sample")) { + db.execSQL("update " + table + " set SampleOut =SampleOut +" + productQty + ",SampleBalance= SampleBalance - " + productQty + " where CounterId=" + counterId + " and ProductId=" + product_Id); + } else if (!invoiceType.isEmpty() && invoiceType.trim().equalsIgnoreCase("GWP")) { + db.execSQL("update " + table + " set GwpOut =GwpOut +" + productQty + ",GwpBalance= GwpBalance - " + productQty + " where CounterId=" + counterId + " and ProductId=" + product_Id); + } else { + db.execSQL("update " + table + " set SaleableOut =SaleableOut +" + productQty + ",SaleableBalance= SaleableBalance - " + productQty + " where CounterId=" + counterId + " and ProductId=" + product_Id); + } + } catch (Exception e) { + e.fillInStackTrace(); + } + + } + + + public void update_tstock_summery_using_promotion(String counterId, String product_Id, String productQty, boolean salaebleflag) { + try { + if (!db.isOpen()) { + open(); + } + String table = CommonString.T_StockSummary; + + if (!salaebleflag) { + db.execSQL("update " + table + " set GwpOut =GwpOut +" + productQty + ",GwpBalance= GwpBalance - " + productQty + " where CounterId=" + counterId + " and ProductId=" + product_Id); + } else { + db.execSQL("update " + table + " set SaleableOut =SaleableOut +" + productQty + ",SaleableBalance= SaleableBalance - " + productQty + " where CounterId=" + counterId + " and ProductId=" + product_Id); + } + + } catch (Exception e) { + e.fillInStackTrace(); + } + + } + + + public T_LeaveRequest getinserted_leave_request_data(String storeid, String user_id, String visit_date, String TransId, boolean manualupload) { + ////////test("Fetching", "Storedata--------------->Start<------------"); + T_LeaveRequest sb = new T_LeaveRequest(); + Cursor dbcursor = null; + try { + if (manualupload) { + dbcursor = db.rawQuery("select * From " + CommonString.Table_Leave_Management + " where " + CommonString.KEY_COUNTER_ID + "='" + storeid + "'AND UNIQUE_CODE='" + TransId + "'and UPLOAD_STATUS='N'", null); + } else { + if (TransId != null) { + dbcursor = db.rawQuery("select * From " + CommonString.Table_Leave_Management + " where " + CommonString.KEY_COUNTER_ID + "='" + storeid + "' AND " + CommonString.KEY_VISIT_DATE + " ='" + visit_date + "'AND USER_ID='" + user_id + "'and UNIQUE_CODE='" + TransId + "'", null); + } else { + dbcursor = db.rawQuery("select * From " + CommonString.Table_Leave_Management + " where " + CommonString.KEY_COUNTER_ID + "='" + storeid + "' AND " + CommonString.KEY_VISIT_DATE + " ='" + visit_date + "'AND USER_ID='" + user_id + "'and UPLOAD_STATUS='N'", null); + } + } + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + sb.setUserId(dbcursor.getString(dbcursor.getColumnIndexOrThrow("USER_ID"))); + sb.setRequestDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Request_Date"))); + sb.setFromDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("From_Date"))); + sb.setUpload_start_date_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Upload_From_Date"))); + sb.setToDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("To_Date"))); + sb.setUpload_end_date_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Upload_To_Date"))); + sb.setLeave_reason(dbcursor.getString(dbcursor.getColumnIndexOrThrow("LeaveReason"))); + sb.setLeaveStatus(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Leave_Status"))); + sb.setTransId(dbcursor.getString(dbcursor.getColumnIndexOrThrow("UNIQUE_CODE"))); + sb.setUpload_status(dbcursor.getString(dbcursor.getColumnIndexOrThrow("UPLOAD_STATUS"))); + sb.setOne_day_leave_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("One_Day_Leave"))); + + sb.setStr_leaveType(dbcursor.getString(dbcursor.getColumnIndexOrThrow("LeaveType"))); + sb.setStr_leaveTypeId(dbcursor.getString(dbcursor.getColumnIndexOrThrow("LeaveTypeId"))); + sb.setUpload_request_date(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_VISIT_DATE))); + dbcursor.moveToNext(); + + } + + dbcursor.close(); + return sb; + } + } catch (Exception e) { + ////////test("Exception ", "when fetching opening stock!!!!!!!!!!!" + e.toString()); + return sb; + } + ////////test("Fetching ", "opening stock---------------------->Stop<-----------"); + return sb; + } + + public MasterBreak getBreakManagementforuploadList(String counterId, String visite_date, String user_Id, String TRansId, boolean manual_upload) { + MasterBreak sale = new MasterBreak(); + Cursor dbcursor = null; + try { + + if (manual_upload) { + dbcursor = db.rawQuery("SELECT * from " + CommonString.Table_Break_Management + " WHERE " + CommonString.KEY_COUNTER_ID + "='" + counterId + "' and UNIQUE_CODE='" + TRansId + "'and UPLOAD_STATUS='N'", null); + } else { + if (TRansId != null) { + dbcursor = db.rawQuery("SELECT * from " + CommonString.Table_Break_Management + " WHERE " + CommonString.KEY_VISIT_DATE + "='" + visite_date + "'AND " + CommonString.KEY_COUNTER_ID + "='" + counterId + "' and USER_ID='" + user_Id + "' and UNIQUE_CODE='" + TRansId + "'", null); + } else { + dbcursor = db.rawQuery("SELECT * from " + CommonString.Table_Break_Management + " WHERE " + CommonString.KEY_VISIT_DATE + "='" + visite_date + "'AND " + CommonString.KEY_COUNTER_ID + "='" + counterId + "' and USER_ID='" + user_Id + "' and UPLOAD_STATUS='N'", null); + } + } + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + sale.setUserId(dbcursor.getString(dbcursor.getColumnIndexOrThrow("USER_ID"))); + sale.setLoginTym(dbcursor.getString(dbcursor.getColumnIndexOrThrow("LoginTym"))); + sale.setBreakType(dbcursor.getString(dbcursor.getColumnIndexOrThrow("BreakType"))); + sale.setBreakId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("BreakId"))); + sale.setStartTym(dbcursor.getString(dbcursor.getColumnIndexOrThrow("StartTym"))); + sale.setEndTym(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EndTym"))); + sale.setTotalDuration(dbcursor.getString(dbcursor.getColumnIndexOrThrow("TotalDuration"))); + sale.setTransId(dbcursor.getString(dbcursor.getColumnIndexOrThrow("UNIQUE_CODE"))); + dbcursor.moveToNext(); + } + + dbcursor.close(); + return sale; + } + + } catch (Exception e) { + ////////test("Exception Brands", e.toString()); + return sale; + } + return sale; + } + + public long insert_consumer_return_headerchild_data(String user_Id, String visit_date, String counter_Id, String UID_code, HashMap> data, List returnheaderList, String bill_img, ArrayList replaceproductList) { + db.delete(CommonString.TABLE_TRANSACTION_WISE_MASTER_TABLE, CommonString.KEY_VISIT_DATE + "<>'" + visit_date + "'", null); + db.delete(CommonString.Table_Consumer_Return, CommonString.KEY_VISIT_DATE + "<>'" + visit_date + "'", null); + db.delete(CommonString.Table_Consumer_Return_Header_Data, CommonString.KEY_VISIT_DATE + "<>'" + visit_date + "'", null); + db.delete(CommonString.Table_Consumer_Return_Replace_Product, CommonString.KEY_VISIT_DATE + "<>'" + visit_date + "'", null); + ContentValues finalvalues = new ContentValues(); + ContentValues values = new ContentValues(); + ContentValues values1 = new ContentValues(); + ContentValues values2 = new ContentValues(); + long l2 = 0, masterreturn = 0; + + try { + db.beginTransaction(); + + finalvalues.put(CommonString.KEY_UUID, UID_code); + finalvalues.put(CommonString.KEY_USER_ID, user_Id); + finalvalues.put(CommonString.KEY_COUNTER_ID, counter_Id); + finalvalues.put(CommonString.KEY_VISIT_DATE, visit_date); + finalvalues.put(CommonString.KEY_STOCK_TYPE, CommonString.CONSUMERRETURN); + finalvalues.put(CommonString.KEY_ENTRY_TYPE, CommonString.KEY_REGULAR); + finalvalues.put(CommonString.KEY_STATUS, CommonString.KEY_N); + masterreturn = db.insert(CommonString.TABLE_TRANSACTION_WISE_MASTER_TABLE, null, finalvalues); + + for (int i = 0; i < returnheaderList.size(); i++) { + values.put("USER_ID", user_Id); + values.put("UNIQUE_CODE", UID_code); + values.put(CommonString.KEY_MASTER_TRANSACTION_ID, masterreturn); + values.put(CommonString.KEY_COUNTER_ID, counter_Id); + values.put(CommonString.KEY_VISIT_DATE, visit_date); + values.put(CommonString.KEY_STORE_NAME, returnheaderList.get(i).getStore_name()); + values.put("STORE_ADDRESS", returnheaderList.get(i).getStore_address()); + values.put("BUYER_NAME", returnheaderList.get(i).getCustomer_name()); + values.put("BILL_NO", returnheaderList.get(i).getConsumer_return_bill_no()); + values.put("CONTACT_NUMBER", returnheaderList.get(i).getMobile_no()); + values.put("EMAIL", returnheaderList.get(i).getConsumer_email_Id()); + values.put("INVOICE_IMG", bill_img); + values.put("GENDER", returnheaderList.get(i).getCustomer_gender()); + values.put("UPLOAD_STATUS", returnheaderList.get(i).getStr_upload_status()); + + long l = db.insert(CommonString.Table_Consumer_Return_Header_Data, null, values); + + for (int j = 0; j < data.get(returnheaderList.get(i)).size(); j++) { + values1.put(CommonString.KEY_MASTER_TRANSACTION_ID, masterreturn); + values1.put(CommonString.KEY_RECCEPT_NUMBER, (int) l); + values1.put("USER_ID", user_Id); + values1.put(CommonString.KEY_COUNTER_ID, counter_Id); + values1.put(CommonString.KEY_VISIT_DATE, visit_date); + values1.put("UNIQUE_CODE", UID_code); + values1.put("UPLOAD_STATUS", returnheaderList.get(i).getStr_upload_status()); + values1.put("PRODUCT_ID", data.get(returnheaderList.get(i)).get(j).getProduct_Id()); + values1.put("PRODUCT", data.get(returnheaderList.get(i)).get(j).getProduct()); + values1.put("QUANTITY", data.get(returnheaderList.get(i)).get(j).getQuantity()); + values1.put("ACTUAL_QTY", data.get(returnheaderList.get(i)).get(j).getActualQty()); + values1.put("PRODUCT_RATE", data.get(returnheaderList.get(i)).get(j).getProduct_rate()); + values1.put("TOTAL_PRICE", data.get(returnheaderList.get(i)).get(j).getTotal_amount()); + values1.put("EAN_CODE", data.get(returnheaderList.get(i)).get(j).getScan_ean_code_or_enterd_ean_code()); + values1.put("REASON_ID", data.get(returnheaderList.get(i)).get(j).getCon_return_reason_Id()); + values1.put("REASON", data.get(returnheaderList.get(i)).get(j).getCon_return_reason()); + + if (db.isOpen()) { + } else { + open(); + } + + update_tstock_summery_using_consumer_return(counter_Id, data.get(returnheaderList.get(i)).get(j).getProduct_Id(), data.get(returnheaderList.get(i)).get(j).getQuantity(), data.get(returnheaderList.get(i)).get(j).getCon_return_reason()); + + l2 = db.insert(CommonString.Table_Consumer_Return, null, values1); + } + + + for (int j = 0; j < replaceproductList.size(); j++) { + values2.put(CommonString.KEY_RECCEPT_NUMBER, (int) l); + values2.put("USER_ID", user_Id); + values2.put(CommonString.KEY_COUNTER_ID, counter_Id); + values2.put(CommonString.KEY_VISIT_DATE, visit_date); + values2.put("UNIQUE_CODE", UID_code); + values2.put("UPLOAD_STATUS", returnheaderList.get(i).getStr_upload_status()); + + values2.put("PRODUCT_ID", replaceproductList.get(j).getProduct_Id()); + values2.put("PRODUCT", replaceproductList.get(j).getProduct()); + values2.put("QUANTITY", replaceproductList.get(j).getQuantity()); + values2.put("PRODUCT_RATE", replaceproductList.get(j).getProduct_rate()); + values2.put("EAN_CODE", replaceproductList.get(j).getScan_ean_code_or_enterd_ean_code()); + if (db.isOpen()) { + } else { + open(); + } + db.execSQL("update T_StockSummary set SaleableOut =SaleableOut +" + replaceproductList.get(j).getQuantity() + ",SaleableBalance= SaleableBalance - " + replaceproductList.get(j).getQuantity() + " where CounterId=" + counter_Id + " and ProductId=" + replaceproductList.get(j).getProduct_Id() + ""); + l2 = db.insert(CommonString.Table_Consumer_Return_Replace_Product, null, values2); + } + } + closeDb(); + } catch (Exception ex) { + closeDb(); + ////////test("Database Exception", " while Insert Posm Master Data " + ex.toString()); + } + + return l2; + } + + public ArrayList getsaleReturnHeaderData(String visite_date, String counterId, String user_Id, boolean flag, boolean flagforsequence, String uuid_Id) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + if (flagforsequence) { + dbcursor = db.rawQuery("Select * FROM " + CommonString.Table_Consumer_Return_Header_Data + "" + " where UNIQUE_CODE='" + uuid_Id + "'", null); + + } else { + if (flag && user_Id == null) { + dbcursor = db.rawQuery("Select * FROM " + CommonString.Table_Consumer_Return_Header_Data + "" + " where " + CommonString.KEY_VISIT_DATE + " ='" + visite_date + "' and " + CommonString.KEY_COUNTER_ID + " ='" + counterId + "' and UPLOAD_STATUS='N'", null); + + } else if (flag) { + dbcursor = db.rawQuery("Select * FROM " + CommonString.Table_Consumer_Return_Header_Data + "" + " where " + CommonString.KEY_VISIT_DATE + " ='" + visite_date + "' and " + CommonString.KEY_COUNTER_ID + " ='" + counterId + "'and USER_ID ='" + user_Id + "' and UPLOAD_STATUS='N'", null); + } else { + dbcursor = db.rawQuery("Select * FROM " + CommonString.Table_Consumer_Return_Header_Data + "" + " where " + CommonString.KEY_VISIT_DATE + " ='" + visite_date + "' and " + CommonString.KEY_COUNTER_ID + " ='" + counterId + "'", null); + + } + } + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + InvoiceGetterSetter sale = new InvoiceGetterSetter(); + sale.setCustomer_name(dbcursor.getString(dbcursor.getColumnIndexOrThrow("BUYER_NAME"))); + sale.setConsumer_return_bill_no(dbcursor.getString(dbcursor.getColumnIndexOrThrow("BILL_NO"))); + sale.setMobile_no(dbcursor.getString(dbcursor.getColumnIndexOrThrow("CONTACT_NUMBER"))); + sale.setConsumer_email_Id(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EMAIL"))); + sale.setCustomer_gender(dbcursor.getString(dbcursor.getColumnIndexOrThrow("GENDER"))); + sale.setReturn_bill_img(dbcursor.getString(dbcursor.getColumnIndexOrThrow("INVOICE_IMG"))); + sale.setReccept_count(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("RECCEPT_COUNT"))); + sale.setUnique_code(dbcursor.getString(dbcursor.getColumnIndexOrThrow("UNIQUE_CODE"))); + sale.setStr_upload_status(dbcursor.getString(dbcursor.getColumnIndexOrThrow("UPLOAD_STATUS"))); + sale.setStrUserId(dbcursor.getString(dbcursor.getColumnIndexOrThrow("USER_ID"))); + sale.setVisit_date(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_VISIT_DATE))); + list.add(sale); + + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list; + } + + } catch (Exception e) { + ////////test("Exception Brands", e.toString()); + return list; + } + return list; + } + + + public long update_leave_management_status(String storeid, String visit_date, String user_Id, String TransId, boolean manual_upload) { + long l = 0; + try { + ContentValues values = new ContentValues(); + + values.put("UPLOAD_STATUS", CommonString.KEY_Y); + if (!db.isOpen()) { + open(); + } + if (manual_upload) { + l = db.update(CommonString.Table_Leave_Management, values, CommonString.KEY_COUNTER_ID + "='" + storeid + "' AND " + CommonString.KEY_VISIT_DATE + " ='" + visit_date + "'and UNIQUE_CODE='" + TransId + "'", null); + + } else { + l = db.update(CommonString.Table_Leave_Management, values, CommonString.KEY_COUNTER_ID + "='" + storeid + "' AND " + CommonString.KEY_VISIT_DATE + " ='" + visit_date + "'AND USER_ID='" + user_Id + "'and UNIQUE_CODE='" + TransId + "'", null); + + } + + + } catch (Exception e) { + e.fillInStackTrace(); + } + return l; + } + + public long update_break_management_status(String storeid, String visit_date, String user_Id, String TransId, boolean manual_upload) { + long l = 0; + try { + ContentValues values = new ContentValues(); + values.put("UPLOAD_STATUS", CommonString.KEY_Y); + if (!db.isOpen()) { + open(); + } + if (manual_upload) { + l = db.update(CommonString.Table_Break_Management, values, CommonString.KEY_COUNTER_ID + "='" + storeid + "' AND " + CommonString.KEY_VISIT_DATE + " ='" + visit_date + "'and UNIQUE_CODE='" + TransId + "'", null); + } else { + l = db.update(CommonString.Table_Break_Management, values, CommonString.KEY_COUNTER_ID + "='" + storeid + "' AND " + CommonString.KEY_VISIT_DATE + " ='" + visit_date + "'AND USER_ID='" + user_Id + "'and UNIQUE_CODE='" + TransId + "'", null); + + } + } catch (Exception e) { + e.fillInStackTrace(); + } + return l; + } + + + public ArrayList getsalesReturnChildData(int reciept_count, String visite_date, String counterId, String user_Id, boolean flag) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + if (flag) { + dbcursor = db.rawQuery("Select * FROM " + CommonString.Table_Consumer_Return + "" + " where RECCEPT_COUNT='" + reciept_count + "' and " + CommonString.KEY_VISIT_DATE + " ='" + visite_date + "' and " + CommonString.KEY_COUNTER_ID + " ='" + counterId + "'and USER_ID ='" + user_Id + "'", null); + + } else { + dbcursor = db.rawQuery("Select * FROM " + CommonString.Table_Consumer_Return + "" + " where RECCEPT_COUNT='" + reciept_count + "' and " + CommonString.KEY_VISIT_DATE + " ='" + visite_date + "' and " + CommonString.KEY_COUNTER_ID + " ='" + counterId + "'", null); + + } + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + InvoiceGetterSetter sale = new InvoiceGetterSetter(); + sale.setUserName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("USER_ID"))); + sale.setProduct_Id(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PRODUCT_ID"))); + sale.setProduct(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PRODUCT"))); + sale.setQuantity(dbcursor.getString(dbcursor.getColumnIndexOrThrow("QUANTITY"))); + sale.setActualQty(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ACTUAL_QTY"))); + sale.setProduct_rate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PRODUCT_RATE"))); + sale.setTotal_amount(dbcursor.getString(dbcursor.getColumnIndexOrThrow("TOTAL_PRICE"))); + sale.setScan_ean_code_or_enterd_ean_code(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EAN_CODE"))); + sale.setCon_return_reason_Id(dbcursor.getString(dbcursor.getColumnIndexOrThrow("REASON_ID"))); + sale.setCon_return_reason(dbcursor.getString(dbcursor.getColumnIndexOrThrow("REASON"))); + sale.setStr_upload_status(dbcursor.getString(dbcursor.getColumnIndexOrThrow("UPLOAD_STATUS"))); + + list.add(sale); + + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list; + } + + } catch (Exception e) { + ////////test("Exception Brands", e.toString()); + return list; + } + return list; + } + + + public ArrayList getsalesReturnReplaceProduct(int reciept_count, String visite_date, String counterId, String user_Id, boolean flag) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + if (flag) { + dbcursor = db.rawQuery("Select * FROM " + CommonString.Table_Consumer_Return_Replace_Product + "" + " where RECCEPT_COUNT='" + reciept_count + "' and " + CommonString.KEY_VISIT_DATE + " ='" + visite_date + "' and " + CommonString.KEY_COUNTER_ID + " ='" + counterId + "'and USER_ID ='" + user_Id + "'", null); + } else { + dbcursor = db.rawQuery("Select * FROM " + CommonString.Table_Consumer_Return_Replace_Product + "" + " where RECCEPT_COUNT='" + reciept_count + "' and " + CommonString.KEY_VISIT_DATE + " ='" + visite_date + "' and " + CommonString.KEY_COUNTER_ID + " ='" + counterId + "'", null); + } + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + InvoiceGetterSetter sale = new InvoiceGetterSetter(); + sale.setProduct_Id(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PRODUCT_ID"))); + sale.setProduct(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PRODUCT"))); + sale.setQuantity(dbcursor.getString(dbcursor.getColumnIndexOrThrow("QUANTITY"))); + sale.setProduct_rate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PRODUCT_RATE"))); + sale.setScan_ean_code_or_enterd_ean_code(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EAN_CODE"))); + list.add(sale); + + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list; + } + + } catch (Exception e) { + ////////test("Exception Brands", e.toString()); + return list; + } + return list; + } + + + //check if data exists for product in T_StockSummary + public boolean isTStockSummaryProductFilled(int productId) { + boolean filled = false; + Cursor dbcursor = null; + try { + dbcursor = db.rawQuery("select * from " + CommonString.T_StockSummary + " where " + CommonString.KEY_ProductId + "=" + productId + "", null); + if (dbcursor != null) { + dbcursor.moveToFirst(); + int icount = dbcursor.getCount(); + dbcursor.close(); + if (icount > 0) { + filled = true; + } else { + filled = false; + } + } + + } catch (Exception e) { + ////////test("Exception--", e.toString()); + return filled; + } + + return filled; + } + + private long updateTStockData(int stock, String type, int productId, boolean completeFlag, String visit_date) { + long id = 0; + + ContentValues values = new ContentValues(); + try { + + values.put("VisitDate", visit_date); + if (type.equalsIgnoreCase(CommonString.SALEABLE)) { + values.put(CommonString.KEY_SALEABLE_IN, stock); + values.put(CommonString.KEY_SaleableBalance, stock); + if (completeFlag) { + values.put("SaleableStatus", "Complete"); + } + } else if (type.equalsIgnoreCase(CommonString.SAMPLE)) { + values.put(CommonString.KEY_SAMPLE_IN, stock); + values.put(CommonString.KEY_SampleBalance, stock); + if (completeFlag) { + values.put("SampleStatus", "Complete"); + } + + } else if (type.equalsIgnoreCase(CommonString.TESTER)) { + values.put(CommonString.KEY_TESTER_IN, stock); + values.put(CommonString.KEY_TesterBalance, stock); + if (completeFlag) { + values.put("TesterStatus", "Complete"); + } + } else { + values.put(CommonString.KEY_GWP_IN, stock); + values.put(CommonString.KEY_GWP_BALANCE, stock); + if (completeFlag) { + values.put("GwpStatus", "Complete"); + } + } + + if (!db.isOpen()) { + open(); + } + + id = db.update(CommonString.T_StockSummary, values, CommonString.KEY_ProductId + "=" + productId + "", null); + + } catch (Exception ex) { + return 0; + } + + return id; + } + + //insert T_Stock_summary row if size zero + private boolean insertTStockSummaryData(TStockSummary stockObj, Integer productId, String counter_id, String type, int stock, boolean completeFlag, String visitDate) { + ContentValues values = new ContentValues(); + try { + db.beginTransaction(); + values.put("Id", stockObj.getId()); + values.put("CounterId", counter_id); + values.put("ProductId", productId); + values.put("VisitDate", visitDate); + + values.put("SaleableStatus", stockObj.getSaleableStatus()); + values.put("TesterStatus", stockObj.getTesterStatus()); + values.put("SampleStatus", stockObj.getSampleStatus()); + values.put("GwpStatus", stockObj.getGwpStatus()); + + if (type.equalsIgnoreCase(CommonString.SALEABLE)) { + values.put("SaleableIn", stock); + values.put("SaleableBalance", stock); + if (completeFlag) { + values.put("SaleableStatus", "Complete"); + } + } else { + values.put("SaleableIn", 0); + values.put("SaleableBalance", 0); + } + + if (type.equalsIgnoreCase(CommonString.SAMPLE)) { + values.put("SampleIn", stock); + values.put("SampleBalance", stock); + if (completeFlag) { + values.put("SampleStatus", "Complete"); + } + } else { + values.put("SampleIn", 0); + values.put("SampleBalance", 0); + } + + if (type.equalsIgnoreCase(CommonString.TESTER)) { + values.put("TesterIn", stock); + values.put("TesterBalance", stock); + if (completeFlag) { + values.put("TesterStatus", "Complete"); + } + } else { + values.put("TesterIn", 0); + values.put("TesterBalance", 0); + } + + if (type.equalsIgnoreCase(CommonString.GWP)) { + values.put("GwpIn", stock); + values.put("GwpBalance", stock); + if (completeFlag) { + values.put("GwpStatus", "Complete"); + } + } else { + values.put("GwpIn", 0); + values.put("GwpBalance", 0); + } + + values.put("SaleableOut", 0); + values.put("SaleableDamage", 0); + values.put("TesterOut", 0); + values.put("TesterDamage", 0); + values.put("SampleOut", 0); + values.put("SampleDamage", 0); + values.put("GwpOut", 0); + values.put("GwpDamage", 0); + + if (!db.isOpen()) { + open(); + } + + long id = db.insert("T_StockSummary", null, values); + if (id == -1) { + throw new Exception(); + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ex.fillInStackTrace(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + + public ArrayList getlistAllUserIdData(String visitDate, String user_id, boolean flag_forspin) { + + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + + if (flag_forspin) { + if (visitDate != null) { + dbcursor = db.rawQuery("select * from User_login where " + CommonString.KEY_VISIT_DATE + "<>'" + visitDate + "'and " + CommonString.KEY_USER_NAME + "='" + user_id + "'", null); + } else { + dbcursor = db.rawQuery("select * from User_login where " + CommonString.KEY_USER_NAME + "='" + user_id + "'", null); + } + } else { + if (visitDate != null) { + dbcursor = db.rawQuery("select * from User_login where " + CommonString.KEY_VISIT_DATE + "='" + visitDate + "'and " + CommonString.KEY_USER_NAME + "='" + user_id + "'", null); + } else { + dbcursor = db.rawQuery("select * from User_login where " + CommonString.KEY_USER_NAME + "='" + user_id + "'", null); + } + } + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + LoginGetterSetter ch = new LoginGetterSetter(); + ch.setUserId(dbcursor.getString(dbcursor.getColumnIndexOrThrow("USER_ID"))); + ch.setImg(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_IMAGE))); + ch.setPassword(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_PASSWORD))); + ch.setUser_checkout(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_USER_Checkout))); + list.add(ch); + dbcursor.moveToNext(); + } + dbcursor.close(); + return list; + } + } catch (Exception e) { + return list; + } + return list; + } + + + public boolean insertBaProfileValue(MasterBAProfileGetterSetter cst) { + db.delete("Master_BAProfile", null, null); + ContentValues values = new ContentValues(); + List data = cst.getMasterBAProfile(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("Answer", data.get(i).getAnswer()); + values.put("AnswerId", data.get(i).getAnswerId()); + values.put("EmpId", data.get(i).getEmpId()); + values.put("QuestionId", data.get(i).getQuestionId()); + values.put("OthersValue", data.get(i).getOthersValue()); + long id = db.insert("Master_BAProfile", null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ex.fillInStackTrace(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + public ArrayList getSaveServerData(String categoryId, String userId) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + + try { + dbcursor = db.rawQuery("select distinct mp.QuestionId as QuestionId,mp.Question as Question,mb.AnswerId as AnswerId,mb.Answer as Answer," + "mp.QuestionType as QuestionType" + ",mp.CategoryId as CategoryId,mb.OthersValue as OthersValue from (select distinct QuestionId, Question, QuestionType, CategoryId from Master_ProfileQuestion) as mp " + "inner join Master_BAProfile mb on mp.QuestionId=mb.QuestionId inner join BA_List bl on bl.EmpId=mb.EmpId " + "where mp.CategoryId='" + categoryId + "' and bl.UserName='" + userId + "'", null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + AuditDataGetterSetter sb = new AuditDataGetterSetter(); + + sb.setQUESTION_ID(dbcursor.getString(dbcursor.getColumnIndexOrThrow("QuestionId"))); + sb.setQUESTION(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Question"))); + sb.setANSWER_ID(dbcursor.getString(dbcursor.getColumnIndexOrThrow("AnswerId"))); + sb.setANSWER(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Answer"))); + sb.setMENU_ID(dbcursor.getString(dbcursor.getColumnIndexOrThrow("CategoryId"))); + sb.setANSWER_TYPE(dbcursor.getString(dbcursor.getColumnIndexOrThrow("QuestionType"))); + sb.setSpin_others_for_edt(dbcursor.getString(dbcursor.getColumnIndexOrThrow("OthersValue"))); + + list.add(sb); + dbcursor.moveToNext(); + } + dbcursor.close(); + return list; + } + } catch (Exception e) { + + return list; + } + return list; + } + + + public long update_ba_counter_img(String storeid, String visit_date, String user_Id, String TransId) { + long l = 0; + try { + ContentValues values = new ContentValues(); + values.put("UPLOAD_STATUS", CommonString.KEY_Y); + + if (!db.isOpen()) { + open(); + } + l = db.update(CommonString.TABLE_COUNTER_IMAGE_DATA, values, CommonString.KEY_COUNTER_ID + "=" + storeid + " AND " + CommonString.KEY_VISIT_DATE + " ='" + visit_date + "'AND USER_ID='" + user_Id + "'and UNIQUE_CODE='" + TransId + "'", null); + + } catch (Exception e) { + e.fillInStackTrace(); + } + return l; + } + + public JourneyPlan getba_counter_img(String counterId, String visite_date, String user_Id, String TRansId) { + JourneyPlan sale = new JourneyPlan(); + Cursor dbcursor = null; + try { + + if (TRansId != null) { + dbcursor = db.rawQuery("SELECT * from " + CommonString.TABLE_COUNTER_IMAGE_DATA + " WHERE " + CommonString.KEY_VISIT_DATE + "='" + visite_date + "'AND " + CommonString.KEY_COUNTER_ID + "=" + counterId + " and UNIQUE_CODE='" + TRansId + "'", null); + + } else { + dbcursor = db.rawQuery("SELECT * from " + CommonString.TABLE_COUNTER_IMAGE_DATA + " WHERE " + CommonString.KEY_VISIT_DATE + "='" + visite_date + "'AND " + CommonString.KEY_COUNTER_ID + "=" + counterId + " and UPLOAD_STATUS='N'", null); + } + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + sale.setCounter_img_onefor_ba(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Counter_Img_One"))); + sale.setCounter_img_two_for_ba(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Counter_Img_Two"))); + sale.setUpload_status_ba(dbcursor.getString(dbcursor.getColumnIndexOrThrow("UPLOAD_STATUS"))); + sale.setTransId(dbcursor.getString(dbcursor.getColumnIndexOrThrow("UNIQUE_CODE"))); + + sale.setPresetup_img_one_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Pre_Setup_Img_One"))); + sale.setPresetup_img_two_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Pre_Setup_Img_Two"))); + sale.setPostsetup_img_one_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Post_Setup_Img_One"))); + sale.setPostsetup_img_two_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Post_Setup_Img_Two"))); + + dbcursor.moveToNext(); + } + + dbcursor.close(); + return sale; + } + + } catch (Exception e) { + ////////test("Exception Brands", e.toString()); + return sale; + } + return sale; + } + + + public ArrayList getba_counterimgList(String counterId, String visite_date, boolean previous_date) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + + if (previous_date) { + dbcursor = db.rawQuery("SELECT * from " + CommonString.TABLE_COUNTER_IMAGE_DATA + " WHERE " + CommonString.KEY_VISIT_DATE + "<>'" + visite_date + "'AND " + CommonString.KEY_COUNTER_ID + "=" + counterId + " and UPLOAD_STATUS='N'", null); + } else { + dbcursor = db.rawQuery("SELECT * from " + CommonString.TABLE_COUNTER_IMAGE_DATA + " WHERE " + CommonString.KEY_VISIT_DATE + "='" + visite_date + "'AND " + CommonString.KEY_COUNTER_ID + "=" + counterId + " and UPLOAD_STATUS='N'", null); + + } + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + JourneyPlan sale = new JourneyPlan(); + sale.setCounter_img_onefor_ba(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Counter_Img_One"))); + sale.setCounter_img_two_for_ba(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Counter_Img_Two"))); + sale.setUpload_status_ba(dbcursor.getString(dbcursor.getColumnIndexOrThrow("UPLOAD_STATUS"))); + sale.setTransId(dbcursor.getString(dbcursor.getColumnIndexOrThrow("UNIQUE_CODE"))); + + sale.setPresetup_img_one_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Pre_Setup_Img_One"))); + sale.setPresetup_img_two_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Pre_Setup_Img_Two"))); + sale.setPostsetup_img_one_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Post_Setup_Img_One"))); + sale.setPostsetup_img_two_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Post_Setup_Img_Two"))); + sale.setUser_type(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_USER_TYPE))); + sale.setUserId(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_USER_ID))); + sale.setVisitDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_VISIT_DATE))); + list.add(sale); + + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list; + } + + } catch (Exception e) { + ////////test("Exception Brands", e.toString()); + return list; + } + + return list; + } + + + public ArrayList getlistLoginData(String visitDate, String user_Id, String counterId) { + + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + if (user_Id != null) { + dbcursor = db.rawQuery("select distinct u.ID as ID,u.PASSWORD as PASSWORD,u.USER_ID as USER_ID,u.Visit_Date as Visit_Date," + "u.STORE_IMAGE as STORE_IMAGE,u.LoginTime as LoginTime,u.RIGHTNAME as RIGHTNAME,u.UserCheckout as UserCheckout," + "u.MPIN as MPIN,b.ProfilePath as ProfilePath,b.Profile_Pic as Profile_Pic from " + "User_login u inner join BA_List b on b.UserName=u.USER_ID where Visit_Date='" + visitDate + "' and u.USER_ID='" + user_Id + "' and b.CounterId=" + counterId + "", null); + + } else { + dbcursor = db.rawQuery("select distinct u.ID as ID,u.PASSWORD as PASSWORD,u.USER_ID as USER_ID,u.Visit_Date as Visit_Date," + "u.STORE_IMAGE as STORE_IMAGE,u.LoginTime as LoginTime,u.RIGHTNAME as RIGHTNAME,u.UserCheckout as UserCheckout," + "u.MPIN as MPIN,b.ProfilePath as ProfilePath,b.Profile_Pic as Profile_Pic from " + "User_login u inner join BA_List b on b.UserName=u.USER_ID where Visit_Date='" + visitDate + "' and b.CounterId=" + counterId + "", null); + } + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + LoginGetterSetter ch = new LoginGetterSetter(); + ch.setUserId(dbcursor.getString(dbcursor.getColumnIndexOrThrow("USER_ID"))); + ch.setImg(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_IMAGE))); + ch.setUserType(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_USER_TYPE))); + ch.setMpin(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_MPIN))); + ch.setUser_checkout(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_USER_Checkout))); + ch.setProfilePath(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ProfilePath"))); + ch.setProfile_Pic(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Profile_Pic"))); + list.add(ch); + dbcursor.moveToNext(); + } + dbcursor.close(); + return list; + } + } catch (Exception e) { + return list; + } + return list; + } + + public JourneyPlan getspecific_storenamewith_counter_name(String date, String counter_id, String userId) { + JourneyPlan sb = new JourneyPlan(); + Cursor dbcursor = null; + try { + + dbcursor = db.rawQuery("SELECT * from Mapping_JourneyPlan where VisitDate='" + date + "' and CounterId=" + counter_id + " and UserId='" + userId + "'", null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + + sb.setCounterId((dbcursor.getInt(dbcursor.getColumnIndexOrThrow("CounterId")))); + sb.setStoreName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("StoreName"))); + sb.setCounterName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("CounterName"))); + sb.setAddress((dbcursor.getString(dbcursor.getColumnIndexOrThrow("Address")))); + sb.setCityName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("CityName"))); + + dbcursor.moveToNext(); + } + dbcursor.close(); + return sb; + } + + } catch (Exception e) { + ////////test("Exception get JCP!", e.toString()); + return sb; + } + + return sb; + } + + public long updateImageLoginData(String userId, String strImg) { + long l = 0; + try { + ContentValues values = new ContentValues(); + values.put("STORE_IMAGE", strImg); + if (!db.isOpen()) { + open(); + } + l = db.update("User_login", values, "USER_ID='" + userId + "'", null); + } catch (Exception e) { + e.fillInStackTrace(); + } + return l; + } + + public long updateLoginMpnData(String userId, String mpin) { + long l = 0; + try { + ContentValues values = new ContentValues(); + values.put("MPIN", mpin); + values.put("UserCheckout", "0"); + if (!db.isOpen()) { + open(); + } + l = db.update("User_login", values, "USER_ID='" + userId + "'", null); + } catch (Exception e) { + e.fillInStackTrace(); + } + + return l; + } + + public ArrayList gettop10Value(String counterId) { + Cursor cursordata = null; + ArrayList auditData = new ArrayList<>(); + try { + if (counterId == null) { + cursordata = db.rawQuery("select * FROM Report_Top10Value", null); + } else { + cursordata = db.rawQuery("select * FROM Report_Top10Value where CounterId=" + counterId + "", null); + } + + if (cursordata != null) { + cursordata.moveToFirst(); + while (!cursordata.isAfterLast()) { + ReportTop10Value sb = new ReportTop10Value(); + sb.setBrandName(cursordata.getString(cursordata.getColumnIndexOrThrow("BrandName"))); + sb.setSubBrandName(cursordata.getString(cursordata.getColumnIndexOrThrow("SubBrandName"))); + sb.setReferenceName(cursordata.getString(cursordata.getColumnIndexOrThrow("ReferenceName"))); + sb.setEanCode(cursordata.getString(cursordata.getColumnIndexOrThrow("EanCode"))); + sb.setProductName(cursordata.getString(cursordata.getColumnIndexOrThrow("ProductName"))); + sb.setMTDValue((cursordata.getDouble(cursordata.getColumnIndexOrThrow("MTDValue")))); + sb.setAvgPerDayValue((cursordata.getDouble(cursordata.getColumnIndexOrThrow("AvgPerDayValue")))); + auditData.add(sb); + cursordata.moveToNext(); + } + cursordata.close(); + } + + } catch (Exception ex) { + + } + return auditData; + } + + + public ArrayList gettop10Valume(String counterId) { + Cursor cursordata = null; + ArrayList auditData = new ArrayList<>(); + try { + if (counterId == null) { + cursordata = db.rawQuery("select * FROM Report_Top10Volume", null); + } else { + cursordata = db.rawQuery("select * FROM Report_Top10Volume where CounterId=" + counterId + "", null); + } + + if (cursordata != null) { + cursordata.moveToFirst(); + while (!cursordata.isAfterLast()) { + ReportTop10Value sb = new ReportTop10Value(); + sb.setBrandName(cursordata.getString(cursordata.getColumnIndexOrThrow("BrandName"))); + sb.setSubBrandName(cursordata.getString(cursordata.getColumnIndexOrThrow("SubBrandName"))); + sb.setReferenceName(cursordata.getString(cursordata.getColumnIndexOrThrow("ReferenceName"))); + sb.setEanCode(cursordata.getString(cursordata.getColumnIndexOrThrow("EanCode"))); + sb.setProductName(cursordata.getString(cursordata.getColumnIndexOrThrow("ProductName"))); + sb.setMTDValue((cursordata.getDouble(cursordata.getColumnIndexOrThrow("MTDVolume")))); + sb.setAvgPerDayValue((cursordata.getDouble(cursordata.getColumnIndexOrThrow("AvgPerDayVolume")))); + auditData.add(sb); + cursordata.moveToNext(); + } + cursordata.close(); + } + + } catch (Exception ex) { + + } + return auditData; + } + + public boolean isBreakManagmentEndTymChecked(String visit_date, String user_id, String counter_Id) { + boolean filled = false; + Cursor dbcursor = null; + try { + + dbcursor = db.rawQuery(" SELECT * from BREAK_MANAGEMENT_TABLE WHERE USER_ID='" + user_id + "'and " + CommonString.KEY_COUNTER_ID + "=" + counter_Id + " and " + CommonString.KEY_VISIT_DATE + "='" + visit_date + "'", null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + String StartTym = dbcursor.getString(dbcursor.getColumnIndexOrThrow("StartTym")); + String EndTym = dbcursor.getString(dbcursor.getColumnIndexOrThrow("EndTym")); + if (!StartTym.equals("") && EndTym.equals("")) { + filled = true; + break; + } else { + filled = false; + } + dbcursor.moveToNext(); + } + dbcursor.close(); + } + } catch (Exception e) { + ////////test("Exception--", e.toString()); + return filled; + } + return filled; + } + + + // NEERAJ CODE ADDED + public ArrayList getinwardStockTransactionList(String counter_id, String date) { + Cursor dbcursor = null; + ArrayList list = new ArrayList<>(); + long id = 0; + try { + dbcursor = db.rawQuery("select * from " + CommonString.TABLE_INSERT_INWARD_STOCK_TRANSACTION + " where " + CommonString.KEY_VISIT_DATE + " <> '" + date + "' and " + CommonString.KEY_COUNTER_ID + " =" + counter_id + "", null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + ProductMaster sb = new ProductMaster(); + sb.setActualQty(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_ACTUAL_QTY))); + sb.setConsumer_qty(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_INVOICE_QTY))); + sb.setTransaction_Id(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_TRANSACTION_ID))); + sb.setUpload_status(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_UPLOAD_STATUS))); + list.add(sb); + dbcursor.moveToNext(); + } + dbcursor.close(); + return list; + } + } catch (Exception e) { + + return list; + } + + return list; + } + + + public ArrayList getManualInwardStockList(String counter_id, String visit_date) { + ArrayList list = new ArrayList<>(); + + Cursor dbcursor = null; + try { + + dbcursor = db.rawQuery("select distinct " + CommonString.KEY_INVOICE_NUMBER + "," + CommonString.KEY_UPLOAD_STATUS + "," + CommonString.KEY_INVOICE_TYPE + "," + CommonString.KEY_INVOICE_DATE + "," + CommonString.KEY_INVOICE_STATUS + "," + CommonString.KEY_SOURCE + "," + CommonString.KEY_COUNTER_CONFIRM + ",count(" + CommonString.KEY_ProductId + ") as NoofLine,sum(" + CommonString.KEY_TOTAL_AMOUNT + ") as FinalAmount" + " from " + CommonString.TABLE_INSERT_MANUAL_INWARD_TRANSACTION + " where " + CommonString.KEY_COUNTER_ID + " =" + counter_id + " and " + CommonString.KEY_VISIT_DATE + " <> '" + visit_date + "' group by InvoiceNo", null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + TCounterInvoice sb = new TCounterInvoice(); + sb.setInvoiceNo(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_INVOICE_NUMBER))); + sb.setInvoiceDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_INVOICE_DATE))); + sb.setInvoiceType(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_INVOICE_TYPE))); + sb.setInvoice_img(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_INVOICE_IMG))); + String val = dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_COUNTER_CONFIRM)); + String value = dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_INVOICE_STATUS)); + + if (val == null || val.equalsIgnoreCase("0")) { + sb.setCounterConfirm(false); + } else { + sb.setCounterConfirm(true); + } + + sb.setApproved_line(dbcursor.getString(dbcursor.getColumnIndexOrThrow("NoofLine"))); + + if (value == null || value.equalsIgnoreCase("0")) { + sb.setInvoiceStatus(false); + } else { + sb.setInvoiceStatus(true); + } + + sb.setNo_ofLine(dbcursor.getString(dbcursor.getColumnIndexOrThrow("NoofLine"))); + sb.setFinalAmount(dbcursor.getString(dbcursor.getColumnIndexOrThrow("FinalAmount"))); + sb.setSource(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_SOURCE))); + sb.setUpload_status(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_UPLOAD_STATUS))); + + list.add(sb); + dbcursor.moveToNext(); + } + dbcursor.close(); + return list; + } + } catch (Exception e) { + + return list; + } + return list; + } + + + public void deleteInwardStockData(String counter_id, String visit_date) { + try { + if (!db.isOpen()) { + open(); + } + db.delete(CommonString.TABLE_INSERT_INWARD_STOCK_TRANSACTION, CommonString.KEY_COUNTER_ID + " =" + counter_id + " and " + CommonString.KEY_VISIT_DATE + " <>'" + visit_date + "'", null); + } catch (Exception e) { + e.fillInStackTrace(); + } + } + + public void deleteManualStockData(String counter_id, String visit_date) { + try { + if (!db.isOpen()) { + open(); + } + db.delete(CommonString.TABLE_INSERT_MANUAL_INWARD_TRANSACTION, CommonString.KEY_COUNTER_ID + " =" + counter_id + " and " + CommonString.KEY_VISIT_DATE + " <>'" + visit_date + "'", null); + } catch (Exception e) { + e.fillInStackTrace(); + } + } + + public GroomingGetterSetter getGroomedList(String counter_Id, String user_Id, String visit_date) { + GroomingGetterSetter sb = new GroomingGetterSetter(); + Cursor dbcursor = null; + try { + + dbcursor = db.rawQuery("Select * from " + CommonString.TABLE_GROOMED_IMAGE_DATA + " where " + CommonString.KEY_COUNTER_ID + "=" + counter_Id + " and " + CommonString.KEY_USER_ID + "='" + user_Id + "'And " + CommonString.KEY_VISIT_DATE + "='" + visit_date + "'", null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + sb.setUser_Id(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_USER_ID))); + sb.setMorning_groom_img_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Mornning_groomed_img"))); + sb.setMorning_groom_time_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Mornning_groomed_time"))); + sb.setNoon_groom_img_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Noon_groomed_img"))); + sb.setNoon_groom_time_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Noon_groomed_time"))); + sb.setEvenning_groom_img_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Evening_groomed_img"))); + sb.setEvenning_groom_time_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Evening_groomed_time"))); + + dbcursor.moveToNext(); + } + + dbcursor.close(); + return sb; + } + } catch (Exception e) { + return sb; + } + + return sb; + } + + public long update_groomed_img(String storeid, String visit_date, String user_Id) { + long l = 0; + try { + ContentValues values = new ContentValues(); + values.put("UPLOAD_STATUS", CommonString.KEY_Y); + if (!db.isOpen()) { + open(); + } + l = db.update(CommonString.TABLE_GROOMED_IMAGE_DATA, values, CommonString.KEY_COUNTER_ID + "=" + storeid + " AND " + CommonString.KEY_VISIT_DATE + " ='" + visit_date + "'AND " + CommonString.KEY_USER_ID + "='" + user_Id + "'", null); + + } catch (Exception e) { + e.fillInStackTrace(); + } + + return l; + } + + public boolean isCounterChecked(String visit_date, String counter_Id) { + boolean filled = false; + Cursor dbcursor = null; + try { + + dbcursor = db.rawQuery("Select * FROM " + CommonString.TABLE_COUNTER_IMAGE_DATA + "" + " where " + CommonString.KEY_VISIT_DATE + " ='" + visit_date + "' and " + CommonString.KEY_COUNTER_ID + " =" + counter_Id + "", null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + String counterimg_one = dbcursor.getString(dbcursor.getColumnIndexOrThrow("Counter_Img_One")); + if (!counterimg_one.equals("")) { + filled = true; + break; + } else { + filled = false; + } + dbcursor.moveToNext(); + } + + dbcursor.close(); + } + } catch (Exception e) { + ////////test("Exception--", e.toString()); + return filled; + } + return filled; + } + + public boolean isCounterCheckedforme(String visit_date, String counter_Id) { + boolean filled = false; + Cursor dbcursor = null; + try { + + dbcursor = db.rawQuery("Select * FROM " + CommonString.TABLE_COUNTER_IMAGE_DATA + "" + " where " + CommonString.KEY_VISIT_DATE + " ='" + visit_date + "' and " + CommonString.KEY_COUNTER_ID + " =" + counter_Id + "", null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + String counterimg_one = dbcursor.getString(dbcursor.getColumnIndexOrThrow("Pre_Setup_Img_One")); + if (!counterimg_one.equals("")) { + filled = true; + break; + } else { + filled = false; + } + dbcursor.moveToNext(); + } + + dbcursor.close(); + } + } catch (Exception e) { + ////////test("Exception--", e.toString()); + return filled; + } + return filled; + } + + public String isGroomedChecked(String counter_Id, String user_name, String visit_date) { + String filled = ""; + Cursor dbcursor = null; + try { + + dbcursor = db.rawQuery("Select * from " + CommonString.TABLE_GROOMED_IMAGE_DATA + " where " + CommonString.KEY_COUNTER_ID + "=" + counter_Id + " and " + CommonString.KEY_USER_ID + "='" + user_name + "'And " + CommonString.KEY_VISIT_DATE + "='" + visit_date + "'", null); + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + String morng_img = dbcursor.getString(dbcursor.getColumnIndexOrThrow("Mornning_groomed_img")); + String noon_img = dbcursor.getString(dbcursor.getColumnIndexOrThrow("Noon_groomed_img")); + String evening_img = dbcursor.getString(dbcursor.getColumnIndexOrThrow("Evening_groomed_img")); + if (!morng_img.equals("") && !noon_img.equals("") && !evening_img.equals("")) { + filled = "Green"; + break; + } else if (!morng_img.equals("") && !noon_img.equals("")) { + filled = "Amber"; + break; + } else if (!noon_img.equals("") && !evening_img.equals("")) { + filled = "Amber"; + break; + } else { + filled = ""; + } + + dbcursor.moveToNext(); + } + + dbcursor.close(); + } + } catch (Exception e) { + ////////test("Exception--", e.toString()); + return filled; + } + return filled; + } + + + public long updateNotificationDetails(String readStatus, String keyId) { + long l = 0; + try { + ContentValues values = new ContentValues(); + values.put(CommonString.KEY_READ_STATUS, readStatus); + if (!db.isOpen()) { + open(); + } + l = db.update(CommonString.TABLE_NOTIFICATION_DATA, values, CommonString.KEY_ID + " ='" + keyId + "'", null); + } catch (Exception e) { + e.fillInStackTrace(); + } + + return l; + } + + + public ArrayList getNotificationList(String userId) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + + dbcursor = getReadableDatabase().rawQuery("select * from Notification_Data WHERE ID NOT IN ( SELECT ID FROM Notification_User_Table WHERE User_Id='" + userId + "')", null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + NotificationData notifyData = new NotificationData(); + notifyData.setId(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_ID))); + notifyData.setBody(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_BODY))); + notifyData.setPath(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_PATH))); + notifyData.setTitle(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_TITLE))); + notifyData.setVisited_date(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_VISIT_DATE))); + notifyData.setType(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_TYPE))); + notifyData.setRead_status(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_READ_STATUS))); + list.add(notifyData); + dbcursor.moveToNext(); + } + dbcursor.close(); + return list; + } + + } catch (Exception e) { + ////////test("Exception Brands", e.toString()); + return list; + } + return list; + } + + public boolean insertPromoOffers(MasterBAProfileGetterSetter cst) { + db.delete("Master_PromoOffers", null, null); + ContentValues values = new ContentValues(); + List data = cst.getMasterPromoOffers(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("PromoId", data.get(i).getPromoId()); + values.put("PromoPath", data.get(i).getPromoPath()); + values.put("PromoOfferTab", data.get(i).getPromoOfferTab()); + values.put("PromoOfferMobile", data.get(i).getPromoOfferMobile()); + values.put("Description", data.get(i).getDescription()); + values.put("StartDate", data.get(i).getStartDate()); + values.put("EndDate", data.get(i).getEndDate()); + if (!db.isOpen()) { + open(); + } + long id = db.insert("Master_PromoOffers", null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ex.fillInStackTrace(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + + public ArrayList getmaterPromoOffers() { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + dbcursor = db.rawQuery("Select * from Master_PromoOffers", null); + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + MasterPromoOffer sb = new MasterPromoOffer(); + sb.setPromoId(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PromoId"))); + sb.setPromoPath(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PromoPath"))); + sb.setPromoOfferTab(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PromoOfferTab"))); + sb.setPromoOfferMobile(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PromoOfferMobile"))); + + sb.setDescription(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Description"))); + sb.setStartDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("StartDate"))); + sb.setEndDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EndDate"))); + list.add(sb); + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list; + } + } catch (Exception e) { + return list; + } + + return list; + } + + public MasterPromoOffer getmaterPromoOffersbypromoId(String promoId) { + MasterPromoOffer sb = new MasterPromoOffer(); + Cursor dbcursor = null; + try { + dbcursor = db.rawQuery("Select * from Master_PromoOffers where PromoId='" + promoId + "'", null); + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + sb.setPromoId(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PromoId"))); + sb.setPromoPath(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PromoPath"))); + sb.setPromoOfferTab(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PromoOfferTab"))); + sb.setPromoOfferMobile(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PromoOfferMobile"))); + sb.setDescription(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Description"))); + sb.setStartDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("StartDate"))); + sb.setEndDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EndDate"))); + + dbcursor.moveToNext(); + } + + dbcursor.close(); + return sb; + } + } catch (Exception e) { + return sb; + } + + return sb; + } + + public int receipt_count_userwise(String visit_date, String counter_Id, String user_name) { + int filled = 0; + Cursor dbcursor = null; + try { + + dbcursor = db.rawQuery("Select count(RECCEPT_COUNT) as RECCEPT_COUNT from SALE_TRACKING_HEADER_TABLE " + " where " + CommonString.KEY_VISIT_DATE + " ='" + visit_date + "' and " + CommonString.KEY_COUNTER_ID + " =" + counter_Id + " and USER_ID='" + user_name + "' group by USER_ID", null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + filled = dbcursor.getInt(dbcursor.getColumnIndexOrThrow("RECCEPT_COUNT")); + dbcursor.moveToNext(); + } + + dbcursor.close(); + } + } catch (Exception e) { + ////////test("Exception--", e.toString()); + return filled; + } + return filled; + } + + + public boolean isGroomedCheckedfornotification(String visit_date, String counter_Id, String user_Id, String coulmn_name) { + boolean filled = false; + Cursor dbcursor = null; + try { + + dbcursor = db.rawQuery("Select * FROM " + CommonString.TABLE_GROOMED_IMAGE_DATA + "" + " where " + CommonString.KEY_VISIT_DATE + " ='" + visit_date + "' and " + CommonString.KEY_COUNTER_ID + " =" + counter_Id + " and " + CommonString.KEY_USER_ID + "='" + user_Id + "'", null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + String groomed_img = dbcursor.getString(dbcursor.getColumnIndexOrThrow(coulmn_name)); + if (groomed_img != null && !groomed_img.equals("")) { + filled = true; + break; + } else { + filled = false; + break; + } + } + + dbcursor.close(); + } + } catch (Exception e) { + ////////test("Exception--", e.toString()); + return filled; + } + return filled; + } + + public boolean isRetailExcellenceFilled(String visit_date, String counter_Id, String user_Id) { + boolean filled = false; + Cursor dbcursor = null; + try { + + dbcursor = db.rawQuery("Select * FROM " + CommonString.Table_Retail_Excellence_Child + "" + " where " + CommonString.KEY_VISIT_DATE + " ='" + visit_date + "' and " + CommonString.KEY_COUNTER_ID + " =" + counter_Id + " and " + "USER_ID" + "='" + user_Id + "'", null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + String answer = dbcursor.getString(dbcursor.getColumnIndexOrThrow("Answer")); + if (answer != null && !answer.equals("")) { + filled = true; + break; + } else { + filled = false; + break; + } + } + + dbcursor.close(); + } + } catch (Exception e) { + ////////test("Exception--", e.toString()); + return filled; + } + return filled; + } + + + public long insertStockTransactionMasterData(String counterId, String visit_date, String userId, String stockType, SaleableGetterSetter stock, String regular_stock) { + db.delete(CommonString.TABLE_TRANSACTION_WISE_MASTER_TABLE, CommonString.KEY_VISIT_DATE + " <>'" + visit_date + "'", null); + db.delete(CommonString.TABLE_TRANSACTION_DATA, CommonString.KEY_VISIT_DATE + " <>'" + visit_date + "'", null); + db.delete(CommonString.TABLE_RETURNTO_DISTRIBUTOR_DATA, CommonString.KEY_VISIT_DATE + " <>'" + visit_date + "'", null); + + ContentValues values = new ContentValues(); + ContentValues returntoDbvalues = new ContentValues(); + ContentValues values1 = new ContentValues(); + List productList = stock.getProductList(); + long masterreturn = 0, l1 = 0, l2 = 0; + try { + db.beginTransaction(); + values1.put(CommonString.KEY_UUID, stock.getTransactionId()); + values1.put(CommonString.KEY_USER_ID, userId); + values1.put(CommonString.KEY_COUNTER_ID, counterId); + values1.put(CommonString.KEY_VISIT_DATE, visit_date); + values1.put(CommonString.KEY_STOCK_TYPE, stockType); + values1.put(CommonString.KEY_ENTRY_TYPE, regular_stock); + values1.put(CommonString.KEY_STATUS, CommonString.KEY_N); + if (!db.isOpen()) { + open(); + } + masterreturn = db.insert(CommonString.TABLE_TRANSACTION_WISE_MASTER_TABLE, null, values1); + if (stockType != null && stockType.equalsIgnoreCase(CommonString.RETURNTO_DB)) { + for (int i = 0; i < productList.size(); i++) { + returntoDbvalues.put(CommonString.KEY_MASTER_TRANSACTION_ID, masterreturn); + returntoDbvalues.put(CommonString.KEY_UUID, stock.getTransactionId()); + returntoDbvalues.put(CommonString.KEY_USER_ID, userId); + returntoDbvalues.put(CommonString.KEY_STOCK_TYPE, stockType); + returntoDbvalues.put(CommonString.KEY_COUNTER_ID, counterId); + returntoDbvalues.put(CommonString.KEY_VISIT_DATE, visit_date); + returntoDbvalues.put(CommonString.KEY_STATUS, CommonString.KEY_N); + returntoDbvalues.put(CommonString.KEY_ProductId, productList.get(i).getProductId()); + returntoDbvalues.put(CommonString.KEY_STOCK, productList.get(i).getStock()); + if (!db.isOpen()) { + open(); + } + l1 = db.insert(CommonString.TABLE_RETURNTO_DISTRIBUTOR_DATA, null, returntoDbvalues); + } + } else { + for (int i = 0; i < productList.size(); i++) { + values.put(CommonString.KEY_UUID, stock.getTransactionId()); + values.put(CommonString.KEY_USER_ID, userId); + values.put(CommonString.KEY_COUNTER_ID, counterId); + values.put(CommonString.KEY_VISIT_DATE, visit_date); + values.put(CommonString.KEY_STOCK_TYPE, stockType); + values.put(CommonString.KEY_MASTER_TRANSACTION_ID, masterreturn); + values.put(CommonString.KEY_ProductId, productList.get(i).getProductId()); + values.put(CommonString.KEY_STATUS, CommonString.KEY_N); + values.put(CommonString.KEY_REASON_ID, productList.get(i).getReasonId()); + values.put(CommonString.KEY_IMAGE, productList.get(i).getImagePath()); + values.put(CommonString.KEY_ENTRY_TYPE, regular_stock); + + if (stockType.trim().equalsIgnoreCase(CommonString.DAMAGE) && regular_stock.trim().equalsIgnoreCase(CommonString.KEY_REGULAR)) { + if (stock.getProductList().get(i).getStock() == -1) { + values.put(CommonString.KEY_STOCK, 0); + } else { + values.put(CommonString.KEY_STOCK, stock.getProductList().get(i).getStock()); + } + } else if (regular_stock != null && regular_stock.trim().equalsIgnoreCase(CommonString.KEY_REGULAR)) { + values.put(CommonString.KEY_STOCK, stock.getProductList().get(i).getStock_receive() - stock.getProductList().get(i).getStock()); + } else { + if (stock.getProductList().get(i).getStock() == -1) { + values.put(CommonString.KEY_STOCK, 0); + } else { + values.put(CommonString.KEY_STOCK, stock.getProductList().get(i).getStock()); + } + } + if (!db.isOpen()) { + open(); + } + l2 = db.insert(CommonString.TABLE_TRANSACTION_DATA, null, values); + } + } + + closeDb(); + } catch (Exception ex) { + closeDb(); + ex.fillInStackTrace(); + } + + return l2; + } + + public long updateStockTransactionDataStatus(String transactionId) { + long l = 0; + ContentValues values = new ContentValues(); + try { + values.put(CommonString.KEY_STATUS, CommonString.KEY_Y); + if (!db.isOpen()) { + open(); + } + l = db.update(CommonString.TABLE_TRANSACTION_DATA, values, CommonString.KEY_UUID + "='" + transactionId + "'", null); + + } catch (Exception ex) { + ex.fillInStackTrace(); + + } + + return l; + + } + + public long updateVisibilityStatus(String transactionId) { + long l = 0; + ContentValues values = new ContentValues(); + try { + values.put(CommonString.KEY_STATUS, CommonString.KEY_Y); + if (!db.isOpen()) { + open(); + } + l = db.update(CommonString.Table_visibilisty, values, CommonString.KEY_UUID + "='" + transactionId + "'", null); + + } catch (Exception ex) { + ex.fillInStackTrace(); + } + return l; + } + + public long updateMasterTransactionDataStatus(String transactionId) { + long l = 0; + ContentValues values = new ContentValues(); + try { + values.put(CommonString.KEY_STATUS, CommonString.KEY_Y); + if (!db.isOpen()) { + open(); + } + l = db.update(CommonString.TABLE_TRANSACTION_WISE_MASTER_TABLE, values, CommonString.KEY_UUID + "='" + transactionId + "'", null); + + } catch (Exception ex) { + ex.fillInStackTrace(); + + } + return l; + + } + + public ServerTime getserverTym(String date) { + ServerTime sb = new ServerTime(); + Cursor dbcursor = null; + try { + + dbcursor = db.rawQuery("SELECT * from ServerTime where ServerDate='" + date + "'", null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + sb.setServerDate((dbcursor.getString(dbcursor.getColumnIndexOrThrow("ServerDate")))); + sb.setServerTime(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ServerTime"))); + dbcursor.moveToNext(); + } + + dbcursor.close(); + return sb; + } + + } catch (Exception e) { + ////////test("Exception get JCP!", e.toString()); + return sb; + } + + return sb; + } + + //ysy + public JourneyPlan getJCP() { + JourneyPlan sb = new JourneyPlan(); + Cursor dbcursor = null; + try { + + dbcursor = db.rawQuery("SELECT * from Mapping_JourneyPlan ", null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + + sb.setMID(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("MID"))); + sb.setBID(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("BID"))); + sb.setCounterGroupId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("CounterGroupId"))); + sb.setVisitDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("VisitDate"))); + + dbcursor.moveToNext(); + } + + dbcursor.close(); + return sb; + } + + } catch (Exception e) { + ////////test("Exception get JCP!", e.toString()); + return sb; + } + + return sb; + } + + public boolean CheckPreviousProduct(String visit_date) { + Cursor dbcursor = null; + boolean status = false; + try { + + dbcursor = db.rawQuery("select * from Product_Master where VisitDate<>'" + visit_date + "'", null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + int icount = dbcursor.getCount(); + dbcursor.close(); + + if (icount > 0) { + status = true; + } else { + status = false; + } + dbcursor.close(); + } + + } catch (Exception e) { + e.fillInStackTrace(); + } + + return status; + } + + + //get Signature Brand Sub Brand and Reference + public ArrayList getDamageBrandSubBrandReference(String counterGroup_Id, String counterId, String visit_date, String damagaged_stock) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + + if (damagaged_stock != null && damagaged_stock.equals("1")) { + dbcursor = db.rawQuery(" select distinct SubAxeName,SignatureName,BrandName,SubBrandName,ReferenceName from Product_Master p left join " + "(Select s.CounterId, s.ProductId, (s.SaleableBalance - ifnull(dm.DamageQty,0)) as SaleableBalance," + " (s.SaleableDamage + ifnull(dm.DamageQty,0)) - ifnull(rd.ReturnQty,0) as SaleableDamage , ifnull(dm.DamageQty,0) as DamageQty," + " ifnull(rd.ReturnQty,0) as ReturnQty from T_StockSummary s Left join " + "(Select ProductId, sum(DamageQty) as DamageQty from (select T.ProductId, T.Stock as DamageQty from TABLE_TRANSACTION_DATA T" + " INNER JOIN DR_TABLE_TRANSACTION_WISE_MASTER M ON T.MASTER_TRANSACTION_ID = M.MASTER_TRANSACTION_ID " + " where T.STOCK_TYPE='DAMAGE' AND T.Visit_Date ='" + visit_date + "' and T.COUNTER_ID =" + counterId + " Union All " + "SELECT ProductId, DamageQty from Damage_PreviousPending Where CounterId =" + counterId + " and Verify ='Pending') as t " + "Group by ProductId) as dm on s.ProductId = dm.ProductId Left Join " + "(Select ProductId, sum(ReturnQty) as ReturnQty from " + "(select ProductId, ReturnQty from Damage_ReturnToDistributor WHERE CounterId=" + counterId + " and VERIFY ='Pending' Union All " + "select ProductId, STOCK as ReturnQty from TABLE_RETURNTO_DISTRIBUTOR WHERE Visit_Date='" + visit_date + "' AND COUNTER_ID=" + counterId + ") as t " + "Group by ProductId ) as rd on trim(s.ProductId) = trim(rd.ProductId) " + "and s.CounterId ='" + counterId + "') as TS ON TS.ProductId = p.ProductId where (TS.SaleableBalance<>0 OR SaleableDamage<>0)", null); + + + } else if (damagaged_stock != null && damagaged_stock.equals("0")) { + ////for damaged return to distributor Query...... + dbcursor = db.rawQuery("select distinct SubAxeName,SignatureName,BrandName,SubBrandName,ReferenceName from " + "(select SubAxeName,SignatureName,BrandName,SubBrandName,ReferenceName, TS.SaleableDamage, ifnull(RN.ReturnQty,0) as ReturnQty, TS.SaleableDamage - ifnull(RN.ReturnQty,0) as DamageQty from Product_Master p" + " INNER JOIN T_StockSummary TS ON TS.ProductId = p.ProductId AND TS.SaleableDamage<>0 LEFT JOIN (SELECT ProductId, sum(ReturnQty) as ReturnQty FROM " + "(select trim(ProductId) as ProductId, ReturnQty from Damage_ReturnToDistributor WHERE CounterId =" + counterId + " and VERIFY ='Pending' Union " + "select trim(ProductId) as ProductId, Stock as ReturnQty from TABLE_RETURNTO_DISTRIBUTOR where COUNTER_ID =" + counterId + " and Visit_Date ='" + visit_date + "') AS T " + "GROUP BY ProductId) AS RN ON P.ProductId = RN.ProductId) as t " + "Where DamageQty >0 ", null); + + + } + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + ProductMaster sb = new ProductMaster(); + sb.setSignatureName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SignatureName"))); + sb.setSubBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SubBrandName"))); + sb.setSubAxeName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SubAxeName"))); + sb.setReferenceName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ReferenceName"))); + sb.setBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("BrandName"))); + + list.add(sb); + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list; + } + } catch (Exception e) { + + return list; + } + + return list; + } + + //get damage default data + //get damage default data + public ArrayList getDefaultDamageChildData(String counterId, String visit_date, String SubBrandName, String ReferenceName, String BrandName, String columnBalance, String damagaged_stock, String counterGroupId) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + if (damagaged_stock != null && damagaged_stock.equals("1")) { + dbcursor = db.rawQuery("select p.ProductId as ProductId, p.ProductName as ProductName, p.EanCode as EanCode, p.Mrp as Mrp,(TS.SaleableDamage +" + " ifnull(dm.DamageQty,0)) - ifnull(rd.ReturnQty,0) as SaleableDamage," + "TS.SaleableBalance - ifnull(dm.DamageQty,0) as SaleableBalance from Product_Master p INNER JOIN T_StockSummary TS " + "ON trim(TS.ProductId) = trim(p.ProductId) LEFT JOIN (Select ProductId, sum(DamageQty) as DamageQty from " + "(select T.ProductId, T.Stock as DamageQty from TABLE_TRANSACTION_DATA T INNER JOIN DR_TABLE_TRANSACTION_WISE_MASTER M ON" + " T.MASTER_TRANSACTION_ID = M.MASTER_TRANSACTION_ID " + "where T.STOCK_TYPE='DAMAGE' AND T.Visit_Date ='" + visit_date + "' and T.COUNTER_ID =" + counterId + " Union All " + " SELECT ProductId, DamageQty from Damage_PreviousPending Where CounterId =" + counterId + " and Verify ='Pending') as t " + "Group by ProductId) as dm on trim(p.ProductId) = trim(dm.ProductId) Left Join (Select ProductId, sum(ReturnQty) as ReturnQty from " + "(select ProductId, ReturnQty from Damage_ReturnToDistributor WHERE CounterId=" + counterId + " and VERIFY ='Pending' Union All " + "select ProductId, STOCK as ReturnQty from TABLE_RETURNTO_DISTRIBUTOR WHERE Visit_Date='" + visit_date + "' AND COUNTER_ID=" + counterId + ") as t Group by ProductId) as rd " + "on trim(p.ProductId) = trim(rd.ProductId) " + "Where p.SubBrandName=trim(\"" + SubBrandName + "\") AND " + "p.ReferenceName=trim(\"" + ReferenceName + "\") AND p.BrandName=trim(\"" + BrandName + "\") AND (TS.SaleableBalance<>0 OR SaleableDamage<>0)", null); + + + } else if (damagaged_stock != null && damagaged_stock.equals("0")) { + ////Qury return to db Child ............................ + dbcursor = db.rawQuery(" select p.ProductId as ProductId, p.ProductName as ProductName, p.EanCode as EanCode, p.Mrp as Mrp , TS.SaleableDamage as SaleableDamage," + "ifnull(RN.ReturnQty,0) as ReturnQty,(TS.SaleableDamage - ifnull(RN.ReturnQty,0)) as DamageQty from Product_Master p" + " INNER JOIN T_StockSummary TS ON TS.ProductId = p.ProductId AND TS.SaleableDamage<>0 LEFT JOIN " + "(SELECT ProductId, sum(ReturnQty) as ReturnQty FROM (select trim(ProductId) as ProductId, ReturnQty from Damage_ReturnToDistributor WHERE CounterId =" + counterId + " and VERIFY ='Pending'" + "Union All select trim(ProductId) as ProductId, Stock as ReturnQty from TABLE_RETURNTO_DISTRIBUTOR where COUNTER_ID =" + counterId + " and Visit_Date ='" + visit_date + "') AS T " + "GROUP BY ProductId) AS RN ON P.ProductId = RN.ProductId " + "Where p.SubBrandName=trim(\"" + SubBrandName + "\") AND p.ReferenceName=trim(\"" + ReferenceName + "\") AND" + " p.BrandName=trim(\"" + BrandName + "\") and DamageQty >0", null); + + } + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + ProductMaster sb = new ProductMaster(); + sb.setProductName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ProductName"))); + sb.setProductId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("ProductId"))); + sb.setEanCode(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EanCode"))); + sb.setMrp(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("Mrp"))); + sb.setImagePath(""); + if (damagaged_stock != null && damagaged_stock.equals("0")) { + ///availeble Damage Stock + sb.setStock_receive(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("DamageQty"))); + sb.setStock(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("DamageQty"))); + ///total damage + sb.setSaleable_stock(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("SaleableDamage"))); + sb.setBlockproductId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("ReturnQty"))); + + } else if (damagaged_stock != null && damagaged_stock.equals("1")) { + ////Query for damaged stock + sb.setStock_receive(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(columnBalance))); + sb.setSaleable_stock(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("SaleableBalance"))); + sb.setBlockproductId(0); + sb.setStock(0); + + } + + list.add(sb); + dbcursor.moveToNext(); + } + dbcursor.close(); + return list; + } + } catch (Exception e) { + + return list; + } + + return list; + } + + //get Signature Brand Sub Brand and Reference + public ArrayList getSubAxe(String counterGroup_Id, boolean normalproducttype) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + if (normalproducttype) { + dbcursor = db.rawQuery("select distinct SubAxeName from Product_Master where ProductType='Normal'", null); + + } else { + dbcursor = db.rawQuery("select distinct SubAxeName from Product_Master where ProductType='GWP'", null); + + } + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + ProductMaster sb = new ProductMaster(); + sb.setSubAxeName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SubAxeName"))); + + list.add(sb); + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list; + } + } catch (Exception e) { + + return list; + } + + return list; + } + + public ArrayList getSubAxeforinward(String counterGroup_Id) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + + dbcursor = db.rawQuery("select distinct SubAxeName from Product_Master", null); + + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + ProductMaster sb = new ProductMaster(); + sb.setSubAxeName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SubAxeName"))); + + list.add(sb); + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list; + } + } catch (Exception e) { + + return list; + } + + return list; + } + + //get Function Name - NuanceName + public ArrayList getFunctionName(String counterGroup_Id, String subAxeName, boolean regularstock, String columnName, String counterId, String visit_date) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + if (regularstock) { + if (subAxeName.equals("")) { + if (columnName.equalsIgnoreCase(CommonString.KEY_SaleableBalance)) { + dbcursor = db.rawQuery("select distinct SubAxeName, NuanceName from Product_Master p inner join" + " (Select s.ProductId, (s.SaleableBalance - ifnull(dm.DamageQty,0)) as SaleableBalance" + " from T_StockSummary s Left join" + " (Select CounterId, ProductId, sum(DamageQty) as DamageQty from (" + " select T.COUNTER_ID as CounterId, T.ProductId as ProductId, T.Stock as DamageQty from TABLE_TRANSACTION_DATA T" + " INNER JOIN DR_TABLE_TRANSACTION_WISE_MASTER M ON T.MASTER_TRANSACTION_ID = M.MASTER_TRANSACTION_ID where" + " T.STOCK_TYPE='DAMAGE' AND T.Visit_Date ='" + visit_date + "' and T.COUNTER_ID =" + counterId + " Union All SELECT CounterId,ProductId,DamageQty from" + " Damage_PreviousPending Where CounterId =" + counterId + " and Verify ='Pending'" + " Union All" + " Select T2.COUNTER_ID AS CounterId, T1.PRODUCT_ID AS ProductId , SUM(T1.QUANTITY) AS DamageQty FROM SALE_TRACKING_TABLE T1 INNER JOIN SALE_TRACKING_HEADER_TABLE T2 ON" + " T2.RECCEPT_COUNT=T1.RECCEPT_COUNT " + " WHERE T2.COUNTER_ID =" + counterId + " AND T2.Visit_Date='" + visit_date + "' AND T2.POS_SALE_FLAG='0' AND T1.INVOICE_TYPE='Saleable' GROUP BY T1.PRODUCT_ID" + " UNION ALL" + " select S.COUNTER_ID,S.PROMO_PRODUCT_ID AS PRODUCT_ID,SUM(S.PROMO_PRODUCT_QTY) AS QUANTITY from APPLYED_PROMOTION_TABLE S INNER JOIN SALE_TRACKING_HEADER_TABLE S1" + " ON S.RECCEPT_COUNT=S1.RECCEPT_COUNT" + " Where S.PROMO_TYPE ='Product' AND S.COUNTER_ID =" + counterId + " AND S1.VISIT_DATE = '" + visit_date + "' AND S1.POS_SALE_FLAG ='0'" + " GROUP BY S.PROMO_PRODUCT_ID) as t" + " Group by CounterId, ProductId) as dm on s.ProductId = dm.ProductId)" + " as TS ON TS.ProductId = p.ProductId where TS.SaleableBalance >0 and p.ProductType='Normal'", null); + + } else { + dbcursor = db.rawQuery("select distinct SubAxeName, NuanceName from Product_Master p inner join T_StockSummary TS" + " ON TS.ProductId = p.ProductId where TS." + columnName + " >0 and TS.CounterId=" + counterId + " and p.ProductType='Normal'", null); + } + } else { + if (columnName.equalsIgnoreCase(CommonString.KEY_SaleableBalance)) { + dbcursor = db.rawQuery("select distinct SubAxeName, NuanceName from Product_Master p inner join" + " (Select s.ProductId as ProductId, (s.SaleableBalance - ifnull(dm.DamageQty,0)) as SaleableBalance" + " from T_StockSummary s Left join" + " (Select CounterId, ProductId, sum(DamageQty) as DamageQty from (" + " select T.COUNTER_ID as CounterId, T.ProductId as ProductId, T.Stock as DamageQty from TABLE_TRANSACTION_DATA T" + " INNER JOIN DR_TABLE_TRANSACTION_WISE_MASTER M ON T.MASTER_TRANSACTION_ID = M.MASTER_TRANSACTION_ID where" + " T.STOCK_TYPE='DAMAGE' AND T.Visit_Date ='" + visit_date + "' and T.COUNTER_ID =" + counterId + " Union All SELECT CounterId,ProductId,DamageQty from" + " Damage_PreviousPending Where CounterId =" + counterId + " and Verify ='Pending'" + " Union All" + " Select T2.COUNTER_ID AS CounterId, T1.PRODUCT_ID AS ProductId , SUM(T1.QUANTITY) AS DamageQty FROM SALE_TRACKING_TABLE T1 INNER JOIN SALE_TRACKING_HEADER_TABLE T2 ON" + " T2.RECCEPT_COUNT=T1.RECCEPT_COUNT " + " WHERE T2.COUNTER_ID =" + counterId + " AND T2.Visit_Date='" + visit_date + "' AND T2.POS_SALE_FLAG='0' AND T1.INVOICE_TYPE='Saleable' GROUP BY T1.PRODUCT_ID" + " UNION ALL" + " select S.COUNTER_ID,S.PROMO_PRODUCT_ID AS PRODUCT_ID,SUM(S.PROMO_PRODUCT_QTY) AS QUANTITY from APPLYED_PROMOTION_TABLE S INNER JOIN SALE_TRACKING_HEADER_TABLE S1" + " ON S.RECCEPT_COUNT=S1.RECCEPT_COUNT" + " Where S.PROMO_TYPE ='Product' AND S.COUNTER_ID =" + counterId + " AND S1.VISIT_DATE = '" + visit_date + "' AND S1.POS_SALE_FLAG ='0'" + " GROUP BY S.PROMO_PRODUCT_ID) as t" + " Group by CounterId, ProductId) as dm on s.ProductId = dm.ProductId)" + " as TS ON TS.ProductId = p.ProductId where TS.SaleableBalance >0 and p.SubAxeName = '" + subAxeName + "'and p.ProductType='Normal'", null); + } else { + dbcursor = db.rawQuery("select distinct NuanceName from Product_Master p inner join T_StockSummary TS ON TS.ProductId = p.ProductId where TS." + columnName + " >0 and p.SubAxeName ='" + subAxeName + "'and TS.CounterId=" + counterId + " and p.ProductType='Normal'", null); + } + } + } else { + if (subAxeName.equals("")) { + dbcursor = db.rawQuery("select distinct SubAxeName, NuanceName from Product_Master where ProductType='Normal'", null); + + } else { + dbcursor = db.rawQuery("select distinct NuanceName from Product_Master where SubAxeName = '" + subAxeName + "' and ProductType='Normal'", null); + } + } + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + ProductMaster sb = new ProductMaster(); + sb.setSubAxeName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SubAxeName"))); + sb.setNuanceName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("NuanceName"))); + list.add(sb); + dbcursor.moveToNext(); + } + dbcursor.close(); + return list; + } + } catch (Exception e) { + + return list; + } + + return list; + } + + public ArrayList getFunctionMEHeader(String counterGroup_Id, String subAxeName, boolean regularstock, String columnName, String counterId, String visit_date) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + if (regularstock) { + if (subAxeName.equals("")) { + dbcursor = db.rawQuery("select distinct SubAxeName, NuanceName from Product_Master p inner join T_StockSummary TS" + " ON TS.ProductId = p.ProductId where TS.CounterId=" + counterId + " and p.ProductType='Normal'", null); + } else { + dbcursor = db.rawQuery("select distinct NuanceName from Product_Master p inner join T_StockSummary TS ON TS.ProductId = p.ProductId where p.SubAxeName ='" + subAxeName + "'and TS.CounterId=" + counterId + " and p.ProductType='Normal'", null); + } + } else { + if (subAxeName.equals("")) { + dbcursor = db.rawQuery("select distinct SubAxeName, NuanceName from Product_Master where ProductType='Normal'", null); + + } else { + dbcursor = db.rawQuery("select distinct NuanceName from Product_Master where SubAxeName = '" + subAxeName + "' and ProductType='Normal'", null); + } + } + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + ProductMaster sb = new ProductMaster(); + sb.setSubAxeName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SubAxeName"))); + sb.setNuanceName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("NuanceName"))); + list.add(sb); + dbcursor.moveToNext(); + } + dbcursor.close(); + return list; + } + } catch (Exception e) { + + return list; + } + + return list; + } + + + public ArrayList getFunctionforFilledName(String counterGroup_Id, String subAxeName, String activity_name) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + + if (activity_name != null && !activity_name.equals("") && activity_name.equalsIgnoreCase("StockCheck")) { + if (subAxeName.equals("")) { + dbcursor = db.rawQuery("select distinct SubAxeName,NuanceName from Product_Master p inner join T_StockSummary TS ON TS.ProductId = p.ProductId where TS.SaleableBalance >0 ", null); + } else { + dbcursor = db.rawQuery("select distinct NuanceName from Product_Master p inner join T_StockSummary TS ON TS.ProductId = p.ProductId where TS.SaleableBalance >0 and p.SubAxeName ='" + subAxeName + "'", null); + } + } else { + if (subAxeName.equals("")) { + dbcursor = db.rawQuery("select distinct SubAxeName, NuanceName from Product_Master p inner join T_StockSummary TS ON TS.ProductId = p.ProductId where TS.TesterBalance >0 ", null); + } else { + dbcursor = db.rawQuery("select distinct NuanceName from Product_Master p inner join T_StockSummary TS ON TS.ProductId = p.ProductId where TS.TesterBalance >0 and p.SubAxeName = '" + subAxeName + "'", null); + } + } + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + ProductMaster sb = new ProductMaster(); + + //sb.setAxeId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("AxeId"))); + //sb.setAxeName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("AxeName"))); + sb.setSubAxeName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SubAxeName"))); + sb.setNuanceName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("NuanceName"))); + //sb.setBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("BrandName"))); + + list.add(sb); + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list; + } + } catch (Exception e) { + return list; + } + return list; + } + + //get child on Nuance - Function + //get stock child default data + public ArrayList getDefaultStockOnFunctionData(String functionName, String columnBalance, String counterId, boolean filledregularstock, String visit_date) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + if (filledregularstock) { + if (columnBalance.equalsIgnoreCase(CommonString.KEY_SaleableBalance)) { + dbcursor = db.rawQuery("select distinct p.SignatureName as SignatureName,p.BrandName as BrandName,p.SubBrandName as SubBrandName," + "p.ReferenceName as ReferenceName,p.ProductId as ProductId,p.ProductName as ProductName,p.EanCode as EanCode,p.Mrp as Mrp," + "TS.SaleableBalance as SaleableBalance from" + " Product_Master p left JOIN(Select s.ProductId,(s.SaleableBalance - ifnull(dm.DamageQty,0)) as SaleableBalance from T_StockSummary s" + " Left join" + " (Select CounterId, ProductId, sum(DamageQty) as DamageQty from (" + " select T.COUNTER_ID as CounterId, T.ProductId, T.Stock as DamageQty from TABLE_TRANSACTION_DATA T" + " INNER JOIN DR_TABLE_TRANSACTION_WISE_MASTER M ON T.MASTER_TRANSACTION_ID = M.MASTER_TRANSACTION_ID where" + " T.STOCK_TYPE='DAMAGE' AND T.Visit_Date ='" + visit_date + "' and T.COUNTER_ID =" + counterId + " Union All SELECT CounterId, ProductId, DamageQty from" + " Damage_PreviousPending Where CounterId ='" + counterId + "' and Verify ='Pending' Union All" + " Select T2.COUNTER_ID AS CounterId,T1.PRODUCT_ID AS ProductId,SUM(T1.QUANTITY) AS DamageQty FROM SALE_TRACKING_TABLE T1 INNER JOIN SALE_TRACKING_HEADER_TABLE T2 ON" + " T2.RECCEPT_COUNT=T1.RECCEPT_COUNT WHERE T2.COUNTER_ID =" + counterId + " AND T2.Visit_Date='" + visit_date + "' AND T2.POS_SALE_FLAG='0' AND T1.INVOICE_TYPE='Saleable' GROUP BY T1.PRODUCT_ID" + " UNION ALL" + " select S.COUNTER_ID, S.PROMO_PRODUCT_ID AS PRODUCT_ID ,SUM(S.PROMO_PRODUCT_QTY) AS QUANTITY from APPLYED_PROMOTION_TABLE S INNER JOIN SALE_TRACKING_HEADER_TABLE S1" + " ON S.RECCEPT_COUNT=S1.RECCEPT_COUNT Where S.PROMO_TYPE ='Product' AND S.COUNTER_ID =" + counterId + " AND S1.VISIT_DATE ='" + visit_date + "' AND S1.POS_SALE_FLAG ='0'" + " GROUP BY S.PROMO_PRODUCT_ID) as t Group by CounterId, ProductId) as dm on s.ProductId = dm.ProductId) as" + " TS ON TS.ProductId = p.ProductId Where p.NuanceName=trim(\"" + functionName + "\") AND p.ProductType =trim('Normal') and TS.SaleableBalance > 0 order by p.ProductName", null); + + } else { + dbcursor = db.rawQuery("select distinct p.SignatureName as SignatureName,p.BrandName as BrandName,p.SubBrandName as SubBrandName," + "p.ReferenceName as ReferenceName,p.ProductId as ProductId," + " p.ProductName as ProductName, p.EanCode as EanCode, p.Mrp as Mrp, TS." + columnBalance + " from Product_Master p Inner JOIN T_StockSummary TS ON TS.ProductId = p.ProductId " + " Where p.NuanceName=trim(\"" + functionName + "\") AND p.ProductType =trim('Normal') and TS." + columnBalance + " > 0 and TS.CounterId=" + counterId + " order by p.ProductName", null); + } + } else { + dbcursor = db.rawQuery("select distinct p.SignatureName as SignatureName,p.BrandName as BrandName,p.SubBrandName as SubBrandName," + "p.ReferenceName as ReferenceName,p.ProductId as ProductId, p.ProductName as ProductName, p.EanCode as EanCode, p.Mrp as Mrp, TS." + columnBalance + " from Product_Master p " + " LEFT JOIN (select * from T_StockSummary where CounterId = " + counterId + ") as TS ON TS.ProductId = p.ProductId " + "Where p.NuanceName=trim(\"" + functionName + "\") AND p.ProductType =trim('Normal') order by p.ProductName", null); + } + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + ProductMaster sb = new ProductMaster(); + sb.setProductName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ProductName"))); + sb.setProductId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("ProductId"))); + sb.setEanCode(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EanCode"))); + sb.setMrp(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("Mrp"))); + if (dbcursor.getString(dbcursor.getColumnIndexOrThrow(columnBalance)) == null) { + sb.setStock(-1); + sb.setStock_receive(-1); + } else { + sb.setStock(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(columnBalance))); + sb.setStock_receive(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(columnBalance))); + } + sb.setSignatureName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SignatureName"))); + sb.setBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("BrandName"))); + sb.setSubBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SubBrandName"))); + sb.setReferenceName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ReferenceName"))); + list.add(sb); + dbcursor.moveToNext(); + } + dbcursor.close(); + return list; + } + } catch (Exception e) { + return list; + } + return list; + } + + public ArrayList getInsertedMEChildData(String functionName, String columnBalance, String visit_date, String counterId) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + dbcursor = db.rawQuery("SELECT distinct ProductId,UploadStatus,ProductName,SubAxeName,AxeName,STOCK,STOCK_RECEIVED,COUNTER_ID,EanCode,Mrp,SignatureName,BrandName,SubBrandName,ReferenceName FROM " + CommonString.TABLE_STORE_STOCK_CHILD_ME_SALE_DATA + " where Visit_Date='" + visit_date + "'AND " + CommonString.KEY_COUNTER_ID + "='" + counterId + "'AND " + "NuanceName" + "='" + functionName + "'", null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + ProductMaster sb = new ProductMaster(); + sb.setProductName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ProductName"))); + sb.setProductId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("ProductId"))); + sb.setEanCode(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EanCode"))); + sb.setMrp(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("Mrp"))); + sb.setUploadStatus(dbcursor.getString(dbcursor.getColumnIndexOrThrow("UploadStatus"))); + sb.setStock(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("STOCK"))); + sb.setStock_receive(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("STOCK"))); + sb.setSignatureName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SignatureName"))); + sb.setBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("BrandName"))); + sb.setSubBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SubBrandName"))); + sb.setReferenceName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ReferenceName"))); + list.add(sb); + dbcursor.moveToNext(); + } + dbcursor.close(); + return list; + } + } catch (Exception e) { + return list; + } + return list; + } + + + public ArrayList getDefaultMESaleFunctionData(String functionName, String columnBalance, String counterId, boolean filledregularstock, String visit_date) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + if (filledregularstock) { + dbcursor = db.rawQuery("select distinct p.SignatureName as SignatureName,p.BrandName as BrandName,p.SubBrandName as SubBrandName," + "p.ReferenceName as ReferenceName,p.ProductId as ProductId," + " p.ProductName as ProductName, p.EanCode as EanCode, p.Mrp as Mrp, TS." + columnBalance + " from Product_Master p Inner JOIN T_StockSummary TS ON TS.ProductId = p.ProductId " + " Where p.NuanceName=trim(\"" + functionName + "\") AND p.ProductType =trim('Normal') and TS." + columnBalance + " > 0 and TS.CounterId=" + counterId + " order by p.ProductName", null); + } else { + dbcursor = db.rawQuery("select distinct p.SignatureName as SignatureName,p.BrandName as BrandName,p.SubBrandName as SubBrandName," + "p.ReferenceName as ReferenceName,p.ProductId as ProductId, p.ProductName as ProductName, p.EanCode as EanCode, p.Mrp as Mrp, TS." + columnBalance + " from Product_Master p " + " LEFT JOIN (select * from T_StockSummary where CounterId = " + counterId + ") as TS ON TS.ProductId = p.ProductId " + "Where p.NuanceName=trim(\"" + functionName + "\") AND p.ProductType =trim('Normal') order by p.ProductName", null); + } + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + ProductMaster sb = new ProductMaster(); + sb.setProductName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ProductName"))); + sb.setProductId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("ProductId"))); + sb.setEanCode(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EanCode"))); + sb.setMrp(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("Mrp"))); + sb.setStock(0); + sb.setStock_receive(0); + sb.setSignatureName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SignatureName"))); + sb.setBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("BrandName"))); + sb.setSubBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SubBrandName"))); + sb.setReferenceName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ReferenceName"))); + list.add(sb); + dbcursor.moveToNext(); + } + dbcursor.close(); + return list; + } + } catch (Exception e) { + return list; + } + return list; + } + + public ArrayList getDefaultStockOnFunctionDataforFilled(String functionName, String counterId, String activity_name) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + String columnBalance = ""; + if (activity_name != null && !activity_name.equals("") && activity_name.equalsIgnoreCase("StockCheck")) { + columnBalance = CommonString.KEY_SaleableBalance; + dbcursor = db.rawQuery("select distinct p.SignatureName as SignatureName,p.BrandName as BrandName,p.SubBrandName as SubBrandName," + "p.ReferenceName as ReferenceName,p.ProductId as ProductId, p.ProductName as ProductName, p.EanCode as EanCode," + " p.Mrp as Mrp, TS." + columnBalance + " from Product_Master p " + " LEFT JOIN T_StockSummary TS ON TS.ProductId = p.ProductId " + "Where p.NuanceName=trim(\"" + functionName + "\") AND p.ProductType = 'Normal' and TS." + columnBalance + " > 0 and TS.CounterId=" + counterId + " order by p.ProductName", null); + + } else { + columnBalance = CommonString.KEY_TesterBalance; + dbcursor = db.rawQuery("select distinct p.SignatureName as SignatureName,p.BrandName as BrandName,p.SubBrandName as SubBrandName," + "p.ReferenceName as ReferenceName,p.ProductId as ProductId," + " p.ProductName as ProductName, p.EanCode as EanCode, p.Mrp as Mrp, TS." + columnBalance + " from Product_Master p " + " LEFT JOIN T_StockSummary TS ON TS.ProductId = p.ProductId " + "Where p.NuanceName=trim(\"" + functionName + "\") AND p.ProductType =trim('Normal') and TS." + columnBalance + " > 0 and TS.CounterId=" + counterId + " order by p.ProductName", null); + } + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + ProductMaster sb = new ProductMaster(); + sb.setProductName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ProductName"))); + sb.setProductId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("ProductId"))); + sb.setEanCode(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EanCode"))); + sb.setMrp(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("Mrp"))); + if (dbcursor.getString(dbcursor.getColumnIndexOrThrow(columnBalance)) == null) { + sb.setStock(-1); + sb.setStock_receive(-1); + } else { + sb.setStock(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(columnBalance))); + sb.setStock_receive(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(columnBalance))); + } + + sb.setSignatureName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SignatureName"))); + sb.setBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("BrandName"))); + sb.setSubBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SubBrandName"))); + sb.setReferenceName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ReferenceName"))); + + list.add(sb); + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list; + } + } catch (Exception e) { + + return list; + } + + return list; + } + + + public ArrayList getStockCheckReport(String visit_date, String counterId, boolean me, String column_name) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + String query = "Select " + column_name + ", sum(SaleableBalance) as StockQty, sum(StockValue) as StockValue from (" + " Select s.ProductId as ProductId, pm." + column_name + " as " + column_name + ", pm.Mrp as Mrp, " + "(ifnull(s.SaleableBalance,0) - ifnull(dm.DamageQty,0)) as SaleableBalance," + " IFNULL(pm.Mrp,0)*(IFNULL(s.SaleableBalance,0) - ifnull(dm.DamageQty,0)) As StockValue from" + " T_StockSummary s inner join Product_Master pm on s.ProductId = pm.ProductId left join (Select CounterId, ProductId," + " sum(DamageQty) as DamageQty from (" + " select T.COUNTER_ID as CounterId, T.ProductId, T.Stock as DamageQty from TABLE_TRANSACTION_DATA T" + " INNER JOIN DR_TABLE_TRANSACTION_WISE_MASTER M" + " ON T.MASTER_TRANSACTION_ID = M.MASTER_TRANSACTION_ID where T.STOCK_TYPE='DAMAGE' AND T.Visit_Date ='" + visit_date + "' and T.COUNTER_ID =" + counterId + " Union All" + " SELECT CounterId, ProductId, DamageQty from Damage_PreviousPending Where CounterId =" + counterId + " and Verify ='Pending') as t" + " Group by CounterId, ProductId) as dm on s.ProductId = dm.ProductId Where s.SaleableBalance>0 and s.CounterId = " + counterId + ") as t group by " + column_name; + if (me) { + query = "Select distinct VisitDate as " + column_name + ",CounterName,CounterCode from Report_MTD_WorkingCounterME"; + } + + dbcursor = db.rawQuery(query, null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + TStockSummary sb = new TStockSummary(); + sb.setBrand_name(dbcursor.getString(dbcursor.getColumnIndexOrThrow(column_name))); + if (me) { + sb.setProductName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("CounterName"))); + sb.setGwpStatus(dbcursor.getString(dbcursor.getColumnIndexOrThrow("CounterCode"))); + } else { + sb.setStock(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("StockQty"))); + sb.setMrp(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("StockValue"))); + } + list.add(sb); + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list; + } + } catch (Exception e) { + + return list; + } + + return list; + } + + public TStockSummary getStockCheckTotalStockWithQty(String visit_date, String counterId) { + TStockSummary list = new TStockSummary(); + Cursor dbcursor = null; + try { + + dbcursor = db.rawQuery("SELECT sum(ifnull(T3.StockQty,0)) as StockQty, sum(ifnull(StockValue,0)) as StockValue FROM" + " (Select NuanceName, sum(SaleableBalance) as StockQty, sum(StockValue) as StockValue from (" + " Select s.ProductId, pm.NuanceName, pm.Mrp, (ifnull(s.SaleableBalance,0) - ifnull(dm.DamageQty,0)) as SaleableBalance," + " IFNULL(pm.Mrp,0)*(IFNULL(s.SaleableBalance,0) - ifnull(dm.DamageQty,0)) As StockValue from" + " T_StockSummary s inner join Product_Master pm on s.ProductId = pm.ProductId left join (Select CounterId, ProductId," + " sum(DamageQty) as DamageQty from (select T.COUNTER_ID as CounterId, T.ProductId, T.Stock as DamageQty from TABLE_TRANSACTION_DATA T" + " INNER JOIN DR_TABLE_TRANSACTION_WISE_MASTER M" + " ON T.MASTER_TRANSACTION_ID = M.MASTER_TRANSACTION_ID where T.STOCK_TYPE='DAMAGE' AND T.Visit_Date ='" + visit_date + "' and T.COUNTER_ID =" + counterId + " Union All" + " SELECT CounterId, ProductId, DamageQty from Damage_PreviousPending Where CounterId =" + counterId + " and Verify ='Pending') as t" + " Group by CounterId, ProductId) as dm on s.ProductId = dm.ProductId Where s.SaleableBalance>0 and s.CounterId =" + counterId + " ) as t group by NuanceName) AS T3", null); + + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + list.setStock(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("StockQty"))); + list.setMrp(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("StockValue"))); + + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list; + } + } catch (Exception e) { + return list; + } + + return list; + } + + + public TStockSummary gettesterstock(String counterId) { + TStockSummary list = new TStockSummary(); + Cursor dbcursor = null; + try { + + dbcursor = db.rawQuery("select sum(ifnull(TS.TesterBalance,0)) as TesterBalance from Product_Master PM" + " Inner Join T_StockSummary TS on TS.ProductId=PM.ProductId where TS.TesterBalance >0 And TS.CounterId=" + counterId, null); + + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + list.setTesterBalance(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("TesterBalance"))); + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list; + } + } catch (Exception e) { + return list; + } + + return list; + } + + //get filter list according to SubAxe + public ArrayList getsub_brand_name(String counterGroup_Id, String column_name, boolean GWPFlag, String subAxe) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + if (!db.isOpen()) open(); + try { + if (GWPFlag) { + dbcursor = db.rawQuery("select distinct " + column_name + " from Product_Master where ProductType ='GWP'", null); + } else { + if (subAxe.equals("")) { + dbcursor = db.rawQuery("select distinct " + column_name + " from Product_Master where ProductType ='Normal' ", null); + } else { + dbcursor = db.rawQuery("select distinct " + column_name + " from Product_Master where ProductType =trim('Normal')" + " AND SubAxeName=trim(\"" + subAxe + "\")", null); + } + } + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + ProductMaster sb = new ProductMaster(); + sb.setBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow(column_name))); + list.add(sb); + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list; + } + } catch (Exception e) { + + return list; + } + + return list; + } + + public ArrayList getSubBrandOrReference(String counterGroup_Id, String column_name, String signatureName, String brandName, String subBrand, boolean GWPFlag, String subAxe) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + String productType = "Normal"; + if (GWPFlag) { + productType = "Gwp"; + } + + if (subAxe.equals("")) { + if (signatureName == null) { + dbcursor = db.rawQuery("select distinct " + column_name + " from Product_Master where ProductType ='" + productType + "'", null); + + } else if (column_name.trim().equalsIgnoreCase("ReferenceName") && subBrand != null) { + dbcursor = db.rawQuery("select distinct " + column_name + " from Product_Master where" + " SubBrandName =trim(\"" + subBrand + "\") and ProductType =trim('" + productType + "')", null); + } else if (brandName != null) { + dbcursor = db.rawQuery("select distinct " + column_name + " from Product_Master where" + " BrandName =trim(\"" + brandName + "\") and ProductType =trim('" + productType + "')", null); + } else { + dbcursor = db.rawQuery("select distinct " + column_name + " from Product_Master where" + " SignatureName =trim(\"" + signatureName + "\") and ProductType =trim('" + productType + "')", null); + } + + } else { + if (signatureName == null) { + dbcursor = db.rawQuery("select distinct " + column_name + " from Product_Master where ProductType =trim('" + productType + "')" + " and SubAxeName=trim(\"" + subAxe + "\")", null); + } else if (column_name.trim().equalsIgnoreCase("ReferenceName") && subBrand != null) { + dbcursor = db.rawQuery("select distinct " + column_name + " from Product_Master where SubBrandName =trim(\"" + subBrand + "\") and" + " ProductType =trim('" + productType + "') and SubAxeName=trim(\"" + subAxe + "\")", null); + } else if (brandName != null) { + dbcursor = db.rawQuery("select distinct " + column_name + " from Product_Master where" + " BrandName =trim(\"" + brandName + "\") and ProductType =trim('" + productType + "') and SubAxeName=trim(\"" + subAxe + "\")", null); + } else { + dbcursor = db.rawQuery("select distinct " + column_name + " from Product_Master where" + " SignatureName =trim(\"" + signatureName + "\") and ProductType =trim('" + productType + "') and SubAxeName=trim(\"" + subAxe + "\")", null); + } + } + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + ProductMaster sb = new ProductMaster(); + sb.setBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow(column_name))); + list.add(sb); + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list; + } + } catch (Exception e) { + + return list; + } + return list; + } + + + public boolean insertreport_attendence_details(MasterBAProfileGetterSetter cst) { + db.delete("Report_AttendanceDetail", null, null); + ContentValues values = new ContentValues(); + List data = cst.getReportAttendanceDetail(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("BAName", data.get(i).getBAName()); + values.put("BAUserId", data.get(i).getBAUserId()); + values.put("AttDate", data.get(i).getAttDate()); + values.put("Attendance", data.get(i).getAttendance()); + long id = db.insert("Report_AttendanceDetail", null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ex.fillInStackTrace(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + public ArrayList getAttendanceDetails() { + Cursor cursordata = null; + ArrayList auditData = new ArrayList<>(); + try { + + cursordata = db.rawQuery("select * FROM Report_AttendanceDetail order by AttDate desc", null); + + if (cursordata != null) { + cursordata.moveToFirst(); + while (!cursordata.isAfterLast()) { + ReportAttendanceDetail sb = new ReportAttendanceDetail(); + sb.setBAName(cursordata.getString(cursordata.getColumnIndexOrThrow("BAName"))); + sb.setBAUserId(cursordata.getString(cursordata.getColumnIndexOrThrow("BAUserId"))); + sb.setAttDate(cursordata.getString(cursordata.getColumnIndexOrThrow("AttDate"))); + sb.setAttendance(cursordata.getString(cursordata.getColumnIndexOrThrow("Attendance"))); + auditData.add(sb); + cursordata.moveToNext(); + } + cursordata.close(); + } + + } catch (Exception ex) { + + } + return auditData; + } + + + public boolean insertreport_attendence_summery(MasterBAProfileGetterSetter cst) { + db.delete("Report_AttendanceSummary", null, null); + ContentValues values = new ContentValues(); + List data = cst.getReportAttendanceSummary(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("AttendanceStatus", data.get(i).getAttendanceStatus()); + values.put("LastMonth", data.get(i).getLastMonth()); + values.put("MTD", data.get(i).getMTD()); + long id = db.insert("Report_AttendanceSummary", null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ex.fillInStackTrace(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + public ArrayList getAttendanceSummary() { + Cursor cursordata = null; + ArrayList auditData = new ArrayList<>(); + try { + + cursordata = db.rawQuery("select * FROM Report_AttendanceSummary order by AttendanceStatus", null); + + if (cursordata != null) { + cursordata.moveToFirst(); + while (!cursordata.isAfterLast()) { + ReportAttendanceSummary sb = new ReportAttendanceSummary(); + sb.setAttendanceStatus(cursordata.getString(cursordata.getColumnIndexOrThrow("AttendanceStatus"))); + sb.setLastMonth(cursordata.getInt(cursordata.getColumnIndexOrThrow("LastMonth"))); + sb.setMTD(cursordata.getInt(cursordata.getColumnIndexOrThrow("MTD"))); + auditData.add(sb); + cursordata.moveToNext(); + } + cursordata.close(); + } + + } catch (Exception ex) { + + } + return auditData; + } + + public ArrayList getlook_creation() { + Cursor cursordata = null; + ArrayList auditData = new ArrayList<>(); + try { + + cursordata = db.rawQuery("select * FROM Master_Looks", null); + + if (cursordata != null) { + cursordata.moveToFirst(); + while (!cursordata.isAfterLast()) { + MasterLook sb = new MasterLook(); + sb.setLooks(cursordata.getString(cursordata.getColumnIndexOrThrow("Looks"))); + auditData.add(sb); + cursordata.moveToNext(); + } + cursordata.close(); + } + + } catch (Exception ex) { + + } + return auditData; + } + + + public boolean insertreport_inword_stock_summery(MasterBAProfileGetterSetter cst) { + db.delete("Report_InwardStockSummary", null, null); + ContentValues values = new ContentValues(); + List data = cst.getReportInwardStockSummary(); + try { + if (data.isEmpty()) { + return false; + } + + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("InvoiceNo", data.get(i).getInvoiceNo()); + values.put("InvoiceDate", data.get(i).getInvoiceDate()); + values.put("InvoiceType", data.get(i).getInvoiceType()); + values.put("Source", data.get(i).getSource()); + values.put("InvoiceValue", data.get(i).getInvoiceValue()); + values.put("TotalLine", data.get(i).getTotalLine()); + values.put("ConfirmLine", data.get(i).getConfirmLine()); + values.put("PendingLine", data.get(i).getPendingLine()); + long id = db.insert("Report_InwardStockSummary", null, values); + + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ex.fillInStackTrace(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + public ArrayList getinwordStockSummary(String counterId) { + Cursor cursordata = null; + ArrayList auditData = new ArrayList<>(); + try { + + cursordata = db.rawQuery("select * FROM Report_InwardStockSummary", null); + + if (cursordata != null) { + cursordata.moveToFirst(); + while (!cursordata.isAfterLast()) { + ReportInwardStockSummary sb = new ReportInwardStockSummary(); + sb.setInvoiceNo(cursordata.getString(cursordata.getColumnIndexOrThrow("InvoiceNo"))); + sb.setInvoiceDate(cursordata.getString(cursordata.getColumnIndexOrThrow("InvoiceDate"))); + sb.setInvoiceType(cursordata.getString(cursordata.getColumnIndexOrThrow("InvoiceType"))); + sb.setSource(cursordata.getString(cursordata.getColumnIndexOrThrow("Source"))); + sb.setInvoiceValue(cursordata.getDouble(cursordata.getColumnIndexOrThrow("InvoiceValue"))); + sb.setTotalLine((cursordata.getInt(cursordata.getColumnIndexOrThrow("TotalLine")))); + sb.setConfirmLine((cursordata.getInt(cursordata.getColumnIndexOrThrow("ConfirmLine")))); + sb.setPendingLine((cursordata.getInt(cursordata.getColumnIndexOrThrow("PendingLine")))); + auditData.add(sb); + cursordata.moveToNext(); + } + cursordata.close(); + } + + } catch (Exception ex) { + + } + return auditData; + } + + + public ArrayList getreport_tester_stock(String counterId, String column) { + Cursor cursordata = null; + ArrayList auditData = new ArrayList<>(); + try { + + if (counterId == null) { + cursordata = db.rawQuery("select distinct sum(ifnull(TesterBalance,0)) as TesterBalance," + column + " from Product_Master" + " PM Inner Join T_StockSummary TS on TS.ProductId=PM.ProductId where TesterBalance>0 GROUP by " + column, null); + } else { + cursordata = db.rawQuery("select distinct sum(ifnull(TesterBalance,0)) as TesterBalance," + column + " from Product_Master" + " PM Inner Join T_StockSummary TS on TS.ProductId=PM.ProductId where TesterBalance>0 and TS.CounterId=" + counterId + " GROUP by " + column, null); + } + + + if (cursordata != null) { + cursordata.moveToFirst(); + while (!cursordata.isAfterLast()) { + TStockSummary sb = new TStockSummary(); + sb.setTesterBalance(cursordata.getInt(cursordata.getColumnIndexOrThrow("TesterBalance"))); + sb.setProductName(cursordata.getString(cursordata.getColumnIndexOrThrow(column))); + auditData.add(sb); + cursordata.moveToNext(); + } + + cursordata.close(); + } + + } catch (Exception ex) { + ex.fillInStackTrace(); + } + + return auditData; + } + + public boolean insert_ba_availability(MasterBAProfileGetterSetter cst) { + db.delete("Report_BA_Availability", null, null); + ContentValues values = new ContentValues(); + List data = cst.getReportBAAvailability(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("Date", data.get(i).getDate()); + values.put("BudgetedMandays", data.get(i).getBudgetedMandays()); + values.put("AchievedMandays", data.get(i).getAchievedMandays()); + values.put("TotalTime", data.get(i).getTotalTime()); + long id = db.insert("Report_BA_Availability", null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ex.fillInStackTrace(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + + public boolean insert_master_look(MasterBAProfileGetterSetter cst) { + db.delete("Master_Looks", null, null); + ContentValues values = new ContentValues(); + List data = cst.getMasterLooks(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("Looks", data.get(i).getLooks()); + long id = db.insert("Master_Looks", null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ex.fillInStackTrace(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + + public boolean insert_me_audit_question(MasterBAProfileGetterSetter cst) { + db.delete("ME_MEAuditQuestion", null, null); + ContentValues values = new ContentValues(); + List data = cst.getMEMEAuditQuestion(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("CategoryId", data.get(i).getCategoryId()); + values.put("Category", data.get(i).getCategory()); + values.put("AuditType", data.get(i).getAuditType()); + values.put("QuestionId", data.get(i).getQuestionId()); + values.put("Question", data.get(i).getQuestion()); + values.put("QuestionType", data.get(i).getQuestionType()); + values.put("AnswerId", data.get(i).getAnswerId()); + values.put("Answer", data.get(i).getAnswer()); + values.put("QuizId", data.get(i).getQuizId()); + values.put("QuizName", data.get(i).getQuizName()); + values.put("ImageAllow", data.get(i).getImageAllow()); + long id = db.insert("ME_MEAuditQuestion", null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ex.fillInStackTrace(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + + public boolean insert_me_quizuploadstatus(MasterBAProfileGetterSetter cst) { + db.delete("ME_MEAuditQuestion_UploadStatus", null, null); + ContentValues values = new ContentValues(); + List data = cst.getMEMEAuditQuestionUploadStatus(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("QuizId", data.get(i).getQuizId()); + values.put("EmpId", data.get(i).getEmpId()); + values.put("UploadStatus", data.get(i).getUploadStatus()); + long id = db.insert("ME_MEAuditQuestion_UploadStatus", null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ex.fillInStackTrace(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + + public ArrayList getreport_ba_availability() { + Cursor cursordata = null; + ArrayList auditData = new ArrayList<>(); + try { + + cursordata = db.rawQuery("select * from Report_BA_Availability order by Date desc", null); + + if (cursordata != null) { + cursordata.moveToFirst(); + while (!cursordata.isAfterLast()) { + ReportBAAvailability sb = new ReportBAAvailability(); + sb.setDate(cursordata.getString(cursordata.getColumnIndexOrThrow("Date"))); + sb.setBudgetedMandays(cursordata.getInt(cursordata.getColumnIndexOrThrow("BudgetedMandays"))); + sb.setAchievedMandays(cursordata.getInt(cursordata.getColumnIndexOrThrow("AchievedMandays"))); + sb.setTotalTime(cursordata.getInt(cursordata.getColumnIndexOrThrow("TotalTime"))); + auditData.add(sb); + cursordata.moveToNext(); + } + + cursordata.close(); + } + + } catch (Exception ex) { + ex.fillInStackTrace(); + } + + return auditData; + } + + public ArrayList getreportMeSale() { + Cursor cursordata = null; + ArrayList auditData = new ArrayList<>(); + try { + cursordata = db.rawQuery("select * from Report_ME_Sale order by VisitDate DESC", null); + + if (cursordata != null) { + cursordata.moveToFirst(); + while (!cursordata.isAfterLast()) { + ReportMESale sb = new ReportMESale(); + sb.setVisitDate(cursordata.getString(cursordata.getColumnIndexOrThrow("VisitDate"))); + sb.setCounterCode(cursordata.getString(cursordata.getColumnIndexOrThrow("CounterCode"))); + sb.setCounterName(cursordata.getString(cursordata.getColumnIndexOrThrow("CounterName"))); + sb.setTotalsale(cursordata.getDouble(cursordata.getColumnIndexOrThrow("TotalSale"))); + sb.setTotalunitsale(cursordata.getInt(cursordata.getColumnIndexOrThrow("TotalUnitSale"))); + auditData.add(sb); + cursordata.moveToNext(); + } + cursordata.close(); + } + } catch (Exception ex) { + ex.fillInStackTrace(); + } + return auditData; + } + + public void update_tstock_summery_using_consumer_return(String counterId, String product_Id, String productQty, String invoiceType) { + try { + if (!db.isOpen()) { + open(); + } + + if (!invoiceType.equals("") && invoiceType.trim().equalsIgnoreCase("Damaged")) { + db.execSQL("update T_StockSummary set SaleableDamage = SaleableDamage + " + productQty + " where CounterId=" + counterId + " and ProductId=" + product_Id + ""); + } else { + db.execSQL("update T_StockSummary set SaleableBalance = SaleableBalance + " + productQty + " where CounterId=" + counterId + " and ProductId=" + product_Id + ""); + } + } catch (Exception e) { + e.fillInStackTrace(); + } + } + + public boolean ischeck_login_data(String user_id) { + boolean filled = false; + Cursor dbcursor = null; + try { + + dbcursor = db.rawQuery("select * from User_login where " + CommonString.KEY_USER_NAME + " ='" + user_id + "'", null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + String user_idget = dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_USER_NAME)); + if (user_idget != null && !user_idget.equals("")) { + filled = true; + break; + } else { + filled = false; + } + dbcursor.moveToNext(); + } + dbcursor.close(); + } + } catch (Exception e) { + ////////test("Exception--", e.toString()); + return filled; + } + return filled; + } + + + public ArrayList get_leave_List(String user_id, String visit_date, boolean flag) { + ////////test("Fetching", "Storedata--------------->Start<------------"); + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + + if (flag) { + dbcursor = db.rawQuery("select RequestDate, UserId, FromDate, ToDate, LeaveStatus,LeaveType,LeaveTypeDesc from T_LeaveRequest where UserId ='" + user_id + + "' order by RequestDate asc, FromDate desc", null); + } else { + dbcursor = db.rawQuery("select d.Visit_Date as RequestDate, d.USER_ID as UserId, d.From_Date as FromDate, d.To_Date as ToDate," + + " ifnull(t.LeaveStatus, 'Pending') as LeaveStatus, d.One_Day_Leave as LeaveType, d.LeaveType as LeaveTypeDesc " + + " from (select * from LEAVE_MANAGEMENT_TABLE where USER_ID='" + user_id + "' and Visit_Date='" + visit_date + + "' ) as d left join " + "(select * from T_LeaveRequest where UserId ='" + user_id + "' and RequestDate ='" + visit_date + "') as t " + + "on d.USER_ID = t.UserId and d.Visit_Date = t.RequestDate and d.From_Date = t.FromDate " + "and d.To_Date = t.ToDate Union " + + "select RequestDate, UserId, FromDate, ToDate, LeaveStatus,LeaveType,LeaveTypeDesc from T_LeaveRequest where UserId ='" + user_id + "' and RequestDate<>'" + + visit_date + "' order by RequestDate asc, From_Date desc", null); + } + + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + T_LeaveRequest sb = new T_LeaveRequest(); + sb.setRequestDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("RequestDate"))); + sb.setFromDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("FromDate"))); + sb.setToDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ToDate"))); + sb.setLeaveStatus(dbcursor.getString(dbcursor.getColumnIndexOrThrow("LeaveStatus"))); + sb.setUserId(dbcursor.getString(dbcursor.getColumnIndexOrThrow("UserId"))); + + String onedayleaveType = dbcursor.getString(dbcursor.getColumnIndexOrThrow("LeaveType")); + if (!onedayleaveType.equals("")) { + String leaveType = dbcursor.getString(dbcursor.getColumnIndexOrThrow("LeaveTypeDesc")); + sb.setStr_leaveType(leaveType + " - " + onedayleaveType); + } else { + sb.setStr_leaveType(dbcursor.getString(dbcursor.getColumnIndexOrThrow("LeaveTypeDesc"))); + } + + list.add(sb); + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list; + } + } catch (Exception e) { + ////////test("Exception ", "when fetching opening stock!!!!!!!!!!!" + e.toString()); + return list; + } + + ////////test("Fetching ", "opening stock---------------------->Stop<-----------"); + return list; + } + + public ArrayList getinserted_leave_requestList(String storeid, String user_id, String visit_date, String upload_status) { + ////////test("Fetching", "Storedata--------------->Start<------------"); + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + if (upload_status != null) { + dbcursor = db.rawQuery("select * From LEAVE_MANAGEMENT_TABLE where " + CommonString.KEY_COUNTER_ID + "=" + storeid + " and " + CommonString.KEY_VISIT_DATE + " ='" + visit_date + "'AND USER_ID='" + user_id + "'and UPLOAD_STATUS='N'", null); + + } else { + dbcursor = db.rawQuery("select * From LEAVE_MANAGEMENT_TABLE where " + CommonString.KEY_COUNTER_ID + "=" + storeid + " and " + CommonString.KEY_VISIT_DATE + " ='" + visit_date + "'AND USER_ID='" + user_id + "'", null); + + } + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + T_LeaveRequest sb = new T_LeaveRequest(); + sb.setRequestDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Request_Date"))); + sb.setFromDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("From_Date"))); + sb.setToDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("To_Date"))); + sb.setUserId(dbcursor.getString(dbcursor.getColumnIndexOrThrow("USER_ID"))); + sb.setUpload_request_date(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_VISIT_DATE))); + + String onedayleaveType = dbcursor.getString(dbcursor.getColumnIndexOrThrow("One_Day_Leave")); + if (!onedayleaveType.equals("")) { + String leaveType = dbcursor.getString(dbcursor.getColumnIndexOrThrow("LeaveType")); + sb.setStr_leaveType(leaveType + " - " + onedayleaveType); + } else { + sb.setStr_leaveType(dbcursor.getString(dbcursor.getColumnIndexOrThrow("LeaveType"))); + } + + list.add(sb); + + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list; + } + } catch (Exception e) { + ////////test("Exception ", "when fetching opening stock!!!!!!!!!!!" + e.toString()); + return list; + } + ////////test("Fetching ", "opening stock---------------------->Stop<-----------"); + return list; + } + + + public long deleteManualStockWithKeyIdData(String counter_id, String visit_date, String keyId) { + long l = 0; + try { + if (!db.isOpen()) { + open(); + } + l = db.delete(CommonString.TABLE_INSERT_MANUAL_INWARD_TRANSACTION, CommonString.KEY_COUNTER_ID + " =" + counter_id + " and " + CommonString.KEY_VISIT_DATE + "='" + visit_date + "'and " + CommonString.KEY_ID + "='" + keyId + "'", null); + + } catch (Exception e) { + e.fillInStackTrace(); + } + return l; + } + + + public long updateTStockSaleableDamageReturnData() { + long l = 0; + try { + if (!db.isOpen()) { + open(); + } + l = db.delete(CommonString.TABLE_DAMAGED_CHILD_DATA, null, null); + + } catch (Exception ex) { + //return 0; + } + return l; + } + + + public long updateStockSummaryDamageValue(int product_id, int damagedQty, String counterId) { + long id = 0; + ContentValues values = new ContentValues(); + try { + if (!db.isOpen()) open(); + values.put(CommonString.KEY_SaleableDamage, damagedQty); + id = db.update(CommonString.T_StockSummary, values, CommonString.KEY_ProductId + "=" + product_id + " and CounterId=" + counterId + "", null); + } catch (Exception ex) { + return 0; + } + return id; + } + + + public long updateT_CounterInvoiceConfirmCounter(String invId, int ProductId) { + long id = 0; + ContentValues values = new ContentValues(); + try { + values.put(CommonString.KEY_COUNTER_CONFIRM, "1"); + if (!db.isOpen()) open(); + id = db.update(CommonString.KEY_TABLE_T_CounterInvoice, values, CommonString.KEY_INVOICE_ID + "='" + invId + "' And ProductId=" + ProductId + "", null); + } catch (Exception ex) { + return 0; + } + return id; + } + + + public ArrayList getMakeoverCaptureByUserMobile(int reciept_count, String mobile_no, String visite_date, String counterId, String user_Id) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + if (mobile_no == null) { + dbcursor = db.rawQuery("SELECT * FROM MAKEOVER_CAPTURE_TABLE WHERE Visit_Date='" + visite_date + "' and COUNTER_ID =" + counterId + " and USER_ID ='" + user_Id + "'", null); + + } else { + dbcursor = db.rawQuery("SELECT * FROM MAKEOVER_CAPTURE_TABLE WHERE CONTACT_NUMBER='" + mobile_no + "'" + "and Visit_Date ='" + visite_date + "' and " + CommonString.KEY_ID + "=" + reciept_count + " and COUNTER_ID =" + counterId + " and USER_ID ='" + user_Id + "'", null); + + } + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + InvoiceGetterSetter sale = new InvoiceGetterSetter(); + if (dbcursor.getString(dbcursor.getColumnIndexOrThrow("POS_SALE_FLAG")).equals("1")) { + sale.setPos_sale_flag(true); + } else { + sale.setPos_sale_flag(false); + } + + sale.setReccept_count(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(CommonString.KEY_ID))); + sale.setStr_termcondition(dbcursor.getString(dbcursor.getColumnIndexOrThrow("TERMCONDITION_FLAG"))); + sale.setCustomer_name(dbcursor.getString(dbcursor.getColumnIndexOrThrow("BUYER_NAME"))); + sale.setMobile_no(dbcursor.getString(dbcursor.getColumnIndexOrThrow("CONTACT_NUMBER"))); + sale.setConsumer_email_Id(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EMAIL_ID"))); + sale.setConsumer_age(dbcursor.getString(dbcursor.getColumnIndexOrThrow("AGE"))); + sale.setConsumer_skinType(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SKIN_TYPE"))); + sale.setLook_creater_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("LOOk"))); + sale.setStr_upload_status(dbcursor.getString(dbcursor.getColumnIndexOrThrow("UPLOAD_STATUS"))); + sale.setCustomer_gender(dbcursor.getString(dbcursor.getColumnIndexOrThrow("GENDER"))); + sale.setBefore_makeover_img(dbcursor.getString(dbcursor.getColumnIndexOrThrow("BEFORE_MAKEOVER_IMG"))); + sale.setAfter_makeover_img(dbcursor.getString(dbcursor.getColumnIndexOrThrow("AFTER_MAKEOVER_IMG"))); + sale.setUnique_code(dbcursor.getString(dbcursor.getColumnIndexOrThrow("UNIQUE_CODE"))); + sale.setStrUserId(dbcursor.getString(dbcursor.getColumnIndexOrThrow("USER_ID"))); + sale.setCst_feed_back_value(dbcursor.getString(dbcursor.getColumnIndexOrThrow("FEEDBACK"))); + sale.setUserName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("USER_ID"))); + + list.add(sale); + + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list; + } + + } catch (Exception e) { + ////////test("Exception Brands", e.toString()); + return list; + } + return list; + } + + + public ArrayList getMakeover(String visite_date, String counterId, String user_Id, String transId, boolean manual_upload) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + if (manual_upload) { + dbcursor = db.rawQuery("SELECT * FROM MAKEOVER_CAPTURE_TABLE WHERE COUNTER_ID =" + counterId + " and POS_SALE_FLAG ='1' " + "and UPLOAD_STATUS='N' and UNIQUE_CODE='" + transId + "'", null); + + } else { + if (user_Id == null) { + dbcursor = db.rawQuery("SELECT * FROM MAKEOVER_CAPTURE_TABLE WHERE Visit_Date='" + visite_date + "' and COUNTER_ID =" + counterId + " and POS_SALE_FLAG='1'", null); + + } else { + dbcursor = db.rawQuery("SELECT * FROM MAKEOVER_CAPTURE_TABLE WHERE Visit_Date='" + visite_date + "' and COUNTER_ID =" + counterId + " and USER_ID ='" + user_Id + "'", null); + } + } + + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + InvoiceGetterSetter sale = new InvoiceGetterSetter(); + if (dbcursor.getString(dbcursor.getColumnIndexOrThrow("POS_SALE_FLAG")).equals("1")) { + sale.setPos_sale_flag(true); + } else { + sale.setPos_sale_flag(false); + } + + sale.setReccept_count(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(CommonString.KEY_ID))); + sale.setStr_termcondition(dbcursor.getString(dbcursor.getColumnIndexOrThrow("TERMCONDITION_FLAG"))); + sale.setCustomer_name(dbcursor.getString(dbcursor.getColumnIndexOrThrow("BUYER_NAME"))); + sale.setMobile_no(dbcursor.getString(dbcursor.getColumnIndexOrThrow("CONTACT_NUMBER"))); + sale.setConsumer_email_Id(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EMAIL_ID"))); + sale.setConsumer_age(dbcursor.getString(dbcursor.getColumnIndexOrThrow("AGE"))); + sale.setConsumer_skinType(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SKIN_TYPE"))); + sale.setLook_creater_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("LOOk"))); + sale.setStr_upload_status(dbcursor.getString(dbcursor.getColumnIndexOrThrow("UPLOAD_STATUS"))); + sale.setCustomer_gender(dbcursor.getString(dbcursor.getColumnIndexOrThrow("GENDER"))); + sale.setBefore_makeover_img(dbcursor.getString(dbcursor.getColumnIndexOrThrow("BEFORE_MAKEOVER_IMG"))); + sale.setAfter_makeover_img(dbcursor.getString(dbcursor.getColumnIndexOrThrow("AFTER_MAKEOVER_IMG"))); + sale.setUnique_code(dbcursor.getString(dbcursor.getColumnIndexOrThrow("UNIQUE_CODE"))); + sale.setStrUserId(dbcursor.getString(dbcursor.getColumnIndexOrThrow("USER_ID"))); + sale.setCst_feed_back_value(dbcursor.getString(dbcursor.getColumnIndexOrThrow("FEEDBACK"))); + sale.setVisit_date(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_VISIT_DATE))); + + list.add(sale); + + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list; + } + + } catch (Exception e) { + ////////test("Exception Brands", e.toString()); + return list; + } + return list; + } + + + public ArrayList getskinGeniusData(String visite_date, String counterId, String user_Id, String transId, boolean manual_upload) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + if (manual_upload) { + dbcursor = db.rawQuery("SELECT * FROM SKIN_GENIUS_TABLE WHERE COUNTER_ID =" + counterId + " and UPLOAD_STATUS='N' and UNIQUE_CODE='" + transId + "'", null); + + } else { + if (user_Id == null) { + dbcursor = db.rawQuery("SELECT * FROM SKIN_GENIUS_TABLE WHERE Visit_Date='" + visite_date + "' and COUNTER_ID =" + counterId + "", null); + + } else { + dbcursor = db.rawQuery("SELECT * FROM SKIN_GENIUS_TABLE WHERE Visit_Date='" + visite_date + "' and COUNTER_ID =" + counterId + " and USER_ID ='" + user_Id + "'", null); + } + } + + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + InvoiceGetterSetter sale = new InvoiceGetterSetter(); + sale.setReccept_count(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(CommonString.KEY_RECCEPT_NUMBER))); + sale.setInvoice_img(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SKIN_GENIUS_IMG"))); + sale.setConsumer_email_Id(dbcursor.getString(dbcursor.getColumnIndexOrThrow("CAPTURED_TIME"))); + sale.setStr_upload_status(dbcursor.getString(dbcursor.getColumnIndexOrThrow("UPLOAD_STATUS"))); + sale.setUnique_code(dbcursor.getString(dbcursor.getColumnIndexOrThrow("UNIQUE_CODE"))); + sale.setStrUserId(dbcursor.getString(dbcursor.getColumnIndexOrThrow("USER_ID"))); + sale.setVisit_date(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_VISIT_DATE))); + + list.add(sale); + + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list; + } + + } catch (Exception e) { + ////////test("Exception Brands", e.toString()); + return list; + } + return list; + } + + + public ArrayList getOpenskinGeniusData(String visite_date, String counterId, String user_Id, String transId, boolean manual_upload) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + if (manual_upload) { + dbcursor = db.rawQuery("SELECT * FROM OPEN_SKIN_GENIUS_TABLE WHERE COUNTER_ID =" + counterId + " and UPLOAD_STATUS='N' and UNIQUE_CODE='" + transId + "'", null); + + } else { + if (user_Id == null) { + dbcursor = db.rawQuery("SELECT * FROM OPEN_SKIN_GENIUS_TABLE WHERE Visit_Date='" + visite_date + "' and COUNTER_ID =" + counterId + "", null); + + } else { + dbcursor = db.rawQuery("SELECT * FROM OPEN_SKIN_GENIUS_TABLE WHERE Visit_Date='" + visite_date + "' and COUNTER_ID =" + counterId + " and USER_ID ='" + user_Id + "'", null); + } + } + + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + InvoiceGetterSetter sale = new InvoiceGetterSetter(); + sale.setReccept_count(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(CommonString.KEY_RECCEPT_NUMBER))); + sale.setMaybellineorskingenius_count(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("OPENSKIN_GENIUS_COUNT"))); + sale.setStr_upload_status(dbcursor.getString(dbcursor.getColumnIndexOrThrow("UPLOAD_STATUS"))); + sale.setUnique_code(dbcursor.getString(dbcursor.getColumnIndexOrThrow("UNIQUE_CODE"))); + sale.setStrUserId(dbcursor.getString(dbcursor.getColumnIndexOrThrow("USER_ID"))); + sale.setVisit_date(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_VISIT_DATE))); + + list.add(sale); + + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list; + } + + } catch (Exception e) { + ////////test("Exception Brands", e.toString()); + return list; + } + return list; + } + + + public ArrayList getOpenMaybellineData(String visite_date, String counterId, String user_Id, String transId, boolean manual_upload) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + if (manual_upload) { + dbcursor = db.rawQuery("SELECT * FROM OPEN_MAYBELLINE_TABLE WHERE COUNTER_ID =" + counterId + " and UPLOAD_STATUS='N' and UNIQUE_CODE='" + transId + "'", null); + + } else { + if (user_Id == null) { + dbcursor = db.rawQuery("SELECT * FROM OPEN_MAYBELLINE_TABLE WHERE Visit_Date='" + visite_date + "' and COUNTER_ID =" + counterId + "", null); + + } else { + dbcursor = db.rawQuery("SELECT * FROM OPEN_MAYBELLINE_TABLE WHERE Visit_Date='" + visite_date + "' and COUNTER_ID =" + counterId + " and USER_ID ='" + user_Id + "'", null); + } + } + + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + InvoiceGetterSetter sale = new InvoiceGetterSetter(); + sale.setReccept_count(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(CommonString.KEY_RECCEPT_NUMBER))); + sale.setMaybellineorskingenius_count(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("OPEN_MAYBELLINE_COUNT"))); + sale.setStr_upload_status(dbcursor.getString(dbcursor.getColumnIndexOrThrow("UPLOAD_STATUS"))); + sale.setUnique_code(dbcursor.getString(dbcursor.getColumnIndexOrThrow("UNIQUE_CODE"))); + sale.setStrUserId(dbcursor.getString(dbcursor.getColumnIndexOrThrow("USER_ID"))); + sale.setVisit_date(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_VISIT_DATE))); + + list.add(sale); + + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list; + } + + } catch (Exception e) { + ////////test("Exception Brands", e.toString()); + return list; + } + return list; + } + + + public ArrayList getMakeoverCapture(String visite_date, String counterId) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + + dbcursor = db.rawQuery("SELECT * FROM MAKEOVER_CAPTURE_TABLE WHERE COUNTER_ID=" + counterId + " and Visit_Date ='" + visite_date + "'and POS_SALE_FLAG='1' and UPLOAD_STATUS='N'", null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + InvoiceGetterSetter sale = new InvoiceGetterSetter(); + sale.setReccept_count(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(CommonString.KEY_ID))); + sale.setStr_termcondition(dbcursor.getString(dbcursor.getColumnIndexOrThrow("TERMCONDITION_FLAG"))); + sale.setCustomer_name(dbcursor.getString(dbcursor.getColumnIndexOrThrow("BUYER_NAME"))); + sale.setMobile_no(dbcursor.getString(dbcursor.getColumnIndexOrThrow("CONTACT_NUMBER"))); + sale.setConsumer_email_Id(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EMAIL_ID"))); + sale.setConsumer_age(dbcursor.getString(dbcursor.getColumnIndexOrThrow("AGE"))); + sale.setConsumer_skinType(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SKIN_TYPE"))); + sale.setLook_creater_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("LOOk"))); + sale.setStr_upload_status(dbcursor.getString(dbcursor.getColumnIndexOrThrow("UPLOAD_STATUS"))); + sale.setCustomer_gender(dbcursor.getString(dbcursor.getColumnIndexOrThrow("GENDER"))); + sale.setBefore_makeover_img(dbcursor.getString(dbcursor.getColumnIndexOrThrow("BEFORE_MAKEOVER_IMG"))); + sale.setAfter_makeover_img(dbcursor.getString(dbcursor.getColumnIndexOrThrow("AFTER_MAKEOVER_IMG"))); + sale.setUnique_code(dbcursor.getString(dbcursor.getColumnIndexOrThrow("UNIQUE_CODE"))); + sale.setStrUserId(dbcursor.getString(dbcursor.getColumnIndexOrThrow("USER_ID"))); + sale.setCst_feed_back_value(dbcursor.getString(dbcursor.getColumnIndexOrThrow("FEEDBACK"))); + + list.add(sale); + + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list; + } + + } catch (Exception e) { + ////////test("Exception Brands", e.toString()); + return list; + } + + return list; + } + + + public ArrayList getAuditQuestionCategoryDataNew(String quizId) { + Cursor cursordata = null; + ArrayList auditData = new ArrayList<>(); + try { + + cursordata = db.rawQuery("Select Distinct CategoryId,Category from ME_MEAuditQuestion where QuizId=" + quizId + "", null); + + if (cursordata != null) { + cursordata.moveToFirst(); + while (!cursordata.isAfterLast()) { + MEMEAuditQuestion sb = new MEMEAuditQuestion(); + + sb.setCategoryId(cursordata.getInt(cursordata.getColumnIndexOrThrow("CategoryId"))); + sb.setCategory(cursordata.getString(cursordata.getColumnIndexOrThrow("Category")).trim()); + + auditData.add(sb); + + cursordata.moveToNext(); + } + + cursordata.close(); + } + + } catch (Exception ex) { + ex.fillInStackTrace(); + } + + return auditData; + + } + + public ArrayList getRetailExcellenceData() { + Cursor cursordata = null; + ArrayList masterRetailExcellenceArrayList = new ArrayList<>(); + try { + cursordata = db.rawQuery("Select Distinct ItemCategoryId,ItemCategoryName from Master_RetailExcellence_Item", null); + + if (cursordata != null) { + cursordata.moveToFirst(); + while (!cursordata.isAfterLast()) { + MasterRetailExcellence sb = new MasterRetailExcellence(); + + sb.setItemCatId(cursordata.getInt(cursordata.getColumnIndexOrThrow("ItemCategoryId"))); + sb.setItemCatName(cursordata.getString(cursordata.getColumnIndexOrThrow("ItemCategoryName")).trim()); + + masterRetailExcellenceArrayList.add(sb); + + cursordata.moveToNext(); + } + + cursordata.close(); + } + + } catch (Exception ex) { + ex.fillInStackTrace(); + } + + return masterRetailExcellenceArrayList; + + } + + + public ArrayList getMeQuiz() { + Cursor cursordata = null; + ArrayList auditData = new ArrayList<>(); + try { + + cursordata = db.rawQuery("Select Distinct QuizId,QuizName from ME_MEAuditQuestion", null); + + if (cursordata != null) { + cursordata.moveToFirst(); + while (!cursordata.isAfterLast()) { + MEMEAuditQuestion sb = new MEMEAuditQuestion(); + sb.setQuizId(cursordata.getInt(cursordata.getColumnIndexOrThrow("QuizId"))); + sb.setQuizName(cursordata.getString(cursordata.getColumnIndexOrThrow("QuizName"))); + + auditData.add(sb); + + cursordata.moveToNext(); + } + + cursordata.close(); + } + + } catch (Exception ex) { + ex.fillInStackTrace(); + } + + return auditData; + + } + + + public ArrayList getAuditCategoryWiseDataNew(int categoryID, String quizId) { + Cursor cursordata = null; + + ArrayList auditData = new ArrayList<>(); + try { + + cursordata = db.rawQuery("Select distinct Question,QuestionId,QuestionType from ME_MEAuditQuestion where CategoryId =" + categoryID + " and QuizId=" + quizId + "", null); + + if (cursordata != null) { + cursordata.moveToFirst(); + while (!cursordata.isAfterLast()) { + MEMEAuditQuestion sb = new MEMEAuditQuestion(); + sb.setQuestion(cursordata.getString(cursordata.getColumnIndexOrThrow("Question")).trim()); + sb.setQuestionId(cursordata.getInt(cursordata.getColumnIndexOrThrow("QuestionId"))); + sb.setQuestionType(cursordata.getString(cursordata.getColumnIndexOrThrow("QuestionType"))); + sb.setAnswer(""); + sb.setAnswerId(0); + sb.setStr_audit_img(""); + sb.setImageAllow(false); + auditData.add(sb); + cursordata.moveToNext(); + } + cursordata.close(); + } + + } catch (Exception ex) { + ////////test("Exception ", " in " + ex); + } + return auditData; + } + + public ArrayList getRetailCategoryWiseDataNew(int ItemCategoryId) { + Cursor cursordata = null; + + ArrayList auditData = new ArrayList<>(); + try { + + cursordata = db.rawQuery("Select distinct ItemId,ItemName from Master_RetailExcellence_Item where ItemCategoryId =" + ItemCategoryId + "", null); + + if (cursordata != null) { + cursordata.moveToFirst(); + while (!cursordata.isAfterLast()) { + MasterRetailExcellence sb = new MasterRetailExcellence(); + sb.setItemName(cursordata.getString(cursordata.getColumnIndexOrThrow("ItemName")).trim()); + sb.setItemId(cursordata.getInt(cursordata.getColumnIndexOrThrow("ItemId"))); + auditData.add(sb); + cursordata.moveToNext(); + } + cursordata.close(); + } + + } catch (Exception ex) { + ////////test("Exception ", " in " + ex.toString()); + } + return auditData; + } + + public ArrayList getAuditAnswerDataNew(MEMEAuditQuestion auditGetSet, String select) { + ArrayList list = new ArrayList<>(); + if (auditGetSet.getQuestionType().equalsIgnoreCase("List Single Choice")) { + MEMEAuditQuestion sb1 = new MEMEAuditQuestion(); + sb1.setAnswerId(0); + sb1.setAnswer(select); + list.add(0, sb1); + } else if (auditGetSet.getQuestionType().equalsIgnoreCase("Text")) { + MEMEAuditQuestion sb1 = new MEMEAuditQuestion(); + sb1.setAnswerId(0); + sb1.setAnswer(""); + list.add(0, sb1); + } + Cursor dbcursor = null; + + try { + + dbcursor = db.rawQuery("Select * from ME_MEAuditQuestion where QuestionId =" + auditGetSet.getQuestionId() + "", null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + MEMEAuditQuestion sb = new MEMEAuditQuestion(); + sb.setAnswerId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("AnswerId"))); + sb.setAnswer(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Answer"))); + String img_allow = dbcursor.getString(dbcursor.getColumnIndexOrThrow("ImageAllow")); + sb.setImageAllow(img_allow.equals("1")); + list.add(sb); + dbcursor.moveToNext(); + } + dbcursor.close(); + return list; + } + } catch (Exception e) { + ////////test("Exception", " answer " + e.toString()); + return list; + } + + ////////test("Fetching", " audit answer-->Stop<-"); + return list; + } + + public long insertRetailExcellence_data(String counter_Id, String visit_Date, String userId, ArrayList savelistheader, HashMap> data, MasterRetailExcellence obj, String unique_code) { + long l = 0, lf = 0; + try { + db.delete(CommonString.Table_Retail_Excellence_Header, CommonString.KEY_VISIT_DATE + " ='" + visit_Date + "'", null); + db.delete(CommonString.Table_Retail_Excellence_Child, CommonString.KEY_VISIT_DATE + " ='" + visit_Date + "'", null); + ContentValues values = new ContentValues(); + ContentValues valuesproduct = new ContentValues(); + db.beginTransaction(); + for (int i = 0; i < savelistheader.size(); i++) { + values.put("USER_ID", userId); + values.put("UNIQUE_CODE", unique_code); + values.put(CommonString.KEY_COUNTER_ID, counter_Id); + values.put(CommonString.KEY_VISIT_DATE, visit_Date); + values.put("UPLOAD_STATUS", CommonString.KEY_N); + values.put("ItemCategoryId", savelistheader.get(i).getItemCatId()); + values.put("ItemCategoryName", savelistheader.get(i).getItemCatName()); + if (!db.isOpen()) { + open(); + } + lf = db.insert(CommonString.Table_Retail_Excellence_Header, null, values); + for (int j = 0; j < data.get(savelistheader.get(i)).size(); j++) { + valuesproduct.put(CommonString.KEY_COMMON_ID, lf); + valuesproduct.put("UPLOAD_STATUS", CommonString.KEY_N); + valuesproduct.put("USER_ID", userId); + valuesproduct.put("UNIQUE_CODE", unique_code); + valuesproduct.put(CommonString.KEY_COUNTER_ID, counter_Id); + valuesproduct.put(CommonString.KEY_VISIT_DATE, visit_Date); + valuesproduct.put("ItemCategoryId", savelistheader.get(i).getItemCatId()); + valuesproduct.put("ItemCategoryName", savelistheader.get(i).getItemCatName()); + valuesproduct.put("ItemId", data.get(savelistheader.get(i)).get(j).getItemId()); + valuesproduct.put("ItemName", data.get(savelistheader.get(i)).get(j).getItemName()); + valuesproduct.put("Answer", data.get(savelistheader.get(i)).get(j).getAnswer()); + if (!db.isOpen()) { + open(); + } + l = db.insert(CommonString.Table_Retail_Excellence_Child, null, valuesproduct); + + } + } + closeDb(); + } catch (Exception ex) { + ex.fillInStackTrace(); + closeDb(); + } + + return l; + } + + public long insert_me_quiz_data(String counter_Id, String visit_Date, String userId, ArrayList listDataHeader, HashMap> listDataChild, MEMEAuditQuestion obj, String unique_code) { + db.delete(CommonString.Table_ME_QUIZ, CommonString.KEY_VISIT_DATE + " <>'" + visit_Date + "'", null); + db.delete(CommonString.Table_ME_QUIZ_MULTI_ANSWER, CommonString.KEY_VISIT_DATE + " <>'" + visit_Date + "'", null); + + db.delete(CommonString.Table_ME_QUIZ, CommonString.KEY_VISIT_DATE + "='" + visit_Date + "' and " + CommonString.KEY_COUNTER_ID + "=" + counter_Id + " and USER_ID='" + userId + "'", null); + db.delete(CommonString.Table_ME_QUIZ_MULTI_ANSWER, CommonString.KEY_VISIT_DATE + "='" + visit_Date + "' and " + CommonString.KEY_COUNTER_ID + "=" + counter_Id + " and USER_ID='" + userId + "'", null); + ContentValues values = new ContentValues(); + ContentValues valuesproduct = new ContentValues(); + long l = 0, l2 = 0, l3 = 0; + try { + db.beginTransaction(); + for (int k = 0; k < listDataHeader.size(); k++) { + for (int j = 0; j < listDataChild.get(listDataHeader.get(k)).size(); j++) { + values.put("USER_ID", userId); + values.put("UNIQUE_CODE", unique_code); + values.put("QuizName", obj.getQuizName()); + values.put("UPLOAD_STATUS", CommonString.KEY_N); + values.put("QuizId", obj.getQuizId().toString()); + values.put(CommonString.KEY_COUNTER_ID, counter_Id); + values.put(CommonString.KEY_VISIT_DATE, visit_Date); + + values.put("CATEGORY", listDataHeader.get(k).getCategory()); + values.put("CATEGORY_Id", listDataHeader.get(k).getCategoryId()); + values.put("QUESTION", listDataChild.get(listDataHeader.get(k)).get(j).getQuestion()); + values.put("QUESTION_Id", listDataChild.get(listDataHeader.get(k)).get(j).getQuestionId()); + values.put("QUESTION_TYPE", listDataChild.get(listDataHeader.get(k)).get(j).getQuestionType()); + values.put("IMAGE_STR", listDataChild.get(listDataHeader.get(k)).get(j).getStr_audit_img()); + if (listDataChild.get(listDataHeader.get(k)).get(j).getImageAllow()) { + values.put("IMAGE_ALLOW", 1); + } else { + values.put("IMAGE_ALLOW", 0); + + } + + if (listDataChild.get(listDataHeader.get(k)).get(j).getQuestionType().equalsIgnoreCase("List Single Choice")) { + values.put("ANSWER", listDataChild.get(listDataHeader.get(k)).get(j).getAnswer()); + values.put("ANSWER_Id", listDataChild.get(listDataHeader.get(k)).get(j).getAnswerId()); + } else if (!listDataChild.get(listDataHeader.get(k)).get(j).getQuestionType().equalsIgnoreCase("List Multiple Choice")) { + values.put("ANSWER", listDataChild.get(listDataHeader.get(k)).get(j).getAnswer()); + values.put("ANSWER_Id", 0); + } + if (!db.isOpen()) { + open(); + } + + l = db.insert(CommonString.Table_ME_QUIZ, null, values); + + if (listDataChild.get(listDataHeader.get(k)).get(j).getQuestionType().equalsIgnoreCase("List Multiple Choice")) { + for (int k2 = 0; k2 < listDataChild.get(listDataHeader.get(k)).get(j).getAnswerList().size(); k2++) { + valuesproduct.put("USER_ID", userId); + valuesproduct.put(CommonString.KEY_COMMON_ID, l); + valuesproduct.put("QuizName", obj.getQuizName()); + valuesproduct.put("QuizId", obj.getQuizId().toString()); + valuesproduct.put(CommonString.KEY_COUNTER_ID, counter_Id); + valuesproduct.put(CommonString.KEY_VISIT_DATE, visit_Date); + valuesproduct.put("CATEGORY_Id", listDataHeader.get(k).getCategoryId().toString()); + valuesproduct.put("QUESTION_Id", listDataChild.get(listDataHeader.get(k)).get(j).getQuestionId()); + valuesproduct.put("QUESTION_TYPE", listDataChild.get(listDataHeader.get(k)).get(j).getQuestionType()); + valuesproduct.put("ANSWER", listDataChild.get(listDataHeader.get(k)).get(j).getAnswerList().get(k2).getAnswer()); + valuesproduct.put("ANSWER_Id", listDataChild.get(listDataHeader.get(k)).get(j).getAnswerList().get(k2).getAnswerId()); + if (listDataChild.get(listDataHeader.get(k)).get(j).getAnswerList().get(k2).isSelected()) { + valuesproduct.put("IS_SELECTED", "1"); + } else { + valuesproduct.put("IS_SELECTED", "0"); + } + if (!db.isOpen()) { + open(); + } + l2 = db.insert(CommonString.Table_ME_QUIZ_MULTI_ANSWER, null, valuesproduct); + } + + } + + } + } + closeDb(); + } catch (Exception ex) { + closeDb(); + ex.fillInStackTrace(); + } + + return l3; + } + + public ArrayList getRetailExcellencedata(String categoryID, String userId, String visit_date, String counterId) { + Cursor cursordata = null; + ArrayList auditData = new ArrayList<>(); + try { + if (categoryID == null && userId == null) { + cursordata = db.rawQuery("SELECT * FROM " + CommonString.Table_Retail_Excellence_Child + " where Visit_Date='" + visit_date + "'AND " + CommonString.KEY_COUNTER_ID + "=" + counterId + " AND UPLOAD_STATUS='N'", null); + } else if (categoryID == null) { + cursordata = db.rawQuery("SELECT * FROM " + CommonString.Table_Retail_Excellence_Child + " where USER_ID='" + userId + "'AND " + CommonString.KEY_VISIT_DATE + "='" + visit_date + "'AND " + CommonString.KEY_COUNTER_ID + "=" + counterId + " AND UPLOAD_STATUS='N'", null); + } else { + cursordata = db.rawQuery("SELECT * FROM " + CommonString.Table_Retail_Excellence_Child + " where ItemCategoryId =" + categoryID + " AND USER_ID='" + userId + "'AND " + CommonString.KEY_VISIT_DATE + "='" + visit_date + "'AND " + CommonString.KEY_COUNTER_ID + "=" + counterId + "", null); + } + + if (cursordata != null) { + cursordata.moveToFirst(); + while (!cursordata.isAfterLast()) { + MasterRetailExcellence sb = new MasterRetailExcellence(); + sb.setUser_Id(cursordata.getString(cursordata.getColumnIndexOrThrow("USER_ID"))); + sb.setKeyId(cursordata.getString(cursordata.getColumnIndexOrThrow(CommonString.KEY_COMMON_ID))); + sb.setItemId(cursordata.getInt(cursordata.getColumnIndexOrThrow("ItemId"))); + sb.setItemName(cursordata.getString(cursordata.getColumnIndexOrThrow("ItemName"))); + sb.setAnswer(cursordata.getString(cursordata.getColumnIndexOrThrow("Answer"))); + auditData.add(sb); + cursordata.moveToNext(); + } + cursordata.close(); + } + + } catch (Exception ex) { + ////////test("Exception ", " in ADDITIONAL_QUESTION " + ex.toString()); + } + return auditData; + } + + public ArrayList getMeSaledata(String categoryID, String userId, String visit_date, String counterId) { + Cursor cursordata = null; + ArrayList productMasterArrayList = new ArrayList<>(); + try { + if (categoryID == null && userId == null) { + cursordata = db.rawQuery("SELECT * FROM " + CommonString.TABLE_STORE_STOCK_CHILD_ME_SALE_DATA + " where Visit_Date='" + visit_date + "'AND " + CommonString.KEY_COUNTER_ID + "=" + counterId + " AND UploadStatus='N'", null); + } else if (categoryID == null) { + cursordata = db.rawQuery("SELECT * FROM " + CommonString.TABLE_STORE_STOCK_CHILD_ME_SALE_DATA + " where USER_ID='" + userId + "'AND " + CommonString.KEY_VISIT_DATE + "='" + visit_date + "'AND " + CommonString.KEY_COUNTER_ID + "=" + counterId + " AND UploadStatus='N'", null); + } else { + cursordata = db.rawQuery("SELECT * FROM " + CommonString.TABLE_STORE_STOCK_CHILD_ME_SALE_DATA + " where ItemCategoryId =" + categoryID + " AND USER_ID='" + userId + "'AND " + CommonString.KEY_VISIT_DATE + "='" + visit_date + "'AND " + CommonString.KEY_COUNTER_ID + "=" + counterId + "", null); + } + + if (cursordata != null) { + cursordata.moveToFirst(); + while (!cursordata.isAfterLast()) { + ProductMaster sb = new ProductMaster(); + sb.setProductId(cursordata.getInt(cursordata.getColumnIndexOrThrow("ProductId"))); + sb.setKeyId(cursordata.getString(cursordata.getColumnIndexOrThrow(CommonString.KEY_COMMON_ID))); + sb.setImagePath(cursordata.getString(cursordata.getColumnIndexOrThrow("ImagePath"))); + sb.setCounter_id(cursordata.getString(cursordata.getColumnIndexOrThrow(CommonString.KEY_COUNTER_ID))); + sb.setStock(cursordata.getInt(cursordata.getColumnIndexOrThrow(CommonString.KEY_STOCK))); + productMasterArrayList.add(sb); + cursordata.moveToNext(); + } + cursordata.close(); + } + + } catch (Exception ex) { + ////////test("Exception ", " in ADDITIONAL_QUESTION " + ex.toString()); + } + + return productMasterArrayList; + } + + public ArrayList getme_quiz_from_database(String categoryID, String userId, String visit_date, String counterId, String quizId) { + Cursor cursordata = null; + ArrayList auditData = new ArrayList<>(); + + try { + if (categoryID == null && userId == null && quizId == null) { + cursordata = db.rawQuery("SELECT * FROM " + CommonString.Table_ME_QUIZ + " where Visit_Date='" + visit_date + "'AND " + CommonString.KEY_COUNTER_ID + "=" + counterId + " AND UPLOAD_STATUS='N'", null); + } else if (categoryID == null && quizId == null) { + cursordata = db.rawQuery("SELECT * FROM " + CommonString.Table_ME_QUIZ + " where USER_ID='" + userId + "'AND " + CommonString.KEY_VISIT_DATE + "='" + visit_date + "'AND " + CommonString.KEY_COUNTER_ID + "=" + counterId + " AND UPLOAD_STATUS='N'", null); + } else { + cursordata = db.rawQuery("SELECT * FROM " + CommonString.Table_ME_QUIZ + " where CATEGORY_Id =" + categoryID + " AND USER_ID='" + userId + "'AND " + CommonString.KEY_VISIT_DATE + "='" + visit_date + "'AND " + CommonString.KEY_COUNTER_ID + "=" + counterId + " and QuizId=" + quizId + "", null); + } + + if (cursordata != null) { + cursordata.moveToFirst(); + while (!cursordata.isAfterLast()) { + MEMEAuditQuestion sb = new MEMEAuditQuestion(); + sb.setQuizId(cursordata.getInt(cursordata.getColumnIndexOrThrow("QuizId"))); + sb.setUser_Id(cursordata.getString(cursordata.getColumnIndexOrThrow("USER_ID"))); + sb.setKeyId(cursordata.getString(cursordata.getColumnIndexOrThrow(CommonString.KEY_ID))); + sb.setQuestion(cursordata.getString(cursordata.getColumnIndexOrThrow("QUESTION"))); + sb.setQuestionId(cursordata.getInt(cursordata.getColumnIndexOrThrow("QUESTION_Id"))); + sb.setQuestionType(cursordata.getString(cursordata.getColumnIndexOrThrow("QUESTION_TYPE"))); + sb.setAnswer(cursordata.getString(cursordata.getColumnIndexOrThrow("ANSWER"))); + sb.setAnswerId(cursordata.getInt(cursordata.getColumnIndexOrThrow("ANSWER_Id"))); + sb.setStr_audit_img(cursordata.getString(cursordata.getColumnIndexOrThrow("IMAGE_STR"))); + if (cursordata.getString(cursordata.getColumnIndexOrThrow("IMAGE_ALLOW")).equals("1")) { + sb.setImageAllow(true); + } else { + sb.setImageAllow(false); + } + + auditData.add(sb); + cursordata.moveToNext(); + } + + cursordata.close(); + } + + } catch (Exception ex) { + ////////test("Exception ", " in ADDITIONAL_QUESTION " + ex.toString()); + } + + return auditData; + } + + + public ArrayList getme_quiz_from(String visit_date, String counterId, boolean previous_date) { + Cursor cursordata = null; + ArrayList auditData = new ArrayList<>(); + try { + + if (previous_date) { + cursordata = db.rawQuery("SELECT distinct USER_ID FROM " + CommonString.Table_ME_QUIZ + " where Visit_Date <>'" + visit_date + "'AND " + CommonString.KEY_COUNTER_ID + "=" + counterId + " AND UPLOAD_STATUS='N'", null); + } else { + cursordata = db.rawQuery("SELECT distinct USER_ID FROM " + CommonString.Table_ME_QUIZ + " where Visit_Date='" + visit_date + "'AND " + CommonString.KEY_COUNTER_ID + "=" + counterId + " AND UPLOAD_STATUS='N'", null); + } + if (cursordata != null) { + cursordata.moveToFirst(); + while (!cursordata.isAfterLast()) { + MEMEAuditQuestion sb = new MEMEAuditQuestion(); + sb.setUser_Id(cursordata.getString(cursordata.getColumnIndexOrThrow("USER_ID"))); + sb.setVisit_date(cursordata.getString(cursordata.getColumnIndexOrThrow(CommonString.KEY_VISIT_DATE))); + auditData.add(sb); + cursordata.moveToNext(); + } + cursordata.close(); + } + + } catch (Exception ex) { + ////////test("Exception ", " in ADDITIONAL_QUESTION " + ex.toString()); + } + + return auditData; + } + + + public ArrayList getRetailExcellence_from(String visit_date, String counterId, boolean previous_date) { + Cursor cursordata = null; + ArrayList auditData = new ArrayList<>(); + try { + + if (previous_date) { + cursordata = db.rawQuery("SELECT distinct USER_ID FROM " + CommonString.Table_Retail_Excellence_Child + " where Visit_Date <>'" + visit_date + "'AND " + CommonString.KEY_COUNTER_ID + "=" + counterId + " AND UPLOAD_STATUS='N'", null); + } else { + cursordata = db.rawQuery("SELECT distinct USER_ID FROM " + CommonString.Table_Retail_Excellence_Child + " where Visit_Date='" + visit_date + "'AND " + CommonString.KEY_COUNTER_ID + "=" + counterId + " AND UPLOAD_STATUS='N'", null); + } + + if (cursordata != null) { + cursordata.moveToFirst(); + while (!cursordata.isAfterLast()) { + MasterRetailExcellence sb = new MasterRetailExcellence(); + sb.setUser_Id(cursordata.getString(cursordata.getColumnIndexOrThrow("USER_ID"))); + sb.setKeyId(cursordata.getString(cursordata.getColumnIndexOrThrow(CommonString.KEY_COMMON_ID))); + sb.setItemId(cursordata.getInt(cursordata.getColumnIndexOrThrow("ItemId"))); + sb.setItemName(cursordata.getString(cursordata.getColumnIndexOrThrow("ItemName"))); + sb.setAnswer(cursordata.getString(cursordata.getColumnIndexOrThrow("Answer"))); + auditData.add(sb); + cursordata.moveToNext(); + } + + cursordata.close(); + } + + } catch (Exception ex) { + ////////test("Exception ", " in ADDITIONAL_QUESTION " + ex.toString()); + } + + return auditData; + } + + public ArrayList getProductMasterMeSale_from(String visit_date, String counterId, boolean previous_date) { + Cursor cursordata = null; + ArrayList productMasterArrayList = new ArrayList<>(); + try { + + if (previous_date) { + cursordata = db.rawQuery("SELECT distinct USER_ID FROM " + CommonString.TABLE_STORE_STOCK_CHILD_ME_SALE_DATA + " where Visit_Date <>'" + visit_date + "'AND " + CommonString.KEY_COUNTER_ID + "=" + counterId + " AND UploadStatus='N'", null); + } else { + cursordata = db.rawQuery("SELECT distinct USER_ID FROM " + CommonString.TABLE_STORE_STOCK_CHILD_ME_SALE_DATA + " where Visit_Date='" + visit_date + "'AND " + CommonString.KEY_COUNTER_ID + "=" + counterId + " AND UploadStatus='N'", null); + } + if (cursordata != null) { + cursordata.moveToFirst(); + while (!cursordata.isAfterLast()) { + ProductMaster sb = new ProductMaster(); + sb.setProductId(cursordata.getInt(cursordata.getColumnIndexOrThrow("ProductId"))); + sb.setKeyId(cursordata.getString(cursordata.getColumnIndexOrThrow(CommonString.KEY_COMMON_ID))); + sb.setImagePath(cursordata.getString(cursordata.getColumnIndexOrThrow("ImagePath"))); + sb.setCounter_id(cursordata.getString(cursordata.getColumnIndexOrThrow(CommonString.KEY_COUNTER_ID))); + sb.setStock(cursordata.getInt(cursordata.getColumnIndexOrThrow(CommonString.KEY_STOCK))); + productMasterArrayList.add(sb); + cursordata.moveToNext(); + } + cursordata.close(); + } + + } catch (Exception ex) { + ////////test("Exception ", " in ADDITIONAL_QUESTION " + ex.toString()); + } + + return productMasterArrayList; + } + + + public ArrayList getme_quiz(String userId, String visit_date, String counterId, String quizId) { + Cursor cursordata = null; + ArrayList auditData = new ArrayList<>(); + + try { + + cursordata = db.rawQuery("SELECT * FROM " + CommonString.Table_ME_QUIZ + " where USER_ID='" + userId + "'AND " + CommonString.KEY_VISIT_DATE + "='" + visit_date + "'AND " + CommonString.KEY_COUNTER_ID + "=" + counterId + " and QuizId=" + quizId + "", null); + + + if (cursordata != null) { + cursordata.moveToFirst(); + while (!cursordata.isAfterLast()) { + MEMEAuditQuestion sb = new MEMEAuditQuestion(); + sb.setQuizId(cursordata.getInt(cursordata.getColumnIndexOrThrow("QuizId"))); + sb.setUser_Id(cursordata.getString(cursordata.getColumnIndexOrThrow("USER_ID"))); + + auditData.add(sb); + cursordata.moveToNext(); + } + + cursordata.close(); + } + + } catch (Exception ex) { + ////////test("Exception ", " in ADDITIONAL_QUESTION " + ex.toString()); + } + + return auditData; + } + + public ArrayList getquiz_answer(String keyId) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + + dbcursor = db.rawQuery("Select * from ME_QUIZ_MULTI_ANS_TABLE where Common_Id ='" + keyId + "' AND IS_SELECTED='1'", null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + MEMEAuditQuestion sb = new MEMEAuditQuestion(); + sb.setAnswerId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("ANSWER_Id"))); + sb.setAnswer(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ANSWER"))); + String img_allow = dbcursor.getString(dbcursor.getColumnIndexOrThrow("IS_SELECTED")); + if (img_allow.equals("1")) { + sb.setSelected(true); + } else { + sb.setSelected(false); + } + + list.add(sb); + dbcursor.moveToNext(); + } + dbcursor.close(); + return list; + } + } catch (Exception e) { + ////////test("Exception", " answer " + e.toString()); + return list; + } + + ////////test("Fetching", " audit answer-->Stop<-"); + return list; + } + + public boolean ischeckedgetquiz_answer(String keyId, String userId, String ansId) { + boolean filled = false; + Cursor dbcursor = null; + try { + + dbcursor = db.rawQuery("Select * from ME_QUIZ_MULTI_ANS_TABLE where Common_Id ='" + keyId + "'and USER_ID='" + userId + "'and ANSWER_Id='" + ansId + "'", null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + String user_idget = dbcursor.getString(dbcursor.getColumnIndexOrThrow("IS_SELECTED")); + if (user_idget != null && user_idget.equals("1")) { + filled = true; + break; + } else { + filled = false; + } + + dbcursor.moveToNext(); + } + dbcursor.close(); + } + } catch (Exception e) { + ////////test("Exception--", e.toString()); + return filled; + } + + return filled; + } + + //jeevan nmjnmn, + public long update_Me_Quiz(String counterId, String user_Id) { + long l = 0; + ContentValues values = new ContentValues(); + try { + values.put("UPLOAD_STATUS", CommonString.KEY_Y); + if (!db.isOpen()) { + open(); + } + l = db.update(CommonString.Table_ME_QUIZ, values, CommonString.KEY_COUNTER_ID + "=" + counterId + " AND USER_ID='" + user_Id + "'", null); + + } catch (Exception e) { + e.fillInStackTrace(); + } + return l; + } + + public long update_retail_excellence(String counterId, String user_Id) { + long l = 0; + ContentValues values = new ContentValues(); + try { + values.put("UPLOAD_STATUS", CommonString.KEY_Y); + if (!db.isOpen()) { + open(); + } + l = db.update(CommonString.Table_Retail_Excellence_Header, values, CommonString.KEY_COUNTER_ID + "=" + counterId + " AND USER_ID='" + user_Id + "'", null); + l = db.update(CommonString.Table_Retail_Excellence_Child, values, CommonString.KEY_COUNTER_ID + "=" + counterId + " AND USER_ID='" + user_Id + "'", null); + } catch (Exception e) { + e.fillInStackTrace(); + } + return l; + } + + public long update_me_sale(String counterId, String user_Id) { + long l = 0; + ContentValues values = new ContentValues(); + try { + values.put("UploadStatus", CommonString.KEY_Y); + if (!db.isOpen()) { + open(); + } + l = db.update(CommonString.TABLE_INSERT_HEADER_ME_SALE_DATA, values, CommonString.KEY_COUNTER_ID + "=" + counterId + " AND USER_ID='" + user_Id + "'", null); + l = db.update(CommonString.TABLE_STORE_STOCK_CHILD_ME_SALE_DATA, values, CommonString.KEY_COUNTER_ID + "=" + counterId + " AND USER_ID='" + user_Id + "'", null); + } catch (Exception e) { + e.fillInStackTrace(); + } + return l; + } + + public long update_makeover(String counterId, String user_Id, String keyId, boolean manual_upload) { + long l = 0; + try { + ContentValues values = new ContentValues(); + values.put("UPLOAD_STATUS", CommonString.KEY_Y); + if (manual_upload) { + if (!db.isOpen()) { + open(); + } + l = db.update(CommonString.Table_Makeover_Capture, values, CommonString.KEY_COUNTER_ID + "=" + counterId + " AND UNIQUE_CODE='" + keyId + "'", null); + + } else { + if (!db.isOpen()) { + open(); + } + l = db.update(CommonString.Table_Makeover_Capture, values, CommonString.KEY_COUNTER_ID + "=" + counterId + " AND USER_ID='" + user_Id + "' AND " + CommonString.KEY_ID + "='" + keyId + "'", null); + } + } catch (Exception e) { + e.fillInStackTrace(); + } + return l; + } + + public boolean insertPromotionMaster(ResponseResult cst) { + db.delete("Master_Promotion", null, null); + ContentValues values = new ContentValues(); + List data = cst.getMasterPromotion(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("CounterId", data.get(i).getCounterId()); + values.put("PromoId", data.get(i).getPromoId()); + values.put("PromotionSetEntityType", data.get(i).getPromotionSetEntityType().trim()); + values.put("PromotionGetEntityType", data.get(i).getPromotionGetEntityType().trim()); + values.put("PromotionSetEntityValue", data.get(i).getPromotionSetEntityValue()); + values.put("PromotionGetEntityValue", data.get(i).getPromotionGetEntityValue()); + values.put("PromotionCode", data.get(i).getPromotionCode().trim()); + values.put("PromotionName", data.get(i).getPromotionName().trim()); + values.put("StartTime", data.get(i).getStartTime()); + values.put("EndTime", data.get(i).getEndTime()); + + values.put("StartDate", data.get(i).getStartDate()); + values.put("EndDate", data.get(i).getEndDate()); + values.put("PromoPath", data.get(i).getPromoPath()); + values.put("PromoOfferTab", data.get(i).getPromoOfferTab()); + values.put("PromoOfferMobile", data.get(i).getPromoOfferMobile()); + values.put("MaxValue", data.get(i).getMaxValue()); + values.put("PromoType", data.get(i).getPromoType().trim()); + + if (!db.isOpen()) { + open(); + } + long id = db.insert("Master_Promotion", null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ex.fillInStackTrace(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + public boolean insertPromotionSetEntityItemMaster(ResponseResult cst) { + db.delete("Master_PromotionSetEntityItem", null, null); + ContentValues values = new ContentValues(); + List data = cst.getMasterPromotionSetEntityItem(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("PromoId", data.get(i).getPromoId()); + values.put("SetEntityListType", data.get(i).getSetEntityListType()); + values.put("SetEntityListItem", data.get(i).getSetEntityListItem()); + values.put("ItemCount", data.get(i).getItemCount()); + values.put("Id", data.get(i).getId()); + + long id = db.insert("Master_PromotionSetEntityItem", null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ex.fillInStackTrace(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + public boolean insertPromotionGetEntityItemMaster(ResponseResult cst) { + db.delete("Master_PromotionGetEntityItem", null, null); + ContentValues values = new ContentValues(); + List data = cst.getMasterPromotionGetEntityItem(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("PromoId", data.get(i).getPromoId()); + values.put("GetEntityListType", data.get(i).getGetEntityListType()); + values.put("GetEntityListItem", data.get(i).getGetEntityListItem()); + + long id = db.insert("Master_PromotionGetEntityItem", null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ex.fillInStackTrace(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + + public boolean insertPromotionGetProductGroupMaster(ResponseResult cst) { + db.delete("Master_PromotionGetProductGroup", null, null); + ContentValues values = new ContentValues(); + List data = cst.getMasterPromotionGetProductGroup(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("ProductGroupId", data.get(i).getProductGroupId()); + values.put("ProductId", data.get(i).getProductId()); + + long id = db.insert("Master_PromotionGetProductGroup", null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ex.fillInStackTrace(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + public boolean insertMasterPromotionSetProductCatalog(ResponseResult cst) { + db.delete("Master_PromotionSetProductCatalog", null, null); + ContentValues values = new ContentValues(); + List data = cst.getMasterPromotionSetProductCatalog(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("CatalogId", data.get(i).getCatalogId()); + values.put("ProductId", data.get(i).getProductId()); + + long id = db.insert("Master_PromotionSetProductCatalog", null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ex.fillInStackTrace(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + public boolean insertMasterPromotionGetProductCatalog(ResponseResult cst) { + db.delete("Master_PromotionGetProductCatalog", null, null); + ContentValues values = new ContentValues(); + List data = cst.getMasterPromotionGetProductCatalog(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("CatalogId", data.get(i).getCatalogId()); + values.put("ProductId", data.get(i).getProductId()); + + long id = db.insert("Master_PromotionGetProductCatalog", null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ex.fillInStackTrace(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + public boolean insertPromotionSetProductGroupMaster(ResponseResult cst) { + db.delete("Master_PromotionSetProductGroup", null, null); + ContentValues values = new ContentValues(); + List data = cst.getMasterPromotionSetProductGroup(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("ProductGroupId", data.get(i).getProductGroupId()); + values.put("ProductId", data.get(i).getProductId()); + + long id = db.insert("Master_PromotionSetProductGroup", null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ex.fillInStackTrace(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + //get Promotion master data + public ArrayList getPromotionMaster(boolean flag) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + if (flag) { + dbcursor = db.rawQuery("Select * from Master_Promotion where PromotionSetEntityType='Product' and" + " PromotionGetEntityType in " + "('Product' ,'Worth','Gift','OffWorth','OffProduct','OffSameProduct','WorthWithProduct')", null); + } else { + dbcursor = db.rawQuery("Select * from Master_Promotion where PromotionSetEntityType='Worth'" + " and PromotionGetEntityType in " + "('Product' ,'Worth' ,'Gift','OffWorth','OffProduct','OffAdditionalProduct','ValueOffAdditionalProduct')", null); + } + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + MasterPromotion sb = new MasterPromotion(); + sb.setPromoId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("PromoId"))); + sb.setPromotionSetEntityType(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PromotionSetEntityType"))); + sb.setPromotionGetEntityType(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PromotionGetEntityType"))); + sb.setPromotionSetEntityValue(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PromotionSetEntityValue"))); + sb.setPromotionGetEntityValue(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PromotionGetEntityValue"))); + sb.setPromotionCode(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PromotionCode"))); + sb.setPromotionName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PromotionName"))); + sb.setStartTime(dbcursor.getString(dbcursor.getColumnIndexOrThrow("StartTime"))); + sb.setEndTime(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EndTime"))); + sb.setStartDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("StartDate"))); + sb.setEndDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EndDate"))); + sb.setPromoPath(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PromoPath"))); + sb.setPromoOfferTab(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PromoOfferTab"))); + sb.setPromoOfferMobile(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PromoOfferMobile"))); + sb.setMaxValue(dbcursor.getString(dbcursor.getColumnIndexOrThrow("MaxValue"))); + sb.setPromoType(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PromoType"))); + list.add(sb); + dbcursor.moveToNext(); + } + dbcursor.close(); + return list; + } + } catch (Exception e) { + ////////test("Exception", " answer " + e.toString()); + return list; + } + + ////////test("Fetching", " audit answer-->Stop<-"); + return list; + } + + + public ArrayList getqualified_Product_List(String counterId, String userId, String visit_date, int promoId) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + + dbcursor = db.rawQuery("select distinct PM.EanCode as EanCode, PM.ProductName as ProductName,TA.Quantity as Quantity,TA.Rate as Rate," + "TA.ProductId as ProductId,TA.PromoId as PromoId" + " from Temp_Promo_AplyDefinition TA inner join" + " Product_Master PM on PM.ProductId=TA.ProductId where COUNTER_ID =" + counterId + " and User_Id = '" + userId + "' and Visit_Date ='" + visit_date + "' and PromoId =" + promoId + " Order By Rate Desc", null); + + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + InvoiceGetterSetter sb = new InvoiceGetterSetter(); + sb.setProduct(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ProductName"))); + sb.setQuantity(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Quantity"))); + sb.setProduct_rate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Rate"))); + sb.setProduct_Id(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ProductId"))); + sb.setPromotion_Id(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PromoId"))); + sb.setScan_ean_code_or_enterd_ean_code(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EanCode"))); + list.add(sb); + dbcursor.moveToNext(); + } + dbcursor.close(); + return list; + } + } catch (Exception e) { + ////////test("Exception", " answer " + e); + return list; + } + + ////////test("Fetching", " audit answer-->Stop<-"); + return list; + } + + public ArrayList getqualifiedOffSameProduct(String counterId, String userId, String visit_date, int promoId) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + dbcursor = db.rawQuery("select distinct PM.EanCode as EanCode, PM.ProductName as ProductName,TA.Quantity as Quantity,TA.Rate as Rate," + "TA.ProductId as ProductId,TA.PromoId as PromoId from Temp_Promotion_OffSameProduct TA inner join" + " Product_Master PM on PM.ProductId=TA.ProductId where COUNTER_ID =" + counterId + " and User_Id = '" + userId + "' and Visit_Date ='" + visit_date + "' and PromoId =" + promoId + " Order By Rate Desc", null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + InvoiceGetterSetter sb = new InvoiceGetterSetter(); + sb.setProduct(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ProductName"))); + sb.setQuantity(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Quantity"))); + sb.setProduct_rate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Rate"))); + sb.setProduct_Id(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ProductId"))); + sb.setPromotion_Id(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PromoId"))); + sb.setScan_ean_code_or_enterd_ean_code(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EanCode"))); + list.add(sb); + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list; + } + } catch (Exception e) { + ////////test("Exception", " answer " + e.toString()); + return list; + } + + ////////test("Fetching", " audit answer-->Stop<-"); + return list; + } + + //get Promotion Set Entity Item + //get Promotion Set Product Group + + @SuppressLint("Recycle") + public ArrayList getPromotiongetProduct(int promoId, String getentityType, String visit_date, String counterId, String userType) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + Cursor dbcursor1 = null; + String balancekey = ""; + String q1 = userType != null && userType.equalsIgnoreCase(CommonString.TAG_FROM_ME) ? " AND T1." + CommonString.KEY_USER_TYPE + "='" + CommonString.TAG_FROM_ME + "'" : " AND T1." + CommonString.KEY_USER_TYPE + "!='" + CommonString.TAG_FROM_ME + "' AND T2.POS_SALE_FLAG='0'"; + String q2 = userType != null && userType.equalsIgnoreCase(CommonString.TAG_FROM_ME) ? " AND S." + CommonString.KEY_USER_TYPE + "='" + CommonString.TAG_FROM_ME + "'" : " AND S." + CommonString.KEY_USER_TYPE + "!='" + CommonString.TAG_FROM_ME + "' AND S1.POS_SALE_FLAG ='0'"; + + String additionQueryMe = "", getDataMe = "(ts.SaleableBalance - ifnull(t.DamageQty,0)) as SaleableBalance"; + String table = "T_StockSummary", query = "", ts_banace_me = " and ts.SaleableBalance >0"; + if (userType != null && userType.equalsIgnoreCase(CommonString.TAG_FROM_ME)) { + ts_banace_me = ""; + getDataMe = "((ts.SaleableBalance + ifnull(tempsale.TempSale,0) ) - ifnull(t.DamageQty,0)) as SaleableBalance"; + + additionQueryMe = " left join (select ProductId, case when (Select count(*) from (" + " Select CounterId, ProductId," + "sum(TempQty) as TempQty from ( Select T2.COUNTER_ID AS CounterId, T1.PRODUCT_ID AS ProductId , SUM(T1.QUANTITY) AS TempQty FROM SALE_TRACKING_TABLE T1" + " INNER JOIN SALE_TRACKING_HEADER_TABLE T2 ON T2.RECCEPT_COUNT=T1.RECCEPT_COUNT WHERE T2.COUNTER_ID =" + counterId + " AND T2.Visit_Date='" + visit_date + "' AND T1.INVOICE_TYPE='Saleable'" + " AND T1.RIGHTNAME !='ME' AND T1.POS_SALE_FLAG !=0 GROUP BY T1.PRODUCT_ID" + " UNION ALL select S.COUNTER_ID as CounterId," + " S.PROMO_PRODUCT_ID AS ProductId , SUM(S.PROMO_PRODUCT_QTY) AS TempQty from APPLYED_PROMOTION_TABLE S INNER JOIN SALE_TRACKING_HEADER_TABLE S1" + " ON S.RECCEPT_COUNT=S1.RECCEPT_COUNT Where S.PROMO_TYPE ='Product' AND S.COUNTER_ID =" + counterId + " AND S1.VISIT_DATE = '" + visit_date + "'" + " AND S.RIGHTNAME !='ME' AND S1.POS_SALE_FLAG !=0 GROUP BY S.PROMO_PRODUCT_ID)as t Group by CounterId, ProductId" + ")" + " c where c.ProductId = t.Productid)>0 then" + " (Select TempQty from (" + " Select CounterId, ProductId," + "sum(TempQty) as TempQty from ( Select T2.COUNTER_ID AS CounterId,T1.PRODUCT_ID AS ProductId,SUM(T1.QUANTITY) AS TempQty FROM SALE_TRACKING_TABLE T1" + " INNER JOIN SALE_TRACKING_HEADER_TABLE T2 ON T2.RECCEPT_COUNT=T1.RECCEPT_COUNT WHERE T2.COUNTER_ID =" + counterId + " AND T2.Visit_Date='" + visit_date + "' AND T1.INVOICE_TYPE='Saleable'" + " AND T1.RIGHTNAME !='ME' AND T1.POS_SALE_FLAG !=0 GROUP BY T1.PRODUCT_ID" + " UNION ALL select S.COUNTER_ID as CounterId," + " S.PROMO_PRODUCT_ID AS ProductId , SUM(S.PROMO_PRODUCT_QTY) AS TempQty from APPLYED_PROMOTION_TABLE S INNER JOIN SALE_TRACKING_HEADER_TABLE S1" + " ON S.RECCEPT_COUNT=S1.RECCEPT_COUNT Where S.PROMO_TYPE ='Product' AND S.COUNTER_ID =" + counterId + " AND S1.VISIT_DATE = '" + visit_date + "'" + " AND S.RIGHTNAME !='ME' AND S1.POS_SALE_FLAG !=0 GROUP BY S.PROMO_PRODUCT_ID)as t Group by CounterId, ProductId" + " ) c where c.productId = t.Productid) else (" + "Select sum(QtySold)as QtySold from (select SaleQty as QtySold from Report_BA_TBASale s where s.ProductId = t.ProductId and s.CounterId=" + counterId + " and VisitDate='" + visit_date + "'" + "UNION all select SaleQty as QtySold from Report_BA_TBAPromoSale s where s.ProductId = t.ProductId and s.CounterId=" + counterId + " and VisitDate='" + visit_date + "')" + ") end as TempSale" + " from T_StockSummary t) as tempsale on ts.ProductId=tempsale.ProductId"; + } + + try { + + dbcursor1 = db.rawQuery("Select * from Master_PromotionGetEntityItem where PromoId=" + promoId, null); + + if (dbcursor1 != null) { + dbcursor1.moveToFirst(); + while (!dbcursor1.isAfterLast()) { + String setentitiy_listType = dbcursor1.getString(dbcursor1.getColumnIndexOrThrow("GetEntityListType")); + ////changes for all Products 03-16-2020................. + String get_entity_list_itemfor_product = dbcursor1.getString(dbcursor1.getColumnIndexOrThrow("GetEntityListItem")); + if (getentityType.equalsIgnoreCase("Gift")) { + balancekey = "GwpBalance"; + } else { + balancekey = "SaleableBalance"; + } + if (setentitiy_listType != null && !setentitiy_listType.isEmpty() && setentitiy_listType.trim().equalsIgnoreCase("ProductGroup")) { + if (getentityType.equalsIgnoreCase("Gift")) { + dbcursor = db.rawQuery("WITH RECURSIVE neat( id, tag, etc) AS(SELECT PromoId, '' , GetEntityListItem || ',' FROM" + " Master_PromotionGetEntityItem WHERE PromoId=" + promoId + " UNION ALL SELECT id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '')" + " select distinct MP.ProductId as ProductId,PM.ProductName as ProductName,PM.Mrp as Mrp,PM.EanCode as EanCode," + "(ts.GwpBalance - ifnull(t.DamageQty,0)) as" + " GwpBalance from Master_PromotionGetProductGroup MP" + " inner join Product_Master PM on PM.ProductID=MP.ProductID inner join " + table + " ts on ts.ProductId= PM.ProductID" + " left join(Select CounterId, ProductId, sum(DamageQty) as DamageQty from(" + " Select T2.COUNTER_ID AS CounterId, T1.PRODUCT_ID AS ProductId , SUM(T1.QUANTITY) AS DamageQty FROM SALE_TRACKING_TABLE T1" + " INNER JOIN SALE_TRACKING_HEADER_TABLE T2 ON T2.RECCEPT_COUNT=T1.RECCEPT_COUNT" + " WHERE T2.COUNTER_ID =" + counterId + " AND T2.Visit_Date='" + visit_date + "' AND T1.INVOICE_TYPE='GWP'" + q1 + " GROUP BY T1.PRODUCT_ID" + " UNION ALL select S.COUNTER_ID, S.PROMO_PRODUCT_ID AS PRODUCT_ID , SUM(S.PROMO_PRODUCT_QTY) AS QUANTITY from" + " APPLYED_PROMOTION_TABLE S" + " INNER JOIN SALE_TRACKING_HEADER_TABLE S1 ON S.RECCEPT_COUNT=S1.RECCEPT_COUNT" + " Where S.PROMO_TYPE ='Gift' AND S.COUNTER_ID = " + counterId + " AND S1.VISIT_DATE = '" + visit_date + "'" + q2 + " GROUP BY S.PROMO_PRODUCT_ID UNION ALL" + " SELECT COUNTER_ID as CounterId,ProductId,Quantity as DamageQty from Temp_Sale" + " where COUNTER_ID =" + counterId + " and Visit_Date ='" + visit_date + "' and Product_Type='GWP' GROUP By ProductId) as t" + " Group by CounterId, ProductId) as t on PM.ProductId = t.ProductId and t.ProductId=MP.ProductId" + " where ProductGroupId in(SELECT tag FROM neat WHERE tag <> '' ORDER BY id ASC , tag ASC) and ts.GwpBalance >0" + + + " and PM.ProductId not in( WITH RECURSIVE neat( id, ProductId, etc) AS(SELECT PromoId, '' , GetExclusionList || ','" + " FROM Master_PromotionGetExclusionList WHERE PromoId=" + promoId + " UNION ALL SELECT id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1)" + " FROM neat WHERE etc <> '') SELECT ProductId FROM neat WHERE ProductId <> '')", null); + } else { + dbcursor = db.rawQuery("WITH RECURSIVE neat( id, tag, etc) AS(SELECT PromoId, '' , GetEntityListItem || ',' FROM" + " Master_PromotionGetEntityItem" + " WHERE PromoId=" + promoId + " UNION ALL SELECT id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '')" + " select distinct MP.ProductId as ProductId,PM.ProductName as ProductName,PM.Mrp as Mrp,PM.EanCode as EanCode," + getDataMe + " from Master_PromotionGetProductGroup MP inner join Product_Master PM" + " on PM.ProductID=MP.ProductID inner join " + table + " ts on ts.ProductId= PM.ProductID" + " left join(Select CounterId, ProductId, sum(DamageQty) as DamageQty from(" + " select T.COUNTER_ID as CounterId, T.ProductId as ProductId, T.Stock as DamageQty from TABLE_TRANSACTION_DATA T" + " INNER JOIN DR_TABLE_TRANSACTION_WISE_MASTER M ON T.MASTER_TRANSACTION_ID = M.MASTER_TRANSACTION_ID where" + " T.STOCK_TYPE='DAMAGE' AND T.Visit_Date ='" + visit_date + "' and T.COUNTER_ID =" + counterId + " Union All SELECT CounterId, ProductId, DamageQty from" + " Damage_PreviousPending Where CounterId =" + counterId + " and Verify ='Pending'" + " Union All Select T2.COUNTER_ID AS CounterId, T1.PRODUCT_ID AS ProductId , SUM(T1.QUANTITY) AS DamageQty FROM SALE_TRACKING_TABLE T1" + " INNER JOIN SALE_TRACKING_HEADER_TABLE T2 ON T2.RECCEPT_COUNT=T1.RECCEPT_COUNT" + " WHERE T2.COUNTER_ID =" + counterId + " AND T2.Visit_Date='" + visit_date + "' AND T1.INVOICE_TYPE='Saleable'" + q1 + " GROUP BY T1.PRODUCT_ID" + " UNION ALL select S.COUNTER_ID, S.PROMO_PRODUCT_ID AS PRODUCT_ID , SUM(S.PROMO_PRODUCT_QTY) AS QUANTITY from" + " APPLYED_PROMOTION_TABLE S INNER JOIN SALE_TRACKING_HEADER_TABLE S1 ON S.RECCEPT_COUNT=S1.RECCEPT_COUNT" + " Where S.PROMO_TYPE ='Product' AND S.COUNTER_ID = " + counterId + " AND S1.VISIT_DATE = '" + visit_date + "'" + q2 + " GROUP BY S.PROMO_PRODUCT_ID UNION ALL" + " SELECT COUNTER_ID as CounterId,ProductId,Quantity as DamageQty from Temp_Sale where" + " COUNTER_ID =" + counterId + " and Visit_Date = '" + visit_date + "' GROUP By ProductId) as t Group by CounterId, ProductId) as t" + " on PM.ProductId = t.ProductId and t.ProductId=MP.ProductId" + additionQueryMe + " where ProductGroupId in(SELECT tag FROM neat WHERE tag <> '' ORDER BY id ASC , tag ASC)" + + + ts_banace_me + + + " and PM.ProductId not in( WITH RECURSIVE neat( id, ProductId, etc) AS(SELECT PromoId, '' , GetExclusionList || ','" + " FROM Master_PromotionGetExclusionList WHERE PromoId=" + promoId + " UNION ALL SELECT id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1)" + " FROM neat WHERE etc <> '') SELECT ProductId FROM neat WHERE ProductId <> '')", null); + + } + + } else if (setentitiy_listType != null && !setentitiy_listType.isEmpty() && setentitiy_listType.trim().equalsIgnoreCase("Catalog")) { + if (!getentityType.equals("") && getentityType.equalsIgnoreCase("Gift")) { + dbcursor = db.rawQuery("WITH RECURSIVE neat( id, tag, etc) AS(SELECT PromoId, '' , GetEntityListItem || ','" + " from Master_PromotionGetEntityItem WHERE PromoId=" + promoId + " UNION ALL SELECT id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1)" + " from neat WHERE etc <> '')" + " select distinct MP.ProductId as ProductId,PM.ProductName as ProductName,PM.Mrp as Mrp,PM.EanCode as EanCode," + "(ts.GwpBalance - ifnull(t.DamageQty,0)) as GwpBalance from Master_PromotionGetProductCatalog MP" + " inner join Product_Master PM on PM.ProductID=MP.ProductID inner join " + table + " ts on ts.ProductId= PM.ProductID" + " left join(Select CounterId, ProductId, sum(DamageQty) as DamageQty from (" + " Select T2.COUNTER_ID AS CounterId, T1.PRODUCT_ID AS ProductId , SUM(T1.QUANTITY) AS DamageQty FROM SALE_TRACKING_TABLE T1" + " INNER JOIN SALE_TRACKING_HEADER_TABLE T2 ON T2.RECCEPT_COUNT=T1.RECCEPT_COUNT" + " WHERE T2.COUNTER_ID =" + counterId + " AND T2.Visit_Date='" + visit_date + "' AND T1.INVOICE_TYPE='GWP'" + q1 + " GROUP BY T1.PRODUCT_ID" + " UNION ALL select S.COUNTER_ID, S.PROMO_PRODUCT_ID AS PRODUCT_ID,SUM(S.PROMO_PRODUCT_QTY) AS QUANTITY from APPLYED_PROMOTION_TABLE S" + " INNER JOIN SALE_TRACKING_HEADER_TABLE S1 ON S.RECCEPT_COUNT=S1.RECCEPT_COUNT" + " Where S.PROMO_TYPE ='Gift' AND S.COUNTER_ID =" + counterId + " AND S1.VISIT_DATE = '" + visit_date + "'" + q2 + " GROUP BY S.PROMO_PRODUCT_ID UNION ALL" + " SELECT COUNTER_ID as CounterId,ProductId,Quantity as DamageQty from Temp_Sale where" + " COUNTER_ID =" + counterId + " and Visit_Date = '" + visit_date + "' and Product_Type='GWP' GROUP By ProductId) as t" + " Group by CounterId, ProductId) as t on PM.ProductId = t.ProductId and t.ProductId=MP.ProductId" + " where CatalogId in(SELECT tag FROM neat WHERE tag <> '' ORDER BY id ASC , tag ASC) and ts.GwpBalance >0" + + + " and PM.ProductId not in( WITH RECURSIVE neat( id, ProductId, etc) AS(SELECT PromoId, '' , GetExclusionList || ','" + " FROM Master_PromotionGetExclusionList WHERE PromoId=" + promoId + " UNION ALL SELECT id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1)" + " FROM neat WHERE etc <> '') SELECT ProductId FROM neat WHERE ProductId <> '')", null); + + } else { + dbcursor = db.rawQuery(" WITH RECURSIVE neat( id, tag, etc) AS(SELECT PromoId, '' , GetEntityListItem || ','" + " from Master_PromotionGetEntityItem WHERE PromoId=" + promoId + " UNION ALL SELECT id, SUBSTR(etc, 0, INSTR(etc, ',')) ," + " SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '')" + " select distinct MP.ProductId as ProductId,PM.ProductName as ProductName,PM.Mrp as Mrp,PM.EanCode as EanCode," + getDataMe + " from" + " Master_PromotionGetProductCatalog MP" + " inner join Product_Master PM on PM.ProductID=MP.ProductID inner join " + table + " ts on ts.ProductId= PM.ProductID" + " left join(Select CounterId, ProductId, sum(DamageQty) as DamageQty from (" + " select T.COUNTER_ID as CounterId, T.ProductId as ProductId, T.Stock as DamageQty from TABLE_TRANSACTION_DATA T" + " INNER JOIN DR_TABLE_TRANSACTION_WISE_MASTER M ON T.MASTER_TRANSACTION_ID = M.MASTER_TRANSACTION_ID where" + " T.STOCK_TYPE='DAMAGE' AND T.Visit_Date ='" + visit_date + "' and T.COUNTER_ID =" + counterId + " Union All" + " SELECT CounterId, ProductId, DamageQty from" + " Damage_PreviousPending Where CounterId =" + counterId + " and Verify ='Pending' Union All" + " Select T2.COUNTER_ID AS CounterId, T1.PRODUCT_ID AS ProductId,SUM(T1.QUANTITY) AS DamageQty FROM SALE_TRACKING_TABLE T1" + " INNER JOIN SALE_TRACKING_HEADER_TABLE T2 ON T2.RECCEPT_COUNT=T1.RECCEPT_COUNT" + " WHERE T2.COUNTER_ID =" + counterId + " AND T2.Visit_Date='" + visit_date + "' AND" + " T1.INVOICE_TYPE='Saleable'" + q1 + " GROUP BY T1.PRODUCT_ID UNION ALL" + " select S.COUNTER_ID, S.PROMO_PRODUCT_ID AS PRODUCT_ID , SUM(S.PROMO_PRODUCT_QTY) AS QUANTITY from" + " APPLYED_PROMOTION_TABLE S INNER JOIN SALE_TRACKING_HEADER_TABLE S1 ON S.RECCEPT_COUNT=S1.RECCEPT_COUNT" + " Where S.PROMO_TYPE ='Product' AND S.COUNTER_ID = " + counterId + " AND S1.VISIT_DATE = '" + visit_date + "'" + q2 + " GROUP BY S.PROMO_PRODUCT_ID UNION ALL" + " SELECT COUNTER_ID as CounterId,ProductId,Quantity as DamageQty from Temp_Sale where" + " COUNTER_ID =" + counterId + " and Visit_Date ='" + visit_date + "' and Product_Type='Saleable' GROUP By ProductId) as t" + " Group by CounterId, ProductId) as t on PM.ProductId = t.ProductId and t.ProductId=MP.ProductId" + additionQueryMe + " where CatalogId in(SELECT tag FROM neat WHERE tag <> '' ORDER BY id ASC , tag ASC)" + ts_banace_me + " and PM.ProductId not in( WITH RECURSIVE neat( id, ProductId, etc) AS(SELECT PromoId, '' , GetExclusionList || ','" + " FROM Master_PromotionGetExclusionList WHERE PromoId=" + promoId + " UNION ALL SELECT id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1)" + " FROM neat WHERE etc <> '') SELECT ProductId FROM neat WHERE ProductId <> '')", null); + } + + } else { + ////changes for all Products 03-16-2020................. + if (get_entity_list_itemfor_product != null && get_entity_list_itemfor_product.equalsIgnoreCase("All")) { + if (getentityType.equalsIgnoreCase("Gift")) { + //-----------Get Gift product All form T_Stock + dbcursor = db.rawQuery("select distinct PM.ProductId as ProductId,PM.ProductName as ProductName," + "PM.Mrp as Mrp,PM.EanCode as EanCode,(ts.GwpBalance - ifnull(t.DamageQty,0)) as GwpBalance from Product_Master PM" + " inner join " + table + " ts on ts.ProductId= PM.ProductID Left join (Select CounterId, ProductId, sum(DamageQty) as DamageQty from (" + " Select T2.COUNTER_ID AS CounterId,T1.PRODUCT_ID AS ProductId,SUM(T1.QUANTITY) AS DamageQty FROM SALE_TRACKING_TABLE T1 INNER JOIN SALE_TRACKING_HEADER_TABLE T2 ON" + " T2.RECCEPT_COUNT=T1.RECCEPT_COUNT" + " WHERE T2.COUNTER_ID =" + counterId + " AND T2.Visit_Date='" + visit_date + "' AND T1.INVOICE_TYPE='GWP'" + q1 + " GROUP BY T1.PRODUCT_ID" + " UNION ALL" + " select S.COUNTER_ID, S.PROMO_PRODUCT_ID AS PRODUCT_ID,SUM(S.PROMO_PRODUCT_QTY) AS QUANTITY from APPLYED_PROMOTION_TABLE S INNER JOIN SALE_TRACKING_HEADER_TABLE S1" + " ON S.RECCEPT_COUNT=S1.RECCEPT_COUNT" + " Where S.PROMO_TYPE ='Gift' AND S.COUNTER_ID =" + counterId + " AND S1.VISIT_DATE ='" + visit_date + "'" + q2 + " GROUP BY S.PROMO_PRODUCT_ID UNION ALL SELECT COUNTER_ID as CounterId,ProductId,Quantity as DamageQty from Temp_Sale" + " where COUNTER_ID =" + counterId + " and Visit_Date = '" + visit_date + "' and Product_Type='GWP' GROUP By ProductId) as t Group by CounterId, ProductId" + " ) as t on PM.ProductId = t.ProductId where ts.GwpBalance >0" + + + " and PM.ProductId not in( WITH RECURSIVE neat( id, ProductId, etc) AS(SELECT PromoId, '' , GetExclusionList || ','" + " FROM Master_PromotionGetExclusionList WHERE PromoId=" + promoId + " UNION ALL SELECT id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1)" + " FROM neat WHERE etc <> '') SELECT ProductId FROM neat WHERE ProductId <> '')", null); + } else { + ////Get product Saleable all from T_Stock Summery------------ + dbcursor = db.rawQuery("select distinct PM.ProductId as ProductId,PM.ProductName as ProductName,PM.Mrp as Mrp,PM.EanCode as EanCode," + "TS.SaleableBalance as SaleableBalance from" + " Product_Master PM left join (" + " Select ts.ProductId as ProductId," + getDataMe + " from " + table + " ts Left join(Select CounterId, ProductId, sum(DamageQty) as DamageQty from(" + " select T.COUNTER_ID as CounterId, T.ProductId, T.Stock as DamageQty from TABLE_TRANSACTION_DATA T" + " INNER JOIN DR_TABLE_TRANSACTION_WISE_MASTER M ON T.MASTER_TRANSACTION_ID = M.MASTER_TRANSACTION_ID where" + " T.STOCK_TYPE='DAMAGE' AND T.Visit_Date ='" + visit_date + "' and T.COUNTER_ID =" + counterId + " Union All SELECT CounterId, ProductId, DamageQty from" + " Damage_PreviousPending Where CounterId =" + counterId + " and Verify ='Pending'" + " Union All" + " Select T2.COUNTER_ID AS CounterId, T1.PRODUCT_ID AS ProductId , SUM(T1.QUANTITY) AS DamageQty FROM SALE_TRACKING_TABLE T1" + " INNER JOIN SALE_TRACKING_HEADER_TABLE T2 ON T2.RECCEPT_COUNT=T1.RECCEPT_COUNT" + " WHERE T2.COUNTER_ID =" + counterId + " AND T2.Visit_Date='" + visit_date + "' AND T1.INVOICE_TYPE='Saleable'" + q1 + " GROUP BY T1.PRODUCT_ID" + " UNION ALL" + " select S.COUNTER_ID, S.PROMO_PRODUCT_ID AS PRODUCT_ID,SUM(S.PROMO_PRODUCT_QTY) AS QUANTITY from APPLYED_PROMOTION_TABLE S" + " INNER JOIN SALE_TRACKING_HEADER_TABLE S1" + " ON S.RECCEPT_COUNT=S1.RECCEPT_COUNT" + " Where S.PROMO_TYPE ='Product' AND S.COUNTER_ID = " + counterId + " AND S1.VISIT_DATE = '" + visit_date + "'" + q2 + " GROUP BY S.PROMO_PRODUCT_ID UNION ALL" + " SELECT COUNTER_ID as CounterId,ProductId,Quantity as DamageQty from Temp_Sale" + " where COUNTER_ID =" + counterId + " and Visit_Date = '" + visit_date + "'and Product_Type='Saleable' GROUP By ProductId" + " ) as t" + " Group by CounterId, ProductId) as t on ts.ProductId = t.ProductId" + additionQueryMe + ") as" + " TS ON TS.ProductId = PM.ProductId " + " where TS.SaleableBalance > 0 order by PM.ProductName and PM.ProductType = 'Normal'" + + + " and PM.ProductId not in( WITH RECURSIVE neat( id, ProductId, etc) AS(SELECT PromoId, '' , GetExclusionList || ','" + " FROM Master_PromotionGetExclusionList WHERE PromoId=" + promoId + " UNION ALL SELECT id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1)" + " FROM neat WHERE etc <> '') SELECT ProductId FROM neat WHERE ProductId <> '')", null); + } + + } else { + ////for some product Query with Master_PromotionGetEntityItem + if (getentityType.equalsIgnoreCase("Gift")) { + ///for get Gift product using mapping------- + dbcursor = db.rawQuery("select distinct PM.ProductId as ProductId,PM.ProductName as ProductName,PM.Mrp as Mrp,PM.EanCode as EanCode," + " (ts.GwpBalance - ifnull(t.DamageQty,0)) as GwpBalance" + " from Product_Master PM inner join " + table + " ts on ts.ProductId= PM.ProductID Left join" + " (Select CounterId, ProductId, sum(DamageQty) as DamageQty from(" + " Select T2.COUNTER_ID AS CounterId,T1.PRODUCT_ID AS ProductId , SUM(T1.QUANTITY) AS DamageQty FROM SALE_TRACKING_TABLE T1" + " INNER JOIN SALE_TRACKING_HEADER_TABLE T2 ON T2.RECCEPT_COUNT=T1.RECCEPT_COUNT" + " WHERE T2.COUNTER_ID =" + counterId + " AND T2.Visit_Date='" + visit_date + "' AND T1.INVOICE_TYPE='GWP'" + q1 + " GROUP BY T1.PRODUCT_ID" + " UNION ALL select S.COUNTER_ID, S.PROMO_PRODUCT_ID AS PRODUCT_ID , SUM(S.PROMO_PRODUCT_QTY) AS QUANTITY from APPLYED_PROMOTION_TABLE S" + " INNER JOIN SALE_TRACKING_HEADER_TABLE S1 ON S.RECCEPT_COUNT=S1.RECCEPT_COUNT" + " Where S.PROMO_TYPE ='Gift' AND S.COUNTER_ID =" + counterId + " AND S1.VISIT_DATE ='" + visit_date + "'" + q2 + " GROUP BY S.PROMO_PRODUCT_ID UNION ALL SELECT COUNTER_ID as CounterId,ProductId,Quantity as DamageQty from Temp_Sale" + " where COUNTER_ID =" + counterId + " and Visit_Date = '" + visit_date + "'and Product_Type='GWP' GROUP By ProductId) as t" + " Group by CounterId, ProductId) as t on PM.ProductId = t.ProductId where PM.ProductId " + " in(WITH RECURSIVE neat( id,ProductId, etc) AS(SELECT PromoId, '' , GetEntityListItem || ',' FROM Master_PromotionGetEntityItem" + " WHERE PromoId=" + promoId + " UNION ALL SELECT id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1)FROM neat WHERE etc <> '')" + " SELECT ProductId FROM neat WHERE ProductId <> '' ORDER BY id ASC , ProductId ASC) and ts.GwpBalance >0" + + + " and PM.ProductId not in( WITH RECURSIVE neat( id, ProductId, etc) AS(SELECT PromoId, '' , GetExclusionList || ','" + " FROM Master_PromotionGetExclusionList WHERE PromoId=" + promoId + " UNION ALL SELECT id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1)" + " FROM neat WHERE etc <> '') SELECT ProductId FROM neat WHERE ProductId <> '')", null); + } else { + //-------For get Saleable product using mapping------------- + dbcursor = db.rawQuery("select distinct PM.ProductId as ProductId,PM.ProductName as ProductName,PM.Mrp as Mrp,PM.EanCode as EanCode," + getDataMe + " from Product_Master PM inner join " + table + " ts on ts.ProductId= PM.ProductID Left join" + " (Select CounterId, ProductId, sum(DamageQty) as DamageQty from(" + " select T.COUNTER_ID as CounterId, T.ProductId, T.Stock as DamageQty from TABLE_TRANSACTION_DATA T" + " INNER JOIN DR_TABLE_TRANSACTION_WISE_MASTER M ON T.MASTER_TRANSACTION_ID = M.MASTER_TRANSACTION_ID where" + " T.STOCK_TYPE='DAMAGE' AND T.Visit_Date ='" + visit_date + "' and T.COUNTER_ID =" + counterId + " Union All SELECT CounterId, ProductId, DamageQty from" + " Damage_PreviousPending Where CounterId =" + counterId + " and Verify ='Pending'Union All" + " Select T2.COUNTER_ID AS CounterId,T1.PRODUCT_ID AS ProductId , SUM(T1.QUANTITY) AS DamageQty FROM SALE_TRACKING_TABLE T1" + " INNER JOIN SALE_TRACKING_HEADER_TABLE T2 ON T2.RECCEPT_COUNT=T1.RECCEPT_COUNT" + " WHERE T2.COUNTER_ID =" + counterId + " AND T2.Visit_Date='" + visit_date + "' AND T1.INVOICE_TYPE='Saleable'" + q1 + " GROUP BY T1.PRODUCT_ID" + " UNION ALL select S.COUNTER_ID, S.PROMO_PRODUCT_ID AS PRODUCT_ID , SUM(S.PROMO_PRODUCT_QTY) AS QUANTITY from APPLYED_PROMOTION_TABLE S" + " INNER JOIN SALE_TRACKING_HEADER_TABLE S1 ON S.RECCEPT_COUNT=S1.RECCEPT_COUNT" + " Where S.PROMO_TYPE ='Product' AND S.COUNTER_ID =" + counterId + " AND S1.VISIT_DATE ='" + visit_date + "'" + q2 + " GROUP BY S.PROMO_PRODUCT_ID UNION ALL SELECT COUNTER_ID as CounterId,ProductId,Quantity as DamageQty from Temp_Sale" + " where COUNTER_ID =" + counterId + " and Visit_Date = '" + visit_date + "'and Product_Type='Saleable' GROUP By ProductId) as t" + " Group by CounterId, ProductId) as t on PM.ProductId = t.ProductId " + additionQueryMe + " where PM.ProductId " + " in(WITH RECURSIVE neat( id,ProductId, etc) AS(SELECT PromoId, '' , GetEntityListItem || ',' FROM Master_PromotionGetEntityItem" + " WHERE PromoId=" + promoId + " UNION ALL SELECT id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1)FROM neat WHERE etc <> '')" + " SELECT ProductId FROM neat WHERE ProductId <> '' ORDER BY id ASC , ProductId ASC) and ts.SaleableBalance >0" + + + " and PM.ProductId not in( WITH RECURSIVE neat( id, ProductId, etc) AS(SELECT PromoId, '' , GetExclusionList || ','" + " FROM Master_PromotionGetExclusionList WHERE PromoId=" + promoId + " UNION ALL SELECT id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1)" + " FROM neat WHERE etc <> '') SELECT ProductId FROM neat WHERE ProductId <> '')", null); + } + } + } + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + MasterPromotionSetProductGroup sb = new MasterPromotionSetProductGroup(); + sb.setProductId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("ProductId"))); + sb.setProductname(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ProductName"))); + sb.setMrp_product(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Mrp"))); + sb.setEan_code(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EanCode"))); + sb.setSallable_stock_qty(dbcursor.getString(dbcursor.getColumnIndexOrThrow(balancekey))); + list.add(sb); + dbcursor.moveToNext(); + } + dbcursor.close(); + return list; + } + } + } + + } catch (Exception e) { + ////////test("Exception", " answer " + e.toString()); + return list; + } + + ////////test("Fetching", " audit answer-->Stop<-"); + return list; + } + + + public boolean insertMasterSurvey(ResponseResult cst) { + db.delete("Master_Survey", null, null); + ContentValues values = new ContentValues(); + List data = cst.getMasterSurvey(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("SurveyId", data.get(i).getSurveyId()); + values.put("SurveyName", data.get(i).getSurveyName()); + values.put("SurveyType", data.get(i).getSurveyType()); + values.put("SurveyQuestionId", data.get(i).getSurveyQuestionId()); + values.put("SurveyQuestion", data.get(i).getSurveyQuestion()); + values.put("SurveyQuestionType", data.get(i).getSurveyQuestionType()); + values.put("SurveyAnswerId", data.get(i).getSurveyAnswerId()); + values.put("SurveyAnswer", data.get(i).getSurveyAnswer()); + values.put("ImageAllow", data.get(i).getImageAllow()); + values.put("UploadStatus", data.get(i).getUploadStatus()); + + long id = db.insert("Master_Survey", null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ex.fillInStackTrace(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + + public boolean insertMasterLeaveType(ResponseResult cst) { + db.delete("Master_LeaveType", null, null); + ContentValues values = new ContentValues(); + List data = cst.getMasterLeaveType(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("LeaveTypeId", data.get(i).getLeaveTypeId()); + values.put("LeaveType", data.get(i).getLeaveType()); + values.put("Show", data.get(i).getShow()); + long id = db.insert("Master_LeaveType", null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ex.fillInStackTrace(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + + public boolean insertdamagedReturnToDistributor(ResponseResult cst) { + db.delete("Damage_ReturnToDistributor", null, null); + ContentValues values = new ContentValues(); + List data = cst.getDamageReturnToDistributor(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("CounterId", data.get(i).getCounterId()); + values.put("ProductId", data.get(i).getProductId()); + values.put("ReturnQty", data.get(i).getReturnQty()); + values.put("Verify", data.get(i).getVerify()); + long id = db.insert("Damage_ReturnToDistributor", null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ex.fillInStackTrace(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + + public boolean insertbaservaystusupload(ResponseResult cst) { + db.delete("Master_Survey_UploadStatus", null, null); + ContentValues values = new ContentValues(); + List data = cst.getMasterSurveyUploadStatus(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("CounterId", data.get(i).getCounterId()); + values.put("EmpId", data.get(i).getEmpId()); + values.put("SurveyId", data.get(i).getSurveyId()); + values.put("SurveyType", data.get(i).getSurveyType()); + values.put("CounterSurveyUpload", data.get(i).getCounterSurveyUpload()); + values.put("BASurveyUpload", data.get(i).getBASurveyUpload()); + long id = db.insert("Master_Survey_UploadStatus", null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ex.fillInStackTrace(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + + public boolean insertGroupWiseSale(ResponseResult cst) { + db.delete("Report_ProductGroupWiseSalesValue", null, null); + ContentValues values = new ContentValues(); + List data = cst.getReportProductGroupWiseSalesValue(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("CounterId", data.get(i).getCounterId()); + values.put("ProductGroupId", data.get(i).getProductGroupId()); + values.put("ProductGroupName", data.get(i).getProductGroupName().trim()); + values.put("MTDTg", data.get(i).getMTDTg()); + values.put("MTDAch", data.get(i).getMTDAch()); + values.put("AchPer", data.get(i).getAchPer()); + values.put("Pending", data.get(i).getPending()); + long id = db.insert("Report_ProductGroupWiseSalesValue", null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ex.fillInStackTrace(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + + public boolean insertReportDaywiseSale(ResponseResult cst, boolean me) { + try { + String table = "Report_SalesDateWise"; + List data = cst.getReportSalesDateWise(); + if (me) { + table = "Report_SalesDateWiseME"; + data = cst.getReportSalesDateWiseMe(); + } + db.delete(table, null, null); + ContentValues values = new ContentValues(); + + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("CounterId", data.get(i).getCounterId()); + values.put("VisitDate", data.get(i).getVisitDate()); + values.put("WeekDays", data.get(i).getWeekDays().trim()); + values.put("Qty", data.get(i).getQty()); + values.put("SalesValue", data.get(i).getSalesValue()); + long id = db.insert(table, null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ex.fillInStackTrace(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + + public boolean insertDamagedPending(ResponseResult cst) { + db.delete("Damage_PreviousPending", null, null); + ContentValues values = new ContentValues(); + List data = cst.getDamagePreviousPending(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("CounterId", data.get(i).getCounterId()); + values.put("ProductId", data.get(i).getProductId()); + values.put("DamageQty", data.get(i).getDamageQty()); + values.put("Verify", data.get(i).getVerify()); + long id = db.insert("Damage_PreviousPending", null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ex.fillInStackTrace(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + public boolean insertMeWorkingcounterDetails(ResponseResult cst) { + try { + List data = cst.getReportMTDWorkingCounterME(); + db.delete("Report_MTD_WorkingCounterME", null, null); + ContentValues values = new ContentValues(); + + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("VisitDate", data.get(i).getVisitDate()); + values.put("CounterCode", data.get(i).getCounterCode()); + values.put("CounterName", data.get(i).getCounterName()); + long id = db.insert("Report_MTD_WorkingCounterME", null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ex.fillInStackTrace(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + public boolean insertreportsalemonth(ResponseResult cst, boolean me) { + try { + String table = "Report_SalesL3MValue"; + List data = cst.getReportSalesL3MValue(); + if (me) { + table = "Report_SalesL3MValueME"; + data = cst.getReportSalesL3MValueMe(); + } + db.delete(table, null, null); + ContentValues values = new ContentValues(); + + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("Month", data.get(i).getMonth()); + values.put("Qty", data.get(i).getQty()); + values.put("SalesValue", data.get(i).getSalesValue()); + long id = db.insert(table, null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ex.fillInStackTrace(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + + public boolean insertpromogetexclusion(ResponseResult cst) { + db.delete("Master_PromotionGetExclusionList", null, null); + ContentValues values = new ContentValues(); + List data = cst.getMasterPromotionGetExclusionList(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("Id", data.get(i).getId()); + values.put("PromoId", data.get(i).getPromoId()); + values.put("GetExclusionList", data.get(i).getGetExclusionList()); + + long id = db.insert("Master_PromotionGetExclusionList", null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ex.fillInStackTrace(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + + public boolean insertpromosetExclusion(ResponseResult cst) { + db.delete("Master_PromotionSetExclusionList", null, null); + ContentValues values = new ContentValues(); + List data = cst.getMasterPromotionSetExclusionList(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("Id", data.get(i).getId()); + values.put("PromoId", data.get(i).getPromoId()); + values.put("SetExclusionList", data.get(i).getSetExclusionList()); + + long id = db.insert("Master_PromotionSetExclusionList", null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ex.fillInStackTrace(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + + public boolean insertdamagestockhistory(ResponseResult cst) { + db.delete("Report_DamageStockHistory", null, null); + ContentValues values = new ContentValues(); + List data = cst.getReportDamageStockHistory(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("CounterId", data.get(i).getCounterId()); + values.put("VisitDate", data.get(i).getVisitDate()); + values.put("ProductCode", data.get(i).getProductCode()); + values.put("ProductName", data.get(i).getProductName()); + values.put("EanCode", data.get(i).getEanCode()); + values.put("Mrp", data.get(i).getMrp()); + values.put("DamageQty", data.get(i).getDamageQty()); + values.put("Verify", data.get(i).getVerify()); + values.put("VerifyDate", data.get(i).getVerifyDate()); + + long id = db.insert("Report_DamageStockHistory", null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ex.fillInStackTrace(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + + public boolean insertsourceofsales(ResponseResult cst) { + db.delete("Master_SourcesOfSales", null, null); + ContentValues values = new ContentValues(); + List data = cst.getMasterSourcesOfSales(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("SourcesOfSale", data.get(i).getSourcesOfSale()); + long id = db.insert("Master_SourcesOfSales", null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ex.fillInStackTrace(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + + public ArrayList getcompanies(boolean flag_nuance, int companyId) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + + String query = "Select Distinct CompetitionBrandId,CompetitionBrand From Master_CompetitonBrandWiseNuance"; + if (flag_nuance) { + query = "Select Distinct CompetitionNuanceId,CompetitionNuance From Master_CompetitonBrandWiseNuance Where CompetitionBrandId =" + companyId + ""; + } + dbcursor = db.rawQuery(query, null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + MasterCompetitonBrandWiseNuance sb = new MasterCompetitonBrandWiseNuance(); + if (flag_nuance) { + sb.setCompetitionNuanceId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("CompetitionNuanceId"))); + sb.setCompetitionNuance(dbcursor.getString(dbcursor.getColumnIndexOrThrow("CompetitionNuance"))); + sb.setCompetitionBrandId(companyId); + } else { + sb.setCompetitionBrandId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("CompetitionBrandId"))); + sb.setCompetitionBrand(dbcursor.getString(dbcursor.getColumnIndexOrThrow("CompetitionBrand"))); + } + + list.add(sb); + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list; + } + + } catch (Exception e) { + return list; + } + + return list; + } + + + public ArrayList getCompPromotionType() { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + + dbcursor = db.rawQuery("Select Distinct CompetitionPromoTypeId,CompetitionPromoType From Master_CompetitionPromoType", null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + MasterCompetitionPromoType sb = new MasterCompetitionPromoType(); + sb.setCompetitionPromoTypeId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("CompetitionPromoTypeId"))); + sb.setCompetitionPromoType(dbcursor.getString(dbcursor.getColumnIndexOrThrow("CompetitionPromoType"))); + + + list.add(sb); + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list; + } + + } catch (Exception e) { + return list; + } + + return list; + } + + public ArrayList getCompOfferSaleRange() { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + + dbcursor = db.rawQuery("Select SaleRange From Master_CompetitionOfferSaleRange", null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + MasterCompetitionOfferSaleRange sb = new MasterCompetitionOfferSaleRange(); + sb.setSaleRange(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SaleRange"))); + + + list.add(sb); + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list; + } + + } catch (Exception e) { + return list; + } + + return list; + } + + public ArrayList getComOfferSet() { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + + dbcursor = db.rawQuery("Select Distinct CompetitionOfferSetId,CompetitionOfferSet From Master_CompetitionOfferSet", null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + MasterCompetitionOfferSet sb = new MasterCompetitionOfferSet(); + sb.setCompetitionOfferSetId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("CompetitionOfferSetId"))); + sb.setCompetitionOfferSet(dbcursor.getString(dbcursor.getColumnIndexOrThrow("CompetitionOfferSet"))); + + list.add(sb); + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list; + } + + } catch (Exception e) { + return list; + } + + return list; + } + + + public ArrayList getComOfferGet(int competitionOfferSetId) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + + dbcursor = db.rawQuery("Select Distinct CompetitionOfferGet,CompetitionOfferGetId,ShowProductTypeDropdown From Master_CompetitionOfferGet " + "Where CompetitionOfferSetId = " + competitionOfferSetId + "", null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + MasterCompetitionOfferGet sb = new MasterCompetitionOfferGet(); + sb.setCometitionOfferGetId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("CompetitionOfferGetId"))); + sb.setCompetitionOfferGet(dbcursor.getString(dbcursor.getColumnIndexOrThrow("CompetitionOfferGet"))); + sb.setShowProductTypeDropdown("1".equals(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ShowProductTypeDropdown")))); + + + list.add(sb); + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list; + } + + } catch (Exception e) { + return list; + } + + return list; + } + + public boolean insertMasterCompetitonBrandWiseNuance(ResponseResult cst) { + db.delete("Master_CompetitonBrandWiseNuance", null, null); + ContentValues values = new ContentValues(); + List data = cst.getMasterCompetitonBrandWiseNuance(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("CompetitionBrandId", data.get(i).getCompetitionBrandId()); + values.put("CompetitionNuanceId", data.get(i).getCompetitionNuanceId()); + values.put("CompetitionBrand", data.get(i).getCompetitionBrand()); + values.put("CompetitionNuance", data.get(i).getCompetitionNuance()); + long id = db.insert("Master_CompetitonBrandWiseNuance", null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ex.fillInStackTrace(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + public boolean insertMasterCompetitionOfferSet(ResponseResult cst) { + db.delete("Master_CompetitionOfferSet", null, null); + ContentValues values = new ContentValues(); + List data = cst.getMasterCompetitionOfferSet(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("CompetitionOfferSetId", data.get(i).getCompetitionOfferSetId()); + values.put("CompetitionOfferSet", data.get(i).getCompetitionOfferSet()); + + long id = db.insert("Master_CompetitionOfferSet", null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ex.fillInStackTrace(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + + public boolean insertMasterCompetitionOfferGet(ResponseResult cst) { + db.delete("Master_CompetitionOfferGet", null, null); + ContentValues values = new ContentValues(); + List data = cst.getMasterCompetitionOfferGet(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("CompetitionOfferSetId", data.get(i).getCompetitionOfferSetId()); + values.put("CompetitionOfferGetId", data.get(i).getCometitionOfferGetId()); + values.put("CompetitionOfferGet", data.get(i).getCompetitionOfferGet()); + values.put("ShowProductTypeDropdown", data.get(i).getShowProductTypeDropdown()); + + long id = db.insert("Master_CompetitionOfferGet", null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ex.fillInStackTrace(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + + public boolean insertMasterCompetitionPromoType(ResponseResult cst) { + db.delete("Master_CompetitionPromoType", null, null); + ContentValues values = new ContentValues(); + List data = cst.getMasterCompetitionPromoType(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("CompetitionPromoTypeId", data.get(i).getCompetitionPromoTypeId()); + values.put("CompetitionPromoType", data.get(i).getCompetitionPromoType()); + + long id = db.insert("Master_CompetitionPromoType", null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ex.fillInStackTrace(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + public boolean insertMasterCompProductType(ResponseResult cst) { + db.delete("Master_CompetitionProductType", null, null); + ContentValues values = new ContentValues(); + List data = cst.getMasterCompetitionProductType(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("CompetitionProductType", data.get(i).getCompetitionProductType()); + values.put("CompetitionProductTypeId", data.get(i).getCompetitionProductTypeId()); + + long id = db.insert("Master_CompetitionProductType", null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + public ArrayList getreportthreemonthsalevalue(String userType) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + + try { + String table = "Report_SalesL3MValue"; + if (userType != null && userType.equalsIgnoreCase(CommonString.TAG_FROM_ME)) { + table = "Report_SalesL3MValueME"; + } + dbcursor = db.rawQuery("Select * from " + table + " ORDER BY Month DESC", null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + ReportSalesL3MValue sb = new ReportSalesL3MValue(); + sb.setMonth(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Month"))); + sb.setQty(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("Qty"))); + sb.setSalesValue(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("SalesValue"))); + list.add(sb); + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list; + } + } catch (Exception e) { + ////////test("Exception", " answer " + e.toString()); + return list; + } + + ////////test("Fetching", " audit answer-->Stop<-"); + return list; + } + + public ArrayList getCompOfferType(boolean compoffer, boolean buyType, boolean buyTypeInput, boolean getTypeInput, int compOfferId, int compBuyTypeId, int compSetTypeId) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + String query = ""; + if (compoffer) { + query = "Select Distinct CompOfferId,CompOffer From Master_CompetitionOffer"; + } else if (buyType) { + query = "Select Distinct CompBuyType,CompBuyTypeId From Master_CompetitionOffer Where CompOfferId =" + compOfferId; + } else if (buyTypeInput) { + query = "Select Distinct CompSetName,CompSetId From Master_CompetitionOffer Where CompBuyTypeId =" + compBuyTypeId; + } else { + query = "Select Distinct CompGetName,CompGetId From Master_CompetitionOffer Where CompSetId =" + compSetTypeId; + } + + dbcursor = db.rawQuery(query, null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + MasterCompetitionOffer sb = new MasterCompetitionOffer(); + if (compoffer) { + sb.setCompOffer(dbcursor.getString(dbcursor.getColumnIndexOrThrow("CompOffer"))); + sb.setCompOfferId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("CompOfferId"))); + } else if (buyType) { + sb.setCompBuyType(dbcursor.getString(dbcursor.getColumnIndexOrThrow("CompBuyType"))); + sb.setCompBuyTypeId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("CompBuyTypeId"))); + } else if (buyTypeInput) { + sb.setCompSetName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("CompSetName"))); + sb.setCompSetId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("CompSetId"))); + } else { + sb.setCompGetName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("CompGetName"))); + sb.setCompGetId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("CompGetId"))); + } + list.add(sb); + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list; + } + } catch (Exception e) { + ////////test("Exception", " answer " + e.toString()); + return list; + } + + ////////test("Fetching", " audit answer-->Stop<-"); + return list; + } + + + public ArrayList getdamagestockhistory(String counterId) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + + try { + + dbcursor = db.rawQuery("Select * from Report_DamageStockHistory Where CounterId=" + counterId + " ORDER BY VisitDate DESC", null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + + while (!dbcursor.isAfterLast()) { + ReportDamageStockHistory sb = new ReportDamageStockHistory(); + sb.setVisitDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("VisitDate"))); + sb.setProductCode(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ProductCode"))); + sb.setProductName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ProductName"))); + sb.setEanCode(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EanCode"))); + sb.setMrp(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("Mrp"))); + sb.setDamageQty(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("DamageQty"))); + sb.setVerify(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Verify"))); + sb.setVerifyDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("VerifyDate"))); + list.add(sb); + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list; + } + } catch (Exception e) { + ////////test("Exception", " answer " + e.toString()); + return list; + } + + ////////test("Fetching", " audit answer-->Stop<-"); + return list; + } + + public ArrayList getreportdaywisesale(String counterId, String userType) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + + try { + String table = "Report_SalesDateWise"; + if (userType != null && userType.equalsIgnoreCase(CommonString.TAG_FROM_ME)) { + table = "Report_SalesDateWiseME"; + } + dbcursor = db.rawQuery("Select * from " + table + " where CounterId=" + counterId + " order by VisitDate desc", null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + + while (!dbcursor.isAfterLast()) { + ReportSalesDateWise sb = new ReportSalesDateWise(); + sb.setCounterId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("CounterId"))); + sb.setVisitDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("VisitDate"))); + sb.setWeekDays(dbcursor.getString(dbcursor.getColumnIndexOrThrow("WeekDays"))); + sb.setQty(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("Qty"))); + sb.setSalesValue(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("SalesValue"))); + list.add(sb); + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list; + } + } catch (Exception e) { + ////////test("Exception", " answer " + e.toString()); + return list; + } + + ////////test("Fetching", " audit answer-->Stop<-"); + return list; + } + + + public ArrayList getmasterLeaveType(String counterId) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + + try { + + dbcursor = db.rawQuery("Select * from Report_ProductGroupWiseSalesValue where CounterId=" + counterId + "", null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + ReportProductGroupWiseSalesValue sb = new ReportProductGroupWiseSalesValue(); + sb.setProductGroupId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("ProductGroupId"))); + sb.setProductGroupName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ProductGroupName"))); + sb.setMTDTg(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("MTDTg"))); + sb.setMTDAch(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("MTDAch"))); + sb.setAchPer(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("AchPer"))); + sb.setPending(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("Pending"))); + list.add(sb); + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list; + } + } catch (Exception e) { + ////////test("Exception", " answer " + e.toString()); + return list; + } + + ////////test("Fetching", " audit answer-->Stop<-"); + return list; + } + + public ArrayList getmasterLeaveType(boolean emargancy) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + + if (emargancy) { + dbcursor = db.rawQuery("Select * from Master_LeaveType where Show ='1'", null); + } else { + dbcursor = db.rawQuery("Select * from Master_LeaveType", null); + } + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + MasterLeaveType sb = new MasterLeaveType(); + + sb.setLeaveTypeId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("LeaveTypeId"))); + sb.setLeaveType(dbcursor.getString(dbcursor.getColumnIndexOrThrow("LeaveType"))); + + list.add(sb); + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list; + } + } catch (Exception e) { + ////////test("Exception", " answer " + e.toString()); + return list; + } + + ////////test("Fetching", " audit answer-->Stop<-"); + return list; + } + + + public long saveBASurveyAnswerData(ArrayList listDataHeader, HashMap> data, String counter_id, String visit_date, JourneyPlan jcp_Object, String surveyType) { + long l = 0, l2 = 0; + if (surveyType.trim().equalsIgnoreCase("BA")) { + db.delete(CommonString.TABLE_BA_SURVEY_HEADER_DATA, CommonString.KEY_COUNTER_ID + " =" + counter_id + "", null); + db.delete(CommonString.TABLE_BA_SURVEY_CHILD_DATA, CommonString.KEY_COUNTER_ID + " = " + counter_id + "", null); + } else { + db.delete(CommonString.TABLE_COUNTER_SURVEY_CHILD_DATA, CommonString.KEY_COUNTER_ID + " =" + counter_id + "", null); + db.delete(CommonString.TABLE_COUNTER_SURVEY_HEADER_DATA, CommonString.KEY_COUNTER_ID + " =" + counter_id + "", null); + } + + ContentValues values = new ContentValues(); + ContentValues values1 = new ContentValues(); + + try { + db.beginTransaction(); + for (int i = 0; i < listDataHeader.size(); i++) { + if (surveyType.equalsIgnoreCase("BA")) { + values.put(CommonString.KEY_BID, jcp_Object.getBID()); + } else { + values.put(CommonString.KEY_MID, jcp_Object.getMID()); + } + values.put(CommonString.KEY_COUNTER_ID, counter_id); + values.put(CommonString.KEY_VISIT_DATE, visit_date); + values.put(CommonString.KEY_Survey_Id, listDataHeader.get(i).getSurveyId()); + values.put(CommonString.KEY_Survey_Name, listDataHeader.get(i).getSurveyName()); + values.put(CommonString.KEY_Survey_Type, listDataHeader.get(i).getSurveyType()); + values.put(CommonString.KEY_UPLOAD_STATUS, "0"); + if (surveyType.trim().equalsIgnoreCase("BA")) { + if (!db.isOpen()) { + open(); + } + l = db.insert(CommonString.TABLE_BA_SURVEY_HEADER_DATA, null, values); + } else { + if (!db.isOpen()) { + open(); + } + l = db.insert(CommonString.TABLE_COUNTER_SURVEY_HEADER_DATA, null, values); + } + for (int j = 0; j < data.get(listDataHeader.get(i)).size(); j++) { + values1.put(CommonString.KEY_COMMON_ID, (int) l); + if (surveyType.equalsIgnoreCase("BA")) { + values1.put(CommonString.KEY_BID, jcp_Object.getBID()); + } else { + values1.put(CommonString.KEY_MID, jcp_Object.getMID()); + } + values1.put(CommonString.KEY_COUNTER_ID, counter_id); + values1.put(CommonString.KEY_Survey_Id, listDataHeader.get(i).getSurveyId()); + values1.put(CommonString.KEY_Survey_Question, data.get(listDataHeader.get(i)).get(j).getSurveyQuestion()); + values1.put(CommonString.KEY_Survey_Question_Id, data.get(listDataHeader.get(i)).get(j).getSurveyQuestionId()); + values1.put(CommonString.KEY_Correct_Answer_Id, data.get(listDataHeader.get(i)).get(j).getCorrect_answer_id()); + values1.put(CommonString.KEY_Image_Allow, data.get(listDataHeader.get(i)).get(j).getImageAllow()); + values1.put(CommonString.KEY_Question_Type, data.get(listDataHeader.get(i)).get(j).getSurveyQuestionType()); + values1.put(CommonString.KEY_Survey_Question_Image, data.get(listDataHeader.get(i)).get(j).getCam_image()); + values1.put(CommonString.KEY_UPLOAD_STATUS, "0"); + values1.put(CommonString.KEY_Correct_Answer, data.get(listDataHeader.get(i)).get(j).getSurveyAnswer()); + if (surveyType.trim().equalsIgnoreCase("BA")) { + if (!db.isOpen()) { + open(); + } + l2 = db.insert(CommonString.TABLE_BA_SURVEY_CHILD_DATA, null, values1); + } else { + if (!db.isOpen()) { + open(); + } + l2 = db.insert(CommonString.TABLE_COUNTER_SURVEY_CHILD_DATA, null, values1); + } + } + } + closeDb(); + } catch (Exception ex) { + closeDb(); + } + + return l2; + } + + + public ArrayList getSurveyData(String surveyType) { + Cursor cursordata = null; + ArrayList auditData = new ArrayList<>(); + try { + cursordata = db.rawQuery("Select distinct SurveyId,SurveyName,UploadStatus from Master_Survey where SurveyType = '" + surveyType + "'", null); + if (cursordata != null) { + cursordata.moveToFirst(); + while (!cursordata.isAfterLast()) { + MasterSurvey sb = new MasterSurvey(); + sb.setSurveyId(cursordata.getInt(cursordata.getColumnIndexOrThrow("SurveyId"))); + sb.setSurveyName(cursordata.getString(cursordata.getColumnIndexOrThrow("SurveyName"))); + sb.setUploadStatus(cursordata.getInt(cursordata.getColumnIndexOrThrow("UploadStatus"))); + auditData.add(sb); + cursordata.moveToNext(); + } + cursordata.close(); + } + + } catch (Exception ex) { + ////////test("Exception ", " in Master_Survey" + ex.toString()); + } + return auditData; + + } + + + public boolean getSurveyUploadStatus(String surveyType, String surveyId, String userId, String counterId) { + Cursor dbcursor = null; + boolean uploadstatus = false; + try { + if (surveyType != null && surveyType.equalsIgnoreCase(CommonString.TAG_FROM_BA)) { + dbcursor = db.rawQuery("select distinct BASurveyUpload as surveyupload from Master_Survey_UploadStatus T1 Inner Join BA_List T2 on T1.EmpId=T2.EmpId " + "where T2.UserName='" + userId + "' and T1.SurveyType='" + surveyType + "' and T1.SurveyId=" + surveyId + " and T2.CounterId=" + counterId + "", null); + + } else { + dbcursor = db.rawQuery("select distinct CounterSurveyUpload as surveyupload from Master_Survey_UploadStatus T1 " + "where T1.SurveyType='" + surveyType + "' and T1.SurveyId=" + surveyId + " and T1.CounterId=" + counterId + "", null); + + } + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + + String user_idget = dbcursor.getString(dbcursor.getColumnIndexOrThrow("surveyupload")); + if (user_idget != null && !user_idget.equals("") && !user_idget.equalsIgnoreCase(CommonString.KEY_N)) { + uploadstatus = true; + break; + + } else { + uploadstatus = false; + } + + dbcursor.moveToNext(); + } + + dbcursor.close(); + } + + } catch (Exception ex) { + return uploadstatus; + + } + + return uploadstatus; + + } + + + public boolean getMeQuizUploadStatus(String QuizId, String userId, String counterId) { + Cursor dbcursor = null; + boolean uploadstatus = false; + try { + + dbcursor = db.rawQuery("select distinct UploadStatus from ME_MEAuditQuestion_UploadStatus T1 Inner Join BA_List T2 on T1.EmpId=T2.EmpId " + "where T2.UserName='" + userId + "' and T2.DesignationName='ME' and T1.QuizId=" + QuizId + " and T2.CounterId=" + counterId + "", null); + + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + + String user_idget = dbcursor.getString(dbcursor.getColumnIndexOrThrow("UploadStatus")); + if (user_idget != null && !user_idget.equals("") && !user_idget.equalsIgnoreCase(CommonString.KEY_N)) { + uploadstatus = true; + break; + + } else { + uploadstatus = false; + } + + dbcursor.moveToNext(); + } + + dbcursor.close(); + } + + } catch (Exception ex) { + return uploadstatus; + + } + + return uploadstatus; + + } + + + public ArrayList getSurveyData(String surveyType, String surveyId) { + Cursor cursordata = null; + ArrayList auditData = new ArrayList<>(); + try { + cursordata = db.rawQuery("Select distinct SurveyId,SurveyName,SurveyType,UploadStatus from Master_Survey where SurveyType = '" + surveyType + "' and SurveyId =" + surveyId + "", null); + if (cursordata != null) { + cursordata.moveToFirst(); + while (!cursordata.isAfterLast()) { + MasterSurvey sb = new MasterSurvey(); + + sb.setSurveyId(cursordata.getInt(cursordata.getColumnIndexOrThrow("SurveyId"))); + sb.setSurveyName(cursordata.getString(cursordata.getColumnIndexOrThrow("SurveyName"))); + sb.setSurveyType(cursordata.getString(cursordata.getColumnIndexOrThrow("SurveyType"))); + sb.setUploadStatus(cursordata.getInt(cursordata.getColumnIndexOrThrow("UploadStatus"))); + + auditData.add(sb); + cursordata.moveToNext(); + } + + cursordata.close(); + } + + } catch (Exception ex) { + ////////test("Exception ", " in Master_Survey" + ex.toString()); + } + return auditData; + + } + + + //Category wise Audit + public ArrayList getSurveyWiseData(int surveyId) { + Cursor cursordata = null; + + ArrayList auditData = new ArrayList<>(); + try { + + cursordata = db.rawQuery("Select distinct SurveyQuestionId,SurveyQuestion,ImageAllow,SurveyQuestionType from " + "Master_Survey where SurveyId =" + surveyId + "", null); + + if (cursordata != null) { + cursordata.moveToFirst(); + while (!cursordata.isAfterLast()) { + BASurveyGetterSetter sb = new BASurveyGetterSetter(); + + sb.setSurveyQuestion(cursordata.getString(cursordata.getColumnIndexOrThrow("SurveyQuestion"))); + sb.setSurveyQuestionId(cursordata.getString(cursordata.getColumnIndexOrThrow("SurveyQuestionId"))); + sb.setSurveyQuestionType(cursordata.getString(cursordata.getColumnIndexOrThrow("SurveyQuestionType"))); + sb.setImageAllow(cursordata.getString(cursordata.getColumnIndexOrThrow("ImageAllow"))); + + auditData.add(sb); + cursordata.moveToNext(); + } + cursordata.close(); + } + + } catch (Exception ex) { + ////////test("Exception ", " in ADDITIONAL_QUESTION " + ex.toString()); + } + return auditData; + } + + public ArrayList getSurveyAnswerData(BASurveyGetterSetter auditGetSet, String select) { + ////////test("Fetching", "Storedata--------------->Start<------------"); + ArrayList list = new ArrayList<>(); + if (auditGetSet.getSurveyQuestionType().equalsIgnoreCase("List Single Choice") || auditGetSet.getSurveyQuestionType().equalsIgnoreCase("List Multiple Choice")) { + BASurveyGetterSetter sb1 = new BASurveyGetterSetter(); + sb1.setSurveyAnswerId("0"); + sb1.setSurveyAnswer(select); + list.add(0, sb1); + } else if (auditGetSet.getSurveyQuestionType().trim().equalsIgnoreCase("Text")) { + BASurveyGetterSetter sb1 = new BASurveyGetterSetter(); + sb1.setSurveyAnswerId("0"); + sb1.setSurveyAnswer(""); + list.add(0, sb1); + } + + + Cursor dbcursor = null; + + try { + + if (auditGetSet.getSurveyQuestionType().trim().equalsIgnoreCase("Text") || auditGetSet.getSurveyQuestionType().trim().equalsIgnoreCase("Number") || auditGetSet.getSurveyQuestionType().trim().equalsIgnoreCase("Decimal")) { + dbcursor = db.rawQuery("Select * from " + CommonString.TABLE_BA_SURVEY_CHILD_DATA + " where Survey_Question_Id =" + auditGetSet.getSurveyQuestionId() + "", null); + } else { + dbcursor = db.rawQuery("Select * from Master_Survey where SurveyQuestionId = " + auditGetSet.getSurveyQuestionId() + "", null); + } + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + BASurveyGetterSetter sb = new BASurveyGetterSetter(); + if (auditGetSet.getSurveyQuestionType().trim().equalsIgnoreCase("Text") || auditGetSet.getSurveyQuestionType().trim().equalsIgnoreCase("Number") || auditGetSet.getSurveyQuestionType().trim().equalsIgnoreCase("Decimal")) { + //sb.setCorrect_answer_id(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Correct_Answer_Id"))); + sb.setSurveyAnswer(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Question_Correct_Answer"))); + sb.setCam_image(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Survey_Question_Image"))); + } else { + sb.setSurveyAnswerId(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SurveyAnswerId"))); + sb.setSurveyAnswer(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SurveyAnswer"))); + } + BASurveyGetterSetter obj = getInsertedChildData(auditGetSet.getSurveyQuestionId()); + if (obj != null) { + sb.setCorrect_answer_id(obj.getCorrect_answer_id()); + sb.setCam_image(obj.getCam_image()); + } else { + sb.setCorrect_answer_id(""); + } + + list.add(sb); + dbcursor.moveToNext(); + } + dbcursor.close(); + return list; + } + } catch (Exception e) { + ////////test("Exception", " answer " + e.toString()); + return list; + } + ////////test("Fetching", " audit answer-->Stop<-"); + return list; + } + + + private BASurveyGetterSetter getInsertedChildData(String question_id) { + Cursor dbcursor = null; + BASurveyGetterSetter sb = null; + try { + dbcursor = db.rawQuery("Select * from " + CommonString.TABLE_BA_SURVEY_CHILD_DATA + " where Survey_Question_Id =" + question_id + "", null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + sb = new BASurveyGetterSetter(); + + sb.setCorrect_answer_id(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Correct_Answer_Id"))); + sb.setCam_image(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Survey_Question_Image"))); + + dbcursor.moveToNext(); + } + dbcursor.close(); + return sb; + } + } catch (Exception e) { + ////////test("Exception", " answer " + e.toString()); + return sb; + } + ////////test("Fetching", " audit answer-->Stop<-"); + return sb; + } + + public ArrayList getBASurveySavedData(String surveyType, JourneyPlan jcp_object, String date) { + Cursor cursordata = null; + + ArrayList surveyData = new ArrayList<>(); + try { + + if (surveyType.trim().equalsIgnoreCase("BA")) { + cursordata = db.rawQuery("Select * from " + CommonString.TABLE_BA_SURVEY_HEADER_DATA + " where Survey_Type = '" + surveyType + "' and " + CommonString.KEY_BID + " = '" + jcp_object.getBID() + "' and " + CommonString.KEY_VISIT_DATE + " = '" + date + "'", null); + } else { + cursordata = db.rawQuery("Select * from " + CommonString.TABLE_COUNTER_SURVEY_HEADER_DATA + " where Survey_Type = '" + surveyType + "' and " + CommonString.KEY_MID + " = '" + jcp_object.getMID() + "' and " + CommonString.KEY_VISIT_DATE + " = '" + date + "'", null); + } + + if (cursordata != null) { + cursordata.moveToFirst(); + while (!cursordata.isAfterLast()) { + MasterSurvey sb = new MasterSurvey(); + sb.setSurveyName(cursordata.getString(cursordata.getColumnIndexOrThrow(CommonString.KEY_Survey_Name))); + sb.setSurveyId(cursordata.getInt(cursordata.getColumnIndexOrThrow(CommonString.KEY_Survey_Id))); + sb.setUploadStatus(cursordata.getInt(cursordata.getColumnIndexOrThrow(CommonString.KEY_UPLOAD_STATUS))); + sb.setSurveyType(cursordata.getString(cursordata.getColumnIndexOrThrow("Survey_Type"))); + sb.setCommon_id(cursordata.getString(cursordata.getColumnIndexOrThrow("KEY_ID"))); + surveyData.add(sb); + cursordata.moveToNext(); + } + + cursordata.close(); + } + + } catch (Exception ex) { + ////////test("Exception ", " in " + ex.toString()); + } + return surveyData; + } + + public ArrayList getChildData(String surveyType, JourneyPlan jcp_object, String visit_date, String common_id) { + Cursor cursordata = null; + + ArrayList surveyData = new ArrayList<>(); + try { + + if (surveyType.trim().equalsIgnoreCase("BA")) { + cursordata = db.rawQuery("Select * from " + CommonString.TABLE_BA_SURVEY_CHILD_DATA + " where " + CommonString.KEY_BID + " = '" + jcp_object.getBID() + "' and " + CommonString.KEY_COMMON_ID + " = '" + common_id + "'", null); + } else { + cursordata = db.rawQuery("Select * from " + CommonString.TABLE_COUNTER_SURVEY_CHILD_DATA + " where " + CommonString.KEY_MID + " = '" + jcp_object.getMID() + "' and " + CommonString.KEY_COMMON_ID + " = '" + common_id + "'", null); + } + if (cursordata != null) { + cursordata.moveToFirst(); + while (!cursordata.isAfterLast()) { + BASurveyGetterSetter sb = new BASurveyGetterSetter(); + + sb.setSurveyId(cursordata.getString(cursordata.getColumnIndexOrThrow(CommonString.KEY_Survey_Id))); + + sb.setSurveyQuestionId(cursordata.getString(cursordata.getColumnIndexOrThrow(CommonString.KEY_Survey_Question_Id))); + + sb.setCam_image(cursordata.getString(cursordata.getColumnIndexOrThrow(CommonString.KEY_Survey_Question_Image))); + + sb.setSurveyAnswer(cursordata.getString(cursordata.getColumnIndexOrThrow(CommonString.KEY_Correct_Answer))); + + sb.setCorrect_answer_id(cursordata.getString(cursordata.getColumnIndexOrThrow(CommonString.KEY_Correct_Answer_Id))); + + surveyData.add(sb); + cursordata.moveToNext(); + } + cursordata.close(); + } + + } catch (Exception ex) { + ////////test("Exception ", " in ADDITIONAL_QUESTION " + ex.toString()); + } + return surveyData; + } + + public void updateBASurveyData(String surveyType, String status) { + ContentValues values = new ContentValues(); + try { + values.put(CommonString.KEY_UPLOAD_STATUS, status); + if (!db.isOpen()) { + open(); + } + if (surveyType.trim().equalsIgnoreCase("BA")) { + db.update(CommonString.TABLE_BA_SURVEY_HEADER_DATA, values, null, null); + db.update(CommonString.TABLE_BA_SURVEY_CHILD_DATA, values, null, null); + } else { + db.update(CommonString.TABLE_COUNTER_SURVEY_HEADER_DATA, values, null, null); + db.update(CommonString.TABLE_COUNTER_SURVEY_CHILD_DATA, values, null, null); + } + } catch (Exception ex) { + ex.fillInStackTrace(); + } + } + + + public void deleteBASurveyData(String counter_id, String visit_date) { + try { + if (!db.isOpen()) { + open(); + } + db.delete(CommonString.TABLE_BA_SURVEY_HEADER_DATA, CommonString.KEY_COUNTER_ID + " =" + counter_id + " and " + CommonString.KEY_VISIT_DATE + " <> '" + visit_date + "'", null); + db.delete(CommonString.TABLE_BA_SURVEY_CHILD_DATA, CommonString.KEY_COUNTER_ID + " =" + counter_id + " and " + CommonString.KEY_VISIT_DATE + " <> '" + visit_date + "'", null); + } catch (Exception e) { + e.fillInStackTrace(); + } + } + + public void deleteCompOffers(String counter_id, String visit_date, String keyId) { + try { + + db.delete(CommonString.TABLE_COMP_OFFERS, CommonString.KEY_COUNTER_ID + " =" + counter_id + " and " + CommonString.KEY_VISIT_DATE + " ='" + visit_date + "' AND " + CommonString.KEY_ID + "=" + keyId + "", null); + } catch (Exception e) { + e.fillInStackTrace(); + } + } + + + public void deleteCounterSurveyData(String counter_id, String visit_date) { + try { + if (!db.isOpen()) { + open(); + } + db.delete(CommonString.TABLE_COUNTER_SURVEY_HEADER_DATA, CommonString.KEY_COUNTER_ID + " =" + counter_id + " and " + CommonString.KEY_VISIT_DATE + " <> '" + visit_date + "'", null); + db.delete(CommonString.TABLE_COUNTER_SURVEY_CHILD_DATA, CommonString.KEY_COUNTER_ID + " =" + counter_id + " and " + CommonString.KEY_VISIT_DATE + " <> '" + visit_date + "'", null); + } catch (Exception e) { + e.fillInStackTrace(); + } + } + + + public ArrayList getBASurveySavedData1(String surveyType, JourneyPlan jcp_object, String date) { + Cursor cursordata = null; + + ArrayList surveyData = new ArrayList<>(); + try { + + if (surveyType.trim().equalsIgnoreCase("BA")) { + cursordata = db.rawQuery("Select * from " + CommonString.TABLE_BA_SURVEY_HEADER_DATA + " where Survey_Type = '" + surveyType + "' and " + CommonString.KEY_BID + " = '" + jcp_object.getBID() + "' and " + CommonString.KEY_VISIT_DATE + " <> '" + date + "'", null); + } else { + cursordata = db.rawQuery("Select * from " + CommonString.TABLE_COUNTER_SURVEY_HEADER_DATA + " where Survey_Type = '" + surveyType + "' and " + CommonString.KEY_MID + " = '" + jcp_object.getMID() + "' and " + CommonString.KEY_VISIT_DATE + " <> '" + date + "'", null); + } + if (cursordata != null) { + cursordata.moveToFirst(); + while (!cursordata.isAfterLast()) { + MasterSurvey sb = new MasterSurvey(); + + sb.setSurveyName(cursordata.getString(cursordata.getColumnIndexOrThrow(CommonString.KEY_Survey_Name))); + + sb.setSurveyId(cursordata.getInt(cursordata.getColumnIndexOrThrow(CommonString.KEY_Survey_Id))); + + sb.setUploadStatus(cursordata.getInt(cursordata.getColumnIndexOrThrow(CommonString.KEY_UPLOAD_STATUS))); + + sb.setSurveyType(cursordata.getString(cursordata.getColumnIndexOrThrow("Survey_Type"))); + sb.setCommon_id(cursordata.getString(cursordata.getColumnIndexOrThrow("KEY_ID"))); + + surveyData.add(sb); + cursordata.moveToNext(); + } + cursordata.close(); + } + + } catch (Exception ex) { + ////////test("Exception ", " in ADDITIONAL_QUESTION " + ex.toString()); + } + return surveyData; + } + + + public long insert_consumer_tempsales_data(String user_Id, String visit_date, String counter_Id, ArrayList invoiceHeaderList) { + db.delete(CommonString.Table_Temp_Consumer_Sale, null, null); + ContentValues values = new ContentValues(); + long l2 = 0; + + try { + + db.beginTransaction(); + for (int i = 0; i < invoiceHeaderList.size(); i++) { + if (!invoiceHeaderList.get(i).getStr_invoiceType().isEmpty() && invoiceHeaderList.get(i).getStr_invoiceType().equalsIgnoreCase("Saleable")) { + values.put("USER_ID", user_Id); + values.put(CommonString.KEY_COUNTER_ID, counter_Id); + values.put(CommonString.KEY_VISIT_DATE, visit_date); + values.put("ProductId", invoiceHeaderList.get(i).getProduct_Id()); + values.put("Quantity", invoiceHeaderList.get(i).getQuantity()); + values.put("Amount", invoiceHeaderList.get(i).getProduct_rate()); + if (!db.isOpen()) { + open(); + } + l2 = db.insert(CommonString.Table_Temp_Consumer_Sale, null, values); + } + } + + closeDb(); + } catch (Exception ex) { + closeDb(); + ////////test("Database Exception", " while Insert Table_Temp_Consumer_Sale Data " + ex.toString()); + } + + return l2; + } + + + public long updatereturntodistributor(String counterId, String uuid) { + long l = 0; + try { + ContentValues values = new ContentValues(); + values.put(CommonString.KEY_STATUS, CommonString.KEY_Y); + if (!db.isOpen()) { + open(); + } + l = db.update(CommonString.TABLE_RETURNTO_DISTRIBUTOR_DATA, values, CommonString.KEY_UUID + " ='" + uuid + "' and " + CommonString.KEY_COUNTER_ID + "=" + counterId + "", null); + } catch (Exception e) { + e.fillInStackTrace(); + } + + return l; + } + + public long updateinwarddms(String counterId, String uuid) { + long l = 0; + try { + + ContentValues values = new ContentValues(); + values.put(CommonString.KEY_UPLOAD_STATUS, CommonString.KEY_Y); + if (!db.isOpen()) { + open(); + } + l = db.update("DR_INWARD_STOCK_TRANSACTION", values, CommonString.KEY_TRANSACTION_ID + " ='" + uuid + "' AND " + CommonString.KEY_COUNTER_ID + "=" + counterId + "", null); + } catch (Exception e) { + e.fillInStackTrace(); + } + + return l; + } + + public long updatemanualinward(String counterId, String uuid) { + long l = 0; + try { + if (!db.isOpen()) { + open(); + } + ContentValues values = new ContentValues(); + values.put(CommonString.KEY_UPLOAD_STATUS, CommonString.KEY_Y); + l = db.update(CommonString.TABLE_INSERT_MANUAL_INWARD_TRANSACTION, values, CommonString.KEY_TRANSACTION_ID + " ='" + uuid + "' and " + CommonString.KEY_COUNTER_ID + "=" + counterId + "", null); + } catch (Exception e) { + e.fillInStackTrace(); + } + + return l; + } + + public long update_SalesTRacking(String counterId, String uuid_Id) { + long l = 0; + try { + if (!db.isOpen()) { + open(); + } + ContentValues values = new ContentValues(); + values.put("UPLOAD_STATUS", CommonString.KEY_Y); + l = db.update(CommonString.Table_Sale_Tracking_Header_Data, values, CommonString.KEY_COUNTER_ID + "=" + counterId + " AND UNIQUE_CODE='" + uuid_Id + "'", null); + l = db.update(CommonString.Table_Sale_Tracking, values, CommonString.KEY_COUNTER_ID + "=" + counterId + " AND UNIQUE_CODE='" + uuid_Id + "'", null); + } catch (Exception e) { + e.fillInStackTrace(); + } + + return l; + } + + public long update_ConsumersReturn(String counterId, String uuid_Id) { + long l = 0; + try { + if (!db.isOpen()) { + open(); + } + ContentValues values = new ContentValues(); + values.put("UPLOAD_STATUS", CommonString.KEY_Y); + l = db.update(CommonString.Table_Consumer_Return_Header_Data, values, CommonString.KEY_COUNTER_ID + "=" + counterId + " AND UNIQUE_CODE='" + uuid_Id + "'", null); + l = db.update(CommonString.Table_Consumer_Return, values, CommonString.KEY_COUNTER_ID + "=" + counterId + " AND UNIQUE_CODE='" + uuid_Id + "'", null); + } catch (Exception e) { + e.fillInStackTrace(); + } + + return l; + } + + + public ArrayList getreturntodistributor_byUUID(String uuid) { + Cursor cursordata = null; + ArrayList auditData = new ArrayList<>(); + try { + + cursordata = db.rawQuery("select * from TABLE_RETURNTO_DISTRIBUTOR where UUID_ID ='" + uuid + "'and STATUS='N'", null); + + if (cursordata != null) { + cursordata.moveToFirst(); + while (!cursordata.isAfterLast()) { + ProductMaster sb = new ProductMaster(); + + sb.setStock_type(cursordata.getString(cursordata.getColumnIndexOrThrow(CommonString.KEY_STOCK_TYPE))); + sb.setCounter_id(cursordata.getString(cursordata.getColumnIndexOrThrow(CommonString.KEY_COUNTER_ID))); + sb.setTransaction_Id(cursordata.getString(cursordata.getColumnIndexOrThrow(CommonString.KEY_UUID))); + sb.setProductId(cursordata.getInt(cursordata.getColumnIndexOrThrow(CommonString.KEY_ProductId))); + sb.setStock(cursordata.getInt(cursordata.getColumnIndexOrThrow(CommonString.KEY_STOCK))); + sb.setUser_id(cursordata.getString(cursordata.getColumnIndexOrThrow(CommonString.KEY_USER_ID))); + + auditData.add(sb); + cursordata.moveToNext(); + } + + cursordata.close(); + } + } catch (Exception ex) { + ////////test("Exception ", " in Master_Survey" + ex.toString()); + } + + return auditData; + + } + + + public long insert_temp_image(String file_name, String visit_date) { + db.delete(CommonString.Table_Temp_Image, CommonString.KEY_VISIT_DATE + " <>'" + visit_date + "'", null); + ContentValues values = new ContentValues(); + long l2 = 0; + + try { + db.beginTransaction(); + values.put(CommonString.KEY_VISIT_DATE, visit_date); + values.put("ImageName", file_name); + long l = db.insert(CommonString.Table_Temp_Image, null, values); + closeDb(); + } catch (Exception ex) { + closeDb(); + ////////test("Database Exception", " while Insert Posm Master Data " + ex.toString()); + } + + + return l2; + } + + + public boolean ischeck_uploaded_image(String visit_date, String imagepath) { + boolean filled = false; + Cursor dbcursor = null; + try { + + dbcursor = db.rawQuery("Select * from " + CommonString.Table_Temp_Image + " where " + CommonString.KEY_VISIT_DATE + "='" + visit_date + "'", null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + String user_idget = dbcursor.getString(dbcursor.getColumnIndexOrThrow("ImageName")); + if (user_idget != null && !user_idget.equals("") && user_idget.equalsIgnoreCase(imagepath)) { + filled = true; + break; + } else { + filled = false; + } + dbcursor.moveToNext(); + } + + dbcursor.close(); + } + } catch (Exception e) { + ////////test("Exception--", e.toString()); + return filled; + } + return filled; + } + + + public ArrayList getsalesReports(String type, String userType) { + Cursor cursordata = null; + ArrayList surveyData = new ArrayList<>(); + try { + String query = "", table = "Report_Sales_Detail"; + if (userType != null && userType.equalsIgnoreCase(CommonString.TAG_FROM_ME)) { + table = "Report_Sales_DetailME"; + } + if (type.equalsIgnoreCase("Product")) { + query = "select P.ProductId, p.ProductName, s.Qty, ifnull(s.SalesValue,0) as Value from " + table + " s " + "inner join Product_Master p on s.ProductId = p.ProductId"; + } else if (type.equalsIgnoreCase("Axe")) { + query = "select p.AxeName as ProductName, sum(ifnull(s.Qty,0)) as Qty, sum(ifnull(s.SalesValue,0)) as Value from " + table + " s " + "inner join Product_Master p on s.ProductId = p.ProductId group by p.AxeName"; + } else if (type.equalsIgnoreCase("Sub Axe")) { + query = "select p.SubAxeName as ProductName, sum(ifnull(s.Qty,0)) as Qty, sum(ifnull(s.SalesValue,0)) as Value from " + table + " s " + "inner join Product_Master p on s.ProductId = p.ProductId group by p.SubAxeName"; + } else if (type.equalsIgnoreCase("Signature")) { + query = "select p.SignatureName as ProductName, sum(ifnull(s.Qty,0)) as Qty, sum(ifnull(s.SalesValue,0)) as Value from " + table + " s " + "inner join Product_Master p on s.ProductId = p.ProductId group by p.SignatureName"; + } else if (type.equalsIgnoreCase("Sub Brand")) { + query = "select p.SubBrandName as ProductName, sum(ifnull(s.Qty,0)) as Qty, sum(ifnull(s.SalesValue,0)) as Value from " + table + " s " + "inner join Product_Master p on s.ProductId = p.ProductId group by p.SubBrandName"; + } else if (type.equalsIgnoreCase("Brand")) { + query = "select p.BrandName as ProductName, sum(ifnull(s.Qty,0)) as Qty, sum(ifnull(s.SalesValue,0)) as Value from " + table + " s " + "inner join Product_Master p on s.ProductId = p.ProductId group by p.BrandName"; + } + + cursordata = db.rawQuery(query, null); + + if (cursordata != null) { + cursordata.moveToFirst(); + while (!cursordata.isAfterLast()) { + ProductMaster sb = new ProductMaster(); + sb.setProductName(cursordata.getString(cursordata.getColumnIndexOrThrow("ProductName"))); + sb.setActualQty(cursordata.getString(cursordata.getColumnIndexOrThrow("Qty"))); + sb.setSaleValue(cursordata.getDouble(cursordata.getColumnIndexOrThrow("Value"))); + surveyData.add(sb); + cursordata.moveToNext(); + } + cursordata.close(); + } + + } catch (Exception ex) { + ////////test("Exception ", " in ADDITIONAL_QUESTION " + ex.toString()); + } + return surveyData; + } + + + public long update_temp_promo_apply_definition(String counterId, String userId, String promoId, String visit_date) { + ContentValues values1 = new ContentValues(); + long l = 0; + try { + values1.put("Qualified_Status", "Ok"); + if (!db.isOpen()) { + open(); + } + l = db.update(CommonString.Table_Temp_Temp_Promo_AplyDefinition, values1, "COUNTER_ID=" + counterId + " and Visit_Date ='" + visit_date + "' and USER_ID ='" + userId + "' and PromoId ='" + promoId + "'", null); + } catch (Exception ex) { + ex.fillInStackTrace(); + } + + return l; + } + + public long update_temp_promo_apply_definitionfor_andpromo(int masterId, String counterId, String userId, int promoId, String visit_date) { + ContentValues values1 = new ContentValues(); + long l = 0; + try { + values1.put("Qualified_Status", "Ok"); + if (!db.isOpen()) { + open(); + } + l = db.update(CommonString.Table_Temp_Temp_Promo_AplyDefinitionfor_and, values1, "COUNTER_ID=" + counterId + " and Visit_Date ='" + visit_date + "' and USER_ID ='" + userId + "' and PromoId =" + promoId + " and MasterId=" + masterId, null); + + } catch (Exception ex) { + ex.fillInStackTrace(); + } + + return l; + } + + public long delete_table_temp() { + long l = 0; + try { + if (!db.isOpen()) { + open(); + } + l = db.delete(CommonString.Table_Temp_Temp_Promo_AplyDefinition, null, null); + } catch (Exception e) { + e.fillInStackTrace(); + } + + return l; + } + + public long delete_table_tempforsameproduct() { + long l = 0; + try { + if (!db.isOpen()) { + open(); + } + l = db.delete(CommonString.Table_Temp_Promotion_OffSameProduct, null, null); + } catch (Exception e) { + e.fillInStackTrace(); + } + + return l; + } + + + public long delete_table_tempfor_andpromo() { + long l = 0; + try { + if (db.isOpen()) { + } else { + open(); + } + + l = db.delete(CommonString.Table_Temp_Temp_Promo_AplyDefinitionfor_and, null, null); + + } catch (Exception e) { + e.fillInStackTrace(); + } + + return l; + } + + public ArrayList getsetintitiytemId(int promoId) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + + try { + + dbcursor = db.rawQuery("Select distinct Id,ItemCount,PromoId from Master_PromotionSetEntityItem where PromoId =" + promoId, null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + MasterPromotionSetEntityItem sb = new MasterPromotionSetEntityItem(); + sb.setId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("Id"))); + sb.setPromoId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("PromoId"))); + sb.setItemCount(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("ItemCount"))); + list.add(sb); + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list; + } + } catch (Exception e) { + + return list; + } + + return list; + } + + + @SuppressLint("Recycle") + public int getPromotiongetProductforAndPromo(int andId, String promoId, boolean flag_for_qty, String userId, String visit_date, String counterId) { + int value = 0; + Cursor dbcursor = null; + Cursor dbcursor1 = null; + try { + + dbcursor1 = db.rawQuery("Select * from Master_PromotionSetEntityItem where PromoId =" + promoId + " and Id=" + andId, null); + + if (dbcursor1 != null) { + dbcursor1.moveToFirst(); + while (!dbcursor1.isAfterLast()) { + String setentitiy_listType = dbcursor1.getString(dbcursor1.getColumnIndexOrThrow("SetEntityListType")); + String setEntityListItem = dbcursor1.getString(dbcursor1.getColumnIndexOrThrow("SetEntityListItem")); + String val_str = ""; + if (flag_for_qty) { + val_str = "Quantity"; + } else { + val_str = "Quantity * Amount"; + } + if (db.isOpen()) { + } else { + open(); + } + if (setentitiy_listType != null && !setentitiy_listType.isEmpty() && setentitiy_listType.trim().equalsIgnoreCase("ProductGroup")) { + ////change by mahesh sir......... + db.execSQL("Insert into Temp_Promo_AplyDefinitionfor_and(COUNTER_ID,Visit_Date,USER_ID,MasterId,PromoId,ProductId, Quantity,Rate)" + " select '" + counterId + "','" + visit_date + "','" + userId + "','" + andId + "','" + promoId + "'," + " a.ProductId, a.Quantity," + " a.Amount from (select * from Temp_Consumer_Sale " + "where USER_ID='" + userId + "'AND Visit_Date='" + visit_date + "'and COUNTER_ID=" + counterId + + + " and ProductId not in(WITH RECURSIVE neat( id, ProductId, etc) AS(SELECT PromoId, '' , SetExclusionList || ','" + " FROM Master_PromotionSetExclusionList WHERE PromoId=" + promoId + " UNION ALL SELECT id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '')" + "SELECT ProductId FROM neat WHERE ProductId <> '')" + + + " ) as a inner join" + " (WITH RECURSIVE neat( id, tag, etc) AS(SELECT PromoId, '' , SetEntityListItem || ',' FROM Master_PromotionSetEntityItem WHERE PromoId=" + promoId + " and Id=" + andId + " UNION ALL SELECT id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '')" + " select * from Master_PromotionSetProductGroup where" + " ProductGroupId in(SELECT tag FROM neat WHERE tag <> '' ORDER BY id ASC , tag ASC) ) b " + "on a.ProductId = b.ProductId"); + + dbcursor = db.rawQuery(" select ifnull(sum(" + val_str + "),0) as Total_Value from (select * from Temp_Consumer_Sale where" + " USER_ID='" + userId + "'AND Visit_Date='" + visit_date + "'and COUNTER_ID=" + counterId + + + " and ProductId not in(WITH RECURSIVE neat( id, ProductId, etc) AS(SELECT PromoId, '' , SetExclusionList || ','" + " FROM Master_PromotionSetExclusionList WHERE PromoId=" + promoId + " UNION ALL SELECT id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '')" + "SELECT ProductId FROM neat WHERE ProductId <> '')" + + + " ) as a inner join " + " (WITH RECURSIVE neat( id, tag, etc) AS(SELECT PromoId, '' , SetEntityListItem || ',' FROM Master_PromotionSetEntityItem WHERE PromoId=" + promoId + " and Id=" + andId + " UNION ALL SELECT id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '') " + " select * from Master_PromotionSetProductGroup where" + " ProductGroupId in(SELECT tag FROM neat WHERE tag <> '' ORDER BY id ASC , tag ASC) ) b " + "on a.ProductId = b.ProductId", null); + + } else if (setentitiy_listType != null && !setentitiy_listType.isEmpty() && setentitiy_listType.trim().equalsIgnoreCase("Catalog")) { + if (!db.isOpen()) { + open(); + } + db.execSQL("Insert into Temp_Promo_AplyDefinitionfor_and(COUNTER_ID,Visit_Date,USER_ID,MasterId,PromoId,ProductId, Quantity,Rate)" + "select '" + counterId + "','" + visit_date + "','" + userId + "','" + andId + "','" + promoId + "'," + " a.ProductId, a.Quantity, a.Amount from (select * from Temp_Consumer_Sale " + " where USER_ID='" + userId + "'AND Visit_Date='" + visit_date + "'and COUNTER_ID=" + counterId + " and ProductId not in(WITH RECURSIVE neat( id, ProductId, etc) AS(SELECT PromoId, '' , SetExclusionList || ','" + " FROM Master_PromotionSetExclusionList WHERE PromoId=" + promoId + " UNION ALL SELECT id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '')" + "SELECT ProductId FROM neat WHERE ProductId <> '')" + + + " ) as a inner join" + " (WITH RECURSIVE neat( id, tag, etc) AS(SELECT PromoId, '' , SetEntityListItem || ',' FROM Master_PromotionSetEntityItem WHERE PromoId=" + promoId + " and Id=" + andId + " UNION ALL SELECT id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '')" + " select * from Master_PromotionSetProductCatalog where" + " CatalogId in(SELECT tag FROM neat WHERE tag <> '' ORDER BY id ASC , tag ASC) ) b " + "on a.ProductId = b.ProductId"); + + dbcursor = db.rawQuery("select ifnull(sum(Quantity),0) as Total_Value from (select * from Temp_Consumer_Sale " + "where USER_ID='" + userId + "'AND Visit_Date='" + visit_date + "'and COUNTER_ID=" + counterId + + + " and ProductId not in(WITH RECURSIVE neat( id, ProductId, etc) AS(SELECT PromoId, '' , SetExclusionList || ','" + " FROM Master_PromotionSetExclusionList WHERE PromoId=" + promoId + " UNION ALL SELECT id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '')" + "SELECT ProductId FROM neat WHERE ProductId <> '')" + + + " ) as a inner join " + "(WITH RECURSIVE neat( id, tag, etc) AS(SELECT PromoId, '' , SetEntityListItem || ',' FROM Master_PromotionSetEntityItem " + "WHERE PromoId=" + promoId + " and Id=" + andId + " UNION ALL SELECT id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '') " + "select * from Master_PromotionSetProductCatalog where CatalogId in(SELECT tag FROM neat WHERE tag <> '' ORDER BY id ASC , tag ASC) ) " + "b on a.ProductId = b.ProductId", null); + + } else { + ///Checked Setentity list item for product + if (!db.isOpen()) { + open(); + } + + if (setEntityListItem != null && setEntityListItem.equalsIgnoreCase("All")) { + db.execSQL("Insert into Temp_Promo_AplyDefinitionfor_and(COUNTER_ID,Visit_Date,USER_ID,MasterId,PromoId,ProductId, Quantity,Rate)" + "select '" + counterId + "','" + visit_date + "','" + userId + "','" + andId + "','" + promoId + "'," + " a.ProductId, a.Quantity, a.Amount from (select * from Temp_Consumer_Sale " + "where USER_ID='" + userId + "'AND Visit_Date='" + visit_date + "'and COUNTER_ID=" + counterId + + + " and ProductId not in(WITH RECURSIVE neat( id, ProductId, etc) AS(SELECT PromoId, '' , SetExclusionList || ','" + " FROM Master_PromotionSetExclusionList WHERE PromoId=" + promoId + " UNION ALL SELECT id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '')" + "SELECT ProductId FROM neat WHERE ProductId <> '')" + " ) as a"); + + dbcursor = db.rawQuery("select ifnull(sum(" + val_str + "),0) as Total_Value from (select * from Temp_Consumer_Sale where" + " USER_ID='" + userId + "'AND Visit_Date='" + visit_date + "' and COUNTER_ID=" + counterId + + + " and ProductId not in(WITH RECURSIVE neat( id, ProductId, etc) AS(SELECT PromoId, '' , SetExclusionList || ','" + " FROM Master_PromotionSetExclusionList WHERE PromoId=" + promoId + " UNION ALL SELECT id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '')" + "SELECT ProductId FROM neat WHERE ProductId <> '')" + + + " )", null); + + } else { + db.execSQL("Insert into Temp_Promo_AplyDefinitionfor_and(COUNTER_ID,Visit_Date,USER_ID,MasterId,PromoId,ProductId, Quantity,Rate)" + "select '" + counterId + "','" + visit_date + "','" + userId + "','" + andId + "','" + promoId + "'," + " a.ProductId, a.Quantity, a.Amount from (select * from Temp_Consumer_Sale" + " where USER_ID='" + userId + "'AND Visit_Date='" + visit_date + "'and COUNTER_ID=" + counterId + + + " and ProductId not in(WITH RECURSIVE neat( id, ProductId, etc) AS(SELECT PromoId, '' , SetExclusionList || ','" + " FROM Master_PromotionSetExclusionList WHERE PromoId=" + promoId + " UNION ALL SELECT id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '')" + "SELECT ProductId FROM neat WHERE ProductId <> '')" + + + " ) as a inner join" + " (WITH RECURSIVE neat( id, ProductId, etc) AS(SELECT PromoId, '' , SetEntityListItem || ',' FROM Master_PromotionSetEntityItem" + " WHERE PromoId=" + promoId + " and Id=" + andId + " UNION ALL SELECT id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '')" + " SELECT ProductId FROM neat WHERE ProductId <> '' ORDER BY id ASC , ProductId ASC) as b on a.ProductId = b.ProductId"); + + dbcursor = db.rawQuery("select ifnull(sum(" + val_str + "),0) as Total_Value from (select * from Temp_Consumer_Sale where" + " USER_ID='" + userId + "'AND Visit_Date='" + visit_date + "'and COUNTER_ID=" + counterId + + + " and ProductId not in(WITH RECURSIVE neat( id, ProductId, etc) AS(SELECT PromoId, '' , SetExclusionList || ','" + " FROM Master_PromotionSetExclusionList WHERE PromoId=" + promoId + " UNION ALL SELECT id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '')" + "SELECT ProductId FROM neat WHERE ProductId <> '')" + + + " ) as a inner join " + "(WITH RECURSIVE neat( id, ProductId, etc) AS(SELECT PromoId, '' , SetEntityListItem || ',' FROM Master_PromotionSetEntityItem " + "WHERE PromoId=" + promoId + " and Id=" + andId + " UNION ALL SELECT id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '')" + "SELECT ProductId FROM neat WHERE ProductId <> '' ORDER BY id ASC , ProductId ASC) as b " + "on a.ProductId = b.ProductId", null); + + } + } + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + value = dbcursor.getInt(dbcursor.getColumnIndexOrThrow("Total_Value")); + dbcursor.moveToNext(); + } + + dbcursor.close(); + return value; + } + + } + } + } catch (Exception e) { + ////////test("Exception", " answer " + e); + return value; + } + + ////////test("Fetching", " audit answer-->Stop<-"); + return value; + } + + public long inserttemp_promo_data(String counterId, String visit_date, String userId, MasterPromotion promotionOb) { + long l = 0; + try { + if (!db.isOpen()) open(); + + db.execSQL("Insert into Temp_Promo_AplyDefinition(COUNTER_ID,Visit_Date,USER_ID,PromoId,ProductId, Quantity,Rate)" + "select '" + counterId + "','" + visit_date + "','" + userId + "','" + promotionOb.getPromoId() + "'," + " a.ProductId, a.Quantity," + " a.Rate from (select * from Temp_Promo_AplyDefinitionfor_and " + "where PromoId=" + promotionOb.getPromoId() + " and COUNTER_ID=" + counterId + " ) as a"); + + if (promotionOb.getPromotionGetEntityType().equalsIgnoreCase("OffSameProduct")) { + db.execSQL("Insert into Temp_Promotion_OffSameProduct(COUNTER_ID,Visit_Date,USER_ID,PromoId,ProductId, Quantity,Rate)" + "select '" + counterId + "','" + visit_date + "','" + userId + "','" + promotionOb.getPromoId() + "'," + " a.ProductId, a.Quantity," + " a.Rate from (select * from Temp_Promo_AplyDefinitionfor_and " + "where PromoId=" + promotionOb.getPromoId() + " and COUNTER_ID=" + counterId + " ) as a"); + + } + } catch (SQLException e) { + e.fillInStackTrace(); + } + return l; + } + + @SuppressLint("Recycle") + public int getPromotiongetProductall(MasterPromotion promotionOb, boolean flag_for_qty, String userId, String visit_date, String counterId) { + int value = 0; + Cursor dbcursor = null; + Cursor dbcursor1 = null; + try { + + dbcursor1 = db.rawQuery("Select * from Master_PromotionSetEntityItem where PromoId =" + promotionOb.getPromoId(), null); + + if (dbcursor1 != null) { + dbcursor1.moveToFirst(); + while (!dbcursor1.isAfterLast()) { + String setentitiy_listType = dbcursor1.getString(dbcursor1.getColumnIndexOrThrow("SetEntityListType")); + String setEntityListItem = dbcursor1.getString(dbcursor1.getColumnIndexOrThrow("SetEntityListItem")); + String val_str = ""; + if (flag_for_qty) { + val_str = "Quantity"; + } else { + val_str = "Quantity * Amount"; + } + if (db.isOpen()) { + } else { + open(); + } + if (setentitiy_listType != null && !setentitiy_listType.isEmpty() && setentitiy_listType.trim().equalsIgnoreCase("ProductGroup")) { + ////change by mahesh sir......... + db.execSQL("Insert into Temp_Promo_AplyDefinition(COUNTER_ID,Visit_Date,USER_ID,PromoId,ProductId, Quantity,Rate)" + "select '" + counterId + "','" + visit_date + "','" + userId + "','" + promotionOb.getPromoId() + "'," + " a.ProductId, a.Quantity, a.Amount" + " from (select * from Temp_Consumer_Sale " + "where USER_ID='" + userId + "'AND Visit_Date='" + visit_date + "'and COUNTER_ID=" + counterId + " and ProductId not in(WITH RECURSIVE neat( id, ProductId, etc) AS(SELECT PromoId, '' , SetExclusionList || ','" + " FROM Master_PromotionSetExclusionList WHERE PromoId=" + promotionOb.getPromoId() + " UNION ALL SELECT id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '')" + "SELECT ProductId FROM neat WHERE ProductId <> '')" + " ) as a inner join" + " (WITH RECURSIVE neat( id, tag, etc) AS(SELECT PromoId, '' , SetEntityListItem || ',' FROM Master_PromotionSetEntityItem" + " WHERE PromoId=" + promotionOb.getPromoId() + " UNION ALL SELECT" + " id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '')" + " select * from Master_PromotionSetProductGroup where" + " ProductGroupId in(SELECT tag FROM neat WHERE tag <> '' ORDER BY id ASC , tag ASC) ) b on a.ProductId = b.ProductId"); + + if (promotionOb.getPromotionGetEntityType().equalsIgnoreCase("OffSameProduct")) { + db.execSQL("Insert into Temp_Promotion_OffSameProduct(COUNTER_ID,Visit_Date,USER_ID,PromoId,ProductId, Quantity,Rate)" + "select '" + counterId + "','" + visit_date + "','" + userId + "','" + promotionOb.getPromoId() + "'," + " a.ProductId, a.Quantity, a.Amount" + " from (select * from Temp_Consumer_Sale " + "where USER_ID='" + userId + "'AND Visit_Date='" + visit_date + "'and COUNTER_ID=" + counterId + + + " and ProductId not in(WITH RECURSIVE neat( id, ProductId, etc) AS(SELECT PromoId, '' , SetExclusionList || ','" + " FROM Master_PromotionSetExclusionList WHERE PromoId=" + promotionOb.getPromoId() + " UNION ALL SELECT id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '')" + "SELECT ProductId FROM neat WHERE ProductId <> '')" + + + " ) as a inner join" + " (WITH RECURSIVE neat( id, tag, etc) AS(SELECT PromoId, '' , SetEntityListItem || ',' FROM Master_PromotionSetEntityItem" + " WHERE PromoId=" + promotionOb.getPromoId() + " UNION ALL SELECT" + " id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '')" + " select * from Master_PromotionSetProductGroup where" + " ProductGroupId in(SELECT tag FROM neat WHERE tag <> '' ORDER BY id ASC , tag ASC) ) b on a.ProductId = b.ProductId"); + } + + dbcursor = db.rawQuery(" select ifnull(sum(" + val_str + "),0) as Total_Value from (select * from Temp_Consumer_Sale where" + " USER_ID='" + userId + "'AND Visit_Date='" + visit_date + "'and COUNTER_ID=" + counterId + " and ProductId not in(WITH RECURSIVE neat( id, ProductId, etc) AS(SELECT PromoId, '' , SetExclusionList || ','" + " FROM Master_PromotionSetExclusionList WHERE PromoId=" + promotionOb.getPromoId() + " UNION ALL SELECT id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '')" + "SELECT ProductId FROM neat WHERE ProductId <> '')" + " ) as a inner join " + " (WITH RECURSIVE neat( id, tag, etc) AS(SELECT PromoId, '' , SetEntityListItem || ',' FROM Master_PromotionSetEntityItem" + " WHERE PromoId=" + promotionOb.getPromoId() + " UNION ALL SELECT id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '') " + " select * from Master_PromotionSetProductGroup where" + " ProductGroupId in(SELECT tag FROM neat WHERE tag <> '' ORDER BY id ASC , tag ASC) ) b on a.ProductId = b.ProductId", null); + + } else if (setentitiy_listType != null && !setentitiy_listType.isEmpty() && setentitiy_listType.trim().equalsIgnoreCase("Catalog")) { + db.execSQL("Insert into Temp_Promo_AplyDefinition(COUNTER_ID,Visit_Date,USER_ID,PromoId,ProductId, Quantity,Rate)" + "select '" + counterId + "','" + visit_date + "','" + userId + "','" + promotionOb.getPromoId() + "'," + " a.ProductId, a.Quantity, a.Amount" + " from (select * from Temp_Consumer_Sale " + "where USER_ID='" + userId + "'AND Visit_Date='" + visit_date + "'and COUNTER_ID=" + counterId + " and ProductId not in(WITH RECURSIVE neat( id, ProductId, etc) AS(SELECT PromoId, '' , SetExclusionList || ','" + " FROM Master_PromotionSetExclusionList WHERE PromoId=" + promotionOb.getPromoId() + " UNION ALL SELECT id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '')" + "SELECT ProductId FROM neat WHERE ProductId <> '')" + " ) as a inner join" + " (WITH RECURSIVE neat( id, tag, etc) AS(SELECT PromoId, '' , SetEntityListItem || ',' " + "FROM Master_PromotionSetEntityItem WHERE PromoId=" + promotionOb.getPromoId() + "" + " UNION ALL SELECT id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '')" + " select * from Master_PromotionSetProductCatalog where" + " CatalogId in(SELECT tag FROM neat WHERE tag <> '' ORDER BY id ASC , tag ASC) ) b " + "on a.ProductId = b.ProductId"); + + if (promotionOb.getPromotionGetEntityType().equalsIgnoreCase("OffSameProduct")) { + db.execSQL("Insert into Temp_Promotion_OffSameProduct(COUNTER_ID,Visit_Date,USER_ID,PromoId,ProductId, Quantity,Rate)" + "select '" + counterId + "','" + visit_date + "','" + userId + "','" + promotionOb.getPromoId() + "'," + " a.ProductId, a.Quantity, a.Amount" + " from (select * from Temp_Consumer_Sale " + "where USER_ID='" + userId + "'AND Visit_Date='" + visit_date + "'and COUNTER_ID=" + counterId + + + " and ProductId not in(WITH RECURSIVE neat( id, ProductId, etc) AS(SELECT PromoId, '' , SetExclusionList || ','" + " FROM Master_PromotionSetExclusionList WHERE PromoId=" + promotionOb.getPromoId() + " UNION ALL SELECT id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '')" + "SELECT ProductId FROM neat WHERE ProductId <> '')" + + + " ) as a inner join" + " (WITH RECURSIVE neat( id, tag, etc) AS(SELECT PromoId, '' , SetEntityListItem || ',' " + "FROM Master_PromotionSetEntityItem WHERE PromoId=" + promotionOb.getPromoId() + " UNION ALL SELECT id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '')" + " select * from Master_PromotionSetProductCatalog where" + " CatalogId in(SELECT tag FROM neat WHERE tag <> '' ORDER BY id ASC , tag ASC) ) b " + "on a.ProductId = b.ProductId"); + } + + dbcursor = db.rawQuery("select ifnull(sum(Quantity),0) as Total_Value from (select * from Temp_Consumer_Sale " + "where USER_ID='" + userId + "'AND Visit_Date='" + visit_date + "'and COUNTER_ID=" + counterId + + + " and ProductId not in(WITH RECURSIVE neat( id, ProductId, etc) AS(SELECT PromoId, '' , SetExclusionList || ','" + " FROM Master_PromotionSetExclusionList WHERE PromoId=" + promotionOb.getPromoId() + " UNION ALL SELECT id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '')" + "SELECT ProductId FROM neat WHERE ProductId <> '')" + + + " ) as a inner join " + "(WITH RECURSIVE neat( id, tag, etc) AS(SELECT PromoId, '' , SetEntityListItem || ',' FROM Master_PromotionSetEntityItem " + "WHERE PromoId=" + promotionOb.getPromoId() + " UNION ALL SELECT id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '') " + "select * from Master_PromotionSetProductCatalog where CatalogId in(SELECT tag FROM neat WHERE tag <> '' ORDER BY id ASC , tag ASC) ) " + "b on a.ProductId = b.ProductId", null); + + } else { + if (!db.isOpen()) { + open(); + } + + if (setEntityListItem != null && setEntityListItem.equalsIgnoreCase("All")) { + db.execSQL("Insert into Temp_Promo_AplyDefinition(COUNTER_ID,Visit_Date,USER_ID,PromoId,ProductId, Quantity,Rate) " + " select '" + counterId + "','" + visit_date + "','" + userId + "','" + promotionOb.getPromoId() + "'," + " a.ProductId, a.Quantity," + " a.Amount from (select * from Temp_Consumer_Sale where " + " USER_ID='" + userId + "'AND Visit_Date='" + visit_date + "' and COUNTER_ID=" + counterId + " and ProductId not in(WITH RECURSIVE neat( id, ProductId, etc) AS(SELECT PromoId, '' , SetExclusionList || ','" + " FROM Master_PromotionSetExclusionList WHERE PromoId=" + promotionOb.getPromoId() + " UNION ALL SELECT id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '')" + "SELECT ProductId FROM neat WHERE ProductId <> '')" + " ) as a"); + + if (promotionOb.getPromotionGetEntityType().equalsIgnoreCase("OffSameProduct")) { + db.execSQL("Insert into Temp_Promotion_OffSameProduct(COUNTER_ID,Visit_Date,USER_ID,PromoId,ProductId, Quantity,Rate) " + " select '" + counterId + "','" + visit_date + "','" + userId + "','" + promotionOb.getPromoId() + "'," + " a.ProductId, a.Quantity," + " a.Amount from (select * from Temp_Consumer_Sale where " + " USER_ID='" + userId + "'AND Visit_Date='" + visit_date + "' and COUNTER_ID=" + counterId + " and ProductId not in(WITH RECURSIVE neat( id, ProductId, etc) AS(SELECT PromoId, '' , SetExclusionList || ','" + " FROM Master_PromotionSetExclusionList WHERE PromoId=" + promotionOb.getPromoId() + " UNION ALL SELECT id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '')" + "SELECT ProductId FROM neat WHERE ProductId <> '')" + " ) as a"); + } + dbcursor = db.rawQuery(" select ifnull(sum(" + val_str + "),0) as Total_Value from (select * from Temp_Consumer_Sale where" + " USER_ID='" + userId + "'AND Visit_Date='" + visit_date + "' and COUNTER_ID=" + counterId + " and ProductId not in(WITH RECURSIVE neat( id, ProductId, etc) AS(SELECT PromoId, '' , SetExclusionList || ','" + " FROM Master_PromotionSetExclusionList WHERE PromoId=" + promotionOb.getPromoId() + " UNION ALL SELECT id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '')" + "SELECT ProductId FROM neat WHERE ProductId <> '')" + " )", null); + + } else { + + db.execSQL("Insert into Temp_Promo_AplyDefinition(COUNTER_ID,Visit_Date,USER_ID,PromoId,ProductId, Quantity,Rate) " + " select '" + counterId + "','" + visit_date + "','" + userId + "','" + promotionOb.getPromoId() + "'," + " a.ProductId, a.Quantity, a.Amount from (select * from Temp_Consumer_Sale where " + " USER_ID='" + userId + "'AND Visit_Date='" + visit_date + "'and COUNTER_ID=" + counterId + + + " and ProductId not in(WITH RECURSIVE neat( id, ProductId, etc) AS(SELECT PromoId, '' , SetExclusionList || ','" + " FROM Master_PromotionSetExclusionList WHERE PromoId=" + promotionOb.getPromoId() + " UNION ALL SELECT id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '')" + "SELECT ProductId FROM neat WHERE ProductId <> '')" + " ) as a inner join" + " (WITH RECURSIVE neat( id, ProductId, etc) AS(SELECT PromoId, '' , SetEntityListItem || ',' FROM Master_PromotionSetEntityItem " + "WHERE PromoId=" + promotionOb.getPromoId() + " UNION ALL SELECT id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '') " + "SELECT ProductId FROM neat WHERE ProductId <> '' ORDER BY id ASC , ProductId ASC) as b on a.ProductId = b.ProductId"); + + if (promotionOb.getPromotionGetEntityType().equalsIgnoreCase("OffSameProduct")) { + db.execSQL("Insert into Temp_Promotion_OffSameProduct(COUNTER_ID,Visit_Date,USER_ID,PromoId,ProductId, Quantity,Rate) " + " select '" + counterId + "','" + visit_date + "','" + userId + "','" + promotionOb.getPromoId() + "'," + " a.ProductId, a.Quantity, a.Amount from (select * from Temp_Consumer_Sale where " + " USER_ID='" + userId + "'AND Visit_Date='" + visit_date + "'and COUNTER_ID=" + counterId + + + " and ProductId not in(WITH RECURSIVE neat( id, ProductId, etc) AS(SELECT PromoId, '' , SetExclusionList || ','" + " FROM Master_PromotionSetExclusionList WHERE PromoId=" + promotionOb.getPromoId() + " UNION ALL SELECT id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '')" + "SELECT ProductId FROM neat WHERE ProductId <> '')" + + + " ) as a inner join" + " (WITH RECURSIVE neat( id, ProductId, etc) AS(SELECT PromoId, '' , SetEntityListItem || ',' FROM Master_PromotionSetEntityItem " + "WHERE PromoId=" + promotionOb.getPromoId() + " UNION ALL SELECT id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '') " + "SELECT ProductId FROM neat WHERE ProductId <> '' ORDER BY id ASC , ProductId ASC) as b on a.ProductId = b.ProductId"); + + } + + dbcursor = db.rawQuery(" select ifnull(sum(" + val_str + "),0) as Total_Value from (select * from Temp_Consumer_Sale where" + " USER_ID='" + userId + "'AND Visit_Date='" + visit_date + "'and COUNTER_ID=" + counterId + " and ProductId not in(WITH RECURSIVE neat( id, ProductId, etc) AS(SELECT PromoId, '' , SetExclusionList || ','" + " FROM Master_PromotionSetExclusionList WHERE PromoId=" + promotionOb.getPromoId() + " UNION ALL SELECT id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '')" + "SELECT ProductId FROM neat WHERE ProductId <> '')" + " ) as a inner join " + "(WITH RECURSIVE neat( id, ProductId, etc) AS(SELECT PromoId, '' , SetEntityListItem || ',' FROM Master_PromotionSetEntityItem" + " WHERE PromoId=" + promotionOb.getPromoId() + " UNION ALL SELECT id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '')" + "SELECT ProductId FROM neat WHERE ProductId <> '' ORDER BY id ASC , ProductId ASC) as b on a.ProductId = b.ProductId", null); + + } + } + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + value = dbcursor.getInt(dbcursor.getColumnIndexOrThrow("Total_Value")); + dbcursor.moveToNext(); + } + + dbcursor.close(); + return value; + } + } + } + + } catch (Exception e) { + ////////test("Exception", " answer " + e.toString()); + return value; + } + + ////////test("Fetching", " audit answer-->Stop<-"); + return value; + } + + + public int checked_applyied_promo(String promoId, String userId, String visit_date, String counterId, String check_promoId) { + int value = 0; + Cursor dbcursor = null; + try { + dbcursor = db.rawQuery("select ifnull(count(*),0) as TotalCount from " + "(select * from Temp_Promo_AplyDefinition where COUNTER_ID =" + counterId + " and User_Id = '" + userId + "' and Visit_Date ='" + visit_date + "' and PromoId =" + promoId + ") as Ck_promoId " + "Inner join " + "(select * from Temp_Promo_AplyDefinition where COUNTER_ID =" + counterId + " and User_Id = '" + userId + "' and Visit_Date ='" + visit_date + "' and PromoId =" + check_promoId + ") as tick_promoid " + "on Ck_promoId.ProductId = tick_promoid.ProductId", null); + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + value = dbcursor.getInt(dbcursor.getColumnIndexOrThrow("TotalCount")); + dbcursor.moveToNext(); + } + dbcursor.close(); + return value; + } + + } catch (Exception e) { + ////////test("Exception", " answer " + e); + return value; + } + ////////test("Fetching", " audit answer-->Stop<-"); + return value; + } + + public ArrayList gettransaction_date(int master_transaction_id) { + Cursor cursordata = null; + ArrayList auditData = new ArrayList<>(); + try { + String str_data = "MASTER_TRANSACTION_ID,User_Id,COUNTER_ID,UUID_ID,STOCK_TYPE,ProductId,REASON_ID,STORE_IMAGE,STOCK,ENTRY_TYPE"; + cursordata = db.rawQuery("select distinct " + str_data + " from TABLE_TRANSACTION_DATA where MASTER_TRANSACTION_ID =" + master_transaction_id + "", null); + + if (cursordata != null) { + cursordata.moveToFirst(); + while (!cursordata.isAfterLast()) { + ProductMaster sb = new ProductMaster(); + sb.setMaster_transaction_id(cursordata.getInt(cursordata.getColumnIndexOrThrow("MASTER_TRANSACTION_ID"))); + sb.setUser_id(cursordata.getString(cursordata.getColumnIndexOrThrow(CommonString.KEY_USER_ID))); + sb.setCounter_id(cursordata.getString(cursordata.getColumnIndexOrThrow("COUNTER_ID"))); + sb.setTransaction_Id(cursordata.getString(cursordata.getColumnIndexOrThrow("UUID_ID"))); + sb.setStock_type(cursordata.getString(cursordata.getColumnIndexOrThrow("STOCK_TYPE"))); + sb.setProductId(cursordata.getInt(cursordata.getColumnIndexOrThrow("ProductId"))); + sb.setReasonId(cursordata.getInt(cursordata.getColumnIndexOrThrow("REASON_ID"))); + sb.setImagePath(cursordata.getString(cursordata.getColumnIndexOrThrow("STORE_IMAGE"))); + sb.setStock(cursordata.getInt(cursordata.getColumnIndexOrThrow("STOCK"))); + String stock_entry_type = cursordata.getString(cursordata.getColumnIndexOrThrow("ENTRY_TYPE")); + if (stock_entry_type != null && !stock_entry_type.equals("") && stock_entry_type.equalsIgnoreCase("FirstTime_Stock_Draft")) { + sb.setEntry_type(CommonString.KEY_DRAFT); + } else if (stock_entry_type != null && !stock_entry_type.equals("") && stock_entry_type.equalsIgnoreCase("FirstTime_Stock_Comp")) { + sb.setEntry_type(CommonString.KEY_COMPLETE); + } else if (stock_entry_type != null && !stock_entry_type.equals("") && stock_entry_type.equalsIgnoreCase(CommonString.KEY_REGULAR)) { + sb.setEntry_type(CommonString.KEY_REGULAR); + } + + auditData.add(sb); + cursordata.moveToNext(); + } + + cursordata.close(); + } + } catch (Exception ex) { + ////////test("Exception ", " in Master_Survey" + ex.toString()); + } + + return auditData; + + } + + + public ArrayList getInwardStockTransactionData(String uuid_id) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + + dbcursor = db.rawQuery("select * from " + CommonString.TABLE_INSERT_INWARD_STOCK_TRANSACTION + " where " + CommonString.KEY_TRANSACTION_ID + " = '" + uuid_id + "'", null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + ProductMaster sb = new ProductMaster(); + String checkVal1 = dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_SKU_CONFIRMATION_CHECK)); + sb.setCounter_id(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_COUNTER_ID))); + sb.setConsumer_qty(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_INVOICE_QTY))); + sb.setActualQty(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_ACTUAL_QTY))); + sb.setProductId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(CommonString.KEY_ProductId))); + sb.setReasonId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(CommonString.KEY_REASON_ID))); + sb.setUser_id(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_USER_ID))); + sb.setInvId(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_INVOICE_ID))); + sb.setInvoice_Status(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_INVOICE_STATUS))); + sb.setInvoice_number(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_INVOICE_NUMBER))); + sb.setInvoice_type(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_INVOICE_TYPE))); + sb.setInvoice_date(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_INVOICE_DATE))); + sb.setTransaction_Id(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_TRANSACTION_ID))); + sb.setSource(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_SOURCE))); + + if (checkVal1 != null && !checkVal1.equals("") && checkVal1.equals("0")) { + sb.setConfirmChecked(false); + } else { + sb.setConfirmChecked(true); + } + + list.add(sb); + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list; + } + + } catch (Exception e) { + return list; + } + + return list; + } + + public ArrayList getManualInwardStock(String uuid_Id) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + + try { + dbcursor = db.rawQuery("select * from " + CommonString.TABLE_INSERT_MANUAL_INWARD_TRANSACTION + " where " + CommonString.KEY_TRANSACTION_ID + " ='" + uuid_Id + "'", null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + ProductMaster sb = new ProductMaster(); + String checkVal1 = dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_COUNTER_CONFIRM)); + sb.setVisit_date(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_VISIT_DATE))); + sb.setCounter_id(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_COUNTER_ID))); + sb.setConsumer_qty(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_INVOICE_QTY))); + sb.setActualQty(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_ACTUAL_QTY))); + sb.setProductId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(CommonString.KEY_ProductId))); + sb.setReasonId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(CommonString.KEY_REASON_ID))); + sb.setUser_id(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_USER_ID))); + sb.setInvId(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_INVOICE_ID))); + sb.setInvoice_Status(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_INVOICE_STATUS))); + sb.setInvoice_number(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_INVOICE_NUMBER))); + sb.setInvoice_type(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_INVOICE_TYPE))); + sb.setInvoice_date(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_INVOICE_DATE))); + sb.setTransaction_Id(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_TRANSACTION_ID))); + sb.setSource(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_SOURCE))); + sb.setDraft_status(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_DRAFT_STATUS))); + sb.setInvoice_img(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_INVOICE_IMG))); + + if (checkVal1 != null && !checkVal1.equals("") && checkVal1.equals("0")) { + sb.setConfirmChecked(false); + } else { + sb.setConfirmChecked(true); + } + + list.add(sb); + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list; + } + } catch (Exception e) { + + return list; + } + + return list; + } + + + public ArrayList getmasterTransaction(String visit_date, String counterId, boolean previous_date) { + Cursor cursordata = null; + ArrayList auditData = new ArrayList<>(); + try { + + if (previous_date) { + cursordata = db.rawQuery("select distinct t1.MASTER_TRANSACTION_ID as MASTER_TRANSACTION_ID,t1.UUID_ID as UUID_ID," + "t1.STOCK_TYPE as STOCK_TYPE,t1.ENTRY_TYPE as ENTRY_TYPE,t1.Visit_Date as Visit_Date,t1.STATUS as STATUS" + " from DR_TABLE_TRANSACTION_WISE_MASTER t1" + " where t1.Visit_Date <>'" + visit_date + "'and t1.COUNTER_ID=" + counterId + " and t1.STATUS <>'Y' order by t1.MASTER_TRANSACTION_ID asc", null); + + } else { + cursordata = db.rawQuery("select distinct t1.MASTER_TRANSACTION_ID as MASTER_TRANSACTION_ID,t1.UUID_ID as UUID_ID,t1.STOCK_TYPE as STOCK_TYPE," + "t1.ENTRY_TYPE as ENTRY_TYPE,t1.Visit_Date as Visit_Date,t1.STATUS as STATUS" + " from DR_TABLE_TRANSACTION_WISE_MASTER t1" + " where t1.Visit_Date ='" + visit_date + "'and t1.COUNTER_ID=" + counterId + " and t1.STATUS <>'Y' order by t1.MASTER_TRANSACTION_ID asc", null); + + } + + if (cursordata != null) { + cursordata.moveToFirst(); + while (!cursordata.isAfterLast()) { + ProductMaster sb = new ProductMaster(); + sb.setMaster_transaction_id(cursordata.getInt(cursordata.getColumnIndexOrThrow("MASTER_TRANSACTION_ID"))); + sb.setTransaction_Id(cursordata.getString(cursordata.getColumnIndexOrThrow("UUID_ID"))); + sb.setStock_type(cursordata.getString(cursordata.getColumnIndexOrThrow("STOCK_TYPE"))); + sb.setVisit_date(cursordata.getString(cursordata.getColumnIndexOrThrow("Visit_Date"))); + sb.setUpload_status(cursordata.getString(cursordata.getColumnIndexOrThrow("STATUS"))); + String stock_entry_type = cursordata.getString(cursordata.getColumnIndexOrThrow("ENTRY_TYPE")); + if (stock_entry_type != null && !stock_entry_type.equals("") && stock_entry_type.equalsIgnoreCase("FirstTime_Stock_Draft")) { + sb.setEntry_type(CommonString.KEY_DRAFT); + } else if (stock_entry_type != null && !stock_entry_type.equals("") && stock_entry_type.equalsIgnoreCase("FirstTime_Stock_Comp")) { + sb.setEntry_type(CommonString.KEY_COMPLETE); + } else if (stock_entry_type != null && !stock_entry_type.equals("") && stock_entry_type.equalsIgnoreCase(CommonString.KEY_REGULAR)) { + sb.setEntry_type(CommonString.KEY_REGULAR); + } + + auditData.add(sb); + cursordata.moveToNext(); + } + + cursordata.close(); + } + } catch (Exception ex) { + ////////test("Exception ", " in Master_Survey" + ex.toString()); + } + + return auditData; + + } + + + public long update_skinGenius_Category(String counterId, String user_Id, String keyId, String table_name) { + long l = 0; + try { + if (!db.isOpen()) { + open(); + } + ContentValues values = new ContentValues(); + values.put("UPLOAD_STATUS", CommonString.KEY_Y); + + l = db.update(table_name, values, CommonString.KEY_COUNTER_ID + "=" + counterId + " AND UNIQUE_CODE='" + keyId + "'", null); + + } catch (Exception e) { + e.fillInStackTrace(); + } + + return l; + } + + public long update_visibility(String counterId, String user_Id, String keyId, String table_name) { + long l = 0; + try { + + ContentValues values = new ContentValues(); + values.put(CommonString.KEY_STATUS, CommonString.KEY_Y); + if (!db.isOpen()) { + open(); + } + l = db.update(table_name, values, CommonString.KEY_COUNTER_ID + "='" + counterId + "' AND " + CommonString.KEY_UUID + "='" + keyId + "'", null); + + } catch (Exception e) { + e.fillInStackTrace(); + } + + return l; + } + + + public long insertSkinGeniusdata(String user_Id, String visit_date, String counter_Id, String UID_code, String skingenius_img, String current_tyme) { + db.delete(CommonString.Table_Skin_Genius_Table, CommonString.KEY_VISIT_DATE + "<>'" + visit_date + "'", null); + db.delete(CommonString.TABLE_TRANSACTION_WISE_MASTER_TABLE, CommonString.KEY_VISIT_DATE + " <>'" + visit_date + "'", null); + ContentValues finalvalues = new ContentValues(); + ContentValues values = new ContentValues(); + long l2 = 0, masterreturn = 0; + try { + if (!db.isOpen()) { + open(); + } + db.beginTransaction(); + finalvalues.put(CommonString.KEY_UUID, UID_code); + finalvalues.put(CommonString.KEY_USER_ID, user_Id); + finalvalues.put(CommonString.KEY_COUNTER_ID, counter_Id); + finalvalues.put(CommonString.KEY_VISIT_DATE, visit_date); + finalvalues.put(CommonString.KEY_STOCK_TYPE, CommonString.SKINGENIUS); + finalvalues.put(CommonString.KEY_ENTRY_TYPE, CommonString.KEY_REGULAR); + finalvalues.put(CommonString.KEY_STATUS, CommonString.KEY_N); + + masterreturn = db.insert(CommonString.TABLE_TRANSACTION_WISE_MASTER_TABLE, null, finalvalues); + + + values.put("USER_ID", user_Id); + values.put("UNIQUE_CODE", UID_code); + values.put(CommonString.KEY_MASTER_TRANSACTION_ID, masterreturn); + values.put(CommonString.KEY_COUNTER_ID, counter_Id); + values.put(CommonString.KEY_VISIT_DATE, visit_date); + values.put("SKIN_GENIUS_IMG", skingenius_img); + values.put("UPLOAD_STATUS", CommonString.KEY_N); + values.put("CAPTURED_TIME", current_tyme); + if (db.isOpen()) { + } else { + open(); + } + + l2 = db.insert(CommonString.Table_Skin_Genius_Table, null, values); + closeDb(); + } catch (Exception ex) { + closeDb(); + ////////test("Database Exception", " while Insert Skin Genius Data " + ex.toString()); + } + + return l2; + } + + + public long insertOpenSkinGeniusdata(String user_Id, String visit_date, String counter_Id, String UID_code, int openskingenius_count) { + db.delete(CommonString.Table_Open_Skin_Genius_Table, CommonString.KEY_VISIT_DATE + "<>'" + visit_date + "'", null); + db.delete(CommonString.TABLE_TRANSACTION_WISE_MASTER_TABLE, CommonString.KEY_VISIT_DATE + " <>'" + visit_date + "'", null); + ContentValues finalvalues = new ContentValues(); + ContentValues values = new ContentValues(); + long l2 = 0, masterreturn = 0; + try { + if (!db.isOpen()) { + open(); + } + db.beginTransaction(); + finalvalues.put(CommonString.KEY_UUID, UID_code); + finalvalues.put(CommonString.KEY_USER_ID, user_Id); + finalvalues.put(CommonString.KEY_COUNTER_ID, counter_Id); + finalvalues.put(CommonString.KEY_VISIT_DATE, visit_date); + finalvalues.put(CommonString.KEY_STOCK_TYPE, CommonString.OPEN_SKINGENIUS); + finalvalues.put(CommonString.KEY_ENTRY_TYPE, CommonString.KEY_REGULAR); + finalvalues.put(CommonString.KEY_STATUS, CommonString.KEY_N); + if (!db.isOpen()) { + open(); + } + masterreturn = db.insert(CommonString.TABLE_TRANSACTION_WISE_MASTER_TABLE, null, finalvalues); + + + values.put("USER_ID", user_Id); + values.put("UNIQUE_CODE", UID_code); + values.put(CommonString.KEY_MASTER_TRANSACTION_ID, masterreturn); + values.put(CommonString.KEY_COUNTER_ID, counter_Id); + values.put(CommonString.KEY_VISIT_DATE, visit_date); + values.put("OPENSKIN_GENIUS_COUNT", openskingenius_count); + values.put("UPLOAD_STATUS", CommonString.KEY_N); + if (db.isOpen()) { + } else { + open(); + } + + l2 = db.insert(CommonString.Table_Open_Skin_Genius_Table, null, values); + + closeDb(); + } catch (Exception ex) { + closeDb(); + ////////test("Database Exception", " while Insert Skin Genius Data " + ex.toString()); + } + + return l2; + } + + public long insertOpenMaybellineNVdata(String user_Id, String visit_date, String counter_Id, String UID_code, int open_maybelline_count) { + db.delete(CommonString.Table_Open_Maybelline_Table, CommonString.KEY_VISIT_DATE + "<>'" + visit_date + "'", null); + db.delete(CommonString.TABLE_TRANSACTION_WISE_MASTER_TABLE, CommonString.KEY_VISIT_DATE + " <>'" + visit_date + "'", null); + ContentValues finalvalues = new ContentValues(); + ContentValues values = new ContentValues(); + long l2 = 0, masterreturn = 0; + try { + if (!db.isOpen()) { + open(); + } + db.beginTransaction(); + finalvalues.put(CommonString.KEY_UUID, UID_code); + finalvalues.put(CommonString.KEY_USER_ID, user_Id); + finalvalues.put(CommonString.KEY_COUNTER_ID, counter_Id); + finalvalues.put(CommonString.KEY_VISIT_DATE, visit_date); + finalvalues.put(CommonString.KEY_STOCK_TYPE, CommonString.OPEN_MAYBELLINE); + finalvalues.put(CommonString.KEY_ENTRY_TYPE, CommonString.KEY_REGULAR); + finalvalues.put(CommonString.KEY_STATUS, CommonString.KEY_N); + + masterreturn = db.insert(CommonString.TABLE_TRANSACTION_WISE_MASTER_TABLE, null, finalvalues); + + + values.put("USER_ID", user_Id); + values.put("UNIQUE_CODE", UID_code); + values.put(CommonString.KEY_MASTER_TRANSACTION_ID, masterreturn); + values.put(CommonString.KEY_COUNTER_ID, counter_Id); + values.put(CommonString.KEY_VISIT_DATE, visit_date); + values.put("OPEN_MAYBELLINE_COUNT", open_maybelline_count); + values.put("UPLOAD_STATUS", CommonString.KEY_N); + if (db.isOpen()) { + } else { + open(); + } + + l2 = db.insert(CommonString.Table_Open_Maybelline_Table, null, values); + + closeDb(); + } catch (Exception ex) { + closeDb(); + ////////test("Database Exception", " while Insert Skin Genius Data " + ex.toString()); + } + + return l2; + } + + public boolean insertMasterCompetitionOffer(ResponseResult cst) { + db.delete("Master_CompetitionOffer", null, null); + ContentValues values = new ContentValues(); + List data = cst.getMastercompetitionoffer(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("CompOfferId", data.get(i).getCompOfferId()); + values.put("CompOffer", data.get(i).getCompOffer()); + values.put("CompBuyTypeId", data.get(i).getCompBuyTypeId()); + values.put("CompBuyType", data.get(i).getCompBuyType()); + values.put("CompSetId", data.get(i).getCompSetId()); + values.put("CompSetName", data.get(i).getCompSetName()); + values.put("CompGetId", data.get(i).getCompGetId()); + values.put("CompGetName", data.get(i).getCompGetName()); + + long id = db.insert("Master_CompetitionOffer", null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ex.fillInStackTrace(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + public boolean insertMasterCompetitionOfferSaleRange(ResponseResult cst) { + db.delete("Master_CompetitionOfferSaleRange", null, null); + ContentValues values = new ContentValues(); + List data = cst.getMasterCompetitionOfferSaleRange(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("SaleRange", data.get(i).getSaleRange()); + + long id = db.insert("Master_CompetitionOfferSaleRange", null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ex.fillInStackTrace(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + public boolean insertMasterRetailExcellence(ResponseResult cst) { + db.delete("Master_RetailExcellence_Item", null, null); + ContentValues values = new ContentValues(); + List data = cst.getMasterRetailExcellenceList(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("ItemCategoryId", data.get(i).getItemCatId()); + values.put("ItemCategoryName", data.get(i).getItemCatName()); + values.put("ItemId", data.get(i).getItemId()); + values.put("ItemName", data.get(i).getItemName()); + + long id = db.insert("Master_RetailExcellence_Item", null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ex.fillInStackTrace(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + public boolean insertDashTVA(ResponseResult cst) { + db.delete("AppDashboard_TVA", null, null); + ContentValues values = new ContentValues(); + List data = cst.getAppDashboardTVA(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("KPI", data.get(i).getkPI()); + values.put("Graph", data.get(i).getGraph()); + values.put("CounterId", data.get(i).getCounterId()); + values.put("Target", data.get(i).getTarget()); + values.put("TotalSale", data.get(i).getTotalSale()); + values.put("Per", data.get(i).getPer()); + + long id = db.insert("AppDashboard_TVA", null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + public boolean insertDashTVADrillDown(ResponseResult cst) { + db.delete("AppDashboard_TVADrillDown", null, null); + ContentValues values = new ContentValues(); + List data = cst.getAppDashboardTVADrillDown(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("KPI", data.get(i).getkPI()); + values.put("Graph", data.get(i).getGraph()); + values.put("CounterId", data.get(i).getCounterId()); + values.put("Target", data.get(i).getTarget()); + values.put("TotalSale", data.get(i).getTotalSale()); + values.put("Per", data.get(i).getPer()); + values.put("ProductGroupId", data.get(i).getProductGroupId()); + values.put("ProductGroupName", data.get(i).getProductGroupName()); + + long id = db.insert("AppDashboard_TVADrillDown", null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + + public AppDashboardTVA getDashboardTVA(String CounterId) { + AppDashboardTVA sb = null; + Cursor dbcursor = null; + + try { + + dbcursor = db.rawQuery("Select * From AppDashboard_TVA where CounterId =" + CounterId, null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + sb = new AppDashboardTVA(); + sb.setkPI(dbcursor.getString(dbcursor.getColumnIndexOrThrow("KPI"))); + sb.setGraph(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Graph"))); + sb.setTarget(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("Target"))); + sb.setTotalSale(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("TotalSale"))); + sb.setPer(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("Per"))); + dbcursor.moveToNext(); + } + dbcursor.close(); + return sb; + } + } catch (Exception e) { + return sb; + } + return sb; + } + + public ArrayList getDashboardTVADrillDown(String CounterId) { + ArrayList list = new ArrayList<>(); + /* AppDashboardTVADrillDown sb = new AppDashboardTVADrillDown(); + sb.setTarget(120000.0); + sb.setTotalSale(2300.0); + sb.setPer(6.8); + sb.setProductGroupName("tr"); + list.add(sb); + sb = new AppDashboardTVADrillDown(); + sb.setTarget(120000.0); + sb.setTotalSale(2300.0); + sb.setPer(6.8); + sb.setProductGroupName("tr"); + list.add(sb);*/ + + Cursor dbcursor = null; + try { + + dbcursor = db.rawQuery("Select * From AppDashboard_TVADrillDown where CounterId =" + CounterId, null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + AppDashboardTVADrillDown sb = new AppDashboardTVADrillDown(); + sb.setkPI(dbcursor.getString(dbcursor.getColumnIndexOrThrow("KPI"))); + sb.setGraph(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Graph"))); + sb.setTarget(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("Target"))); + sb.setTotalSale(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("TotalSale"))); + sb.setPer(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("Per"))); + sb.setProductGroupId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("ProductGroupId"))); + sb.setProductGroupName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ProductGroupName"))); + list.add(sb); + dbcursor.moveToNext(); + } + dbcursor.close(); + return list; + } + } catch (Exception e) { + return list; + } + return list; + } + + + public boolean insertDashLeaderBoard(ResponseResult cst) { + db.delete("AppDashboard_LeaderBoard", null, null); + ContentValues values = new ContentValues(); + List data = cst.getAppDashboardLeaderBoard(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("KPI", data.get(i).getKpi()); + values.put("Graph", data.get(i).getGraph()); + values.put("EmpId", data.get(i).getEmpId()); + values.put("EmpName", data.get(i).getEmpName()); + values.put("EmpCode", data.get(i).getEmpCode()); + values.put("TotalSale", data.get(i).getTotalSale()); + values.put("Target", data.get(i).getTarget()); + values.put("Per", data.get(i).getPer()); + values.put("CounterId", data.get(i).getCounterId()); + values.put("CounterCode", data.get(i).getCounterCode()); + values.put("CounterName", data.get(i).getCounterName()); + + long id = db.insert("AppDashboard_LeaderBoard", null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + public AppDashboardTVA getLeaderDashboard() { + AppDashboardTVA sb = null; + Cursor dbcursor = null; + try { + + dbcursor = db.rawQuery("Select * From AppDashboard_LeaderBoard ORDER by Per DESC", null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + sb = new AppDashboardTVA(); + sb.setkPI(dbcursor.getString(dbcursor.getColumnIndexOrThrow("KPI"))); + sb.setPer(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("Per"))); + sb.setGraph(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EmpName"))); + sb.setCounter_name(dbcursor.getString(dbcursor.getColumnIndexOrThrow("CounterName"))); + int counterId = dbcursor.getInt(dbcursor.getColumnIndexOrThrow("CounterId")); + String counterCode = dbcursor.getString(dbcursor.getColumnIndexOrThrow("CounterCode")); + sb.setCounter_code(counterCode + "/" + counterId); + dbcursor.moveToNext(); + } + dbcursor.close(); + return sb; + } + } catch (Exception e) { + return sb; + } + return sb; + } + + public ArrayList getDashboardInfo(String counterId, String _userId) { + ArrayList list = new ArrayList<>(); + try { + if (!db.isOpen()) open(); + if (getDashboardTVA(counterId) != null) list.add(getDashboardTVA(counterId)); + if (getLeaderDashboard() != null) list.add(getLeaderDashboard()); + if (getDashboardIncentive(counterId, _userId) != null) + list.add(getDashboardIncentive(counterId, _userId)); + + } catch (Exception e) { + e.fillInStackTrace(); + return list; + } + return list; + } + + public ArrayList getLeaderDashboards() { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + + dbcursor = db.rawQuery("Select * From AppDashboard_LeaderBoard ORDER by Per DESC", null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + AppDashboardTVADrillDown sb = new AppDashboardTVADrillDown(); + sb.setkPI(dbcursor.getString(dbcursor.getColumnIndexOrThrow("KPI"))); + sb.setPer(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("Per"))); + sb.setGraph(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EmpName"))); + String countername = dbcursor.getString(dbcursor.getColumnIndexOrThrow("CounterName")); + int counterId = dbcursor.getInt(dbcursor.getColumnIndexOrThrow("CounterId")); + sb.setProductGroupName(countername + "/" + counterId); + list.add(sb); + dbcursor.moveToNext(); + } + dbcursor.close(); + return list; + } + } catch (Exception e) { + return list; + } + return list; + } + + public boolean insertDashIncentive(ResponseResult cst) { + db.delete("AppDashboard_Incentive", null, null); + ContentValues values = new ContentValues(); + List data = cst.getAppDashboardIncentive(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("Per", data.get(i).getPer()); + values.put("KPI", data.get(i).getKpi()); + values.put("Tier", data.get(i).getTier()); + values.put("UserId", data.get(i).getUserId()); + values.put("ChannelName", data.get(i).getChannelName()); + values.put("CounterId", data.get(i).getCounterId()); + values.put("Offtake", data.get(i).getOfftake()); + + values.put("LY_AVG_Sale", data.get(i).getLYAVGSale()); + values.put("MJF_AVG_Sale", data.get(i).getMJFAVGSale()); + values.put("SL_Incentive", data.get(i).getSLIncentive()); + values.put("Flat_Incentive", data.get(i).getFlatIncentive()); + values.put("ToatlIncentive", data.get(i).getToatlIncentive()); + values.put("MaximumIncentive", data.get(i).getMaximumIncentive()); + + long id = db.insert("AppDashboard_Incentive", null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + public AppDashboardTVA getDashboardIncentive(String CounterId, String userId) { + AppDashboardTVA sb = null; + Cursor dbcursor = null; + try { + + dbcursor = db.rawQuery("Select * From AppDashboard_Incentive where CounterId =" + CounterId + " and UserId = '" + userId + "'", null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + sb = new AppDashboardTVA(); + sb.setTarget(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("MaximumIncentive"))); + double totalIncentive = dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("ToatlIncentive")); + sb.setkPI(dbcursor.getString(dbcursor.getColumnIndexOrThrow("KPI"))); + sb.setPer(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("Per"))); + sb.setTotalSale((int) totalIncentive); + sb.setGraph(""); + dbcursor.moveToNext(); + } + dbcursor.close(); + return sb; + } + } catch (Exception e) { + return sb; + } + return sb; + } + + + public AppDashboardIncentive getDashboardIncentiveDetail(String CounterId, String userId) { + AppDashboardIncentive sb = null; + Cursor dbcursor = null; + try { + + dbcursor = db.rawQuery("Select * From AppDashboard_Incentive where CounterId =" + CounterId + " and UserId = '" + userId + "'", null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + sb = new AppDashboardIncentive(); + sb.setMaximumIncentive(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("MaximumIncentive"))); + sb.setToatlIncentive(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("ToatlIncentive"))); + sb.setOfftake(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("Offtake"))); + sb.setLYAVGSale(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("LY_AVG_Sale"))); + sb.setMJFAVGSale(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("MJF_AVG_Sale"))); + sb.setSLIncentive(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("SL_Incentive"))); + sb.setFlatIncentive(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("Flat_Incentive"))); + sb.setTier(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Tier"))); + sb.setKpi(dbcursor.getString(dbcursor.getColumnIndexOrThrow("KPI"))); + sb.setPer(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("Per"))); + + dbcursor.moveToNext(); + } + dbcursor.close(); + return sb; + } + } catch (Exception e) { + return sb; + } + return sb; + } + + + public boolean insertDashOffTakeCounter(ResponseResult cst) { + db.delete("AppDashboard_L3MOffTake_Counter", null, null); + ContentValues values = new ContentValues(); + List data = cst.getL3MOffTakeCounter(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("KPI", data.get(i).getKpi()); + values.put("CounterId", data.get(i).getCounterId()); + values.put("Data", new Gson().toJson(data.get(i).getData())); + long id = db.insert("AppDashboard_L3MOffTake_Counter", null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + + public ArrayList getL3OffTakeCounter(String CounterId) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + + dbcursor = db.rawQuery("Select * From AppDashboard_L3MOffTake_Counter where CounterId =" + CounterId, null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + L3MOffTakeCounter sb = new L3MOffTakeCounter(); + OffTakeData offTakeData = new Gson().fromJson(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Data")), OffTakeData.class); + sb.setData(offTakeData); + sb.setKpi(dbcursor.getString(dbcursor.getColumnIndexOrThrow("KPI"))); + list.add(sb); + dbcursor.moveToNext(); + } + dbcursor.close(); + return list; + } + } catch (Exception e) { + return list; + } + return list; + } + + public boolean insertDashOffTakeNuance(ResponseResult cst) { + db.delete("AppDashboard_L3MOffTake_Nuance", null, null); + ContentValues values = new ContentValues(); + List data = cst.getL3MOffTakeNuance(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("KPI", data.get(i).getKpi()); + values.put("CounterId", data.get(i).getCounterId()); + values.put("NuanceId", data.get(i).getNuanceId()); + values.put("NuanceName", data.get(i).getNuanceName()); + values.put("Month_Year", data.get(i).getMonthYear()); + values.put("OffTake", data.get(i).getOffTake()); + long id = db.insert("AppDashboard_L3MOffTake_Nuance", null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + public boolean insertDashOffTakeSubAxe(ResponseResult cst) { + db.delete("AppDashboard_L3MOffTake_SubAxe", null, null); + ContentValues values = new ContentValues(); + List data = cst.getL3MOffTakeSubAxe(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("KPI", data.get(i).getKpi()); + values.put("CounterId", data.get(i).getCounterId()); + values.put("SubAxeId", data.get(i).getSubAxeId()); + values.put("SubAxeName", data.get(i).getSubAxeName()); + values.put("Month_Year", data.get(i).getMonthYear()); + values.put("OffTake", data.get(i).getOffTake()); + long id = db.insert("AppDashboard_L3MOffTake_SubAxe", null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + public boolean insertDailyTVA(ResponseResult cst) { + db.delete("ReportDaily_TVA", null, null); + ContentValues values = new ContentValues(); + List data = cst.getReportDailyTVA(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("KPI", data.get(i).getKpi()); + values.put("CounterId", data.get(i).getCounterId()); + values.put("VisitDate", data.get(i).getVisitDate()); + values.put("UserId", data.get(i).getUserId()); + values.put("Target", data.get(i).getTarget()); + values.put("TotalSale", data.get(i).getTotalSale()); + values.put("Per", data.get(i).getPer()); + long id = db.insert("ReportDaily_TVA", null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + public ArrayList getDailyTVAReport(String CounterId, String _UserId) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + + dbcursor = db.rawQuery("Select * From ReportDaily_TVA where CounterId =" + CounterId + " and UserId ='" + _UserId + "'", null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + DailyTVA sb = new DailyTVA(); + sb.setKpi(dbcursor.getString(dbcursor.getColumnIndexOrThrow("KPI"))); + sb.setVisitDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("VisitDate"))); + sb.setTotalSale(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("TotalSale"))); + sb.setTarget(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("Target"))); + sb.setPer(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("Per"))); + list.add(sb); + dbcursor.moveToNext(); + } + dbcursor.close(); + return list; + } + } catch (Exception e) { + return list; + } + return list; + } + + public DailyTVA getTotalDailyTVA(String CounterId, String _UserId) { + DailyTVA sb = null; + Cursor dbcursor = null; + try { + + dbcursor = db.rawQuery("SELECT DISTINCT sum(ifnull(TotalSale,0))as TotalSale,sum(ifnull(Target,0))as Target ,((sum(ifnull(TotalSale,0))/sum(ifnull(Target,0)))*100)as Per From ReportDaily_TVA where CounterId =" + CounterId + " and UserId ='" + _UserId + "'", null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + sb = new DailyTVA(); + sb.setTotalSale(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("TotalSale"))); + sb.setTarget(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("Target"))); + sb.setPer(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("Per"))); + dbcursor.moveToNext(); + } + dbcursor.close(); + return sb; + } + } catch (Exception e) { + return sb; + } + return sb; + } + + public boolean insertReportSalesGrowthCounter(ResponseResult cst) { + db.delete("Report_SalesGrowth_Counter", null, null); + ContentValues values = new ContentValues(); + List data = cst.getReportSalesGrowthCounter(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("KPI", data.get(i).getKpi()); + values.put("CounterId", data.get(i).getCounterId()); + values.put("Last_Year_SameMonthSale", data.get(i).getLastYearSameMonthSale()); + values.put("L3M_Avg_Sale", data.get(i).getL3MAvgSale()); + values.put("Current_Month_Sale", data.get(i).getCurrentMonthSale()); + values.put("Growth_over_Last_Year_Per", data.get(i).getGrowthOverLastYearPer()); + values.put("Growth_over_L3M_Per", data.get(i).getGrowthOverL3MPer()); + values.put("Closing_Stock_LastMonth", data.get(i).getClosingStockLastMonth()); + values.put("NOD", data.get(i).getNod()); + long id = db.insert("Report_SalesGrowth_Counter", null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + public boolean insertSalesGrowthCounterSubAxe(ResponseResult cst) { + db.delete("Report_SalesGrowth_CounterDetail", null, null); + ContentValues values = new ContentValues(); + List data = cst.getReportSalesGrowthSubAxe(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("KPI", data.get(i).getKpi()); + values.put("CounterId", data.get(i).getCounterId()); + values.put("CounterCode", data.get(i).getCounterCode()); + values.put("CounterName", data.get(i).getCounterName()); + values.put("ParamCode", data.get(i).getParamCode()); + values.put("ParamName", data.get(i).getParamName()); + values.put("Last_Year_SameMonthSale", data.get(i).getLastYearSameMonthSale()); + values.put("L3M_Avg_Sale", data.get(i).getL3MAvgSale()); + values.put("Current_Month_Sale", data.get(i).getCurrentMonthSale()); + values.put("Growth_over_Last_Year_Per", data.get(i).getGrowthOverLastYearPer()); + values.put("Growth_over_L3M_Per", data.get(i).getGrowthOverL3MPer()); + values.put("Closing_Stock_LastMonth", data.get(i).getClosingStockLastMonth()); + values.put("NOD", data.get(i).getNod()); + long id = db.insert("Report_SalesGrowth_CounterDetail", null, values); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + public ArrayList getSalesGrowthReport(String CounterId, boolean details) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + String table = "Report_SalesGrowth_Counter"; + if (details) table = "Report_SalesGrowth_CounterDetail"; + dbcursor = db.rawQuery("Select * From " + table + " where CounterId =" + CounterId, null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + SalesGrowthSubAxe sb = new SalesGrowthSubAxe(); + if (details) { + sb.setParamCode(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ParamCode"))); + sb.setParamName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ParamName"))); + } else { + sb.setParamCode(null); + sb.setParamName(null); + } + sb.setKpi(dbcursor.getString(dbcursor.getColumnIndexOrThrow("KPI"))); + sb.setLastYearSameMonthSale(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("Last_Year_SameMonthSale"))); + sb.setL3MAvgSale(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("L3M_Avg_Sale"))); + sb.setCurrentMonthSale(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("Current_Month_Sale"))); + sb.setGrowthOverLastYearPer(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("Growth_over_Last_Year_Per"))); + sb.setGrowthOverL3MPer(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("Growth_over_L3M_Per"))); + sb.setClosingStockLastMonth(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("Closing_Stock_LastMonth"))); + sb.setNod(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("NOD"))); + list.add(sb); + dbcursor.moveToNext(); + } + dbcursor.close(); + return list; + } + } catch (Exception e) { + return list; + } + return list; + } + + public boolean insertTesterCounter(TesterCounter cst) { + db.delete("Report_TesterCounter", null, null); + ContentValues values = new ContentValues(); + List data = cst.getReportTesterCounter(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("KPI", data.get(i).getKPI()); + values.put("CounterId", data.get(i).getCounterId()); + values.put("CounterName", data.get(i).getCounterName()); + values.put("OpeningStock", data.get(i).getOpeningStock()); + values.put("InvoicedQty", data.get(i).getInvoicedQty()); + values.put("ReceivedQty", data.get(i).getReceivedQty()); + values.put("TesterStockAvailable", data.get(i).getTesterStockAvailable()); + values.put("TesterUsed", data.get(i).getTesterUsed()); + values.put("TesterUsedPer", data.get(i).getTesterUsedPer()); + long id = db.insert("Report_TesterCounter", null, values); + //test("JeevanP", "" + id); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + + public boolean insertTesterCounterDetail(ResponseResult cst) { + db.delete("Report_TesterCounterDetail", null, null); + ContentValues values = new ContentValues(); + List data = cst.getReportTesterCounterDetail(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("KPI", data.get(i).getKpi()); + values.put("CounterId", data.get(i).getCounterId()); + + values.put("ParamId", data.get(i).getParamId()); + values.put("ParamCode", data.get(i).getParamCode()); + values.put("ParamName", data.get(i).getParamName()); + + values.put("CounterName", data.get(i).getCounterName()); + values.put("OpeningStock", data.get(i).getOpeningStock()); + values.put("InvoicedQty", data.get(i).getInvoicedQty()); + values.put("ReceivedQty", data.get(i).getReceivedQty()); + values.put("TesterStockAvailable", data.get(i).getTesterStockAvailable()); + values.put("TesterUsed", data.get(i).getTesterUsed()); + values.put("TesterUsedPer", data.get(i).getTesterUsedPer()); + long id = db.insert("Report_TesterCounterDetail", null, values); + //test("JeevanP", "" + id); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + public boolean insertCounterVolume(ResponseResult cst) { + db.delete("Report_CounterVolume", null, null); + ContentValues values = new ContentValues(); + List data = cst.getReportCounterVolume(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("KPI", data.get(i).getKpi()); + values.put("CounterId", data.get(i).getCounterId()); + values.put("CounterCode", data.get(i).getCounterCode()); + values.put("CounterName", data.get(i).getCounterName()); + values.put("MTDVolume", data.get(i).getMTDVolume()); + values.put("AvgPerDayVolume", data.get(i).getAvgPerDayVolume()); + long id = db.insert("Report_CounterVolume", null, values); + //test("JeevanP", "" + id); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + public ArrayList getTesterCounterUsageReport(String CounterId, boolean detail) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + String table = "Report_TesterCounter"; + if (detail) table = "Report_TesterCounterDetail"; + dbcursor = db.rawQuery("Select * From " + table + " where CounterId =" + CounterId, null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + ReportTesterCounterDetail sb = new ReportTesterCounterDetail(); + if (detail) { + sb.setParamId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("ParamId"))); + sb.setParamCode(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ParamCode"))); + sb.setParamName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ParamName"))); + } else { + sb.setParamId(null); + sb.setParamCode(null); + sb.setParamName(null); + } + + sb.setKpi(dbcursor.getString(dbcursor.getColumnIndexOrThrow("KPI"))); + sb.setInvoicedQty(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("InvoicedQty"))); + sb.setReceivedQty(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("ReceivedQty"))); + sb.setTesterUsed(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("TesterUsed"))); + sb.setOpeningStock(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("OpeningStock"))); + sb.setTesterStockAvailable(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("TesterStockAvailable"))); + sb.setTesterUsedPer(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("TesterUsedPer"))); + list.add(sb); + dbcursor.moveToNext(); + } + dbcursor.close(); + return list; + } + } catch (Exception e) { + return list; + } + return list; + } + + public boolean insertCounterVolumeDetail(ResponseResult cst) { + db.delete("Report_CounterVolumeDetail", null, null); + ContentValues values = new ContentValues(); + List data = cst.getReportCounterVolumeDetail(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("KPI", data.get(i).getKpi()); + values.put("CounterId", data.get(i).getCounterId()); + values.put("CounterCode", data.get(i).getCounterCode()); + values.put("CounterName", data.get(i).getCounterName()); + values.put("MTDVolume", data.get(i).getMTDVolume()); + values.put("AvgPerDayVolume", data.get(i).getAvgPerDayVolume()); + values.put("ParamId", data.get(i).getParamId()); + values.put("ParamCode", data.get(i).getParamCode()); + values.put("ParamName", data.get(i).getParamName()); + + + long id = db.insert("Report_CounterVolumeDetail", null, values); + //test("JeevanP", "" + id); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + public boolean insertCounterValue(ResponseResult cst) { + db.delete("Report_ConterValue", null, null); + ContentValues values = new ContentValues(); + List data = cst.getReportConterValue(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("KPI", data.get(i).getKpi()); + values.put("CounterId", data.get(i).getCounterId()); + values.put("CounterCode", data.get(i).getCounterCode()); + values.put("CounterName", data.get(i).getCounterName()); + values.put("MTDValue", data.get(i).getMTDValue()); + values.put("AvgPerDayValue", data.get(i).getAvgPerDayValue()); + long id = db.insert("Report_ConterValue", null, values); + //test("JeevanP", "" + id); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + public boolean insertCounterValueDetail(ResponseResult cst) { + db.delete("Report_ConterValueDetail", null, null); + ContentValues values = new ContentValues(); + List data = cst.getReportConterValueDetail(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("KPI", data.get(i).getKpi()); + values.put("CounterId", data.get(i).getCounterId()); + values.put("CounterCode", data.get(i).getCounterCode()); + values.put("CounterName", data.get(i).getCounterName()); + values.put("MTDValue", data.get(i).getMTDValue()); + values.put("AvgPerDayValue", data.get(i).getAvgPerDayValue()); + values.put("ParamId", data.get(i).getParamId()); + values.put("ParamCode", data.get(i).getParamCode()); + values.put("ParamName", data.get(i).getParamName()); + + + long id = db.insert("Report_ConterValueDetail", null, values); + //test("JeevanP", "" + id); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + public boolean insertCounterInwardStockDetail(ResponseResult cst) { + db.delete("Report_CounterInwardStockDetail", null, null); + ContentValues values = new ContentValues(); + List data = cst.getReportCounterInwardStockDetail(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("KPI", data.get(i).getKpi()); + values.put("CounterId", data.get(i).getCounterId()); + values.put("CounterCode", data.get(i).getCounterCode()); + values.put("CounterName", data.get(i).getCounterName()); + values.put("ParamId", data.get(i).getParamId()); + values.put("ParamCode", data.get(i).getParamCode()); + values.put("ParamName", data.get(i).getParamName()); + values.put("InvoiceQty", data.get(i).getInvoiceQty()); + values.put("ActualQty", data.get(i).getActualQty()); + values.put("DamageQty", data.get(i).getDamageQty()); + values.put("MissedQty", data.get(i).getMissedQty()); + + long id = db.insert("Report_CounterInwardStockDetail", null, values); + //test("JeevanP", "" + id); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + public boolean insertCounterStockLedgerDetail(ResponseResult cst) { + db.delete("Report_CounterStockLedgerDetail", null, null); + ContentValues values = new ContentValues(); + List data = cst.getReportCounterStockLedgerDetail(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("KPI", data.get(i).getKpi()); + values.put("CounterId", data.get(i).getCounterId()); + values.put("CounterCode", data.get(i).getCounterCode()); + values.put("CounterName", data.get(i).getCounterName()); + values.put("ParamId", data.get(i).getParamId()); + values.put("ParamCode", data.get(i).getParamCode()); + values.put("ParamName", data.get(i).getParamName()); + values.put("OpeningStock", data.get(i).getOpeningStock()); + values.put("StockIn", data.get(i).getStockIn()); + values.put("SaleOut", data.get(i).getSaleOut()); + values.put("SaleableBalance", data.get(i).getSaleableBalance()); + + long id = db.insert("Report_CounterStockLedgerDetail", null, values); + //test("JeevanP", "" + id); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + public ArrayList getCounterInwordStkDetails(String CounterId, boolean inward_detail) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + String table = "Report_CounterInwardStockDetail"; + if (!inward_detail) table = "Report_CounterStockLedgerDetail"; + dbcursor = db.rawQuery("Select * From " + table + " where CounterId =" + CounterId, null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + ReportCounterInwardStockDetail sb = new ReportCounterInwardStockDetail(); + sb.setParamId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("ParamId"))); + sb.setParamCode(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ParamCode"))); + sb.setParamName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ParamName"))); + sb.setKpi(dbcursor.getString(dbcursor.getColumnIndexOrThrow("KPI"))); + + sb.setInvoiceQty(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(inward_detail ? "InvoiceQty" : "OpeningStock"))); + sb.setActualQty(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(inward_detail ? "ActualQty" : "StockIn"))); + sb.setDamageQty(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(inward_detail ? "DamageQty" : "SaleOut"))); + sb.setMissedQty(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(inward_detail ? "MissedQty" : "SaleableBalance"))); + list.add(sb); + dbcursor.moveToNext(); + } + dbcursor.close(); + return list; + } + } catch (Exception e) { + return list; + } + return list; + } + + public ArrayList getCounterVolumeDetails(String CounterId, boolean value) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + String table = "Report_CounterVolumeDetail"; + if (value) table = "Report_ConterValueDetail"; + dbcursor = db.rawQuery("Select * From " + table + " where CounterId =" + CounterId, null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + ReportCounterVolumeDetail sb = new ReportCounterVolumeDetail(); + sb.setParamId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("ParamId"))); + sb.setParamCode(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ParamCode"))); + sb.setParamName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ParamName"))); + sb.setKpi(dbcursor.getString(dbcursor.getColumnIndexOrThrow("KPI"))); + + sb.setMTDVolume(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow(value ? "MTDValue" : "MTDVolume"))); + sb.setAvgPerDayVolume(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow(value ? "AvgPerDayValue" : "AvgPerDayVolume"))); + + list.add(sb); + dbcursor.moveToNext(); + } + dbcursor.close(); + return list; + } + } catch (Exception e) { + return list; + } + return list; + } + + public ReportCounterVolume getCounterVolume(String CounterId, boolean value) { + ReportCounterVolume sb = null; + Cursor dbcursor = null; + try { + String table = "Report_CounterVolume"; + if (value) table = "Report_ConterValue"; + dbcursor = db.rawQuery("Select * From " + table + " where CounterId =" + CounterId, null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + sb = new ReportCounterVolume(); + sb.setMTDVolume(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow(value ? "MTDValue" : "MTDVolume"))); + + sb.setAvgPerDayVolume(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow(value ? "AvgPerDayValue" : "AvgPerDayVolume"))); + dbcursor.moveToNext(); + } + dbcursor.close(); + return sb; + } + } catch (Exception e) { + return sb; + } + return sb; + } + + public boolean insertCounterInwardStock(ResponseResult cst) { + db.delete("Report_CounterInwardStock", null, null); + ContentValues values = new ContentValues(); + List data = cst.getReportCounterInwardStock(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("KPI", data.get(i).getKpi()); + values.put("CounterId", data.get(i).getCounterId()); + values.put("CounterCode", data.get(i).getCounterCode()); + values.put("CounterName", data.get(i).getCounterName()); + values.put("InvoiceQty", data.get(i).getInvoiceQty()); + values.put("ActualQty", data.get(i).getActualQty()); + values.put("DamageQty", data.get(i).getDamageQty()); + values.put("MissedQty", data.get(i).getMissedQty()); + long id = db.insert("Report_CounterInwardStock", null, values); + //test("JeevanP", "" + id); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + public ReportCounterInwardStock getCounterInwordStk(String CounterId, boolean inward_detail) { + ReportCounterInwardStock sb = null; + Cursor dbcursor = null; + try { + String table = "Report_CounterInwardStock"; + if (!inward_detail) table = "Report_CounterStockLedger"; + + dbcursor = db.rawQuery("Select * From " + table + " where CounterId =" + CounterId, null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + sb = new ReportCounterInwardStock(); + sb.setInvoiceQty(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(inward_detail ? "InvoiceQty" : "OpeningStock"))); + sb.setActualQty(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(inward_detail ? "ActualQty" : "StockIn"))); + sb.setDamageQty(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(inward_detail ? "DamageQty" : "SaleOut"))); + sb.setMissedQty(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(inward_detail ? "MissedQty" : "SaleableBalance"))); + dbcursor.moveToNext(); + } + dbcursor.close(); + return sb; + } + } catch (Exception e) { + return sb; + } + return sb; + } + + public boolean insertCounterStockledger(ResponseResult cst) { + db.delete("Report_CounterStockLedger", null, null); + ContentValues values = new ContentValues(); + List data = cst.getReportCounterStockLedger(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("KPI", data.get(i).getKpi()); + values.put("CounterId", data.get(i).getCounterId()); + values.put("CounterCode", data.get(i).getCounterCode()); + values.put("CounterName", data.get(i).getCounterName()); + values.put("OpeningStock", data.get(i).getOpeningStock()); + values.put("StockIn", data.get(i).getStockIn()); + values.put("SaleOut", data.get(i).getSaleOut()); + values.put("SaleableBalance", data.get(i).getSaleableBalance()); + long id = db.insert("Report_CounterStockLedger", null, values); + //test("JeevanP", "" + id); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + public boolean insertBaTbaSales(ResponseResult cst) { + db.delete("Report_BA_TBASale", null, null); + ContentValues values = new ContentValues(); + List data = cst.gettBATBASale(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("CounterId", data.get(i).getCounterId()); + values.put("CounterCode", data.get(i).getCounterCode()); + values.put("ProductId", data.get(i).getProductId()); + values.put("ProductCode", data.get(i).getProductCode()); + values.put("ProductName", data.get(i).getProductName()); + values.put("VisitDate", data.get(i).getVisitDate()); + values.put("SaleQty", data.get(i).getSaleQty()); + values.put("SaleValues", data.get(i).getSaleValues()); + long id = db.insert("Report_BA_TBASale", null, values); + //test("JeevanP", "" + id); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + public boolean insertBaTbaPromoSales(ResponseResult cst) { + db.delete("Report_BA_TBAPromoSale", null, null); + ContentValues values = new ContentValues(); + List data = cst.gettBATBAPromoSale(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("CounterId", data.get(i).getCounterId()); + values.put("CounterCode", data.get(i).getCounterCode()); + values.put("ProductId", data.get(i).getProductId()); + values.put("ProductCode", data.get(i).getProductCode()); + values.put("ProductName", data.get(i).getProductName()); + values.put("VisitDate", data.get(i).getVisitDate()); + values.put("SaleQty", data.get(i).getSaleQty()); + values.put("SaleValues", data.get(i).getSaleValues()); + values.put("PromoType", data.get(i).getpromoType()); + long id = db.insert("Report_BA_TBAPromoSale", null, values); + //test("JeevanP", "" + id); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + public boolean insertLeaveDetails(ResponseResult cst) { + db.delete("T_LeaveRequestDetail", null, null); + ContentValues values = new ContentValues(); + List data = cst.getTLeaveRequestDetail(); + try { + if (data.isEmpty()) { + return false; + } + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("Id", data.get(i).getId()); + values.put("UserId", data.get(i).getUserId()); + values.put("Year", data.get(i).getYear()); + values.put("Month", data.get(i).getMonth()); + values.put("Day", data.get(i).getDay()); + values.put("LeaveType", data.get(i).getLeaveType()); + values.put("LeaveSubType", data.get(i).getLeaveSubType()); + values.put("Reason", data.get(i).getReason()); + values.put("ApprovedStatus", data.get(i).getApprovedStatus()); + long id = db.insert("T_LeaveRequestDetail", null, values); + //test("JeevanP", "" + id); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + public TLeaveRequestDetail getLeaveDetails(String _userId, String status, int year, int month, int day) { + TLeaveRequestDetail sb = null; + Cursor dbcursor = null; + try { + + dbcursor = db.rawQuery("Select * From T_LeaveRequestDetail where UserId ='" + _userId + "' And ApprovedStatus ='" + status + "'And Year=" + year + " And Month=" + month + " And Day=" + day, null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + sb = new TLeaveRequestDetail(); + sb.setLeaveType(dbcursor.getString(dbcursor.getColumnIndexOrThrow("LeaveType"))); + sb.setLeaveSubType(dbcursor.getString(dbcursor.getColumnIndexOrThrow("LeaveSubType"))); + sb.setApprovedStatus(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ApprovedStatus"))); + sb.setReason(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Reason"))); + dbcursor.moveToNext(); + } + dbcursor.close(); + return sb; + } + } catch (Exception e) { + return sb; + } + return sb; + } + + public ArrayList getHolidaysOrLeaves(String _userId, String type) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + String query = "Select * From T_LeaveRequestDetail where UserId ='" + _userId + "' Order by Id and ApprovedStatus"; + if (type.equals("GovtHolidays")) { + query = "Select * from Master_HolidayList"; + } + dbcursor = db.rawQuery(query, null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + TLeaveRequestDetail sb = new TLeaveRequestDetail(); + if (type.equals("GovtHolidays")) { + sb.setLeaveType(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Date"))); + sb.setReason(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Occasion"))); + } else { + sb.setYear(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("Year"))); + sb.setMonth(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("Month"))); + sb.setDay(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("Day"))); + sb.setLeaveType(dbcursor.getString(dbcursor.getColumnIndexOrThrow("LeaveType"))); + sb.setLeaveSubType(dbcursor.getString(dbcursor.getColumnIndexOrThrow("LeaveSubType"))); + sb.setApprovedStatus(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ApprovedStatus"))); + sb.setReason(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Reason"))); + } + list.add(sb); + + dbcursor.moveToNext(); + } + dbcursor.close(); + return list; + } + } catch (Exception e) { + return list; + } + return list; + } + + public List getLeaveDetails(String _userId, String status) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + + dbcursor = db.rawQuery("Select * From T_LeaveRequestDetail where UserId ='" + _userId + "' And ApprovedStatus ='" + status + "'", null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + int year = dbcursor.getInt(dbcursor.getColumnIndexOrThrow("Year")); + int month = dbcursor.getInt(dbcursor.getColumnIndexOrThrow("Month")); + int day = dbcursor.getInt(dbcursor.getColumnIndexOrThrow("Day")); + list.add(CalendarDay.from(year, month, day)); + dbcursor.moveToNext(); + } + dbcursor.close(); + return list; + } + } catch (Exception e) { + return list; + } + + return list; + } + + public boolean insertHolidays(ResponseResult cst) { + db.delete("Master_HolidayList", null, null); + ContentValues values = new ContentValues(); + List data = cst.getMasterHolidayList(); + try { + if (data.isEmpty()) { + return false; + } + + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("Id", data.get(i).getId()); + values.put("Date", data.get(i).getDate()); + values.put("Occasion", data.get(i).getOccasion()); + long id = db.insert("Master_HolidayList", null, values); + //test("JeevanP", "" + id); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + public boolean insertLeaveLedger(ResponseResult cst) { + db.delete("T_LeaveLedgerSummary", null, null); + ContentValues values = new ContentValues(); + List data = cst.getTLeaveLedgerSummary(); + try { + if (data.isEmpty()) { + return false; + } + + db.beginTransaction(); + for (int i = 0; i < data.size(); i++) { + values.put("UserId", data.get(i).getEmpId()); + values.put("LeaveType", data.get(i).getLeaveType()); + values.put("Earned", data.get(i).getEarned()); + values.put("TakenThisMonth", data.get(i).getTakenThisMonth()); + values.put("TotalLeavesTaken", data.get(i).getTotalLeavesTaken()); + values.put("Balance", data.get(i).getBalance()); + long id = db.insert("T_LeaveLedgerSummary", null, values); + //test("JeevanP", "" + id); + if (id == -1) { + throw new Exception(); + } + } + closeDb(); + return true; + } catch (Exception ex) { + closeDb(); + ////////test("Database Exception ", ex.toString()); + return false; + } + } + + public TLeaveLedgerSummary getLeaveLedger(String _userId, boolean personal) { + TLeaveLedgerSummary sb = null; + Cursor dbcursor = null; + try { + + String query = "LeaveType != 'Personal Leave'"; + if (personal) { + query = "LeaveType = 'Personal Leave'"; + } + + dbcursor = db.rawQuery("Select * from T_LeaveLedgerSummary Where UserId='" + _userId + + "' and " + query, null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + sb = new TLeaveLedgerSummary(); + sb.setLeaveType(dbcursor.getString(dbcursor.getColumnIndexOrThrow("LeaveType"))); + sb.setEarned(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("Earned"))); + sb.setTakenThisMonth(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("TakenThisMonth"))); + sb.setTotalLeavesTaken(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("TotalLeavesTaken"))); + sb.setBalance(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("Balance"))); + dbcursor.moveToNext(); + } + dbcursor.close(); + return sb; + } + } catch (Exception e) { + return sb; + } + return sb; + } + + public TLeaveLedgerSummary getLeaveLedgerTotal(String _userId) { + TLeaveLedgerSummary sb = null; + Cursor dbcursor = null; + try { + + dbcursor = db.rawQuery("Select distinct sum(Earned)as Earned,sum(TakenThisMonth)as TakenThisMonth,sum(TotalLeavesTaken)as TotalLeavesTaken,sum(Balance)as Balance from T_LeaveLedgerSummary Where UserId='" + _userId + "'", null); + + if (dbcursor != null) { + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + sb = new TLeaveLedgerSummary(); + sb.setEarned(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("Earned"))); + sb.setTakenThisMonth(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("TakenThisMonth"))); + sb.setTotalLeavesTaken(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("TotalLeavesTaken"))); + sb.setBalance(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("Balance"))); + dbcursor.moveToNext(); + } + + dbcursor.close(); + return sb; + } + } catch (Exception e) { + return sb; + } + return sb; + } + + public void updateStatus(String id, String counterId, String bID, String status, double latitude, double longitude) { + ContentValues values = new ContentValues(); + try { + values.put("GeoTag", status); + values.put("Latitude", latitude); + values.put("Longitude", longitude); + db.update("Mapping_JourneyPlan", values, "StoreId" + " = " + id + " And BID = " + bID + " And CounterId = " + counterId, null); + } catch (Exception ignored) { + } + } + + + public long InsertSTOREgeotag(String storeid, String counterId, String bId, String userId, double lat, double longitude, String path) { + db.delete(CommonString.TABLE_STORE_GEOTAGGING, "STORE_ID = " + storeid + " And " + + CommonString.KEY_COUNTER_ID + "=" + counterId + " And BiD = " + bId, null); + + ContentValues values = new ContentValues(); + try { + values.put("STORE_ID", storeid); + values.put(CommonString.KEY_COUNTER_ID, counterId); + values.put(CommonString.KEY_USERNAME, userId); + values.put("BiD", bId); + values.put("LATITUDE", Double.toString(lat)); + values.put("LONGITUDE", Double.toString(longitude)); + values.put("GEO_IMG", path); + values.put("GEOTAG", CommonString.KEY_N); + return db.insert(CommonString.TABLE_STORE_GEOTAGGING, null, values); + + } catch (Exception ex) { + return 0; + } + } + + public long updateInsertedGeoTagStatus(String storeId, String counterId, String useriD, String status) { + ContentValues values = new ContentValues(); + try { + values.put("GEOTAG", status); + return db.update(CommonString.TABLE_STORE_GEOTAGGING, values, "STORE_ID = " + storeId + " And " + + CommonString.KEY_COUNTER_ID + "= " + counterId + " and " + CommonString.KEY_USERNAME + "='" + useriD + "'", null); + } catch (Exception ex) { + return 0; + } + } + + public ArrayList getinsertGeotaggingData(String storeid, String counterId, String userId, String status) { + ArrayList list = new ArrayList<>(); + Cursor dbcursor = null; + try { + if (status != null) { + dbcursor = db.rawQuery("Select * from " + CommonString.TABLE_STORE_GEOTAGGING + + " where " + CommonString.KEY_COUNTER_ID + " ='" + counterId + "' and GEOTAG = '" + status + "' And STORE_ID = " + storeid + + " And " + CommonString.KEY_USERNAME + "='" + userId + "'", null); + } else { + dbcursor = db.rawQuery("Select * from " + CommonString.TABLE_STORE_GEOTAGGING + + " where " + CommonString.KEY_COUNTER_ID + " ='" + counterId + "' And STORE_ID = " + storeid + + " And " + CommonString.KEY_USERNAME + "='" + userId + "'", null); + } + dbcursor.moveToFirst(); + while (!dbcursor.isAfterLast()) { + GeotaggingBeans geoTag = new GeotaggingBeans(); + geoTag.setBid(dbcursor.getString(dbcursor.getColumnIndexOrThrow("BiD"))); + geoTag.setStoreid(dbcursor.getString(dbcursor.getColumnIndexOrThrow("STORE_ID"))); + geoTag.setCounterId(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_COUNTER_ID))); + geoTag.setLatitude(Double.parseDouble(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_LATITUDE)))); + geoTag.setLongitude(Double.parseDouble(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_LONGITUDE)))); + geoTag.setImage(dbcursor.getString(dbcursor.getColumnIndexOrThrow("GEO_IMG"))); + list.add(geoTag); + dbcursor.moveToNext(); + } + + dbcursor.close(); + return list; + + } catch (Exception e) { + return list; + } + + } + @SuppressLint("LongLogTag") + public boolean insertMappingAppRestrictedKPI(MasterBAProfileGetterSetter data) { + db.delete("Mapping_AppRestrictedKPI", null, null); + List mappingAppRestrictedKPIList = data.getMappingAppRestrictedKPI(); + ContentValues values = new ContentValues(); + try { + db.beginTransaction(); + if (mappingAppRestrictedKPIList.isEmpty()) { + return false; + } + for (MappingAppRestrictedKPI mappingAppRestrictedKPI : mappingAppRestrictedKPIList) { + values.put("KPIName", mappingAppRestrictedKPI.getKPIName()); + values.put("FieldValueType", mappingAppRestrictedKPI.getFieldValueType()); + values.put("FieldValue", mappingAppRestrictedKPI.getFieldValue()); + values.put("KPIFieldEnable", mappingAppRestrictedKPI.getKPIFieldEnable()); + if (!db.isOpen()) { + open(); + } + long id = db.insert("Mapping_AppRestrictedKPI", null, values); + if (id == -1) { + throw new Exception(); + } + } + // do ALL your inserts here + db.setTransactionSuccessful(); + db.endTransaction(); + return true; + } catch (Exception ex) { + ex.fillInStackTrace(); + // do ALL your inserts here + db.setTransactionSuccessful(); + db.endTransaction(); + Log.d("Exception in Mapping_AppRestrictedKPI", ex.toString()); + return false; + } + } + + public boolean getHideManualInwordCount() { + int count = 0; + boolean status = false; + Cursor outerCursor = null; + Cursor countCursor = null; + try { + outerCursor = db.rawQuery("SELECT DISTINCT FieldValueType, FieldValue, KPIFieldEnable FROM Mapping_AppRestrictedKPI", null); + if (outerCursor != null && outerCursor.moveToFirst()) { + do { + String fieldValueType = outerCursor.getString(outerCursor.getColumnIndexOrThrow("FieldValueType")); + String fieldValue = outerCursor.getString(outerCursor.getColumnIndexOrThrow("FieldValue")); + String kpiFieldEnable = outerCursor.getString(outerCursor.getColumnIndexOrThrow("KPIFieldEnable")); + // Construct query dynamically, make sure field names and values are safe + String query = "SELECT COUNT(*) FROM Mapping_JourneyPlan WHERE " + fieldValueType + " IN (?)"; + + countCursor = db.rawQuery(query, new String[]{fieldValue}); + + if (countCursor != null && countCursor.moveToFirst()) { + count += countCursor.getInt(0); // Accumulate count + if (count>0) { + status = kpiFieldEnable!=null && !kpiFieldEnable.isEmpty() && kpiFieldEnable.equals("1")?true:false; + } + countCursor.close(); + } + + } while (outerCursor.moveToNext()); + + outerCursor.close(); + } + } catch (Exception e) { + e.fillInStackTrace(); + } finally { + if (outerCursor != null && !outerCursor.isClosed()) outerCursor.close(); + if (countCursor != null && !countCursor.isClosed()) countCursor.close(); + } + + return status; + } +} + diff --git a/app/src/main/java/com/cpm/lorealbaautomation/DealarBoardActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/DealarBoardActivity.java new file mode 100644 index 0000000..533d8ac --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/DealarBoardActivity.java @@ -0,0 +1,2053 @@ +package com.cpm.lorealbaautomation; + +import android.Manifest; + +import android.annotation.SuppressLint; +import android.app.Activity; +import android.app.AlertDialog; +import android.app.DatePickerDialog; +import android.app.Dialog; +import android.app.ProgressDialog; +import android.content.ActivityNotFoundException; +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.IntentFilter; +import android.content.IntentSender; +import android.content.SharedPreferences; +import android.content.pm.PackageInfo; +import android.content.pm.PackageManager; +import android.graphics.Bitmap; + +import android.graphics.Color; +import android.graphics.drawable.BitmapDrawable; +import android.graphics.drawable.ColorDrawable; +import android.graphics.drawable.Drawable; +import android.location.Location; +import android.location.LocationManager; +import android.net.ConnectivityManager; +import android.net.NetworkInfo; +import android.net.Uri; +import android.os.Bundle; + +import androidx.annotation.NonNull; + +import com.google.android.gms.common.api.ResolvableApiException; +import com.google.android.gms.location.FusedLocationProviderClient; +import com.google.android.gms.location.SettingsClient; +import com.google.android.material.floatingactionbutton.FloatingActionButton; +import com.google.android.material.navigation.NavigationView; + +import androidx.core.app.ActivityCompat; +import androidx.core.content.ContextCompat; +import androidx.core.widget.NestedScrollView; +import androidx.localbroadcastmanager.content.LocalBroadcastManager; +import androidx.core.view.GravityCompat; +import androidx.drawerlayout.widget.DrawerLayout; +import androidx.appcompat.app.ActionBarDrawerToggle; +import androidx.appcompat.app.AppCompatActivity; +import androidx.appcompat.widget.Toolbar; +import androidx.recyclerview.widget.LinearLayoutManager; + +import android.text.InputFilter; +import android.util.Log; +import android.view.Gravity; +import android.view.LayoutInflater; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; +import android.view.Window; +import android.view.WindowManager; +import android.view.inputmethod.EditorInfo; +import android.widget.LinearLayout; +import android.widget.RelativeLayout; +import android.widget.TextView; +import android.widget.Toast; + +import com.google.android.gms.location.LocationRequest; +import com.google.android.gms.location.LocationServices; +import com.google.android.gms.location.LocationSettingsRequest; +import com.google.gson.Gson; +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.adapter.LeaveDetailAdapter; +import com.cpm.lorealbaautomation.constant.AlertandMessages; +import com.cpm.lorealbaautomation.constant.CommonFunctions; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.dailyactivity.BAProfileActivity; +import com.cpm.lorealbaautomation.dailyactivity.CounterImageActivity; +import com.cpm.lorealbaautomation.dailyactivity.CounterProfileActivity; +import com.cpm.lorealbaautomation.dailyactivity.GroomedActivity; +import com.cpm.lorealbaautomation.dailyactivity.NotificationsActivity; +import com.cpm.lorealbaautomation.dailyactivity.RetailExcellenceActivity; +import com.cpm.lorealbaautomation.dailyactivity.ServiceActivity; +import com.cpm.lorealbaautomation.databinding.DialogApplyLeaveBinding; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.download.DownloadActivity; +import com.cpm.lorealbaautomation.download.Downloader; +import com.cpm.lorealbaautomation.gettersetter.LoginGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.GroomingGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterProfile; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterProfileQuestionGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterPromoOffer; +import com.cpm.lorealbaautomation.gsonGetterSetter.ResponseResult; +import com.cpm.lorealbaautomation.leavemanagement.LeaveManagemntActivity; +import com.cpm.lorealbaautomation.password.ChangePasswordActivity; +import com.cpm.lorealbaautomation.pinviewactivity.PinViewActivity; +import com.cpm.lorealbaautomation.promooffer.PromoOffersActivity; +import com.cpm.lorealbaautomation.reports.MeSaleReport; +import com.cpm.lorealbaautomation.reports.PerformanceHistoryActivity; +import com.cpm.lorealbaautomation.reports.ReportsActivity; +import com.cpm.lorealbaautomation.retrofit.PostApi; +import com.cpm.lorealbaautomation.tbaleavemodel.Common; +import com.cpm.lorealbaautomation.tbaleavemodel.TBAMESearch; +import com.cpm.lorealbaautomation.upload.CommonUpload; +import com.cpm.lorealbaautomation.upload.UploadKeyData; +import com.cpm.lorealbaautomation.utils.DrawableClickListener; + +import org.json.JSONObject; + +import java.io.File; +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.TimeUnit; + +import de.hdodenhof.circleimageview.CircleImageView; +import okhttp3.MediaType; +import okhttp3.OkHttpClient; +import okhttp3.RequestBody; +import retrofit2.Call; +import retrofit2.Callback; +import retrofit2.Response; +import retrofit2.Retrofit; +import retrofit2.converter.gson.GsonConverterFactory; + +import static com.cpm.lorealbaautomation.constant.CommonFunctions.checkincomplete_upload_data; +import static com.cpm.lorealbaautomation.constant.CommonFunctions.getCroppedBitmap; +import static com.cpm.lorealbaautomation.constant.CommonFunctions.getCurrentTime_only; +import static com.cpm.lorealbaautomation.constant.CommonFunctions.getResizedBitmap; +import static com.cpm.lorealbaautomation.dailyactivity.StoreImageActivity.convertBitmap; + +public class DealarBoardActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, View.OnClickListener { + private SharedPreferences preferences = null; + int downloadindex = 0; + Lorealba_Database db; + View headerView; + Context context; + private String counterId = "", visitDate = ""; + NavigationView navigationView; + String user_name, user_type, loginTym = "", serverTym = "", DASHBOARD_REFRESH_TIME = ""; + ArrayList allLoginListData = new ArrayList<>(); + public static final String PROGRESS_UPDATE = "progress_update"; + ProgressDialog loading; + TextView txt_dashboard, txt_more; + private double lat = 0.0; + private double lon = 0.0; + private static final int REQUEST_LOCATION = 1; + private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 1000; + Location mLastLocation; + LocationRequest mLocationRequest; + SharedPreferences.Editor editor = null; + LinearLayout rl_pending_data; + TextView textCartItemCount; + int mCartItemCount = 0; + CircleImageView circleView; + TextView version_code; + private FusedLocationProviderClient fusedLocationClient; + + public BaMenuRefreshListener getBaMenuRefreshListener() { + return baMenuRefreshListener; + } + + public void setBaMenuRefreshListener(BaMenuRefreshListener baMenuRefreshListener) { + this.baMenuRefreshListener = baMenuRefreshListener; + } + + private BaMenuRefreshListener baMenuRefreshListener; + + public CounterMenuRefreshListener getCounterMenuRefreshListener() { + return counterMenuRefreshListener; + } + + public void setCounterMenuRefreshListener(CounterMenuRefreshListener counterMenuRefreshListener) { + this.counterMenuRefreshListener = counterMenuRefreshListener; + } + + private CounterMenuRefreshListener counterMenuRefreshListener; + + public DealarBoardActivity.OfferMenuRefreshListener getOfferMenuRefreshListener() { + return OfferMenuRefreshListener; + } + + public void setOfferMenuRefreshListener(DealarBoardActivity.OfferMenuRefreshListener offerMenuRefreshListener) { + OfferMenuRefreshListener = offerMenuRefreshListener; + } + + private OfferMenuRefreshListener OfferMenuRefreshListener; + + public DashboardRefreshListener getDashboardRefreshListener() { + return dashboardRefreshListener; + } + + public void setDashboardRefreshListener(DashboardRefreshListener dashboardRefreshListener) { + this.dashboardRefreshListener = dashboardRefreshListener; + } + + private DashboardRefreshListener dashboardRefreshListener; + LinearLayout rl_ba, rl_me, rl_ba2, no_data_lay; + NestedScrollView dealerb_scroll_view; + FloatingActionButton fab_download; + + int mYear, mMonth, mDay; + DatePickerDialog dpd; + Calendar c; + private TBAMESearch tbameSearch = null; + private CustomDialogLeaveApply customDialogLeave = null; + String blockCharacterSet = "[';:-+{('}@=#$%^&*?)\"]"; + InputFilter filter = (source, start, end, dest, dstart, dend) -> { + if (source != null && blockCharacterSet.contains(("" + source))) { + return ""; + } + return null; + }; + + @SuppressLint("SetTextI18n") + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_dealar_board); + context = this; + fusedLocationClient = LocationServices.getFusedLocationProviderClient(this); + CommonFunctions.hideKeyboard(this); + Toolbar toolbar = findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + if (!CommonFunctions.isTablet(context)) { + toolbar.setTitleTextAppearance(context, R.style.changestext_sizefor_mobile); + } + preferences = PrefHelper.getPrefs(context); + editor = preferences.edit(); + downloadindex = preferences.getInt(CommonString.KEY_DOWNLOAD_INDEX, 0); + DASHBOARD_REFRESH_TIME = preferences.getString(CommonString.KEY_DASHBOARD_REFRESH_TIME, ""); + DrawerLayout drawer = findViewById(R.id.drawer_layout); + version_code = (TextView) findViewById(R.id.version_code); + rl_pending_data = (LinearLayout) findViewById(R.id.rl_pending_data); + txt_dashboard = (TextView) findViewById(R.id.txt_dashboard); + txt_more = (TextView) findViewById(R.id.txt_more); + no_data_lay = (LinearLayout) findViewById(R.id.no_data_lay); + dealerb_scroll_view = (NestedScrollView) findViewById(R.id.dealerb_scroll_view); + fab_download = (FloatingActionButton) findViewById(R.id.fab_download); + rl_ba = (LinearLayout) findViewById(R.id.rl_ba); + rl_ba2 = (LinearLayout) findViewById(R.id.rl_ba2); + rl_me = (LinearLayout) findViewById(R.id.rl_me); + navigationView = findViewById(R.id.nav_view); + try { + if (!CommonFunctions.isTablet(context)) { + navigationView.setItemIconSize(58); + } + } catch (Exception ignored) { + } + ActionBarDrawerToggle toggle = new ActionBarDrawerToggle((Activity) context, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); + drawer.addDrawerListener(toggle); + toggle.syncState(); + navigationView.setNavigationItemSelectedListener(this); + headerView = LayoutInflater.from(this).inflate(R.layout.nav_header_dealar_board, navigationView, false); + checkAndRequestPermissions(); + createLocationRequest(); + getLastLocation(); + //find location + + counterId = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + visitDate = preferences.getString(CommonString.KEY_DATE, ""); + user_name = preferences.getString(CommonString.KEY_USERNAME, ""); + user_type = preferences.getString(CommonString.KEY_USER_TYPE, ""); + // //test("usertype",user_type); + + TextView tv_username = (TextView) headerView.findViewById(R.id.nav_user_name); + TextView tv_usertype = (TextView) headerView.findViewById(R.id.nav_user_type); + circleView = (CircleImageView) headerView.findViewById(R.id.circleView); + tv_username.setText(user_name); + navigationView.addHeaderView(headerView); + + db = new Lorealba_Database(context); + db.open(); + ArrayList allLoginData = db.getlistAllData(visitDate, user_name); + if (!allLoginData.isEmpty() && allLoginData.get(0).getUserType() != null) { + tv_usertype.setText(allLoginData.get(0).getUserType()); + } + + setTitle(user_name); + registerReceiver(); +// checkRunTimePermission(); + serverTym = db.getserverTym(visitDate).getServerTime(); + ////update device time from server time............. + if (CommonFunctions.checkNetIsAvailable(context)) { + CommonFunctions.GetServerTym(context, user_name, db); + } + + download_data(); + fab_download.setOnClickListener(view -> { + // Handle the camera action + if (CommonFunctions.checkNetIsAvailable(context)) { + startActivity(new Intent(context, DownloadActivity.class).putExtra(CommonString.TAG_FROM, 0)); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + } else { + AlertandMessages.showToastMsg(context, getString(R.string.nonetwork)); + } + }); + + txt_dashboard.setText(getString(R.string.dashboard) + " Last Updated at - " + DASHBOARD_REFRESH_TIME + " - " + visitDate); + txt_more.setOnClickListener(this); + + String couter_code = preferences.getString(CommonString.KEY_COUNTER_CODE, ""); + TextView txt_counter_code = (TextView) findViewById(R.id.txt_counter_code); + txt_counter_code.setText("Counter Code - " + couter_code + " / Id - " + counterId); + } + + + private void registerReceiver() { + LocalBroadcastManager bManager = LocalBroadcastManager.getInstance(this); + IntentFilter intentFilter = new IntentFilter(); + intentFilter.addAction(PROGRESS_UPDATE); + bManager.registerReceiver(mBroadcastReceiver, intentFilter); + } + + private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() { + @Override + public void onReceive(Context context, Intent intent) { + if (Objects.equals(intent.getAction(), PROGRESS_UPDATE)) { + db.open(); + mCartItemCount = db.getNotificationList(user_name).size(); + setupBadge(mCartItemCount); + } + } + }; + + @Override + public void onBackPressed() { + DrawerLayout drawer = findViewById(R.id.drawer_layout); + if (drawer.isDrawerOpen(GravityCompat.START)) { + drawer.closeDrawer(GravityCompat.START); + } + // finish(); + } + + @Override + public void onClick(View view) { + if (view.getId() == R.id.txt_more) { + final ArrayList[] masterPromoOffers = new ArrayList[]{new ArrayList<>()}; + final ArrayList[] finalPromoOffers = new ArrayList[]{new ArrayList<>()}; + masterPromoOffers[0] = db.getmaterPromoOffers(); + if (!masterPromoOffers[0].isEmpty()) { + finalPromoOffers[0] = new ArrayList<>(); + for (int k = 0; k < masterPromoOffers[0].size(); k++) { + if (CommonFunctions.isTablet(context)) { + String path = CommonString.getPromosFolder(context) + masterPromoOffers[0].get(k).getPromoOfferTab(); + File dir = new File(path); + if (dir.exists()) { + finalPromoOffers[0].add(masterPromoOffers[0].get(k)); + } + } else { + String path = CommonString.getPromosFolder(context) + masterPromoOffers[0].get(k).getPromoOfferMobile(); + File dir = new File(path); + if (dir.exists()) { + finalPromoOffers[0].add(masterPromoOffers[0].get(k)); + } + } + } + } + + if (!finalPromoOffers[0].isEmpty()) { + startActivity(new Intent(context, PromoOffersActivity.class)); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + } else { + AlertandMessages.showToastMsg(context, "Promotion Banner Not Available"); + } + } + } + + + public interface BaMenuRefreshListener { + void onRefresh(String value); + } + + public interface CounterMenuRefreshListener { + void onRefresh(String value); + } + + public interface DashboardRefreshListener { + void onRefresh(String value); + } + + public interface OfferMenuRefreshListener { + void onRefresh(); + } + + @Override + public boolean onPrepareOptionsMenu(Menu menu) { + MenuItem menuItem = menu.findItem(R.id.user_info); + Menu subMenu = menuItem.getSubMenu(); + assert subMenu != null; + subMenu.clear(); + MenuItem profilemenuItem = menu.findItem(R.id.user_logout); + Menu profilesubMenu = profilemenuItem.getSubMenu(); + assert profilesubMenu != null; + profilesubMenu.clear(); + MenuItem break_menuitem = menu.findItem(R.id.take_break_nav); + db.open(); + break_menuitem.setVisible(db.isBreakManagmentEndTymChecked(visitDate, user_name, counterId)); + if (!allLoginListData.isEmpty()) { + for (int i = 0; i < allLoginListData.size(); i++) { + if (!allLoginListData.get(i).getUserId().equals(user_name) && allLoginListData.get(i).getUser_checkout().equals("0")) { + Bitmap bitmp = null; + Drawable drawable = null; + db.open(); + MasterProfile baProfileGetterSetter = db.getBaProfileData(allLoginListData.get(i).getUserId(), visitDate, false); + if (baProfileGetterSetter != null && baProfileGetterSetter.getProfilePic() != null) { + if (new File(CommonString.getProfileFolder(context) + baProfileGetterSetter.getProfilePic()).exists()) { + bitmp = convertBitmap(CommonString.getProfileFolder(context) + baProfileGetterSetter.getProfilePic()); + if (bitmp != null) { + if (CommonFunctions.isTablet(context)) { + bitmp = getResizedBitmap(bitmp, 70); + } else { + bitmp = getResizedBitmap(bitmp, 240); + } + bitmp = getCroppedBitmap(bitmp); + + if (bitmp != null) { + drawable = new BitmapDrawable(getResources(), bitmp); + } + } + } + } else if (allLoginListData != null && allLoginListData.get(i).getProfile_Pic() != null && !allLoginListData.get(i).getProfile_Pic().equals("")) { + if (new File(CommonString.getProfileFolder(context) + allLoginListData.get(i).getProfile_Pic()).exists()) { + bitmp = convertBitmap(CommonString.getProfileFolder(context) + allLoginListData.get(i).getProfile_Pic()); + if (bitmp != null) { + if (CommonFunctions.isTablet(context)) { + bitmp = getResizedBitmap(bitmp, 70); + } else { + bitmp = getResizedBitmap(bitmp, 240); + } + bitmp = getCroppedBitmap(bitmp); + if (bitmp != null) { + drawable = new BitmapDrawable(getResources(), bitmp); + } + } + } + } + if (drawable == null) { + assert allLoginListData != null; + subMenu.add(0, i, 0, allLoginListData.get(i).getUserId()).setShortcut('3', 'c').setIcon(R.mipmap.user_for_menu); + } else { + subMenu.add(0, i, 0, allLoginListData.get(i).getUserId()).setShortcut('3', 'c').setIcon(drawable); + } + } + } + } + + subMenu.add(0, 112, 0, "New User").setShortcut('4', 's').setIcon(R.mipmap.user_for_menu); + + Bitmap bitmpprofile = null; + Drawable drawableprofile = null; + db.open(); + MasterProfile baProfileGetterSetter = db.getBaProfileData(user_name, visitDate, false); + if (baProfileGetterSetter != null && baProfileGetterSetter.getProfilePic() != null) { + if (new File(CommonString.getProfileFolder(context) + baProfileGetterSetter.getProfilePic()).exists()) { + bitmpprofile = convertBitmap(CommonString.getProfileFolder(context) + baProfileGetterSetter.getProfilePic()); + if (bitmpprofile != null) { + if (CommonFunctions.isTablet(context)) { + bitmpprofile = getResizedBitmap(bitmpprofile, 70); + } else { + bitmpprofile = getResizedBitmap(bitmpprofile, 240); + } + + bitmpprofile = getCroppedBitmap(bitmpprofile); + if (bitmpprofile != null) { + drawableprofile = new BitmapDrawable(getResources(), bitmpprofile); + } + } + } + + } else if (!db.getlistLoginData(visitDate, user_name, counterId).isEmpty() && !db.getlistLoginData(visitDate, user_name, counterId).get(0).getProfile_Pic().isEmpty()) { + if (new File(CommonString.getProfileFolder(context) + db.getlistLoginData(visitDate, user_name, counterId).get(0).getProfile_Pic()).exists()) { + bitmpprofile = convertBitmap(CommonString.getProfileFolder(context) + db.getlistLoginData(visitDate, user_name, counterId).get(0).getProfile_Pic()); + if (bitmpprofile != null) { + if (CommonFunctions.isTablet(context)) { + bitmpprofile = getResizedBitmap(bitmpprofile, 70); + } else { + bitmpprofile = getResizedBitmap(bitmpprofile, 240); + } + bitmpprofile = getCroppedBitmap(bitmpprofile); + if (bitmpprofile != null) { + drawableprofile = new BitmapDrawable(getResources(), bitmpprofile); + } + } + } + } + + if (drawableprofile == null) { + profilesubMenu.add(0, 10, 0, R.string.Profile).setShortcut('3', 'c').setIcon(R.mipmap.profile); + } else { + profilesubMenu.add(0, 10, 0, R.string.Profile).setShortcut('3', 'c').setIcon(drawableprofile); + } + + profilesubMenu.add(0, 11, 0, "Logout").setShortcut('3', 'c').setIcon(R.mipmap.logout_item); + + MenuItem profile = menu.findItem(10); + profile.setEnabled(!db.isBreakManagmentEndTymChecked(visitDate, user_name, counterId)); + return super.onPrepareOptionsMenu(menu); + } + + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + getMenuInflater().inflate(R.menu.dealar_board, menu); + final MenuItem menuItem = menu.findItem(R.id.notification_img_nav); + View actionView = (View) menuItem.getActionView(); + assert actionView != null; + textCartItemCount = (TextView) actionView.findViewById(R.id.cart_badge); + db.open(); + mCartItemCount = db.getNotificationList(user_name).size(); + setupBadge(mCartItemCount); + actionView.setOnClickListener(v -> onOptionsItemSelected(menuItem)); + return super.onCreateOptionsMenu(menu); + } + + private void setupBadge(int mCartItemCount) { + if (textCartItemCount != null) { + if (this.mCartItemCount == 0) { + if (textCartItemCount.getVisibility() != View.GONE) { + textCartItemCount.setVisibility(View.GONE); + } + } else { + textCartItemCount.setText(String.valueOf(mCartItemCount)); + if (textCartItemCount.getVisibility() != View.VISIBLE) { + textCartItemCount.setVisibility(View.VISIBLE); + } + } + } + } + + @SuppressLint("NonConstantResourceId") + @Override + public boolean onOptionsItemSelected(MenuItem item) { + int id = item.getItemId(); + + if (id == 112) {//for New User Login + Intent in = new Intent(context, UserLoginActivity.class); + in.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); + in.putExtra("Previous_Login", "Previous_Login"); + startActivity(in); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + DealarBoardActivity.this.finish(); + } else if (id == 10) {//for Profile + db.open(); + if (!db.getlistAllData(visitDate, user_name).isEmpty()) { + if (!db.getBAProfileListAllData(user_name, visitDate).isEmpty()) { + Intent profile = new Intent(context, BAProfileActivity.class); + startActivity(profile); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + } else { + AlertandMessages.showToastMsg(context, " Profile Data Not Found"); + } + } + + } else if (id == 11) {//for logout + ////upload data if not upload + if (checkNetIsAvailable()) { + AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle(R.string.parinaam).setMessage(R.string.alertlogout); + builder.setPositiveButton(android.R.string.yes, (dialogInterface, i) -> { + if (!db.getmasterTransaction(visitDate, counterId, false).isEmpty()) { + CommonFunctions.call_upload(context); + } else { + if (checkincomplete_upload_data(visitDate, counterId, db, false)) { + CommonUpload.Checkout_service(loading, context, lat, lon, user_name, counterId, visitDate, db, true); + } else { + CommonUpload downloadData = new CommonUpload(context, db, loading, counterId, visitDate, user_name, lat, lon); + downloadData.CommonUploadwithrecursive(context, db, false); + } + } + }).setNegativeButton(android.R.string.cancel, (dialogInterface, i) -> dialogInterface.cancel()); + builder.show(); + } else { + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE); + } + + } else if (id == R.id.notification_img_nav) { + if (!db.getNotificationList().isEmpty()) { + startActivity(new Intent(context, NotificationsActivity.class)); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + } else { + AlertandMessages.showToastMsg(context, getResources().getString(R.string.notification_error_msg)); + } + + } else { + + String userId = Objects.requireNonNull(item.getTitle()).toString(); + String mpin = preferences.getString(userId, null); + if (mpin != null) { + Intent in1 = new Intent(context, PinViewActivity.class); + in1.putExtra(CommonString.IS_PASSWORD_CHECK, true); + in1.putExtra(CommonString.KEY_USERNAME, userId.toLowerCase()); + startActivity(in1); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + finish(); + } else if (userId != null && !userId.isEmpty()) { + startActivity(new Intent(context, UserLoginActivity.class)); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + DealarBoardActivity.this.finish(); + } + + } + + return super.onOptionsItemSelected(item); + } + + + private void hideItem() { + Menu nav_Menu = navigationView.getMenu(); + if (user_type != null && user_type.equalsIgnoreCase(CommonString.TAG_FROM_ME)) { + nav_Menu.findItem(R.id.nav_reset_password).setVisible(true); + nav_Menu.findItem(R.id.nav_report).setVisible(true); + nav_Menu.findItem(R.id.nav_me_report).setVisible(false); + nav_Menu.findItem(R.id.nav_per_history).setVisible(false); + nav_Menu.findItem(R.id.nav_per_history).setVisible(false); + } else { + nav_Menu.findItem(R.id.nav_reset_password).setVisible(true); + nav_Menu.findItem(R.id.nav_report).setVisible(true); + nav_Menu.findItem(R.id.nav_me_report).setVisible(false); + nav_Menu.findItem(R.id.nav_per_history).setVisible(false); + } + + /////new change for leave apply + if (user_type != null && user_type.equalsIgnoreCase(CommonString.TAG_FROM_BA)) { + nav_Menu.findItem(R.id.nav_apply_leave).setVisible(false); + nav_Menu.findItem(R.id.nav_leave_detail).setVisible(false); + nav_Menu.findItem(R.id.nav_leave_ledger).setVisible(false); + } else { + nav_Menu.findItem(R.id.nav_apply_leave).setVisible(true); + nav_Menu.findItem(R.id.nav_leave_detail).setVisible(true); + nav_Menu.findItem(R.id.nav_leave_ledger).setVisible(true); + } + } + + @SuppressWarnings("StatementWithEmptyBody") + @Override + public boolean onNavigationItemSelected(MenuItem item) { + // Handle navigation view item clicks here. + int id = item.getItemId(); + if (id == R.id.sync_data_nav) { + // Handle the camera action + startActivity(new Intent(context, DownloadActivity.class).putExtra(CommonString.TAG_FROM, 0)); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + } else if (id == R.id.nav_ba_profile) { + Intent profile = new Intent(context, BAProfileActivity.class); + startActivity(profile); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + + } else if (id == R.id.nav_counter_menu) { + Intent profile = new Intent(context, CounterProfileActivity.class); + startActivity(profile); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + } else if (id == R.id.nav_services) { + startActivity(new Intent(context, ServiceActivity.class)); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + } else if (id == R.id.nav_reset_password) { + startActivity(new Intent(context, ChangePasswordActivity.class)); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + } else if (id == R.id.nav_logout) { + if (checkNetIsAvailable()) { + AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle(R.string.parinaam).setMessage(R.string.alertlogout); + builder.setPositiveButton(android.R.string.yes, (dialogInterface, i) -> { + if (!db.getmasterTransaction(visitDate, counterId, false).isEmpty()) { + CommonFunctions.call_upload(context); + } else { + if (checkincomplete_upload_data(visitDate, counterId, db, false)) { + CommonUpload.Checkout_service(loading, context, lat, lon, user_name, counterId, visitDate, db, true); + } else { + CommonUpload downloadData = new CommonUpload(context, db, loading, counterId, visitDate, user_name, lat, lon); + downloadData.CommonUploadwithrecursive(context, db, false); + } + } + }).setNegativeButton(android.R.string.cancel, (dialogInterface, i) -> dialogInterface.cancel()); + builder.show(); + } else { + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE); + } + + /*Intent intent = new Intent(context, UserLoginActivity.class); + intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); + startActivity(intent);*/ + } else if (id == R.id.nav_report) { + startActivity(new Intent(context, ReportsActivity.class).putExtra("from", user_type)); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + } else if (id == R.id.nav_d2d_ars) { + String url = preferences.getString(CommonString.KEY_D2D_ARS_URL, ""); + if (!url.isEmpty()) { + openurlinchrome(url); + } else { + Toast.makeText(context, "Url not available", Toast.LENGTH_SHORT).show(); + } + } else if (id == R.id.nav_per_history) { + startActivity(new Intent(context, PerformanceHistoryActivity.class)); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + } else if (id == R.id.nav_me_report) { + startActivity(new Intent(context, MeSaleReport.class)); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + } else if (id == R.id.nav_manual_upload) { + startActivity(new Intent(context, UploadKeyData.class)); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + } else if (id == R.id.nav_apply_leave) { + customDialogLeave = new CustomDialogLeaveApply((AppCompatActivity) context, true); + customDialogLeave.show(); + } else if (id == R.id.nav_leave_detail) { + customDialogLeave = new CustomDialogLeaveApply((AppCompatActivity) context, false); + customDialogLeave.show(); + } else if (id == R.id.nav_leave_ledger) { + startActivity(new Intent(context, LeaveManagemntActivity.class).putExtra(CommonString.TAG_FROM, "TBA/ME")); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + } + DrawerLayout drawer = findViewById(R.id.drawer_layout); + drawer.closeDrawer(GravityCompat.START); + + return true; + } + + private void openurlinchrome(String url) { + try { + Uri uri = Uri.parse("googlechrome://navigate?url=" + url); + Intent i = new Intent(Intent.ACTION_VIEW, uri); + i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + startActivity(i); + } catch (ActivityNotFoundException e) { + Uri uri = Uri.parse(url); + Intent i = new Intent(Intent.ACTION_VIEW, uri); + i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + startActivity(i); + } + } + + @SuppressLint("SetTextI18n") + @Override + protected void onResume() { + super.onResume(); + context = this; + editor = preferences.edit(); + visitDate = preferences.getString(CommonString.KEY_DATE, ""); + user_type = preferences.getString(CommonString.KEY_USER_TYPE, ""); + downloadindex = preferences.getInt(CommonString.KEY_DOWNLOAD_INDEX, 0); + db.open(); + if (!db.isProductMasterFilled(visitDate)) { + no_data_lay.setVisibility(View.VISIBLE); + fab_download.show(); + dealerb_scroll_view.setVisibility(View.GONE); + } else { + no_data_lay.setVisibility(View.GONE); + fab_download.hide(); + dealerb_scroll_view.setVisibility(View.VISIBLE); + } + + checkAndRequestPermissions(); + createLocationRequest(); + getLastLocation(); + //find location + + checkgpsEnableDevice(); + /////set picture current user + Bitmap bitmpprofile = null; + db.open(); + MasterProfile baProfileGetterSetter = db.getBaProfileData(user_name, visitDate, false); + if (baProfileGetterSetter != null && baProfileGetterSetter.getProfilePic() != null) { + if (new File(CommonString.getProfileFolder(context) + baProfileGetterSetter.getProfilePic()).exists()) { + bitmpprofile = convertBitmap(CommonString.getProfileFolder(context) + baProfileGetterSetter.getProfilePic()); + } + db.open(); + } else if (!db.getlistLoginData(visitDate, user_name, counterId).isEmpty() && !db.getlistLoginData(visitDate, user_name, counterId).get(0).getProfile_Pic().isEmpty()) { + db.open(); + if (new File(CommonString.getProfileFolder(context) + db.getlistLoginData(visitDate, user_name, counterId).get(0).getProfile_Pic()).exists()) { + db.open(); + bitmpprofile = convertBitmap(CommonString.getProfileFolder(context) + db.getlistLoginData(visitDate, user_name, counterId).get(0).getProfile_Pic()); + } + } + + if (bitmpprofile != null) { + circleView.setImageBitmap(bitmpprofile); + } else { + circleView.setImageResource(R.mipmap.user_100); + } + if (user_type.equalsIgnoreCase(CommonString.TAG_FROM_ME)) { + calculateme_counter(); + } else { + callall_method(); + } + db.open(); + allLoginListData = db.getlistLoginData(visitDate, null, counterId); + + if (user_type != null && user_type.equalsIgnoreCase(CommonString.TAG_FROM_ME)) { + rl_me.setVisibility(View.VISIBLE); + rl_ba.setVisibility(View.GONE); + rl_ba2.setVisibility(View.GONE); + } else { + rl_me.setVisibility(View.GONE); + rl_ba2.setVisibility(View.VISIBLE); + rl_ba.setVisibility(View.VISIBLE); + } + + hideItem(); + //UploadKeyData image service + File f = new File(CommonString.getImagesFolder(context)); + if (!getFileNames(Objects.requireNonNull(f.listFiles())).isEmpty()) { + ArrayList finalList = new ArrayList<>(); + for (int k = 0; k < getFileNames(Objects.requireNonNull(f.listFiles())).size(); k++) { + if (!db.ischeck_uploaded_image(visitDate, getFileNames(Objects.requireNonNull(f.listFiles())).get(k))) { + finalList.add(getFileNames(Objects.requireNonNull(f.listFiles())).get(k)); + } + } + + if (!finalList.isEmpty()) { + Intent intentu = new Intent(context, Downloader.class); + intentu.putExtra(CommonString.KEY_UPLOADIMAGE, "1"); + Downloader.enqueueWork(context, intentu); + } + } + + try { + PackageInfo pInfo = context.getPackageManager().getPackageInfo(getPackageName(), 0); + String version = pInfo.versionName; + version_code.setText("Version : " + version); + } catch (PackageManager.NameNotFoundException e) { + e.fillInStackTrace(); + version_code.setText("Version : 0.0"); + } + + alert_for_date(context, visitDate); + updateuserInterface(); + invalidateOptionsMenu(); + ///Dashboard Ui Report Updated + //checkNDownloadSalesReport(); + DASHBOARD_REFRESH_TIME = preferences.getString(CommonString.KEY_DASHBOARD_REFRESH_TIME, ""); + txt_dashboard.setText(getString(R.string.dashboard) + " Last Updated at - " + DASHBOARD_REFRESH_TIME + " - " + visitDate); + checkpending_datafor_upload(); + } + + public void alert_for_date(final Context context, final String visit_date) { + @SuppressLint("SimpleDateFormat") DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy"); + Date date_device = new Date(); + if (!dateFormat.format(date_device).equalsIgnoreCase(visit_date)) { + AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle("Alert Dialog").setMessage("Your Device date does not match login Date. You will be logged out now").setPositiveButton(android.R.string.ok, (dialog, which) -> { + startActivity(new Intent(context, IMEILoginActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)); + DealarBoardActivity.this.finish(); + dialog.dismiss(); + }); + builder.show(); + } + } + + + @SuppressLint("VisibleForTests") + protected void createLocationRequest() { + LocationRequest mLocationRequest = new LocationRequest(); + // Location updates intervals in sec + // 5 sec + int UPDATE_INTERVAL = 5000; + mLocationRequest.setInterval(UPDATE_INTERVAL); + // 1 sec + int FATEST_INTERVAL = 1000; + mLocationRequest.setFastestInterval(FATEST_INTERVAL); + mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); + // 10 meters + int DISPLACEMENT = 5; + mLocationRequest.setSmallestDisplacement(DISPLACEMENT); + } + + private void checkgpsEnableDevice() { + if (!hasGPSDevice(context)) { + Toast.makeText(context, "Gps not Supported", Toast.LENGTH_SHORT).show(); + } + + final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); + if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER) && hasGPSDevice(context)) { + enableLocationSettings(); + } else { + if (manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { + hasGPSDevice(context); + } + } + } + + private void enableLocationSettings() { + @SuppressLint("VisibleForTests") LocationRequest locationRequest = LocationRequest.create() + .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY) // new Priority constant + .setInterval(30 * 1000) + .setFastestInterval(5 * 1000); + LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder() + .addLocationRequest(locationRequest) + .setAlwaysShow(true); // show dialog if GPS is off + + SettingsClient settingsClient = LocationServices.getSettingsClient(this); + + settingsClient.checkLocationSettings(builder.build()) + .addOnSuccessListener(locationSettingsResponse -> { + // All location settings are satisfied. You can request location updates here. + }).addOnFailureListener(e -> { + if (e instanceof ResolvableApiException) { + try { + ResolvableApiException resolvable = (ResolvableApiException) e; + resolvable.startResolutionForResult((Activity) context, REQUEST_LOCATION); + } catch (IntentSender.SendIntentException sendEx) { + // Ignore the error. + sendEx.fillInStackTrace(); + } + } + }); + } + + private boolean hasGPSDevice(Context context) { + final LocationManager mgr = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); + if (mgr == null) + return false; + final List providers = mgr.getAllProviders(); + if (providers == null) + return false; + return providers.contains(LocationManager.GPS_PROVIDER); + } + + + private boolean checkNetIsAvailable() { + ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); + NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); + return activeNetwork != null && activeNetwork.isConnectedOrConnecting(); + } + + private void updateuserInterface() { + /////Only for Dashboard data................ + if (getDashboardRefreshListener() != null) { + getDashboardRefreshListener().onRefresh(""); + } + + /////Only for offers data................ + if (getOfferMenuRefreshListener() != null) { + getOfferMenuRefreshListener().onRefresh(); + } + + /////for counter images disable icon............. + db.open(); + if (!db.getinserted_counter_images(counterId, visitDate).getCounter_img_two_for_ba().isEmpty() || !db.getinserted_counter_images(counterId, visitDate).getCounter_img_onefor_ba().isEmpty()) { + if (getBaMenuRefreshListener() != null) { + getBaMenuRefreshListener().onRefresh("0"); + } + if (getCounterMenuRefreshListener() != null) { + getCounterMenuRefreshListener().onRefresh("0"); + } + } else { + if (getBaMenuRefreshListener() != null) { + getBaMenuRefreshListener().onRefresh("1"); + } + if (getCounterMenuRefreshListener() != null) { + getCounterMenuRefreshListener().onRefresh("1"); + } + } + /////Only for break managment + db.open(); + if (db.isBreakManagmentEndTymChecked(visitDate, user_name, counterId)) { + if (getBaMenuRefreshListener() != null) { + getBaMenuRefreshListener().onRefresh("2"); + } + if (getCounterMenuRefreshListener() != null) { + getCounterMenuRefreshListener().onRefresh("2"); + } + } + } + + private void uploadGroomedData() { + db.open(); + loginTym = db.get_baLoginTym(visitDate, user_name).getUserLoginTym(); + loginTym = CommonFunctions.setTimeFormat(loginTym); + if (loginTym != null && !loginTym.isEmpty()) { + if (calculateTotalDuration(loginTym) > 8) { + GroomingGetterSetter groomedList = db.getGroomedList(counterId, user_name, visitDate); + if (groomedList != null && !groomedList.getMorning_groom_img_str().isEmpty() || groomedList != null && !groomedList.getNoon_groom_img_str().isEmpty() || groomedList != null && !groomedList.getEvenning_groom_img_str().isEmpty()) { + //download service + Intent intent = new Intent(context, Downloader.class); + intent.putExtra(CommonString.KEY_Groomed_Image, groomedList); + Downloader.enqueueWork(context, intent); + } + } + } + } + + + private void calculateloginTym() { + try { + boolean flag = true; + if (db.isCounterChecked(visitDate, counterId)) { + loginTym = db.get_baLoginTym(visitDate, user_name).getUserLoginTym(); + loginTym = CommonFunctions.setTimeFormat(loginTym); + SimpleDateFormat simpleDateFormat = null; + ////for morning tym after Added 45 minutes + String morngTym = addtime_str(loginTym, 45, 0); + String morngEndTym = addtime_str(loginTym, 0, 3); + simpleDateFormat = new SimpleDateFormat("hh:mm:ss a", Locale.ENGLISH); + Date date1 = simpleDateFormat.parse(morngTym); + Date date2 = simpleDateFormat.parse(getTime()); + Date date3 = simpleDateFormat.parse(morngEndTym); + assert date2 != null; + if (date2.after(date1) && date2.before(date3)) { + db.open(); + if (!db.isGroomedCheckedfornotification(visitDate, counterId, user_name, "Mornning_groomed_img")) { + flag = false; + showCommentforGrooming(context); + } else if (!user_type.equalsIgnoreCase(CommonString.TAG_FROM_ME) && !db.getRetailExcellenceData().isEmpty()) { + if (!db.isRetailExcellenceFilled(visitDate, counterId, user_name)) { + flag = false; + showCommentforRetailExcellence(context); + } + } + } + + ////for nooo tym after adding 03:10 + String noonTym = addtime_str(loginTym, 10, 03); + String endNoonTym = addtime_str(loginTym, 59, 05); + simpleDateFormat = new SimpleDateFormat("hh:mm:ss a", Locale.ENGLISH); + date1 = simpleDateFormat.parse(noonTym); + date2 = simpleDateFormat.parse(getTime()); + date3 = simpleDateFormat.parse(endNoonTym); + if (flag) { + db.open(); + assert date2 != null; + if (date2.after(date1) && date2.before(date3)) { + if (!db.isGroomedCheckedfornotification(visitDate, counterId, user_name, "Noon_groomed_img")) { + flag = false; + showCommentforGrooming(context); + } else if (!user_type.equalsIgnoreCase(CommonString.TAG_FROM_ME) && !db.getRetailExcellenceData().isEmpty()) { + if (!db.isRetailExcellenceFilled(visitDate, counterId, user_name)) { + flag = false; + showCommentforRetailExcellence(context); + } + } + } + } + + ////for evenning tym after adding 03:10 + String evngTym = addtime_str(loginTym, 10, 6); + String EndevngTym = addtime_str(loginTym, 59, 8); + simpleDateFormat = new SimpleDateFormat("hh:mm:ss a", Locale.ENGLISH); + date1 = simpleDateFormat.parse(evngTym); + date2 = simpleDateFormat.parse(getTime()); + date3 = simpleDateFormat.parse(EndevngTym); + if (flag) { + assert date2 != null; + db.open(); + if (date2.after(date1) && date2.before(date3)) { + if (!db.isGroomedCheckedfornotification(visitDate, counterId, user_name, "Evening_groomed_img")) { + showCommentforGrooming(context); + } else if (!user_type.equalsIgnoreCase(CommonString.TAG_FROM_ME) && !db.getRetailExcellenceData().isEmpty()) { + if (!db.isRetailExcellenceFilled(visitDate, counterId, user_name)) { + showCommentforRetailExcellence(context); + } + } + } + } + } else { + db.open(); + if (db.isProductMasterFilled(visitDate)) { + showCommentforCounter(context); + } + } + } catch (ParseException e) { + e.fillInStackTrace(); + } + } + + + private String addtime_str(String str, int minuts, int hours) { + SimpleDateFormat displayFormat = null; + SimpleDateFormat parseFormat = null; + Calendar calendar = null; + Date date = null; + + try { + if (str != null && !str.isEmpty()) { + parseFormat = new SimpleDateFormat("hh:mm:ss a", Locale.ENGLISH); + displayFormat = new SimpleDateFormat("hh:mm:ss a", Locale.ENGLISH); + date = parseFormat.parse(str); + calendar = Calendar.getInstance(); + assert date != null; + calendar.setTime(date); + calendar.add(Calendar.HOUR, hours); + calendar.add(Calendar.MINUTE, minuts); + //test(displayFormat.format(calendar.getTime())); + } + } catch (ParseException e) { + e.fillInStackTrace(); + } + + assert displayFormat != null; + assert calendar != null; + return displayFormat.format(calendar.getTime()); + } + + + private String getTime() { + Calendar currnetDateTime = Calendar.getInstance(); + SimpleDateFormat df = new SimpleDateFormat("hh:mm:ss a", Locale.ENGLISH); + return df.format(currnetDateTime.getTime()); + } + + + public void showCommentforGrooming(final Context context) { + getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); + final Dialog dialog_for = new Dialog(context); + Objects.requireNonNull(dialog_for.getWindow()).setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT)); + dialog_for.setContentView(R.layout.comment_layout); + + Window window = dialog_for.getWindow(); + WindowManager.LayoutParams wlp = window.getAttributes(); + wlp.gravity = Gravity.CENTER; + window.setAttributes(wlp); + RelativeLayout rl_dialog = dialog_for.findViewById(R.id.rl_dialog); + rl_dialog.setOnClickListener(view -> { + startActivity(new Intent(context, GroomedActivity.class)); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + dialog_for.dismiss(); + }); + + dialog_for.show(); + + } + + public void showCommentforRetailExcellence(final Context context) { + getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); + final Dialog dialog_for = new Dialog(context); + Objects.requireNonNull(dialog_for.getWindow()).setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT)); + dialog_for.setContentView(R.layout.comment_retail_excellence); + + Window window = dialog_for.getWindow(); + WindowManager.LayoutParams wlp = window.getAttributes(); + wlp.gravity = Gravity.CENTER; + window.setAttributes(wlp); + RelativeLayout rl_dialog = dialog_for.findViewById(R.id.rl_dialog); + rl_dialog.setOnClickListener(view -> { + startActivity(new Intent(context, RetailExcellenceActivity.class)); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + dialog_for.dismiss(); + }); + + dialog_for.show(); + + } + + + public void showCommentforCounter(final Context context) { + getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); + final Dialog dialogcounter = new Dialog(context); + Objects.requireNonNull(dialogcounter.getWindow()).setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT)); + dialogcounter.setContentView(R.layout.commentfor_counter_layout); + + Window window = dialogcounter.getWindow(); + WindowManager.LayoutParams wlp = window.getAttributes(); + wlp.gravity = Gravity.CENTER; + window.setAttributes(wlp); + dialogcounter.setCanceledOnTouchOutside(false); + RelativeLayout rl_dialog = dialogcounter.findViewById(R.id.rl_dialog); + rl_dialog.setOnClickListener(view -> { + startActivity(new Intent(context, CounterImageActivity.class)); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + dialogcounter.dismiss(); + }); + dialogcounter.show(); + + } + + + private int calculateTotalDuration(String loginTym) { + SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh:mm:ss a", Locale.ENGLISH); + int days = 0, hours = 0, min = 0; + try { + Date date1 = simpleDateFormat.parse(loginTym); + Date date2 = simpleDateFormat.parse(getTime()); + assert date2 != null; + assert date1 != null; + long difference = date2.getTime() - date1.getTime(); + days = (int) (difference / (1000 * 60 * 60 * 24)); + hours = (int) ((difference - (1000 * 60 * 60 * 24 * days)) / (1000 * 60 * 60)); + min = (int) (difference - (1000 * 60 * 60 * 24 * days) - (1000 * 60 * 60 * hours)) / (1000 * 60); + hours = (hours < 0 ? -hours : hours); + Log.i("======= Hours", " :: " + hours); + } catch (ParseException e) { + e.fillInStackTrace(); + } + + return hours; + } + + private int calculateTotalDurationinminutes(String currentTime) { + SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh:mm:ss", Locale.ENGLISH); + int days = 0, hours = 0, min = 0; + try { + Date date1 = simpleDateFormat.parse(currentTime); + Date date2 = simpleDateFormat.parse(getCurrentTime_only()); + assert date2 != null; + assert date1 != null; + long difference = date2.getTime() - date1.getTime(); + days = (int) (difference / (1000 * 60 * 60 * 24)); + hours = (int) ((difference - (1000 * 60 * 60 * 24 * days)) / (1000 * 60 * 60)); + min = (int) (difference - (1000 * 60 * 60 * 24 * days) - (1000 * 60 * 60 * hours)) / (1000 * 60); + hours = (hours < 0 ? -hours : hours); + Log.i("======= Hours", " :: " + hours); + } catch (ParseException e) { + e.fillInStackTrace(); + } + + return min; + } + + + //--------------Download all data........................--------- + private void download_data() { + int incorrect_tStockSummery = preferences.getInt(CommonString.KEY_INCORRECT_TSTOCK_SUMMERY + visitDate, 0); + db.open(); + if (!db.isProductMasterFilled(visitDate)) { + startActivity(new Intent(context, DownloadActivity.class).putExtra(CommonString.TAG_FROM, 0)); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + } else if (incorrect_tStockSummery == 2) { + startActivity(new Intent(context, DownloadActivity.class).putExtra(CommonString.TAG_FROM, 0)); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + } + } + + private void callall_method() { + try { + db.open(); + if (db.isProductMasterFilled(visitDate)) { + uploadGroomedData(); + loginTym = db.get_baLoginTym(visitDate, user_name).getUserLoginTym(); + loginTym = CommonFunctions.setTimeFormat(loginTym); + calculateloginTym(); + } + } catch (Exception e) { + e.fillInStackTrace(); + } + } + + private void calculateme_counter() { + db.open(); + if (!db.isCounterCheckedforme(visitDate, counterId)) { + db.open(); + if (db.isProductMasterFilled(visitDate)) { + db.open(); + showCommentforCounter(context); + } + } + } + + private void checkAndRequestPermissions() { + int CAMERA = ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA); + int ACCESS_NETWORK_STATE = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_NETWORK_STATE); + int ACCESS_COARSE_LOCATION = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION); + int locationPermission = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION); + int READ_PHONE_STATE = ContextCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE); + List listPermissionsNeeded = new ArrayList<>(); + + if (CAMERA != PackageManager.PERMISSION_GRANTED) { + listPermissionsNeeded.add(Manifest.permission.CAMERA); + } + + if (ACCESS_NETWORK_STATE != PackageManager.PERMISSION_GRANTED) { + listPermissionsNeeded.add(Manifest.permission.ACCESS_NETWORK_STATE); + } + if (ACCESS_COARSE_LOCATION != PackageManager.PERMISSION_GRANTED) { + listPermissionsNeeded.add(Manifest.permission.ACCESS_COARSE_LOCATION); + } + if (locationPermission != PackageManager.PERMISSION_GRANTED) { + listPermissionsNeeded.add(Manifest.permission.ACCESS_FINE_LOCATION); + } + + if (READ_PHONE_STATE != PackageManager.PERMISSION_GRANTED) { + listPermissionsNeeded.add(Manifest.permission.READ_PHONE_STATE); + } + + + if (!listPermissionsNeeded.isEmpty()) { + ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), CommonString.PERMISSION_ALL); + } + } + + private void showDialogOK(String message, DialogInterface.OnClickListener okListener) { + new AlertDialog.Builder(this).setMessage(message).setPositiveButton("OK", okListener).setNegativeButton("Cancel", okListener).create().show(); + } + + @Override + public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { + super.onRequestPermissionsResult(requestCode, permissions, grantResults); + //test("", "Permission callback called-------"); + if (requestCode == CommonString.PERMISSION_ALL) { + Map perms = new HashMap<>(); + // Initialize the map with both permissions + perms.put(Manifest.permission.CAMERA, PackageManager.PERMISSION_GRANTED); + perms.put(Manifest.permission.ACCESS_NETWORK_STATE, PackageManager.PERMISSION_GRANTED); + perms.put(Manifest.permission.ACCESS_COARSE_LOCATION, PackageManager.PERMISSION_GRANTED); + perms.put(Manifest.permission.ACCESS_FINE_LOCATION, PackageManager.PERMISSION_GRANTED); + perms.put(Manifest.permission.READ_PHONE_STATE, PackageManager.PERMISSION_GRANTED); + // Fill with actual results from user + if (grantResults.length > 0) { + for (int i = 0; i < permissions.length; i++) + perms.put(permissions[i], grantResults[i]); + // Check for both permissions + boolean allPermissionsGranted = + Integer.valueOf(PackageManager.PERMISSION_GRANTED).equals(perms.get(Manifest.permission.CAMERA)) && + Integer.valueOf(PackageManager.PERMISSION_GRANTED).equals(perms.get(Manifest.permission.ACCESS_NETWORK_STATE)) && + Integer.valueOf(PackageManager.PERMISSION_GRANTED).equals(perms.get(Manifest.permission.ACCESS_COARSE_LOCATION)) && + Integer.valueOf(PackageManager.PERMISSION_GRANTED).equals(perms.get(Manifest.permission.ACCESS_FINE_LOCATION)) && + Integer.valueOf(PackageManager.PERMISSION_GRANTED).equals(perms.get(Manifest.permission.READ_PHONE_STATE)); + + if (allPermissionsGranted) { + getLastLocation(); + + createLocationRequest(); + } + } else { + //test("", "Some permissions are not granted ask again "); + //permission is denied (this is the first time, when "never ask again" is not checked) so ask again explaining the usage of permission +// // shouldShowRequestPermissionRationale will return true + //show the dialog or snackbar saying its necessary and try again otherwise proceed with setup. + if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA) || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_NETWORK_STATE) || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_COARSE_LOCATION) || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION) || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_PHONE_STATE)) { + showDialogOK("Location,File,Call and Camera Services Permission required for this app", (dialog, which) -> { + switch (which) { + case DialogInterface.BUTTON_POSITIVE: + checkAndRequestPermissions(); + break; + case DialogInterface.BUTTON_NEGATIVE: + // proceed with logic by disabling the related features or quit the app. + Intent startMain = new Intent(Intent.ACTION_MAIN); + startMain.addCategory(Intent.CATEGORY_HOME); + startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + startActivity(startMain); + break; + } + }); + } else { + Toast.makeText(this, "Go to settings and enable permissions", Toast.LENGTH_LONG).show(); + } + } + } + } + + private void getLastLocation() { + if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && + ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { + // Request location permissions + return; + } + try { + fusedLocationClient.getLastLocation() + .addOnSuccessListener(this, location -> { + if (location != null) { + lat = location.getLatitude(); + lon = location.getLongitude(); + //test("Location", "Lat: " + lat + ", Lng: " + lon); + } + }); + } catch (Exception e) { + e.fillInStackTrace(); //test("Location", "Lat: " + lat + ", Lng: " + lon);} + } + + } + + public ArrayList getFileNames(File[] file) { + ArrayList arrayFiles = new ArrayList(); + for (File value : file) arrayFiles.add(value.getName()); + return arrayFiles; + } + + private void checkpending_datafor_upload() { + db.open(); + if (!db.getmasterTransaction(visitDate, counterId, false).isEmpty()) { + rl_pending_data.setVisibility(View.VISIBLE); + } else { + rl_pending_data.setVisibility(View.GONE); + } + } + + public void downloadDataUniversalWithoutWait(final ArrayList jsonStringList, + final ArrayList KeyNames, int downloadindex, final ProgressDialog pd) { + final String[] data_global = {""}; + String jsonString = "", KeyName = ""; + int jsonIndex = 0; + + if (!jsonStringList.isEmpty()) { + final OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(20, TimeUnit.SECONDS).writeTimeout(20, TimeUnit.SECONDS).connectTimeout(20, TimeUnit.SECONDS).build(); + jsonString = jsonStringList.get(downloadindex); + KeyName = KeyNames.get(downloadindex); + jsonIndex = downloadindex; + pd.setMessage("Downloading Dashboard Data (" + downloadindex + "/" + jsonStringList.size() + ") \n" + KeyName); + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsonString); + Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build(); + PostApi api = adapter.create(PostApi.class); + Call call = api.getDownloadAll(jsonData); + final int[] finalJsonIndex = {jsonIndex}; + final String finalKeyName = KeyName; + call.enqueue(new Callback() { + @SuppressLint("SetTextI18n") + @Override + public void onResponse(@NonNull Call call, @NonNull Response response) { + String responseBody = response.body(); + String data = null; + if (responseBody != null && response.isSuccessful()) { + try { + data = response.body(); + assert data != null; + if (data.isEmpty()) { + data_global[0] = ""; + } else { + data_global[0] = data; + { + switch (finalKeyName) { + ///jp_download Report + case "Report_SalesValue": + if (!data.contains("No Data")) { + MasterProfileQuestionGetterSetter reportSaleValueObject = new Gson().fromJson(data, MasterProfileQuestionGetterSetter.class); + db.open(); + if (reportSaleValueObject != null && !db.insertReportSaleValue(reportSaleValueObject)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Report_SalesValue not saved"); + } + } else { + db.open(); + db.delete_table_data("Report_SalesValue"); + } + + break; + + case "Report_AvgTransactionPerDay": + if (!data.contains("No Data")) { + MasterProfileQuestionGetterSetter reportavGTransationValueObject = new Gson().fromJson(data, MasterProfileQuestionGetterSetter.class); + db.open(); + if (reportavGTransationValueObject != null && !db.insertReportAvgTransationperDay(reportavGTransationValueObject)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Report_AvgTransactionPerDay not saved"); + } + } else { + db.open(); + db.delete_table_data("Report_AvgTransactionPerDay"); + } + + + break; + + case "Report_AvgUnitsPerBill": + if (!data.contains("No Data")) { + MasterProfileQuestionGetterSetter reportAvgUnitPerBillObject = new Gson().fromJson(data, MasterProfileQuestionGetterSetter.class); + db.open(); + if (reportAvgUnitPerBillObject != null && !db.insertReportAvgPerBillDay(reportAvgUnitPerBillObject)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Report_AvgUnitsPerBill not saved"); + } + } else { + db.open(); + db.delete_table_data("Report_AvgUnitsPerBill"); + } + + + break; + + case "Report_AvgBillValue": + if (!data.contains("No Data")) { + MasterProfileQuestionGetterSetter reportAvgBillUnitObject = new Gson().fromJson(data, MasterProfileQuestionGetterSetter.class); + db.open(); + if (reportAvgBillUnitObject != null && !db.insertReportAvgBillUnit(reportAvgBillUnitObject)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Report_AvgBillValue not saved"); + } + } else { + db.open(); + db.delete_table_data("Report_AvgBillValue"); + } + break; + + case "Report_AvgLinPerBill": + if (!data.contains("No Data")) { + MasterProfileQuestionGetterSetter reportAvgLinPerBillObject = new Gson().fromJson(data, MasterProfileQuestionGetterSetter.class); + db.open(); + if (reportAvgLinPerBillObject != null && !db.insertReportAvgLinPerBill(reportAvgLinPerBillObject)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Report_AvgLinPerBill not saved"); + } + } else { + db.open(); + db.delete_table_data("Report_AvgLinPerBill"); + } + + break; + + case "Report_SellingPrice": + if (!data.contains("No Data")) { + MasterProfileQuestionGetterSetter reportSalingPrizeObject = new Gson().fromJson(data, MasterProfileQuestionGetterSetter.class); + db.open(); + if (reportSalingPrizeObject != null && !db.insertReportSelingPrice(reportSalingPrizeObject)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Report_SellingPrice not saved"); + } + } else { + db.open(); + db.delete_table_data("Report_SellingPrice"); + } + break; + case "Report_ProductGroupWiseSalesValue": + if (!data.contains("No Data")) { + ResponseResult productGroupwiseSaleObject = new Gson().fromJson(data, ResponseResult.class); + db.open(); + if (productGroupwiseSaleObject != null && !db.insertGroupWiseSale(productGroupwiseSaleObject)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Report_ProductGroupWiseSalesValue not saved"); + } + } else { + db.open(); + db.delete_table_data("Report_ProductGroupWiseSalesValue"); + } + + break; + + + } + } + } + + finalJsonIndex[0]++; + if (finalJsonIndex[0] != KeyNames.size()) { + downloadDataUniversalWithoutWait(jsonStringList, KeyNames, finalJsonIndex[0], pd); + } else { + + /////update Dashboard UI reports....... + editor = preferences.edit(); + editor.putString(CommonString.KEY_DASHBOARD_REFRESH_TIME, CommonFunctions.getCurrentTime_only()); + editor.commit(); + if (pd.isShowing()) { + pd.dismiss(); + } + /////Only for Dashboard data................ + if (getDashboardRefreshListener() != null) { + getDashboardRefreshListener().onRefresh(""); + } + + DASHBOARD_REFRESH_TIME = preferences.getString(CommonString.KEY_DASHBOARD_REFRESH_TIME, ""); + txt_dashboard.setText(getString(R.string.dashboard) + " Last Updated at - " + DASHBOARD_REFRESH_TIME + " - " + visitDate); + } + + } catch (Exception e) { + e.fillInStackTrace(); + pd.dismiss(); + } + } else { + pd.dismiss(); + } + } + + @Override + public void onFailure(@NonNull Call call, @NonNull Throwable t) { + pd.dismiss(); + } + }); + } + } + + ////TBA/ME apply leave code + public class CustomDialogLeaveApply extends Dialog { + private CustomDialogLeaveApply oneButtonDialog; + private DialogApplyLeaveBinding binding = null; + private final boolean markleave; + + public CustomDialogLeaveApply(AppCompatActivity activity, boolean mark_leave) { + super(activity); + this.markleave = mark_leave; + } + + public CustomDialogLeaveApply getInstance(AppCompatActivity activity, boolean mark_leave) { + return oneButtonDialog = (oneButtonDialog == null) ? new CustomDialogLeaveApply(activity, mark_leave) : oneButtonDialog; + } + + @SuppressLint("SetTextI18n") + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + requestWindowFeature(Window.FEATURE_NO_TITLE); + binding = DialogApplyLeaveBinding.inflate(getLayoutInflater()); + setContentView(binding.getRoot()); + // Set the dialog window properties + Window window = customDialogLeave.getWindow(); + if (window != null) { + window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); + window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); + // Adjust margins + ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) binding.getRoot().getLayoutParams(); + + if (CommonFunctions.isTablet(context)) { + layoutParams.setMargins(75, 5, 75, 5); // Left, Top, Right, Bottom margins in pixels + } else { + layoutParams.setMargins(15, 5, 15, 5); // Left, Top, Right, Bottom margins in pixels + } + binding.getRoot().setLayoutParams(layoutParams); + } + + binding.edtapplyForleaveReason.setFilters(new InputFilter[]{filter, new InputFilter.LengthFilter(550)}); + binding.imgClose.setOnClickListener(v -> dismiss()); + + binding.etEmployeeCode.setOnEditorActionListener((v, actionId, event) -> { + if (actionId == EditorInfo.IME_ACTION_DONE) { + // Your action on done + if (Objects.requireNonNull(binding.etEmployeeCode.getText()).toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter Employee/Legacy Code"); + } else { + CommonFunctions.dismissKeyboard(binding.getRoot()); + getEmployeeDetails(binding.etEmployeeCode.getText().toString(), binding.tvEmpName, binding.tvEmpCode, + binding.tvEmpDesignation); + } + return true; + } + return false; + }); + + binding.etEmployeeCode.setDrawableClickListener(target -> { + if (Objects.requireNonNull(target) == DrawableClickListener.DrawablePosition.RIGHT) { + if (Objects.requireNonNull(binding.etEmployeeCode.getText()).toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter Employee/Legacy Code"); + } else { + CommonFunctions.dismissKeyboard(binding.getRoot()); + getEmployeeDetails(binding.etEmployeeCode.getText().toString(), binding.tvEmpName, binding.tvEmpCode, binding.tvEmpDesignation); + } + } + }); + + binding.etEmployeeCodeforHistory.setOnEditorActionListener((v, actionId, event) -> { + if (actionId == EditorInfo.IME_ACTION_DONE) { + // Your action on done + if (Objects.requireNonNull(binding.etEmployeeCodeforHistory.getText()).toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter Employee/Legacy Code"); + } else { + ///API call + getLeaveHistory(binding); + CommonFunctions.dismissKeyboard(binding.getRoot()); + } + return true; + } + return false; + }); + + binding.etEmployeeCodeforHistory.setDrawableClickListener(target -> { + if (Objects.requireNonNull(target) == DrawableClickListener.DrawablePosition.RIGHT) { + if (Objects.requireNonNull(binding.etEmployeeCodeforHistory.getText()).toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter Employee/Legacy Code"); + } else { + ///API call + getLeaveHistory(binding); + CommonFunctions.dismissKeyboard(binding.getRoot()); + } + } + }); + + binding.rlFromDateInfo.setOnClickListener(v -> { + if (binding.radioBFullday.isChecked() || binding.radioHalfDay.isChecked()) { + c = Calendar.getInstance(); + mYear = c.get(Calendar.YEAR); + mMonth = c.get(Calendar.MONTH); + mDay = c.get(Calendar.DAY_OF_MONTH); + // Launch Date Picker Dialog + dpd = new DatePickerDialog(context, (view, year, monthOfYear, dayOfMonth) -> { + String month_of_year = "", start_day_Of_Month = ""; + if ((monthOfYear + 1) < 10) { + month_of_year = "0" + (monthOfYear + 1); + } else { + month_of_year = String.valueOf(monthOfYear + 1); + } + if ((dayOfMonth) < 10) { + start_day_Of_Month = "0" + dayOfMonth; + } else { + start_day_Of_Month = String.valueOf(dayOfMonth); + } + String cmp_date = month_of_year + "/" + start_day_Of_Month + "/" + year; + binding.tvFromDate.setText(cmp_date); + binding.tvToDate.setText(""); + if (binding.radioHalfDay.isChecked()) { + binding.tvToDate.setText(cmp_date); + } + }, mYear, mMonth, mDay); + Calendar calendar = Calendar.getInstance(); + dpd.getDatePicker().setMinDate(calendar.getTimeInMillis() - 1000); + calendar = Calendar.getInstance(); + calendar.add(Calendar.MONTH, 2); + dpd.getDatePicker().setMaxDate(calendar.getTimeInMillis()); + dpd.show(); + } + }); + + binding.rlToDateInfo.setOnClickListener(v -> { + if (binding.radioBFullday.isChecked() && !binding.tvFromDate.getText().toString().isEmpty()) { + c = Calendar.getInstance(); + mYear = c.get(Calendar.YEAR); + mMonth = c.get(Calendar.MONTH); + mDay = c.get(Calendar.DAY_OF_MONTH); + dpd = new DatePickerDialog(context, (view, year, monthOfYear, dayOfMonth) -> { + try { + String month_of_year = "", day_Of_Month = ""; + if ((monthOfYear + 1) < 10) { + month_of_year = "0" + (monthOfYear + 1); + } else { + month_of_year = String.valueOf(monthOfYear + 1); + } + if ((dayOfMonth) < 10) { + day_Of_Month = "0" + dayOfMonth; + } else { + day_Of_Month = String.valueOf(dayOfMonth); + } + + binding.tvToDate.setText(month_of_year + "/" + day_Of_Month + "/" + year); + + } catch (Exception e) { + e.fillInStackTrace(); + } + }, mYear, mMonth, mDay); + String[] fromDate = binding.tvFromDate.getText().toString().split("/"); + Calendar calendar = Calendar.getInstance(); + calendar.set(Integer.parseInt(fromDate[2]), Integer.parseInt(fromDate[0]) - 1, Integer.parseInt(fromDate[1])); + dpd.getDatePicker().setMinDate(calendar.getTimeInMillis()); + calendar = Calendar.getInstance(); + calendar.set(Integer.parseInt(fromDate[2]), Integer.parseInt(fromDate[0]) + 1, Integer.parseInt(fromDate[1])); + dpd.getDatePicker().setMaxDate(calendar.getTimeInMillis()); + dpd.show(); + } + }); + } + + @SuppressLint("SetTextI18n") + @Override + protected void onStart() { + super.onStart(); + setCancelable(false); + if (markleave) { + binding.tvDialogTitle.setText("Apply For Leave"); + binding.btnSubmit.setVisibility(View.VISIBLE); + binding.rlApplyLeaveDetail.setVisibility(View.VISIBLE); + binding.rlLeaveHistory.setVisibility(View.GONE); + } else { + binding.tvDialogTitle.setText("Leave History"); + binding.btnSubmit.setVisibility(View.GONE); + binding.rlApplyLeaveDetail.setVisibility(View.GONE); + binding.rlLeaveHistory.setVisibility(View.VISIBLE); + } + + binding.radioBFullday.setOnCheckedChangeListener((buttonView, isChecked) -> { + if (isChecked) { + binding.radioHalfDay.setChecked(false); + binding.radioBFullday.setChecked(true); + binding.tvFromDateInfo.setText("Date From"); + binding.rlToDateInfo.setEnabled(true); + binding.tvFromDate.setText(""); + binding.tvToDate.setText(""); + binding.tvTodatePlaceholder.setTextColor(ContextCompat.getColor(context, R.color.black)); + } + }); + + binding.radioHalfDay.setOnCheckedChangeListener((buttonView, isChecked) -> { + if (isChecked) { + binding.radioHalfDay.setChecked(true); + binding.radioBFullday.setChecked(false); + binding.tvFromDateInfo.setText("Select Date"); + binding.rlToDateInfo.setEnabled(false); + binding.tvFromDate.setText(""); + binding.tvToDate.setText(""); + binding.tvTodatePlaceholder.setTextColor(ContextCompat.getColor(context, R.color.gray)); + } + }); + binding.btnSubmit.setOnClickListener(v -> { + if (tbameSearch == null && binding.tvEmpCode.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter Employee/Legacy Code"); + } else if (!binding.radioBFullday.isChecked() && !binding.radioHalfDay.isChecked()) { + AlertandMessages.showToastMsg(context, "Please Select Leave Type(Full/Half day)"); + } else if (!binding.radioHalfDay.isChecked() && binding.radioBFullday.isChecked() && binding.tvFromDate.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Select Date From"); + } else if (!binding.radioHalfDay.isChecked() && binding.radioBFullday.isChecked() && binding.tvToDate.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Select Date to"); + } else if (!binding.radioBFullday.isChecked() && binding.radioHalfDay.isChecked() && binding.tvFromDate.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Select Date"); + } else if (Objects.requireNonNull(binding.edtapplyForleaveReason.getText()).toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter Reason"); + } else { + if (CommonFunctions.checkNetIsAvailable(context)) { + submitLeaveRequest(tbameSearch.getEmpId().toString(), + binding.radioBFullday.isChecked() ? binding.radioBFullday.getText().toString() + : binding.radioHalfDay.getText().toString(), + binding.tvFromDate.getText().toString(), binding.tvToDate.getText().toString(), + binding.edtapplyForleaveReason.getText().toString()); + } else { + AlertandMessages.showToastMsg(context, getString(R.string.nonetwork)); + } + } + }); + } + } + + private void submitLeaveRequest(String empId, String leaveType, String date_from, String + date_to, String leaveReason) { + ProgressDialog pd = null; + try { + pd = new ProgressDialog(context); + pd.setTitle("Applying Leave Request"); + pd.setMessage("Please wait....."); + pd.show(); + JSONObject json = new JSONObject().put("EmpId", empId) + .put("LeaveType", leaveType).put("FromDate", date_from).put("ToDate", leaveType.equals("Half Day") ? date_from : date_to) + .put("Reason", leaveReason).put("UserId", ""); + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), json.toString()); + Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS) + .writeTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build()).addConverterFactory(GsonConverterFactory.create()).build(); + ProgressDialog finalPd = pd; + adapter.create(PostApi.class).LeaveRequest(jsonData).enqueue(new Callback() { + @Override + public void onResponse(@NonNull Call call, @NonNull Response response) { + String responseBody = response.body(); + String data = null; + if (responseBody != null && response.isSuccessful()) { + try { + data = response.body(); + assert data != null; + if (!data.isEmpty() && !data.contains("No Data")) { + Common common = new Gson().fromJson(data, Common.class); + if (common != null && !common.getLeaveRequest().isEmpty()) { + assert common.getLeaveRequest().get(0).getResult() != null; + if (common.getLeaveRequest().get(0).getResult().equalsIgnoreCase(CommonString.KEY_SUCCESS)) { + if (finalPd.isShowing()) finalPd.dismiss(); + showAlert(customDialogLeave, "Leave request applied successfully."); + } else { + if (finalPd.isShowing()) finalPd.dismiss(); + showAlert(customDialogLeave, common.getLeaveRequest().get(0).getResult()); + } + } else { + if (finalPd.isShowing()) finalPd.dismiss(); + AlertandMessages.showToastMsg(context, getString(R.string.something_went_wrong)); + } + } else { + if (finalPd.isShowing()) finalPd.dismiss(); + AlertandMessages.showToastMsg(context, getString(R.string.something_went_wrong)); + } + if (finalPd.isShowing()) finalPd.dismiss(); + } catch (Exception e) { + if (finalPd.isShowing()) finalPd.dismiss(); + AlertandMessages.showToastMsg(context, "Error in data.Please try again..."); + } + } else { + if (finalPd.isShowing()) finalPd.dismiss(); + AlertandMessages.showToastMsg(context, "Error in Data,Please try again..."); + } + } + + @Override + public void onFailure(@NonNull Call call, @NonNull Throwable t) { + if (finalPd.isShowing()) finalPd.dismiss(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE); + } + }); + } catch (Exception ignored) { + if (pd != null && pd.isShowing()) pd.dismiss(); + } + + } + + private void showAlert(CustomDialogLeaveApply customDialogLeave, String str) { + try { + AlertDialog.Builder builder = new AlertDialog.Builder(context); + builder.setTitle(getString(R.string.parinaam)); + builder.setMessage(str).setCancelable(false) + .setPositiveButton(android.R.string.ok, (dialog, id) -> { + if (str.equals("Leave request applied successfully.")) { + if (customDialogLeave != null) customDialogLeave.cancel(); + } else dialog.dismiss(); + }); + AlertDialog alert = builder.create(); + alert.show(); + } catch (Exception e) { + e.fillInStackTrace(); + } + } + + private void getLeaveHistory(DialogApplyLeaveBinding binding) { + ProgressDialog pd = null; + try { + pd = new ProgressDialog(context); + pd.setTitle("Processing"); + pd.setMessage("Please wait....."); + pd.show(); + JSONObject json = new JSONObject().put("Downloadtype", "TBAME_LeaveHistory") + .put("Username", "").put("Param1", Objects.requireNonNull(binding.etEmployeeCodeforHistory.getText()).toString()).put("Param2", ""); + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), json.toString()); + Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS) + .writeTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build()).addConverterFactory(GsonConverterFactory.create()).build(); + ProgressDialog finalPd = pd; + adapter.create(PostApi.class).getDownloadAll(jsonData).enqueue(new Callback() { + @Override + public void onResponse(@NonNull Call call, @NonNull Response response) { + String responseBody = response.body(); + String data = null; + if (responseBody != null && response.isSuccessful()) { + try { + data = response.body(); + assert data != null; + if (!data.isEmpty() && !data.contains("No Data")) { + Common common = new Gson().fromJson(data, Common.class); + if (common != null && !common.getTBAMELeaveHistory().isEmpty()) { + runOnUiThread(() -> { + binding.tvEmpNameHistory.setText(CommonFunctions.capitalizeFirstLetter(common.getTBAMELeaveHistory().get(0).getName())); + binding.tvEmpDesignationHistory.setText(common.getTBAMELeaveHistory().get(0).getDesignation()); + binding.tvEmpCodeHistory.setText(common.getTBAMELeaveHistory().get(0).getEmpCode()); + binding.recyclerLeaveDetail.setAdapter(new LeaveDetailAdapter(context, common.getTBAMELeaveHistory())); + binding.recyclerLeaveDetail.setLayoutManager(new LinearLayoutManager(context)); + binding.rlLeaveDetailItem.setVisibility(View.VISIBLE); + }); + } + } else { + runOnUiThread(() -> { + binding.tvEmpNameHistory.setText(""); + binding.tvEmpCodeHistory.setText(""); + binding.tvEmpDesignationHistory.setText(""); + binding.rlLeaveDetailItem.setVisibility(View.GONE); + }); + AlertandMessages.showToastMsg(context, "No Leave history found for this employee . Please check Employee code and re-sync"); + } + if (finalPd.isShowing()) finalPd.dismiss(); + } catch (Exception e) { + runOnUiThread(() -> { + binding.tvEmpNameHistory.setText(""); + binding.tvEmpCodeHistory.setText(""); + binding.tvEmpDesignationHistory.setText(""); + binding.rlLeaveDetailItem.setVisibility(View.GONE); + }); + if (finalPd.isShowing()) finalPd.dismiss(); + AlertandMessages.showAlert((Activity) context, "Error in Leave history data.", true); + } + } else { + runOnUiThread(() -> { + binding.tvEmpNameHistory.setText(""); + binding.tvEmpCodeHistory.setText(""); + binding.tvEmpDesignationHistory.setText(""); + binding.rlLeaveDetailItem.setVisibility(View.GONE); + }); + if (finalPd.isShowing()) finalPd.dismiss(); + AlertandMessages.showAlert((Activity) context, "Error in downloading Data,Please try again... ", true); + } + } + + @Override + public void onFailure(@NonNull Call call, @NonNull Throwable t) { + runOnUiThread(() -> { + binding.tvEmpNameHistory.setText(""); + binding.tvEmpCodeHistory.setText(""); + binding.tvEmpDesignationHistory.setText(""); + binding.rlLeaveDetailItem.setVisibility(View.GONE); + }); + if (finalPd.isShowing()) finalPd.dismiss(); + AlertandMessages.showAlert((Activity) context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE, true); + } + }); + } catch (Exception ignored) { + if (pd != null && pd.isShowing()) pd.dismiss(); + } + } + + private void getEmployeeDetails(String empId, TextView tvEmpName, TextView + tvEmpId, TextView empDesignation) { + ProgressDialog pd = null; + try { + pd = new ProgressDialog(context); + pd.setTitle("Processing"); + pd.setMessage("Please wait....."); + pd.show(); + JSONObject json = new JSONObject().put("Downloadtype", "TBAME_Search").put("Username", "").put("Param1", empId) + .put("Param2", ""); + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), json.toString()); + Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS) + .writeTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build()).addConverterFactory(GsonConverterFactory.create()).build(); + ProgressDialog finalPd = pd; + adapter.create(PostApi.class).getDownloadAll(jsonData).enqueue(new Callback() { + @Override + public void onResponse(@NonNull Call call, @NonNull Response response) { + String responseBody = response.body(); + String data = null; + if (responseBody != null && response.isSuccessful()) { + try { + data = response.body(); + assert data != null; + if (!data.isEmpty() && !data.contains("No Data")) { + Common common = new Gson().fromJson(data, Common.class); + if (common != null && !common.getTBAMESearch().isEmpty()) { + tbameSearch = common.getTBAMESearch().get(0); + runOnUiThread(() -> { + tvEmpName.setText(common.getTBAMESearch().get(0).getName()); + tvEmpId.setText(common.getTBAMESearch().get(0).getEmpCode()); + empDesignation.setText(common.getTBAMESearch().get(0).getDesignation()); + }); + } else { + tbameSearch = null; + runOnUiThread(() -> { + tvEmpName.setText(""); + tvEmpId.setText(""); + empDesignation.setText(""); + }); + AlertandMessages.showToastMsg(context, "Employee Detail not available. Please check Employee/Legacy code and re-sync"); + } + } else { + tbameSearch = null; + runOnUiThread(() -> { + tvEmpName.setText(""); + tvEmpId.setText(""); + empDesignation.setText(""); + }); + AlertandMessages.showToastMsg(context, "Employee Detail not available. Please check Employee/Legacy code and re-sync"); + } + if (finalPd.isShowing()) finalPd.dismiss(); + } catch (Exception e) { + tbameSearch = null; + runOnUiThread(() -> { + tvEmpName.setText(""); + tvEmpId.setText(""); + empDesignation.setText(""); + }); + if (finalPd.isShowing()) finalPd.dismiss(); + AlertandMessages.showToastMsg(context, "Error in data. " + e.getMessage()); + } + } else { + tbameSearch = null; + runOnUiThread(() -> { + tvEmpName.setText(""); + tvEmpId.setText(""); + empDesignation.setText(""); + }); + if (finalPd.isShowing()) finalPd.dismiss(); + AlertandMessages.showToastMsg(context, "Error in downloading Data,Please try again... "); + } + } + + @Override + public void onFailure(@NonNull Call call, @NonNull Throwable t) { + tbameSearch = null; + runOnUiThread(() -> { + tvEmpName.setText(""); + tvEmpId.setText(""); + empDesignation.setText(""); + }); + if (finalPd.isShowing()) finalPd.dismiss(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE); + } + }); + } catch (Exception ignored) { + if (pd != null && pd.isShowing()) pd.dismiss(); + } + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/Get_IMEI_number/ImeiNumberClass.java b/app/src/main/java/com/cpm/lorealbaautomation/Get_IMEI_number/ImeiNumberClass.java new file mode 100644 index 0000000..47bfbd8 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/Get_IMEI_number/ImeiNumberClass.java @@ -0,0 +1,57 @@ +package com.cpm.lorealbaautomation.Get_IMEI_number; + +import android.content.Context; +import android.os.Build; +import androidx.appcompat.app.AppCompatActivity; +import android.telephony.TelephonyManager; + +public class ImeiNumberClass extends AppCompatActivity { + + private TelephonyManager mTelephonyManager; + Context context; + + public ImeiNumberClass(Context context) { + this.context = context; + } + + public String[] getDeviceImei() { + + String deviceid[] = null; + mTelephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); + if (mTelephonyManager != null) { + deviceid = getSimImei(); + } else { + return new String[]{"0"}; + } + return deviceid; + } + + + public String[] getSimImei() { + TelephonyInfo telephonyInfo = TelephonyInfo.getInstance(context); + + String imeiSIM1 = null, imeiSIM2 = null; + + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { + if (mTelephonyManager.getPhoneCount() > 1) { + imeiSIM1 = telephonyInfo.getImeiSIM1(); + imeiSIM2 = telephonyInfo.getImeiSIM2(); + return new String[]{imeiSIM1, imeiSIM2}; + } else { + imeiSIM1 = telephonyInfo.getImeiSIM1(); + return new String[]{imeiSIM1}; + } + } else { + if (telephonyInfo.isDualSIM()) { + imeiSIM1 = telephonyInfo.getImeiSIM1(); + imeiSIM2 = telephonyInfo.getImeiSIM2(); + return new String[]{imeiSIM1, imeiSIM2}; + } else { + imeiSIM1 = telephonyInfo.getImeiSIM1(); + return new String[]{imeiSIM1}; + } + } + } + + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/Get_IMEI_number/TelephonyInfo.java b/app/src/main/java/com/cpm/lorealbaautomation/Get_IMEI_number/TelephonyInfo.java new file mode 100644 index 0000000..93ecd78 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/Get_IMEI_number/TelephonyInfo.java @@ -0,0 +1,141 @@ +package com.cpm.lorealbaautomation.Get_IMEI_number; + +import android.content.Context; +import android.telephony.TelephonyManager; + +import java.lang.reflect.Method; + +/** + * Created by deepakp on 9/27/2017. + */ + +public class TelephonyInfo { + + private static TelephonyInfo telephonyInfo; + private String imeiSIM1; + private String imeiSIM2; + + public String getImeiSIM1() { + return imeiSIM1; + } + + public String getImeiSIM2() { + return imeiSIM2; + } + + + public boolean isDualSIM() { + return imeiSIM2 != null; + } + + + public static TelephonyInfo getInstance(Context context) { + + if (telephonyInfo == null) { + + telephonyInfo = new TelephonyInfo(); + + telephonyInfo.imeiSIM1 = null; + telephonyInfo.imeiSIM2 = null; + try { + telephonyInfo.imeiSIM1 = getDeviceIdBySlot(context, "getDeviceIdGemini", 0); + telephonyInfo.imeiSIM2 = getDeviceIdBySlot(context, "getDeviceIdGemini", 1); + } catch (GeminiMethodNotFoundException e) { + e.fillInStackTrace(); + + try { + telephonyInfo.imeiSIM1 = getDeviceIdBySlot(context, "getDeviceId", 0); + telephonyInfo.imeiSIM2 = getDeviceIdBySlot(context, "getDeviceId", 1); + } catch (GeminiMethodNotFoundException e1) { + //Call here for next manufacturer's predicted method name if you wish + e1.fillInStackTrace(); + try { + telephonyInfo.imeiSIM1 = getDeviceIdBySlotNew(context, "getDeviceId", 0); + telephonyInfo.imeiSIM2 = getDeviceIdBySlotNew(context, "getDeviceId", 1); + } catch (GeminiMethodNotFoundException e2) { + e2.fillInStackTrace(); + } + } + } + } + + return telephonyInfo; + } + + + private static String getDeviceIdBySlot(Context context, String predictedMethodName, int slotID) throws GeminiMethodNotFoundException { + + String imei = null; + + TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); + + try { + + Class telephonyClass = Class.forName(telephony.getClass().getName()); + Class[] parameter = new Class[1]; + parameter[0] = int.class; + Method getSimID = telephonyClass.getMethod(predictedMethodName, parameter); + + Object[] obParameter = new Object[1]; + obParameter[0] = slotID; + Object ob_phone = getSimID.invoke(telephony, obParameter); + + + if (ob_phone != null) { + imei = ob_phone.toString(); + } + } catch (Exception e) { + e.fillInStackTrace(); + if (e instanceof NoSuchMethodException && predictedMethodName.equalsIgnoreCase("getDeviceId")) { + Class telephonyClass = null; + try { + telephonyClass = Class.forName(telephony.getClass().getName()); + Class[] parameter = new Class[1]; + parameter[0] = int.class; + Method getSimID = telephonyClass.getMethod("getDefault", parameter); + Object[] obParameter = new Object[1]; + obParameter[0] = slotID; + //TelephonyManager ob_phone = (TelephonyManager) getSimID.invoke(null, obParameter); + TelephonyManager ob_phone = (TelephonyManager) getSimID.invoke(telephony, obParameter); + if (ob_phone != null) { + imei = ob_phone.getDeviceId().toString(); + } + } catch (Exception e1) { + e1.fillInStackTrace(); + throw new GeminiMethodNotFoundException(predictedMethodName); + } + + } else { + throw new GeminiMethodNotFoundException(predictedMethodName); + } + + } + + return imei; + } + + private static String getDeviceIdBySlotNew(Context context, String predictedMethodName, int slotID) throws GeminiMethodNotFoundException { + String imei = "0"; + TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); + try { + if (telephony.getDeviceId() != null) { + imei = telephony.getDeviceId().toString(); + } + } catch (Exception e) { + e.fillInStackTrace(); + } + + return imei; + } + + + private static class GeminiMethodNotFoundException extends Exception { + + private static final long serialVersionUID = -996812356902545308L; + + public GeminiMethodNotFoundException(String info) { + super(info); + } + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/IMEILoginActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/IMEILoginActivity.java new file mode 100644 index 0000000..ebf05c2 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/IMEILoginActivity.java @@ -0,0 +1,742 @@ +package com.cpm.lorealbaautomation; + +import static com.cpm.lorealbaautomation.constant.CommonFunctions.checkincomplete_upload_data; + +import android.Manifest; +import android.annotation.SuppressLint; +import android.app.Activity; +import android.app.AlertDialog; +import android.app.Dialog; +import android.app.ProgressDialog; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.IntentSender; +import android.content.SharedPreferences; +import android.content.pm.PackageInfo; +import android.content.pm.PackageManager; +import android.database.sqlite.SQLiteDatabase; +import android.location.Location; +import android.location.LocationManager; +import android.os.Build; +import android.os.Bundle; +import android.os.Environment; +import android.provider.Settings; +import android.util.Log; +import android.view.Gravity; +import android.view.View; +import android.view.Window; +import android.view.WindowManager; +import android.widget.LinearLayout; +import android.widget.TextView; +import android.widget.Toast; + +import androidx.annotation.NonNull; +import androidx.appcompat.app.AppCompatActivity; +import androidx.core.app.ActivityCompat; +import androidx.core.content.ContextCompat; + +import com.google.android.gms.common.ConnectionResult; +import com.google.android.gms.common.GooglePlayServicesUtil; +import com.google.android.gms.common.api.GoogleApiClient; +import com.google.android.gms.common.api.PendingResult; +import com.google.android.gms.common.api.Status; +import com.google.android.gms.location.LocationListener; +import com.google.android.gms.location.LocationRequest; +import com.google.android.gms.location.LocationServices; +import com.google.android.gms.location.LocationSettingsRequest; +import com.google.android.gms.location.LocationSettingsResult; +import com.google.android.gms.location.LocationSettingsStatusCodes; +import com.google.firebase.crashlytics.FirebaseCrashlytics; +import com.google.gson.Gson; +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.Get_IMEI_number.ImeiNumberClass; +import com.cpm.lorealbaautomation.constant.AlertandMessages; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.dailyactivity.NotificationDetailActivity; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.gsonGetterSetter.CounterDeviceLoginGetterSetter; +import com.cpm.lorealbaautomation.retrofit.PostApi; +import com.cpm.lorealbaautomation.upload.ManualUploadActivity; +import org.json.JSONException; +import org.json.JSONObject; +import java.io.File; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.TimeUnit; + +import okhttp3.MediaType; +import okhttp3.OkHttpClient; +import okhttp3.RequestBody; +import okhttp3.ResponseBody; +import retrofit2.Call; +import retrofit2.Callback; +import retrofit2.Response; +import retrofit2.Retrofit; +import retrofit2.converter.gson.GsonConverterFactory; + +public class IMEILoginActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, + GoogleApiClient.OnConnectionFailedListener, LocationListener { + private String[] imeiNumbers; + private String app_ver; + private Context context; + private static final int LOGIN_AFTER_NOTIFICATION = 2; + ProgressDialog loading = null; + private Retrofit adapter; + private SharedPreferences preferences = null; + private SharedPreferences.Editor editor = null; + private double lat = 0.0; + private double lon = 0.0; + private int versionCode; + private String manufacturer; + private String model; + private String os_version; + GoogleApiClient mGoogleApiClient; + private static int UPDATE_INTERVAL = 200; // 5 sec + private static int FATEST_INTERVAL = 100; // 1 sec + private static int DISPLACEMENT = 1; // 10 meters + private static final int REQUEST_LOCATION = 1; + private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 1000; + private Location mLastLocation; + private LocationRequest mLocationRequest; + private static final int PERMISSION_ALL = 99; + private ImeiNumberClass imei; + Lorealba_Database db; + String title = "", body = "", path = "", counter_id, type, visit_date; + TextView versioncode_txt; + LinearLayout rl_counterlogin; + CounterDeviceLoginGetterSetter userapp_databaseObject = null; + + @SuppressLint("SetTextI18n") + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + requestWindowFeature(Window.FEATURE_NO_TITLE); + getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); + setContentView(R.layout.activity_counter_login); + FirebaseCrashlytics.getInstance().setCrashlyticsCollectionEnabled(true); + if (getIntent().getExtras() != null) { + long value = 0; + for (String key : getIntent().getExtras().keySet()) { + if (key.equalsIgnoreCase("title")) { + title = getIntent().getExtras().getString(key); + } else if (key.equalsIgnoreCase("body")) { + body = getIntent().getExtras().getString(key); + } else if (key.equalsIgnoreCase("path")) { + path = getIntent().getExtras().getString(key); + } else if (key.equalsIgnoreCase("Mediatype")) { + type = getIntent().getExtras().getString(key); + } + } + assert title != null; + if (!title.isEmpty() && !Objects.requireNonNull(body).isEmpty()) { + context = this; + db = new Lorealba_Database(context); + db.open(); + value = db.insertNotificationData(title, body, path, visit_date, type, counter_id); + if (value > 0) { + Toast.makeText(context, "Notification Inserted", Toast.LENGTH_SHORT).show(); + } else { + Toast.makeText(context, "Notification Not Inserted", Toast.LENGTH_SHORT).show(); + } + } else { + getViewId(); + } + + if (!title.isEmpty()) { + Intent in = new Intent(this, NotificationDetailActivity.class); + in.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); + in.putExtra("Type", type); + in.putExtra("Title", title); + in.putExtra("Body", body); + in.putExtra("Path", path); + in.putExtra("KEY_ID", value + ""); + startActivityForResult(in, LOGIN_AFTER_NOTIFICATION); + } + } else { + getViewId(); + } + + versioncode_txt = (TextView) findViewById(R.id.versioncode_txt); + rl_counterlogin = (LinearLayout) findViewById(R.id.rl_counterlogin); + rl_counterlogin.setVisibility(View.GONE); + try { + PackageInfo pInfo = context.getPackageManager().getPackageInfo(getPackageName(), 0); + String version = pInfo.versionName; + versioncode_txt.setText("Version : " + version); + } catch (PackageManager.NameNotFoundException e) { + e.fillInStackTrace(); + versioncode_txt.setText("Version : 0.0"); + } + } + + @Override + protected void onResume() { + super.onResume(); + context = this; + if (mGoogleApiClient != null) { + mGoogleApiClient.connect(); + } + + checkgpsEnableDevice(); + if (checkAndRequestPermissions()) { + imeiNumbers = imei.getDeviceImei(); + getDeviceName(); + } + } + + @SuppressLint("VisibleForTests") + protected void createLocationRequest() { + mLocationRequest = new LocationRequest(); + if (mLocationRequest != null) + mLocationRequest.setInterval(UPDATE_INTERVAL); + mLocationRequest.setFastestInterval(FATEST_INTERVAL); + mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); + mLocationRequest.setSmallestDisplacement(DISPLACEMENT); + } + + private void checkgpsEnableDevice() { + if (!hasGPSDevice(context)) { + Toast.makeText(context, "Gps not Supported", Toast.LENGTH_SHORT).show(); + } + final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); + if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER) && hasGPSDevice(context)) { + enableLoc(); + } else if (manager.isProviderEnabled(LocationManager.GPS_PROVIDER) && hasGPSDevice(context)) { + } + } + + private boolean hasGPSDevice(Context context) { + final LocationManager mgr = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); + if (mgr == null) + return false; + final List providers = mgr.getAllProviders(); + if (providers == null) + return false; + return providers.contains(LocationManager.GPS_PROVIDER); + } + + @SuppressLint("VisibleForTests") + private void enableLoc() { + LocationRequest locationRequest = LocationRequest.create(); + locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); + locationRequest.setInterval(30 * 1000); + locationRequest.setFastestInterval(5 * 1000); + LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest); + builder.setAlwaysShow(true); + if (mGoogleApiClient != null) { + PendingResult result = LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build()); + result.setResultCallback(result1 -> { + final Status status = result1.getStatus(); + if (status.getStatusCode() == LocationSettingsStatusCodes.RESOLUTION_REQUIRED) { + try { + // Show the dialog by calling startResolutionForResult(), + // and check the result in onActivityResult(). + status.startResolutionForResult((Activity) context, REQUEST_LOCATION); + } catch (IntentSender.SendIntentException e) { + // Ignore the error. + } + } + }); + } + } + + + private boolean checkPlayServices() { + int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(context); + if (resultCode != ConnectionResult.SUCCESS) { + if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) { + GooglePlayServicesUtil.getErrorDialog(resultCode, (Activity) context, PLAY_SERVICES_RESOLUTION_REQUEST).show(); + } else { + Toast.makeText(context, getResources().getString(R.string.notsuppoted), Toast.LENGTH_LONG).show(); + finish(); + } + return false; + } + return true; + } + + protected synchronized void buildGoogleApiClient() { + if (mGoogleApiClient == null) { + mGoogleApiClient = new GoogleApiClient.Builder(context).addConnectionCallbacks(this).addOnConnectionFailedListener(this) + .addApi(LocationServices.API).build(); + } + } + + + @SuppressLint("ObsoleteSdkInt") + private void AttempLogin() { + try { + try { + app_ver = String.valueOf(getPackageManager().getPackageInfo(getPackageName(), 0).versionName); + } catch (PackageManager.NameNotFoundException e) { + // TODO Auto-generated catch block + e.fillInStackTrace(); + } + + loading = ProgressDialog.show(IMEILoginActivity.this, "Processing", "Please wait...", false, false); + versionCode = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode; + JSONObject jsonObject = new JSONObject(); + + jsonObject.put("OSVersion", os_version); + jsonObject.put("Manufacturer", manufacturer); + jsonObject.put("ModelNumber", model); + jsonObject.put("Networkstatus", "0"); + jsonObject.put("Attmode", "0"); + jsonObject.put("Appversion", app_ver); + jsonObject.put("Latitude", lat); + jsonObject.put("Longitude", lon); + jsonObject.put("CounterCode", "0"); + jsonObject.put("AppId", BuildConfig.APPLICATION_ID); + + if (Build.VERSION.SDK_INT > Build.VERSION_CODES.P) { + @SuppressLint("HardwareIds") String android_id = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID); + jsonObject.put("IMEINumber1", android_id); + } else { + if (imeiNumbers != null && imeiNumbers.length > 0) { + jsonObject.put("IMEINumber1", imeiNumbers[0]); + } else { + jsonObject.put("IMEINumber1", "0"); + } + } + + String jsonString = jsonObject.toString(); + Log.e("jsonlogindata", jsonString); + try { + final OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout + (CommonString.TIMEOUT, TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build(); + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsonString); + adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build(); + PostApi api = adapter.create(PostApi.class); + Call call = api.getLogindetail(jsonData); + call.enqueue(new Callback() { + @Override + public void onResponse(@NonNull Call call, @NonNull Response response) { + ResponseBody responseBody = response.body(); + String data = null; + if (responseBody != null && response.isSuccessful()) { + try { + assert response.body() != null; + data = response.body().string(); + data = data.substring(1, data.length() - 1).replace("\\", ""); + Gson gson = new Gson(); + final CounterDeviceLoginGetterSetter userObject = gson.fromJson(data, CounterDeviceLoginGetterSetter.class); + if (data.equalsIgnoreCase(CommonString.KEY_FAILURE)) { + AlertandMessages.showAlertCounterlogin((Activity) context, CommonString.KEY_FAILURE + " Please try again"); + loading.dismiss(); + + if (loading != null && loading.isShowing()) { + loading.dismiss(); + } + } else if (userObject != null) { + JSONObject jsonObject1 = new JSONObject(); + jsonObject1.put("Downloadtype", "AppDatabaseName"); + jsonObject1.put("Username", ""); + jsonObject1.put("Param1", ""); + jsonObject1.put("Param2", ""); + + final OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS) + .writeTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build(); + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsonObject1.toString()); + adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build(); + PostApi api = adapter.create(PostApi.class); + Call call_appdatabase = api.getDownloadAll(jsonData); + call_appdatabase.enqueue(new Callback() { + @Override + public void onResponse(@NonNull Call call, @NonNull Response response) { + String responseBody_dab = response.body(); + String data_datab = null; + if (responseBody_dab != null && response.isSuccessful()) { + data_datab = response.body(); + assert data_datab != null; + if (!data_datab.isEmpty()) { + if (!data_datab.contains("No Data")) { + userapp_databaseObject = new Gson().fromJson(data_datab, CounterDeviceLoginGetterSetter.class); + } + } + if (userapp_databaseObject != null && !userapp_databaseObject.getAppDatabaseName().isEmpty()) { + int temp_db_versioncode = preferences.getInt(CommonString.KEY_TEMP_DB_VERSION, 0); + if (userapp_databaseObject.getAppDatabaseName().get(0).getAppVersion() != temp_db_versioncode) { + ////for Database delete + delete_local_database(); + } + editor.putInt(CommonString.KEY_TEMP_DB_VERSION, userapp_databaseObject.getAppDatabaseName().get(0).getAppVersion()); + } + editor.putString(CommonString.KEY_VERSION, userObject.getCounterDeviceLogin().get(0).getAppVersion().toString()); + editor.putString(CommonString.KEY_PATH, userObject.getCounterDeviceLogin().get(0).getAppPath()); + editor.putString(CommonString.KEY_DATE, userObject.getCounterDeviceLogin().get(0).getVisitDate()); + editor.putString(CommonString.KEY_COUNTER_ID, userObject.getCounterDeviceLogin().get(0).getCounterId().toString()); + editor.putString(CommonString.KEY_COUNTER_CODE, userObject.getCounterDeviceLogin().get(0).getCounterCode()); + editor.putString(CommonString.KEY_COUNTER_NAME, userObject.getCounterDeviceLogin().get(0).getCounterName()); + editor.apply(); + if (userObject.getCounterDeviceLogin().get(0).getAppVersion().equals(versionCode)) { + //-------upload previous day pending data--------------------- + if (userObject.getCounterDeviceLogin().get(0).getCounterId().equals(0)) { + loading.dismiss(); + if (loading != null && loading.isShowing()) { + loading.dismiss(); + } + Intent intent = new Intent(getBaseContext(), CounterLoginActivity.class); + startActivity(intent); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + finish(); + } else { + db.open(); + String datee = userObject.getCounterDeviceLogin().get(0).getVisitDate(); + if (!db.getmasterTransaction(datee, userObject.getCounterDeviceLogin().get(0).getCounterId().toString(), true).isEmpty() + || !checkincomplete_upload_data(datee, + userObject.getCounterDeviceLogin().get(0).getCounterId().toString(), db, true)) { + startActivity(new Intent(context, ManualUploadActivity.class).putExtra(CommonString.TAG_OBJECT, + userObject.getCounterDeviceLogin().get(0).getCounterId())); + } else { + Intent intent = new Intent(getBaseContext(), UserLoginActivity.class); + startActivity(intent); + } + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + IMEILoginActivity.this.finish(); + if (loading != null && loading.isShowing()) { + loading.dismiss(); + } + } + } else { + loading.dismiss(); + if (loading != null && loading.isShowing()) { + loading.dismiss(); + } + Intent intent = new Intent(getBaseContext(), AutoUpdateActivity.class); + intent.putExtra(CommonString.KEY_PATH, preferences.getString(CommonString.KEY_PATH, "")); + startActivity(intent); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + IMEILoginActivity.this.finish(); + } + } else { + loading.dismiss(); + if (loading != null && loading.isShowing()) { + loading.dismiss(); + } + AlertandMessages.showAlertCounterlogin((Activity) context, CommonString.MESSAGE_NO_RESPONSE_SERVER); + } + } + + @Override + public void onFailure(@NonNull Call call, @NonNull Throwable t) { + loading.dismiss(); + if (loading != null && loading.isShowing()) { + loading.dismiss(); + } + AlertandMessages.showAlertCounterlogin((Activity) context, CommonString.MESSAGE_SOCKETEXCEPTION); + + } + }); + + } else { + loading.dismiss(); + if (loading != null && loading.isShowing()) { + loading.dismiss(); + } + + AlertandMessages.showAlertCounterlogin((Activity) context, CommonString.MESSAGE_NO_RESPONSE_SERVER); + } + + } catch (Exception e) { + loading.dismiss(); + FirebaseCrashlytics.getInstance().recordException(e); + if (loading != null && loading.isShowing()) { + loading.dismiss(); + } + + e.fillInStackTrace(); + AlertandMessages.showAlertCounterlogin((Activity) context, CommonString.MESSAGE_SOCKETEXCEPTION + " - " + e.toString()); + } + } else { + loading.dismiss(); + if (loading != null && loading.isShowing()) { + loading.dismiss(); + } + AlertandMessages.showAlertCounterlogin((Activity) context, CommonString.MESSAGE_NO_RESPONSE_SERVER); + } + } + + @Override + public void onFailure(@NonNull Call call, @NonNull Throwable t) { + loading.dismiss(); + AlertandMessages.showAlertCounterlogin((Activity) context, CommonString.MESSAGE_SOCKETEXCEPTION); + + } + }); + + } catch (Exception e) { + loading.dismiss(); + if (loading != null && loading.isShowing()) { + loading.dismiss(); + } + e.fillInStackTrace(); + AlertandMessages.showAlertCounterlogin((Activity) context, CommonString.MESSAGE_SOCKETEXCEPTION + " - " + e.toString()); + + } + + } catch (PackageManager.NameNotFoundException e) { + loading.dismiss(); + if (loading != null && loading.isShowing()) { + loading.dismiss(); + } + AlertandMessages.showAlertCounterlogin((Activity) context, CommonString.MESSAGE_SOCKETEXCEPTION + " - " + e.toString()); + + } catch (JSONException e) { + loading.dismiss(); + if (loading != null && loading.isShowing()) { + loading.dismiss(); + } + } + } + + public void getDeviceName() { + try { + manufacturer = Build.MANUFACTURER; + model = Build.MODEL; + os_version = Build.VERSION.RELEASE; + } catch (Exception e) { + e.fillInStackTrace(); + } + } + + private void delete_local_database() { + boolean deleted = true; + try { + File datadbfile = Environment.getDataDirectory(); + String currentDBPath = "//data//" + BuildConfig.APPLICATION_ID + "//databases//" + Lorealba_Database.DATABASE_NAME; + File currentDB = new File(datadbfile, currentDBPath); + deleted = SQLiteDatabase.deleteDatabase(currentDB); + if (deleted) { + AlertandMessages.showToastMsg(context, "Database Deleted Successfully"); + } + new Lorealba_Database(context).open(); + } catch (Exception e) { + e.fillInStackTrace(); + } + + } + + + @Override + public void onConnected(Bundle bundle) { + if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { + // TODO: Consider calling + // ActivityCompat#requestPermissions + // here to request the missing permissions, and then overriding + // public void onRequestPermissionsResult(int requestCode, String[] permissions, + // int[] grantResults) + // to handle the case where the user grants the permission. See the documentation + // for ActivityCompat#requestPermissions for more details. + return; + } + mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); + if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED + || ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) { + if (mLastLocation != null) { + lat = mLastLocation.getLatitude(); + lon = mLastLocation.getLongitude(); + } + + startLocationUpdates(); + } + } + + @Override + public void onConnectionSuspended(int i) { + mGoogleApiClient.connect(); + } + + @Override + public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { + if (mGoogleApiClient != null) { + mGoogleApiClient.connect(); + } + } + + @Override + public void onLocationChanged(Location location) { + if (mGoogleApiClient != null) { + LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this); + } + + } + + protected void onStart() { + super.onStart(); + if (mGoogleApiClient != null) { + mGoogleApiClient.connect(); + } + } + + protected void startLocationUpdates() { + if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) { + if (mGoogleApiClient != null) { + LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this); + } + } + } + + void getViewId() { + context = this; + db = new Lorealba_Database(context); + db.open(); + preferences = PrefHelper.getPrefs(context); + counter_id = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + editor = preferences.edit(); + imei = new ImeiNumberClass(context); + if (checkAndRequestPermissions()) { + imeiNumbers = imei.getDeviceImei(); + getDeviceName(); + AttempLogin(); + } + + try { + app_ver = String.valueOf(getPackageManager().getPackageInfo(getPackageName(), 0).versionName); + } catch (PackageManager.NameNotFoundException e) { + // TODO Auto-generated catch block + e.fillInStackTrace(); + } + } + + @Override + public void onActivityResult(int requestCode, int resultCode, Intent data) { + super.onActivityResult(requestCode, resultCode, data); + switch (requestCode) { + case (LOGIN_AFTER_NOTIFICATION): { + if (resultCode == Activity.RESULT_OK) { + // TODO Extract the data returned from the child Activity. + getViewId(); + } + break; + } + } + } + + private boolean checkAndRequestPermissions() { + int CAMERA = ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA); + int ACCESS_NETWORK_STATE = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_NETWORK_STATE); + int ACCESS_COARSE_LOCATION = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION); + int locationPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION); + int READ_PHONE_STATE = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE); + List listPermissionsNeeded = new ArrayList<>(); + + if (CAMERA != PackageManager.PERMISSION_GRANTED) { + listPermissionsNeeded.add(Manifest.permission.CAMERA); + } + + if (ACCESS_NETWORK_STATE != PackageManager.PERMISSION_GRANTED) { + listPermissionsNeeded.add(Manifest.permission.ACCESS_NETWORK_STATE); + } + if (ACCESS_COARSE_LOCATION != PackageManager.PERMISSION_GRANTED) { + listPermissionsNeeded.add(Manifest.permission.ACCESS_COARSE_LOCATION); + } + if (locationPermission != PackageManager.PERMISSION_GRANTED) { + listPermissionsNeeded.add(Manifest.permission.ACCESS_FINE_LOCATION); + } + + if (READ_PHONE_STATE != PackageManager.PERMISSION_GRANTED) { + listPermissionsNeeded.add(Manifest.permission.READ_PHONE_STATE); + } + + + if (!listPermissionsNeeded.isEmpty()) { + ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), PERMISSION_ALL); + return false; + } + return true; + } + + private void showDialogOK(DialogInterface.OnClickListener okListener) { + new AlertDialog.Builder(this).setMessage("Location,File,Call and Camera Services Permission required for this app").setPositiveButton("OK", okListener).setNegativeButton("Cancel", okListener).create().show(); + } + @Override + public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) { + super.onRequestPermissionsResult(requestCode, permissions, grantResults); + Log.d("", "Permission callback called-------"); + if (requestCode == PERMISSION_ALL) { + Map perms = new HashMap<>(); + // Initialize the map with both permissions + perms.put(Manifest.permission.CAMERA, PackageManager.PERMISSION_GRANTED); + perms.put(Manifest.permission.ACCESS_NETWORK_STATE, PackageManager.PERMISSION_GRANTED); + perms.put(Manifest.permission.ACCESS_COARSE_LOCATION, PackageManager.PERMISSION_GRANTED); + perms.put(Manifest.permission.ACCESS_FINE_LOCATION, PackageManager.PERMISSION_GRANTED); + perms.put(Manifest.permission.READ_PHONE_STATE, PackageManager.PERMISSION_GRANTED); + // Fill with actual results from user + if (grantResults.length > 0) { + for (int i = 0; i < permissions.length; i++) + perms.put(permissions[i], grantResults[i]); + // Check for both permissions + boolean allPermissionsGranted = + Integer.valueOf(PackageManager.PERMISSION_GRANTED).equals(perms.get(Manifest.permission.CAMERA)) && + Integer.valueOf(PackageManager.PERMISSION_GRANTED).equals(perms.get(Manifest.permission.ACCESS_NETWORK_STATE)) && + Integer.valueOf(PackageManager.PERMISSION_GRANTED).equals(perms.get(Manifest.permission.ACCESS_COARSE_LOCATION)) && + Integer.valueOf(PackageManager.PERMISSION_GRANTED).equals(perms.get(Manifest.permission.ACCESS_FINE_LOCATION)) && + Integer.valueOf(PackageManager.PERMISSION_GRANTED).equals(perms.get(Manifest.permission.READ_PHONE_STATE)); + + if (allPermissionsGranted){ + getDeviceName(); + imeiNumbers = imei.getDeviceImei(); + AttempLogin(); + } + + Log.d("", "sms & location services permission granted"); + } else { + Log.d("", "Some permissions are not granted ask again "); + if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA) || + ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_NETWORK_STATE) || + ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_COARSE_LOCATION) || + ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION) || + ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_PHONE_STATE)) { + showDialogOK( + (dialog, which) -> { + switch (which) { + case DialogInterface.BUTTON_POSITIVE: + checkAndRequestPermissions(); + break; + case DialogInterface.BUTTON_NEGATIVE: + // proceed with logic by disabling the related features or quit the app. + Intent startMain = new Intent(Intent.ACTION_MAIN); + startMain.addCategory(Intent.CATEGORY_HOME); + startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + startActivity(startMain); + break; + } + }); + } else { + Toast.makeText(this, "Go to settings and enable permissions", Toast.LENGTH_LONG).show(); + } + } + } + } + + public class MultiPurposeDialog extends Dialog { + public MultiPurposeDialog(Context context) { + super(context); + WindowManager.LayoutParams wmLayoutParams = Objects.requireNonNull(getWindow()).getAttributes(); + wmLayoutParams.gravity = Gravity.CENTER; + getWindow().setAttributes(wmLayoutParams); + setTitle(null); + setCancelable(false); + setOnCancelListener(null); + LinearLayout layout = new LinearLayout(context); + layout.setOrientation(LinearLayout.VERTICAL); + } + } + + @Override + protected void onDestroy() { + super.onDestroy(); + try { + if (loading != null && loading.isShowing()) { + loading.dismiss(); + } + } catch (Exception e) { + e.fillInStackTrace(); + } + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/LorealBa.java b/app/src/main/java/com/cpm/lorealbaautomation/LorealBa.java new file mode 100644 index 0000000..afe8250 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/LorealBa.java @@ -0,0 +1,9 @@ +package com.cpm.lorealbaautomation; +import android.app.Application; + +public class LorealBa extends Application { + @Override + public void onCreate() { + super.onCreate(); + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/UserLoginActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/UserLoginActivity.java new file mode 100644 index 0000000..7c3da8f --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/UserLoginActivity.java @@ -0,0 +1,598 @@ +package com.cpm.lorealbaautomation; + +import android.Manifest; +import android.annotation.SuppressLint; +import android.app.Activity; +import android.app.AlertDialog; +import android.app.ProgressDialog; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.SharedPreferences; +import android.content.pm.PackageInfo; +import android.content.pm.PackageManager; +import android.os.Bundle; + +import com.google.firebase.messaging.FirebaseMessaging; +import com.cpm.lorealbaautomation.delegates.PrefHelper; + +import android.util.Log; +import android.view.View; +import android.view.Window; +import android.view.WindowManager; +import android.widget.Button; +import android.widget.EditText; +import android.widget.LinearLayout; +import android.widget.TextView; +import android.widget.Toast; + +import androidx.annotation.NonNull; +import androidx.appcompat.app.AppCompatActivity; +import androidx.appcompat.widget.Toolbar; +import androidx.core.app.ActivityCompat; +import androidx.core.content.ContextCompat; + +import com.google.gson.Gson; +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.constant.AlertandMessages; +import com.cpm.lorealbaautomation.constant.CommonFunctions; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.dailyactivity.NotificationDetailActivity; +import com.cpm.lorealbaautomation.dailyactivity.TabLoginActivity; +import com.cpm.lorealbaautomation.gettersetter.LoginGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.BaListGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.JCPGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.TableStructure; +import com.cpm.lorealbaautomation.gsonGetterSetter.TableStructureGetterSetter; +import com.cpm.lorealbaautomation.retrofit.DownloadAllDatawithRetro; +import com.cpm.lorealbaautomation.retrofit.PostApi; +import com.cpm.lorealbaautomation.retrofit.UploadDataWithRetrofit; + +import org.json.JSONException; +import org.json.JSONObject; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.TimeUnit; + +import okhttp3.MediaType; +import okhttp3.OkHttpClient; +import okhttp3.RequestBody; +import retrofit2.Call; +import retrofit2.Callback; +import retrofit2.Response; +import retrofit2.Retrofit; +import retrofit2.converter.gson.GsonConverterFactory; + +public class UserLoginActivity extends AppCompatActivity implements View.OnClickListener { + String counterId = "", visitdate = "", jsonString = "", result = "", counterName = "", counter_code = "", title = "", body = "", path = "", type; + SharedPreferences preferences; + private SharedPreferences.Editor editor = null; + private Context context; + LinearLayout lay_ba, lay_ma, lay_tba; + Button btncontinue; + String userId; + Lorealba_Database db; + int downloadindex = 0; + ProgressDialog loading = null; + ArrayList bsListData = new ArrayList<>(); + ArrayList allLoginListData = new ArrayList<>(); + EditText user_password; + String TAG = getClass().getSimpleName(); + JSONObject jsonObject = new JSONObject(); + TextView counter_name, versioncode_txt; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + requestWindowFeature(Window.FEATURE_NO_TITLE); + getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); + setContentView(R.layout.activity_user_login); + getViewId(); + + FirebaseMessaging.getInstance().getToken() + .addOnCompleteListener(task -> { + if (!task.isSuccessful()) { + Log.w(TAG, "Fetching FCM registration token failed", task.getException()); + return; + } + + // Get new FCM registration token + String token = task.getResult(); + try { + jsonObject.put("CounterId", counterId); + jsonObject.put("RegistrationId", token); + jsonString = jsonObject.toString(); + UploadDataWithRetrofit upload = new UploadDataWithRetrofit(context); + result = upload.uploadDeviceTokenDetails(jsonString, CommonString.UPLOAD_DEVICE_TOKEN_DETAILS); + } catch (JSONException e) { + e.fillInStackTrace(); + } + + // Log and toast + //test(TAG, "Token: " + token); + }); + + + } + + + @SuppressLint("SetTextI18n") + void getViewId() { + context = this; + db = new Lorealba_Database(context); + db.open(); + preferences = PrefHelper.getPrefs(context); + editor = preferences.edit(); + Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); + lay_ba = (LinearLayout) findViewById(R.id.lay_ba); + lay_ma = (LinearLayout) findViewById(R.id.lay_ma); + lay_tba = (LinearLayout) findViewById(R.id.lay_tba); + btncontinue = (Button) findViewById(R.id.btncontinue); + + user_password = (EditText) findViewById(R.id.user_password); + counter_name = (TextView) findViewById(R.id.counter_name); + versioncode_txt = (TextView) findViewById(R.id.versioncode_txt); + setSupportActionBar(toolbar); + Objects.requireNonNull(getSupportActionBar()).setHomeButtonEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + setTitle(getString(R.string.user_login)); + + counterId = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + counter_code = preferences.getString(CommonString.KEY_COUNTER_CODE, ""); + counterName = preferences.getString(CommonString.KEY_COUNTER_NAME, ""); + visitdate = preferences.getString(CommonString.KEY_DATE, ""); + counter_name.setText("Counter Name : " + counterName + "\n" + "Counter Code : " + counter_code); + lay_ba.setOnClickListener(this); + lay_ma.setOnClickListener(this); + lay_tba.setOnClickListener(this); + btncontinue.setOnClickListener(this); + checkAndRequestPermissions(); + + bsListData = db.getBAListAllData(visitdate, counterId); + if (bsListData.size() == 0) { + UploadDataTask(); + } + + if (getIntent().getExtras() != null) { + for (String key : getIntent().getExtras().keySet()) { + if (key.equalsIgnoreCase("title")) { + title = getIntent().getExtras().getString(key); + } else if (key.equalsIgnoreCase("body")) { + body = getIntent().getExtras().getString(key); + } else if (key.equalsIgnoreCase("path")) { + path = getIntent().getExtras().getString(key); + } else if (key.equalsIgnoreCase("type")) { + type = getIntent().getExtras().getString(key); + } + } + + assert title != null; + assert body != null; + if (!title.equalsIgnoreCase("") && !body.equalsIgnoreCase("")) { + db.open(); + long value = db.insertNotificationData(title, body, path, visitdate, type, counterId); + if (value > 0) { + Toast.makeText(context, "Notification Inserted", Toast.LENGTH_SHORT).show(); + } else { + Toast.makeText(context, "Notification Not Inserted", Toast.LENGTH_SHORT).show(); + } + } + + if (!title.equals("")) { + Intent in = new Intent(this, NotificationDetailActivity.class); + in.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); + in.putExtra("Type", type); + in.putExtra("Title", title); + in.putExtra("Body", body); + in.putExtra("Path", path); + startActivity(in); + } + } + } + + @SuppressLint("NonConstantResourceId") + @Override + public void onClick(View v) { + if (v.getId() == R.id.lay_ba) { + db.open(); + if (db.getBAListAllData(visitdate, counterId).size() > 0) { + editor.putString(CommonString.TAG_FROM, CommonString.TAG_FROM_BA); + editor.putString(CommonString.TAG_MODE, CommonString.MODE_FROM_BA_LOGIN); + editor.putString(CommonString.KEY_USER_TYPE, CommonString.TAG_FROM_BA); + editor.commit(); + + Intent balogin = new Intent(context, TabLoginActivity.class); + balogin.putExtra(CommonString.TAG_FROM, CommonString.TAG_FROM_BA); + balogin.putExtra(CommonString.TAG_MODE, CommonString.MODE_FROM_BA_LOGIN); + startActivity(balogin); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + } else { + DownloadData(CommonString.TAG_FROM_BA); + } + + } else if (v.getId() == R.id.lay_ma) { + db.open(); + if (db.getBAListAllData(visitdate, counterId).size() > 0) { + editor.putString(CommonString.TAG_FROM, CommonString.TAG_FROM_ME); + editor.putString(CommonString.TAG_MODE, CommonString.MODE_FROM_ME_LOGIN); + editor.putString(CommonString.KEY_USER_TYPE, CommonString.TAG_FROM_ME); + editor.commit(); + Intent malogin = new Intent(context, TabLoginActivity.class); + malogin.putExtra(CommonString.TAG_FROM, CommonString.TAG_FROM_ME); + malogin.putExtra(CommonString.TAG_MODE, CommonString.MODE_FROM_ME_LOGIN); + startActivity(malogin); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + } else { + DownloadData(CommonString.TAG_FROM_ME); + } + + + } else if (v.getId() == R.id.lay_tba) { + db.open(); + if (db.getBAListAllData(visitdate, counterId).size() > 0) { + editor.putString(CommonString.TAG_FROM, CommonString.TAG_FROM_TBA); + editor.putString(CommonString.TAG_MODE, CommonString.MODE_FROM_TBA_LOGIN); + editor.putString(CommonString.KEY_USER_TYPE, CommonString.TAG_FROM_TBA); + editor.commit(); + + Intent tbalogin = new Intent(context, TabLoginActivity.class); + tbalogin.putExtra(CommonString.TAG_FROM, CommonString.TAG_FROM_TBA); + tbalogin.putExtra(CommonString.TAG_MODE, CommonString.MODE_FROM_TBA_LOGIN); + startActivity(tbalogin); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + + } else { + DownloadData(CommonString.TAG_FROM_TBA); + } + + } + } + + public void UploadDataTask() { + try { + ArrayList keysList = new ArrayList<>(); + ArrayList jsonList = new ArrayList<>(); + ArrayList KeyNames = new ArrayList<>(); + keysList.add("Table_Structure"); + keysList.add("BA_List"); + keysList.add("Mapping_JourneyPlan"); + keysList.size(); + for (int i = 0; i < keysList.size(); i++) { + JSONObject jsonObject = new JSONObject(); + jsonObject.put("Downloadtype", keysList.get(i)); + jsonObject.put("Username", ""); + jsonObject.put("Param1", counterId); + jsonObject.put("Param2", ""); + jsonList.add(jsonObject.toString()); + KeyNames.add(keysList.get(i)); + } + if (jsonList.size() > 0) { + ProgressDialog pd = new ProgressDialog(context); + DownloadAllDatawithRetro downloadData = new DownloadAllDatawithRetro(context, db, pd, CommonString.TAG_FROM_CURRENT); + downloadData.listSize = jsonList.size(); + downloadData.downloadDataUniversalBa(jsonList, KeyNames, downloadindex, CommonString.DOWNLOAD_ALL_SERVICE); + } + + } catch (Exception e) { + e.fillInStackTrace(); + } + } + + + @SuppressLint("SetTextI18n") + @Override + protected void onResume() { + super.onResume(); + db.open(); + allLoginListData = db.getlistAllData(visitdate, userId); + checkAndRequestPermissions(); + try { + PackageInfo pInfo = context.getPackageManager().getPackageInfo(getPackageName(), 0); + String version = pInfo.versionName; + versioncode_txt.setText("Version : " + version); + } catch (PackageManager.NameNotFoundException e) { + e.fillInStackTrace(); + versioncode_txt.setText("Version : 0.0"); + } + } + + + private boolean checkAndRequestPermissions() { + int CAMERA = ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA); + int ACCESS_NETWORK_STATE = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_NETWORK_STATE); + int ACCESS_COARSE_LOCATION = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION); + int locationPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION); + int READ_PHONE_STATE = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE); + List listPermissionsNeeded = new ArrayList<>(); + + if (CAMERA != PackageManager.PERMISSION_GRANTED) { + listPermissionsNeeded.add(Manifest.permission.CAMERA); + } + + if (ACCESS_NETWORK_STATE != PackageManager.PERMISSION_GRANTED) { + listPermissionsNeeded.add(Manifest.permission.ACCESS_NETWORK_STATE); + } + if (ACCESS_COARSE_LOCATION != PackageManager.PERMISSION_GRANTED) { + listPermissionsNeeded.add(Manifest.permission.ACCESS_COARSE_LOCATION); + } + if (locationPermission != PackageManager.PERMISSION_GRANTED) { + listPermissionsNeeded.add(Manifest.permission.ACCESS_FINE_LOCATION); + } + + if (READ_PHONE_STATE != PackageManager.PERMISSION_GRANTED) { + listPermissionsNeeded.add(Manifest.permission.READ_PHONE_STATE); + } + + + if (!listPermissionsNeeded.isEmpty()) { + ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), CommonString.PERMISSION_ALL); + return false; + } + + return true; + } + + private void showDialogOK(String message, DialogInterface.OnClickListener okListener) { + new AlertDialog.Builder(this).setMessage(message).setPositiveButton("OK", okListener).setNegativeButton("Cancel", okListener).create().show(); + } + + @Override + public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) { + super.onRequestPermissionsResult(requestCode, permissions, grantResults); + //test("", "Permission callback called-------"); + switch (requestCode) { + case CommonString.PERMISSION_ALL: { + Map perms = new HashMap<>(); + // Initialize the map with both permissions + perms.put(Manifest.permission.CAMERA, PackageManager.PERMISSION_GRANTED); + perms.put(Manifest.permission.ACCESS_NETWORK_STATE, PackageManager.PERMISSION_GRANTED); + perms.put(Manifest.permission.ACCESS_COARSE_LOCATION, PackageManager.PERMISSION_GRANTED); + perms.put(Manifest.permission.ACCESS_FINE_LOCATION, PackageManager.PERMISSION_GRANTED); + perms.put(Manifest.permission.READ_PHONE_STATE, PackageManager.PERMISSION_GRANTED); + // Fill with actual results from user + if (grantResults.length > 0) { + for (int i = 0; i < permissions.length; i++) + perms.put(permissions[i], grantResults[i]); + // Check for both permissions + boolean allPermissionsGranted = + Integer.valueOf(PackageManager.PERMISSION_GRANTED).equals(perms.get(Manifest.permission.CAMERA)) && + Integer.valueOf(PackageManager.PERMISSION_GRANTED).equals(perms.get(Manifest.permission.ACCESS_NETWORK_STATE)) && + Integer.valueOf(PackageManager.PERMISSION_GRANTED).equals(perms.get(Manifest.permission.ACCESS_COARSE_LOCATION)) && + Integer.valueOf(PackageManager.PERMISSION_GRANTED).equals(perms.get(Manifest.permission.ACCESS_FINE_LOCATION)) && + Integer.valueOf(PackageManager.PERMISSION_GRANTED).equals(perms.get(Manifest.permission.READ_PHONE_STATE)); + if (allPermissionsGranted) { + + } + } else { + //test("", "Some permissions are not granted ask again "); + if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA) || + ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_NETWORK_STATE) || + ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_COARSE_LOCATION) || + ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION) || + ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_PHONE_STATE)) { + showDialogOK("Location,File,Call and Camera Services Permission required for this app", (dialog, which) -> { + switch (which) { + case DialogInterface.BUTTON_POSITIVE: + checkAndRequestPermissions(); + break; + case DialogInterface.BUTTON_NEGATIVE: + // proceed with logic by disabling the related features or quit the app. + Intent startMain = new Intent(Intent.ACTION_MAIN); + startMain.addCategory(Intent.CATEGORY_HOME); + startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + startActivity(startMain); + break; + } + }); + } + //permission is denied (and never ask again is checked) + //shouldShowRequestPermissionRationale will return false + else { + Toast.makeText(this, "Go to settings and enable permissions", Toast.LENGTH_LONG).show(); + // //proceed with logic by disabling the related features or quit the app. + } + } + } + } + } + + public void DownloadData(String userType) { + try { + if (CommonFunctions.checkNetIsAvailable(context)) { + ArrayList keysList = new ArrayList<>(); + ArrayList jsonList = new ArrayList<>(); + ArrayList KeyNames = new ArrayList<>(); + keysList.add("Table_Structure"); + keysList.add("BA_List"); + keysList.add("Mapping_JourneyPlan"); + keysList.size(); + for (int i = 0; i < keysList.size(); i++) { + JSONObject jsonObject = new JSONObject(); + jsonObject.put("Downloadtype", keysList.get(i)); + jsonObject.put("Username", ""); + jsonObject.put("Param1", counterId); + jsonObject.put("Param2", ""); + jsonList.add(jsonObject.toString()); + KeyNames.add(keysList.get(i)); + } + + if (jsonList.size() > 0) { + loading = ProgressDialog.show(context, "Downloading", "Please wait...", false, true); + downloadBaList(context, jsonList, KeyNames, downloadindex, userType, loading); + } + + } else { + AlertandMessages.showToastMsg(context, getString(R.string.nonetwork)); + } + } catch (Exception e) { + e.fillInStackTrace(); + } + } + + public void downloadBaList(final Context context, final ArrayList jsonStringList, final ArrayList KeyNames, int downloadindex, final String userType, final ProgressDialog loading) { + final String[] data_global = {""}; + String jsonString = "", KeyName = ""; + int jsonIndex = 0; + if (jsonStringList.size() > 0) { + OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, + TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build(); + jsonString = jsonStringList.get(downloadindex); + KeyName = KeyNames.get(downloadindex); + jsonIndex = downloadindex; + + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsonString); + Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build(); + PostApi api = adapter.create(PostApi.class); + Call call = api.getDownloadAll(jsonData); + final int[] finalJsonIndex = {jsonIndex}; + final String finalKeyName = KeyName; + + call.enqueue(new Callback() { + @Override + public void onResponse(@NonNull Call call, @NonNull Response response) { + String responseBody = response.body(); + String data = null; + if (responseBody != null && response.isSuccessful()) { + try { + data = response.body(); + if (data.equals("")) { + data_global[0] = ""; + } else { + data_global[0] = data; + if (finalKeyName.equalsIgnoreCase("Table_Structure")) { + TableStructureGetterSetter tableStructureObj = new Gson().fromJson(data, TableStructureGetterSetter.class); + String isAllTableCreated = createTable(tableStructureObj); + + if (isAllTableCreated != CommonString.KEY_SUCCESS) { + loading.dismiss(); + if (loading != null && loading.isShowing()) { + loading.dismiss(); + } + + AlertandMessages.showAlert((Activity) context, isAllTableCreated + " not created", true); + } + } else { + switch (finalKeyName) { + case "BA_List": + if (!data.contains("No Data")) { + JCPGetterSetter baListObject = new Gson().fromJson(data, JCPGetterSetter.class); + if (baListObject != null && !db.insertBalistData(baListObject)) { + AlertandMessages.showToastMsg(context, "Ba List data not saved"); + } + } else { + throw new Exception(); + } + + break; + + case "Mapping_JourneyPlan": + if (!data.contains("No Data")) { + JCPGetterSetter jcpObject = new Gson().fromJson(data, JCPGetterSetter.class); + if (jcpObject != null && !db.insertJCPData(jcpObject)) { + AlertandMessages.showToastMsg(context, "JCP data not saved"); + } + } + + break; + } + } + } + + finalJsonIndex[0]++; + if (finalJsonIndex[0] != KeyNames.size()) { + downloadBaList(context, jsonStringList, KeyNames, finalJsonIndex[0], userType, loading); + } else { + loading.dismiss(); + + if (loading != null && loading.isShowing()) { + loading.dismiss(); + } + + AlertandMessages.showToastMsg(context, "BA List data downloaded Successfully"); + + if (userType.equalsIgnoreCase(CommonString.TAG_FROM_BA)) { + editor.putString(CommonString.TAG_FROM, CommonString.TAG_FROM_BA); + editor.putString(CommonString.TAG_MODE, CommonString.MODE_FROM_BA_LOGIN); + editor.putString(CommonString.KEY_USER_TYPE, CommonString.TAG_FROM_BA); + editor.commit(); + + Intent balogin = new Intent(context, TabLoginActivity.class); + balogin.putExtra(CommonString.TAG_FROM, CommonString.TAG_FROM_BA); + balogin.putExtra(CommonString.TAG_MODE, CommonString.MODE_FROM_BA_LOGIN); + startActivity(balogin); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + } else if (userType.equalsIgnoreCase(CommonString.TAG_FROM_ME)) { + + editor.putString(CommonString.TAG_FROM, CommonString.TAG_FROM_ME); + editor.putString(CommonString.TAG_MODE, CommonString.MODE_FROM_ME_LOGIN); + editor.putString(CommonString.KEY_USER_TYPE, CommonString.TAG_FROM_ME); + editor.commit(); + + Intent malogin = new Intent(context, TabLoginActivity.class); + malogin.putExtra(CommonString.TAG_FROM, CommonString.TAG_FROM_ME); + malogin.putExtra(CommonString.TAG_MODE, CommonString.MODE_FROM_ME_LOGIN); + startActivity(malogin); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + } else if (userType.equalsIgnoreCase(CommonString.TAG_FROM_TBA)) { + + editor.putString(CommonString.TAG_FROM, CommonString.TAG_FROM_TBA); + editor.putString(CommonString.TAG_MODE, CommonString.MODE_FROM_TBA_LOGIN); + editor.putString(CommonString.KEY_USER_TYPE, CommonString.TAG_FROM_TBA); + editor.commit(); + + Intent tbalogin = new Intent(context, TabLoginActivity.class); + tbalogin.putExtra(CommonString.TAG_FROM, CommonString.TAG_FROM_TBA); + tbalogin.putExtra(CommonString.TAG_MODE, CommonString.MODE_FROM_TBA_LOGIN); + startActivity(tbalogin); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + } + } + + } catch (Exception e) { + e.fillInStackTrace(); + loading.dismiss(); + + if (loading != null && loading.isShowing()) { + loading.dismiss(); + } + + AlertandMessages.showToastMsg(context, "Ba List Data Not Found. Please Contact To Supervisor"); + + } + } else { + loading.dismiss(); + if (loading != null && loading.isShowing()) { + loading.dismiss(); + } + AlertandMessages.showAlertlogin((Activity) context, CommonString.MESSAGE_NO_RESPONSE_SERVER); + } + } + + @Override + public void onFailure(@NonNull Call call, @NonNull Throwable t) { + loading.dismiss(); + if (loading != null && loading.isShowing()) { + loading.dismiss(); + } + + AlertandMessages.showAlertlogin((Activity) context, CommonString.MESSAGE_SOCKETEXCEPTION); + } + }); + } + } + + String createTable(TableStructureGetterSetter tableGetSet) { + List tableList = tableGetSet.getTableStructure(); + for (int i = 0; i < tableList.size(); i++) { + String table = tableList.get(i).getSqlText(); + if (db.createtable(table) == 0) { + return table; + } + } + return CommonString.KEY_SUCCESS; + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/adapter/ApprovedLeaveAdapter.java b/app/src/main/java/com/cpm/lorealbaautomation/adapter/ApprovedLeaveAdapter.java new file mode 100644 index 0000000..db6dbae --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/adapter/ApprovedLeaveAdapter.java @@ -0,0 +1,90 @@ +package com.cpm.lorealbaautomation.adapter; + +import android.annotation.SuppressLint; +import android.content.Context; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.TextView; +import androidx.annotation.NonNull; +import androidx.appcompat.widget.LinearLayoutCompat; +import androidx.cardview.widget.CardView; +import androidx.recyclerview.widget.RecyclerView; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.constant.CommonFunctions; +import com.cpm.lorealbaautomation.gsonGetterSetter.leaves.TLeaveRequestDetail; +import java.util.List; + +public class ApprovedLeaveAdapter extends RecyclerView.Adapter { + LayoutInflater inflator; + String type; + List data; + + public ApprovedLeaveAdapter(Context context, String type, List data) { + inflator = LayoutInflater.from(context); + this.data = data; + this.type = type; + } + + @NonNull + @Override + public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) { + View view = inflator.inflate(type.equals("GovtHolidays") ? R.layout.item_gov_holidays : R.layout.item_approved_leaves, parent, false); + return new MyViewHolder(view); + } + + @SuppressLint({"NotifyDataSetChanged", "SetTextI18n"}) + @Override + public void onBindViewHolder(@NonNull final MyViewHolder holder, final int position) { + final TLeaveRequestDetail current = data.get(position); + if (type.equals("GovtHolidays")) { + holder.titleTV.setText(current.getLeaveType()); + holder.descTV.setText(current.getReason()); + } else { + String day = current.getDay().toString().length() == 1 ? "0" + current.getDay().toString() : current.getDay().toString(); + String month = current.getMonth().toString().length() == 1 ? "0" + current.getMonth().toString() : current.getMonth().toString(); + holder.dateTV.setText(CommonFunctions.formatDate(month + "/" + day + "/" + current.getYear().toString())); + + + if (!current.getApprovedStatus().isEmpty() && current.getApprovedStatus().equalsIgnoreCase("Pending")) { + holder.pendingCardView.setVisibility(View.VISIBLE); + holder.rejectCardView.setVisibility(View.GONE); + holder.approveCardView.setVisibility(View.GONE); + } else if (!current.getApprovedStatus().isEmpty() && current.getApprovedStatus().equalsIgnoreCase("Reject")) { + holder.pendingCardView.setVisibility(View.GONE); + holder.rejectCardView.setVisibility(View.VISIBLE); + holder.approveCardView.setVisibility(View.GONE); + } else { + holder.pendingCardView.setVisibility(View.GONE); + holder.rejectCardView.setVisibility(View.GONE); + holder.approveCardView.setVisibility(View.VISIBLE); + } + + holder.titleTV.setText(current.getLeaveSubType() != null && !current.getLeaveSubType().isEmpty() ? current.getLeaveType() + " - " + current.getLeaveSubType() : current.getLeaveType()); + holder.descTV.setText(current.getReason()); + } + } + + @Override + public int getItemCount() { + return data.size(); + } + + class MyViewHolder extends RecyclerView.ViewHolder { + LinearLayoutCompat rlParent; + TextView dateTV, titleTV, descTV; + CardView approveCardView, pendingCardView, rejectCardView; + + public MyViewHolder(View itemView) { + super(itemView); + rlParent = (LinearLayoutCompat) itemView.findViewById(R.id.rlParent); + dateTV = (TextView) itemView.findViewById(R.id.dateTV); + titleTV = (TextView) itemView.findViewById(R.id.titleTV); + descTV = (TextView) itemView.findViewById(R.id.descTV); + approveCardView = (CardView) itemView.findViewById(R.id.approveCardView); + pendingCardView = (CardView) itemView.findViewById(R.id.pendingCardView); + rejectCardView = (CardView) itemView.findViewById(R.id.rejectCardView); + } + } +} + diff --git a/app/src/main/java/com/cpm/lorealbaautomation/adapter/InvoiceTypeSpinnerAdapter.java b/app/src/main/java/com/cpm/lorealbaautomation/adapter/InvoiceTypeSpinnerAdapter.java new file mode 100644 index 0000000..035a01a --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/adapter/InvoiceTypeSpinnerAdapter.java @@ -0,0 +1,55 @@ +package com.cpm.lorealbaautomation.adapter; + +import android.annotation.SuppressLint; +import android.content.Context; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.ArrayAdapter; +import android.widget.TextView; +import androidx.annotation.NonNull; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterInvoiceType; +import java.util.ArrayList; +import java.util.List; + + +public class InvoiceTypeSpinnerAdapter extends ArrayAdapter { + List list; + Context context; + int resourceId; + + public InvoiceTypeSpinnerAdapter(Context context, int resourceId, ArrayList list) { + super(context, resourceId, list); + this.context = context; + this.list = list; + this.resourceId = resourceId; + } + + @SuppressLint("ViewHolder") + @NonNull + @Override + public View getView(int position, View convertView, @NonNull ViewGroup parent) { + View view = convertView; + LayoutInflater inflater =(LayoutInflater.from(context)); + view = inflater.inflate(resourceId, parent, false); + MasterInvoiceType cm = list.get(position); + TextView txt_spinner = (TextView) view.findViewById(R.id.txt_sp_text); + txt_spinner.setText(list.get(position).getInvoiceType()); + + return view; + } + + @Override + public View getDropDownView(int position, View convertView, @NonNull ViewGroup parent) { + View view = convertView; + LayoutInflater inflater = (LayoutInflater.from(context)); + view = inflater.inflate(resourceId, parent, false); + MasterInvoiceType cm = list.get(position); + TextView txt_spinner = (TextView) view.findViewById(R.id.txt_sp_text); + txt_spinner.setText(cm.getInvoiceType()); + + return view; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/adapter/InwardStkDetailAdapter.java b/app/src/main/java/com/cpm/lorealbaautomation/adapter/InwardStkDetailAdapter.java new file mode 100644 index 0000000..231d85f --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/adapter/InwardStkDetailAdapter.java @@ -0,0 +1,73 @@ +package com.cpm.lorealbaautomation.adapter; + +import android.annotation.SuppressLint; +import android.content.Context; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.TextView; + +import androidx.annotation.NonNull; +import androidx.core.content.ContextCompat; +import androidx.recyclerview.widget.RecyclerView; + +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.gsonGetterSetter.inwordDetail.ReportCounterInwardStockDetail; + +import java.util.List; + +public class InwardStkDetailAdapter extends RecyclerView.Adapter { + LayoutInflater inflator; + List data; + + public InwardStkDetailAdapter(Context context, List data) { + inflator = LayoutInflater.from(context); + this.data = data; + } + + @NonNull + @Override + public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) { + View view = inflator.inflate(R.layout.row_counter_inward_details, parent, false); + return new MyViewHolder(view); + } + + @SuppressLint({"SetTextI18n", "DefaultLocale"}) + @Override + public void onBindViewHolder(@NonNull final MyViewHolder holder, final int position) { + final ReportCounterInwardStockDetail current = data.get(position); + setText(holder.tvParamCode, position, current.getParamCode(), inflator.getContext()); + setText(holder.tvParamName, position, current.getParamName(), inflator.getContext()); + + setText(holder.tvInvoiceQty, position, current.getInvoiceQty() != null ? current.getInvoiceQty().toString() : "0", inflator.getContext()); + setText(holder.tvActualQty, position, current.getActualQty() != null ? current.getActualQty().toString() : "0", inflator.getContext()); + setText(holder.tvDamageQty, position, current.getDamageQty() != null ? current.getDamageQty().toString() : "0", inflator.getContext()); + setText(holder.tvMissedQty, position, current.getMissedQty() != null ? current.getMissedQty().toString() : "0", inflator.getContext()); + } + + @Override + public int getItemCount() { + return data.size(); + } + + class MyViewHolder extends RecyclerView.ViewHolder { + TextView tvInvoiceQty, tvActualQty, tvDamageQty,tvMissedQty, tvParamCode, tvParamName; + + public MyViewHolder(View itemView) { + super(itemView); + tvMissedQty = (TextView) itemView.findViewById(R.id.tvMissedQty); + tvInvoiceQty = (TextView) itemView.findViewById(R.id.tvInvoiceQty); + tvActualQty = (TextView) itemView.findViewById(R.id.tvActualQty); + tvDamageQty = (TextView) itemView.findViewById(R.id.tvDamageQty); + tvParamCode = (TextView) itemView.findViewById(R.id.tvParamCode); + tvParamName = (TextView) itemView.findViewById(R.id.tvParamName); + } + } + + @SuppressLint("DefaultLocale") + private void setText(TextView tv, int pos, String value, Context context) { + tv.setTextColor(ContextCompat.getColor(context, R.color.black)); + tv.setText(value); + tv.setId(pos); + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/adapter/LeaveDetailAdapter.java b/app/src/main/java/com/cpm/lorealbaautomation/adapter/LeaveDetailAdapter.java new file mode 100644 index 0000000..e4cc86d --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/adapter/LeaveDetailAdapter.java @@ -0,0 +1,82 @@ +package com.cpm.lorealbaautomation.adapter; + +import android.annotation.SuppressLint; +import android.content.Context; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.LinearLayout; +import android.widget.TextView; + +import androidx.annotation.NonNull; +import androidx.core.content.ContextCompat; +import androidx.recyclerview.widget.RecyclerView; + +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.constant.CommonFunctions; +import com.cpm.lorealbaautomation.tbaleavemodel.TBAMELeaveHistory; + +import java.util.List; + +public class LeaveDetailAdapter extends RecyclerView.Adapter { + LayoutInflater inflator; + List data; + + public LeaveDetailAdapter(Context context, List data) { + inflator = LayoutInflater.from(context); + this.data = data; + } + + @NonNull + @Override + public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) { + View view = inflator.inflate(R.layout.item_leave_details, parent, false); + return new MyViewHolder(view); + } + + @SuppressLint({"NotifyDataSetChanged", "SetTextI18n"}) + @Override + public void onBindViewHolder(@NonNull final MyViewHolder holder, final int position) { + final TBAMELeaveHistory current = data.get(position); + if (position % 2 == 0) { + holder.rlLeaveDetail.setBackgroundColor(ContextCompat.getColor(inflator.getContext(), R.color.white)); + } else { + holder.rlLeaveDetail.setBackgroundColor(ContextCompat.getColor(inflator.getContext(), R.color.gray)); + } + if (CommonFunctions.isTablet(inflator.getContext())) { + holder.tvDatefromTo.setText(current.getFromDate() + " - " + current.getToDate()); + } else { + holder.tvDatefromTo.setText(current.getFromDate() + "\n" + current.getToDate()); + } + + holder.tvDatefromTo.setId(position); + holder.tvLeaveType.setText(current.getLeaveType()); + holder.tvLeaveType.setId(position); + holder.tvNoOfDays.setText(current.getNoOfDays() != null ? current.getNoOfDays().toString() : "0"); + holder.tvNoOfDays.setId(position); + holder.tvStatus.setText(current.getApprovedStatus()); + holder.tvStatus.setId(position); + holder.tvRemark.setText(current.getRejectRemark()); + holder.tvRemark.setId(position); + } + + @Override + public int getItemCount() { + return data.size(); + } + + class MyViewHolder extends RecyclerView.ViewHolder { + LinearLayout rlLeaveDetail; + TextView tvDatefromTo, tvLeaveType, tvNoOfDays, tvStatus, tvRemark; + + public MyViewHolder(View itemView) { + super(itemView); + rlLeaveDetail = (LinearLayout) itemView.findViewById(R.id.rlLeaveDetail); + tvDatefromTo = (TextView) itemView.findViewById(R.id.tvDatefromTo); + tvLeaveType = (TextView) itemView.findViewById(R.id.tvLeaveType); + tvNoOfDays = (TextView) itemView.findViewById(R.id.tvNoOfDays); + tvStatus = (TextView) itemView.findViewById(R.id.tvStatus); + tvRemark = (TextView) itemView.findViewById(R.id.tvRemark); + } + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/adapter/MyPager.java b/app/src/main/java/com/cpm/lorealbaautomation/adapter/MyPager.java new file mode 100644 index 0000000..fc4e681 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/adapter/MyPager.java @@ -0,0 +1,105 @@ +package com.cpm.lorealbaautomation.adapter; + +import android.content.Context; +import android.content.Intent; +import android.content.res.Configuration; +import android.graphics.Bitmap; +import android.graphics.BitmapFactory; + +import androidx.annotation.NonNull; +import androidx.viewpager.widget.PagerAdapter; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.ImageView; + +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterPromoOffer; +import com.cpm.lorealbaautomation.promooffer.PromoOfferDetailsActivity; + +import java.io.File; +import java.util.ArrayList; + +public class MyPager extends PagerAdapter { + Context context; + ArrayList list; + + public MyPager(Context context, ArrayList list) { + this.context = context; + this.list = list; + } + + /* + This callback is responsible for creating a page. We inflate the layout and set the drawable + to the ImageView based on the position. In the end we add the inflated layout to the parent + container .This method returns an object key to identify the page view, but in this example page view + itself acts as the object key + */ + @NonNull + @Override + public Object instantiateItem(@NonNull ViewGroup container, int position) { + View view = LayoutInflater.from(context).inflate(R.layout.linear_layout, null); + ImageView imageView = view.findViewById(R.id.image); + final MasterPromoOffer object = list.get(position); + + if (object.getPromoId()!=null && !object.getPromoId().isEmpty() && object.getPromoId().equalsIgnoreCase("No Data")){ + imageView.setImageResource(R.mipmap.no_promo_banner); + }else { + if (isTablet(context)) { + String path = CommonString.getPromosFolder(context) + object.getPromoOfferTab(); + File dir = new File(path); + if (dir.exists()) { + Bitmap myBitmap = BitmapFactory.decodeFile(dir.getAbsolutePath()); + imageView.setImageBitmap(myBitmap); + } + } else { + String path = CommonString.getPromosFolder(context) + object.getPromoOfferMobile(); + File dir = new File(path); + if (dir.exists()) { + Bitmap myBitmap = BitmapFactory.decodeFile(dir.getAbsolutePath()); + imageView.setImageBitmap(myBitmap); + } + } + + + imageView.setOnClickListener(view1 -> context.startActivity(new Intent(context, PromoOfferDetailsActivity.class) + .putExtra(CommonString.KEY_PROMO_ID,object.getPromoId()))); + } + + container.addView(view); + return view; + } + + /* + This callback is responsible for destroying a page. Since we are using view only as the + object key we just directly remove the view from parent container + */ + @Override + public void destroyItem(ViewGroup container, int position, @NonNull Object view) { + container.removeView((View) view); + } + + /* + Returns the count of the total pages + */ + @Override + public int getCount() { + return list.size(); + } + + /* + Used to determine whether the page view is associated with object key returned by instantiateItem. + Since here view only is the key we return view==object + */ + @Override + public boolean isViewFromObject(@NonNull View view, @NonNull Object object) { + return object == view; + } + + public boolean isTablet(Context context) { + boolean xlarge = ((context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == 4); + boolean large = ((context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE); + return (xlarge || large); + } +} \ No newline at end of file diff --git a/app/src/main/java/com/cpm/lorealbaautomation/adapter/ReasonSpinnerAdapter.java b/app/src/main/java/com/cpm/lorealbaautomation/adapter/ReasonSpinnerAdapter.java new file mode 100644 index 0000000..d64ceaa --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/adapter/ReasonSpinnerAdapter.java @@ -0,0 +1,59 @@ +package com.cpm.lorealbaautomation.adapter; + +import android.annotation.SuppressLint; +import android.content.Context; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.ArrayAdapter; +import android.widget.TextView; +import androidx.annotation.NonNull; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterNonStockReason; +import java.util.ArrayList; +import java.util.List; + + +public class ReasonSpinnerAdapter extends ArrayAdapter { + List list; + Context context; + int resourceId; + + public ReasonSpinnerAdapter(Context context, int resourceId, ArrayList list) { + super(context, resourceId, list); + this.context = context; + this.list = list; + this.resourceId = resourceId; + } + + @SuppressLint("ViewHolder") + @NonNull + @Override + public View getView(int position, View convertView, @NonNull ViewGroup parent) { + View view = convertView; + LayoutInflater inflater = (LayoutInflater.from(context)); + view = inflater.inflate(resourceId, parent, false); + MasterNonStockReason cm = null; + if (position < list.size()) cm = list.get(position); + TextView txt_spinner = (TextView) view.findViewById(R.id.txt_sp_text); + if (cm != null && cm.getReason() != null) { + txt_spinner.setText(cm.getReason()); + } + + return view; + } + + @Override + public View getDropDownView(int position, View convertView, @NonNull ViewGroup parent) { + View view = convertView; + LayoutInflater inflater = (LayoutInflater.from(context)); + view = inflater.inflate(resourceId, parent, false); + MasterNonStockReason cm = null; + if (position < list.size()) cm = list.get(position); + TextView txt_spinner = (TextView) view.findViewById(R.id.txt_sp_text); + if (cm != null && cm.getReason() != null) { + txt_spinner.setText(cm.getReason()); + } + return view; + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/adapter/SubAxeValueAdapter.java b/app/src/main/java/com/cpm/lorealbaautomation/adapter/SubAxeValueAdapter.java new file mode 100644 index 0000000..8f889a7 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/adapter/SubAxeValueAdapter.java @@ -0,0 +1,128 @@ +package com.cpm.lorealbaautomation.adapter; + +import android.annotation.SuppressLint; +import android.content.Context; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.TextView; + +import androidx.annotation.NonNull; +import androidx.cardview.widget.CardView; +import androidx.recyclerview.widget.RecyclerView; + +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.constant.AlertandMessages; +import com.cpm.lorealbaautomation.constant.CommonFunctions; +import com.cpm.lorealbaautomation.gsonGetterSetter.ProductMaster; + +import java.util.List; + +public class SubAxeValueAdapter extends RecyclerView.Adapter { + LayoutInflater inflator; + List masterList; + private String selectedSubAxe; + boolean disable, network_check; + Onclick onclick; + + public SubAxeValueAdapter(Context context, List data, String selectedSubAxe, boolean disable, boolean network_check, Onclick onclick) { + inflator = LayoutInflater.from(context); + this.selectedSubAxe = selectedSubAxe; + this.network_check = network_check; + this.onclick = onclick; + this.masterList = data; + this.disable = disable; + } + + @NonNull + @Override + public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) { + View view = inflator.inflate(R.layout.item_filter, parent, false); + return new MyViewHolder(view); + } + + @SuppressLint({"NotifyDataSetChanged"}) + @Override + public void onBindViewHolder(final MyViewHolder holder, final int position) { + final ProductMaster current = masterList.get(position); + holder.tv_item.setText(current.getSubAxeName()); + holder.tv_item.setId(position); + + if (!disable) { + holder.tv_item.setOnClickListener(v -> { + if (network_check && !CommonFunctions.checkNetIsAvailable(inflator.getContext())) { + AlertandMessages.showToastMsg(inflator.getContext(), inflator.getContext().getString(R.string.nonetwork)); + return; + } + String placeHolder = "Axe Name"; + selectedSubAxe = current.getSubAxeName(); + switch (current.getSubAxeName()) { + case "Product": + placeHolder = "Product Name"; + break; + case "Axe": + placeHolder = "Axe Name"; + break; + case "Sub Axe": + placeHolder = "Sub Axe Name"; + break; + case "Signature": + placeHolder = "Signature Name"; + break; + case "Sub Brand": + placeHolder = "Sub Brand Name"; + break; + case "Brand": + placeHolder = "Brand Name"; + break; + + default: + break; + } + + onclick.onClick(current.getSubAxeName(), placeHolder); + current.setSelected(true); + notifyDataSetChanged(); + }); + } + + if (!disable) { + holder.tv_item.setTextColor(inflator.getContext().getResources().getColor(R.color.white)); + holder.tv_item.setId(position); + if (current.getSubAxeName().equalsIgnoreCase(selectedSubAxe)) { + holder.card.setCardBackgroundColor(inflator.getContext().getResources().getColor(R.color.dashboard_ach)); + holder.card.setId(position); + } else { + holder.card.setCardBackgroundColor(inflator.getContext().getResources().getColor(R.color.grey_dark_background)); + holder.card.setId(position); + } + } else { + holder.card.setCardBackgroundColor(inflator.getContext().getResources().getColor(R.color.circular_progress_default_background)); + holder.card.setId(position); + + holder.tv_item.setTextColor(inflator.getContext().getResources().getColor(R.color.disable_txt_color)); + holder.tv_item.setId(position); + } + } + + @Override + public int getItemCount() { + return masterList.size(); + } + + class MyViewHolder extends RecyclerView.ViewHolder { + TextView tv_item; + CardView card; + + public MyViewHolder(View itemView) { + super(itemView); + tv_item = (TextView) itemView.findViewById(R.id.tv_item); + card = (CardView) itemView.findViewById(R.id.item_card); + + } + } + + public interface Onclick { + void onClick(String filterText, String placeHolder); + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/adapter/VolumeDetailAdapter.java b/app/src/main/java/com/cpm/lorealbaautomation/adapter/VolumeDetailAdapter.java new file mode 100644 index 0000000..40e78d9 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/adapter/VolumeDetailAdapter.java @@ -0,0 +1,69 @@ +package com.cpm.lorealbaautomation.adapter; + +import android.annotation.SuppressLint; +import android.content.Context; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.TextView; + +import androidx.annotation.NonNull; +import androidx.core.content.ContextCompat; +import androidx.recyclerview.widget.RecyclerView; + +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.gsonGetterSetter.countervolune.ReportCounterVolumeDetail; + +import java.util.List; + +public class VolumeDetailAdapter extends RecyclerView.Adapter { + LayoutInflater inflator; + List data; + + public VolumeDetailAdapter(Context context, List data) { + inflator = LayoutInflater.from(context); + this.data = data; + } + + @NonNull + @Override + public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) { + View view = inflator.inflate(R.layout.row_counter_volume, parent, false); + return new MyViewHolder(view); + } + + @SuppressLint({"SetTextI18n", "DefaultLocale"}) + @Override + public void onBindViewHolder(@NonNull final MyViewHolder holder, final int position) { + final ReportCounterVolumeDetail current = data.get(position); + setText(holder.tvParamCode, position, current.getParamCode(), inflator.getContext()); + setText(holder.tvParamName, position, current.getParamName(), inflator.getContext()); + setText(holder.tvRMTDVolume, position, current.getMTDVolume() != null ? current.getMTDVolume().toString() : "0", inflator.getContext()); + setText(holder.tvAvgPerDayVolume, position, current.getAvgPerDayVolume() != null ? current.getAvgPerDayVolume().toString() : "0", inflator.getContext()); + + } + + @Override + public int getItemCount() { + return data.size(); + } + + class MyViewHolder extends RecyclerView.ViewHolder { + TextView tvAvgPerDayVolume, tvRMTDVolume, tvParamCode, tvParamName; + + public MyViewHolder(View itemView) { + super(itemView); + tvAvgPerDayVolume = (TextView) itemView.findViewById(R.id.tvAvgPerDayVolume); + tvRMTDVolume = (TextView) itemView.findViewById(R.id.tvRMTDVolume); + tvParamCode = (TextView) itemView.findViewById(R.id.tvParamCode); + tvParamName = (TextView) itemView.findViewById(R.id.tvParamName); + } + } + + @SuppressLint("DefaultLocale") + private void setText(TextView tv, int pos, String value, Context context) { + tv.setTextColor(ContextCompat.getColor(context, R.color.black)); + tv.setText(value); + tv.setId(pos); + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/autoconnectblutooth/BluetoothA2DPRequester.java b/app/src/main/java/com/cpm/lorealbaautomation/autoconnectblutooth/BluetoothA2DPRequester.java new file mode 100644 index 0000000..6929806 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/autoconnectblutooth/BluetoothA2DPRequester.java @@ -0,0 +1,41 @@ +package com.cpm.lorealbaautomation.autoconnectblutooth; +import android.bluetooth.BluetoothA2dp; +import android.bluetooth.BluetoothAdapter; +import android.bluetooth.BluetoothProfile; +import android.content.Context; + +public class BluetoothA2DPRequester implements BluetoothProfile.ServiceListener { + Callback mCallback; + + /** + * Creates a new instance of an A2DP Proxy requester with the + * callback that should receive the proxy once it is acquired + * @param callback the callback that should receive the proxy + */ + public BluetoothA2DPRequester(Callback callback) { + mCallback = callback; + } + + /** + * Start an asynchronous request to acquire the A2DP proxy. The callback + * will be notified when the proxy is acquired + * @param c the context used to obtain the proxy + * @param adapter the BluetoothAdapter that should receive the request for proxy + */ + public void request (Context c, BluetoothAdapter adapter) { + adapter.getProfileProxy(c, this, BluetoothProfile.A2DP); + } + @Override + public void onServiceConnected(int i, BluetoothProfile bluetoothProfile) { + if (mCallback != null) { + mCallback.onA2DPProxyReceived((BluetoothA2dp) bluetoothProfile); + } + } + @Override + public void onServiceDisconnected(int i) { + //It's a one-off connection attempt; we don't care about the disconnection event. + } + public static interface Callback { + public void onA2DPProxyReceived (BluetoothA2dp proxy); + } +} \ No newline at end of file diff --git a/app/src/main/java/com/cpm/lorealbaautomation/autoconnectblutooth/BluetoothActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/autoconnectblutooth/BluetoothActivity.java new file mode 100644 index 0000000..21d8634 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/autoconnectblutooth/BluetoothActivity.java @@ -0,0 +1,140 @@ +package com.cpm.lorealbaautomation.autoconnectblutooth; + +import android.Manifest; +import android.annotation.SuppressLint; +import android.bluetooth.BluetoothA2dp; +import android.bluetooth.BluetoothAdapter; +import android.bluetooth.BluetoothDevice; +import android.content.pm.PackageManager; +import android.os.Bundle; +import android.app.Activity; +import android.util.Log; + +import androidx.core.content.ContextCompat; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.HashSet; +import java.util.Set; + +public class BluetoothActivity extends Activity implements BluetoothBroadcastReceiver.Callback, BluetoothA2DPRequester.Callback { + private static final String TAG = "BluetoothActivity"; + + /** + * This is the name of the device to connect to. You can replace this with the name of + * your device. + */ + private static final String HTC_MEDIA = "HTC Car A100 V2.4B"; + + /** + * Local reference to the device's BluetoothAdapter + */ + private BluetoothAdapter mAdapter; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + //Store a local reference to the BluetoothAdapter + mAdapter = BluetoothAdapter.getDefaultAdapter(); + + //Already connected, skip the rest + if (mAdapter.isEnabled()) { + onBluetoothConnected(); + return; + } + + //Check if we're allowed to enable Bluetooth. If so, listen for a + //successful enabling + if (ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) { + return; + } + if (mAdapter.enable()) { + BluetoothBroadcastReceiver.register(this, this); + } else { + //test(TAG, "Unable to enable Bluetooth. Is Airplane Mode enabled?"); + } + } + + @Override + public void onBluetoothError() { + //test(TAG, "There was an error enabling the Bluetooth Adapter."); + } + + @Override + public void onBluetoothConnected() { + new BluetoothA2DPRequester(this).request(this, mAdapter); + } + + @Override + public void onA2DPProxyReceived(BluetoothA2dp proxy) { + Method connect = getConnectMethod(); + BluetoothDevice device = findBondedDeviceByName(mAdapter, HTC_MEDIA); + + //If either is null, just return. The errors have already been logged + if (connect == null || device == null) { + return; + } + + try { + connect.setAccessible(true); + connect.invoke(proxy, device); + } catch (InvocationTargetException ex) { + //test(TAG, "Unable to invoke connect(BluetoothDevice) method on proxy. " + ex.toString()); + } catch (IllegalAccessException ex) { + //test(TAG, "Illegal Access! " + ex.toString()); + } + } + + /** + * Wrapper around some reflection code to get the hidden 'connect()' method + * + * @return the connect(BluetoothDevice) method, or null if it could not be found + */ + @SuppressLint("DiscouragedPrivateApi") + private Method getConnectMethod() { + try { + return BluetoothA2dp.class.getDeclaredMethod("connect", BluetoothDevice.class); + } catch (NoSuchMethodException ex) { + //test(TAG, "Unable to find connect(BluetoothDevice) method in BluetoothA2dp proxy."); + return null; + } + } + + /** + * Search the set of bonded devices in the BluetoothAdapter for one that matches + * the given name + * + * @param adapter the BluetoothAdapter whose bonded devices should be queried + * @param name the name of the device to search for + * @return the BluetoothDevice by the given name (if found); null if it was not found + */ + @SuppressLint("MissingPermission") + private static BluetoothDevice findBondedDeviceByName(BluetoothAdapter adapter, String name) { + for (BluetoothDevice device : getBondedDevices(adapter)) { + if (name.matches(device.getName())) { + Log.v(TAG, String.format("Found device with name %s and address %s.", device.getName(), device.getAddress())); + return device; + } + } + Log.w(TAG, String.format("Unable to find device with name %s.", name)); + return null; + } + + /** + * Safety wrapper around BluetoothAdapter#getBondedDevices() that is guaranteed + * to return a non-null result + * + * @param adapter the BluetoothAdapter whose bonded devices should be obtained + * @return the set of all bonded devices to the adapter; an empty set if there was an error + */ + private static Set getBondedDevices(BluetoothAdapter adapter) { + @SuppressLint("MissingPermission") + Set results = adapter.getBondedDevices(); + if (results == null) { + results = new HashSet<>(); + } + + return results; + } +} \ No newline at end of file diff --git a/app/src/main/java/com/cpm/lorealbaautomation/autoconnectblutooth/BluetoothBroadcastReceiver.java b/app/src/main/java/com/cpm/lorealbaautomation/autoconnectblutooth/BluetoothBroadcastReceiver.java new file mode 100644 index 0000000..d7a0edd --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/autoconnectblutooth/BluetoothBroadcastReceiver.java @@ -0,0 +1,97 @@ +package com.cpm.lorealbaautomation.autoconnectblutooth; +import android.annotation.SuppressLint; +import android.bluetooth.BluetoothAdapter; +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.os.Build; +import android.util.Log; + +public class BluetoothBroadcastReceiver extends BroadcastReceiver { + private static final String TAG = "BluetoothBroadcastReceiver"; + + private Callback mCallback; + + private BluetoothBroadcastReceiver (Callback callback) { + mCallback = callback; + } + + /** + * Convenience method to register a new instance of this receiver with the + * necessary IntentFilter, which will notify the callback upon a successful + * connection or error case. + * @param callback the callback that should be notified on success or failure + * of Bluetooth being enabled + * @param c the context from which to register the receiver + */ + + @SuppressLint("UnspecifiedRegisterReceiverFlag") + public static void register (Callback callback, Context c) { + if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.S_V2){ + c.registerReceiver(new BluetoothBroadcastReceiver(callback), getFilter()); + }else { + c.registerReceiver(new BluetoothBroadcastReceiver(callback), getFilter(), Context.RECEIVER_NOT_EXPORTED); + } + } + + private static IntentFilter getFilter () { + return new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED); + } + + @SuppressLint("LongLogTag") + @Override + public void onReceive (Context context, Intent intent) { + if (!BluetoothAdapter.ACTION_STATE_CHANGED.equals(intent.getAction())) { + Log.v(TAG, "Received irrelevant broadcast. Disregarding."); + return; + } + + //This is a State Change event, get the state extra, falling back to ERROR + //if it isn't there (which shouldn't happen) + int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR); + + switch (state) { + case BluetoothAdapter.STATE_CONNECTED: + safeUnregisterReceiver(context, this); + fireOnBluetoothConnected(); + break; + case BluetoothAdapter.ERROR: + safeUnregisterReceiver(context, this); + fireOnBluetoothError(); + break; + } + } + + /** + * Convenience method to do a checked unregistration of a broadcast receiver. Occasionally + * you can get into a state where the receiver was already unregistered, throwing an + * IllegalArgumentException. This method just swallows that exception and logs the error. + * @param c the context from which to unregister the receiver + * @param receiver the receiver that should be unregistered if it is not already unregistered + */ + private static void safeUnregisterReceiver (Context c, BroadcastReceiver receiver) { + try { + c.unregisterReceiver(receiver); + } catch (IllegalArgumentException ex) { + Log.w(TAG, "Tried to unregister BluetoothBroadcastReceiver that was not registered."); + } + } + + private void fireOnBluetoothConnected () { + if (mCallback != null) { + mCallback.onBluetoothConnected(); + } + } + + private void fireOnBluetoothError () { + if (mCallback != null) { + mCallback.onBluetoothError(); + } + } + + public static interface Callback { + public void onBluetoothConnected(); + public void onBluetoothError(); + } +} \ No newline at end of file diff --git a/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/BigButtonView.java b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/BigButtonView.java new file mode 100644 index 0000000..0091bf6 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/BigButtonView.java @@ -0,0 +1,239 @@ +package com.cpm.lorealbaautomation.blurlockview; + +import android.animation.ObjectAnimator; +import android.content.Context; +import android.content.res.Resources; +import android.graphics.Typeface; +import androidx.core.content.ContextCompat; +import android.util.AttributeSet; +import android.util.TypedValue; +import android.view.Gravity; +import android.view.LayoutInflater; +import android.view.MotionEvent; +import android.view.View; +import android.view.ViewGroup; +import android.widget.FrameLayout; +import android.widget.TextView; +import com.cpm.lorealbaautomation.R; + + +/** + * Created by Weiping on 2016/3/16. + */ + +public class BigButtonView extends FrameLayout { + + private FrameLayout frameLayout; + private View clickEffect; + private TextView text; + private TextView subText; + private String textString = ""; + private String subTextString = ""; + private ObjectAnimator clickEffectAnimator; + private int duration = 500; + private OnPressListener onPressListener; + + public BigButtonView(Context context) { + this(context, null); + } + + public BigButtonView(Context context, AttributeSet attrs) { + super(context, attrs); + + LayoutInflater.from(context).inflate(R.layout.big_button_view, this, true); + + Resources resources = getResources(); + + frameLayout = (FrameLayout)findViewById(R.id.frame_layout); + + text = (TextView)findViewById(R.id.text); + text.setText(textString); + text.setTextColor(ContextCompat.getColor(context, R.color.default_big_button_text_color)); + text.setTextSize(resources.getInteger(R.integer.default_big_button_text_size)); + + subText = (TextView)findViewById(R.id.sub_text); + subText.setText(subTextString); + subText.setTextColor(ContextCompat.getColor(context, R.color.default_big_button_sub_text_color)); + subText.setTextSize(resources.getInteger(R.integer.default_big_button_sub_text_size)); + + clickEffect = findViewById(R.id.click_effect); + clickEffect.setAlpha(0); + clickEffectAnimator = ObjectAnimator.ofFloat(clickEffect, "alpha", 1f, 0f); + clickEffectAnimator.setDuration(duration); + } + + /** + * Set the listener, for returning what happened to BlurLockView. + * + * @param onPressListener OnPressListener. + */ + public void setOnPressListener(OnPressListener onPressListener) { + this.onPressListener = onPressListener; + } + + /** + * Set the width of the button. + * + * @param width Width, in pixels. + */ + public void setWidth(int width) { + ViewGroup.LayoutParams layoutParams = frameLayout.getLayoutParams(); + layoutParams.width = width; + frameLayout.setLayoutParams(layoutParams); + } + + /** + * Set the height of the button. + * + * @param height Height, in pixels. + */ + public void setHeight(int height) { + ViewGroup.LayoutParams layoutParams = frameLayout.getLayoutParams(); + layoutParams.height = height; + frameLayout.setLayoutParams(layoutParams); + } + + /** + * Set the resource of background. + * + * @param resourceId ResourceId. + */ + public void setBackground(int resourceId) { + frameLayout.setBackgroundResource(resourceId); + } + + /** + * Set the resource of click effect. + * + * @param resourceId ResourceId. + */ + public void setEffect(int resourceId) { + clickEffect.setBackgroundResource(resourceId); + } + + /** + * Set the duration of the effect. + * + * @param duration Duration, in ms. + */ + public void setEffectDuration(int duration) { + this.duration = duration; + } + + /** + * Set the text size of the main text. + * + * @param size Text size, in sp. + */ + public void setTextSize(int size) { + text.setTextSize(TypedValue.COMPLEX_UNIT_SP, size); + } + + /** + * Set the text size of the sub text. + * + * @param size Text size, in sp. + */ + public void setSubTextSize(int size) { + subText.setTextSize(TypedValue.COMPLEX_UNIT_SP, size); + } + + /** + * Set the text color of main text. + * + * @param color Color. + */ + public void setTextColor(int color) { + text.setTextColor(color); + } + + /** + * Set the text color of sub text. + * + * @param color Color. + */ + public void setSubTextColor(int color) { + subText.setTextColor(color); + } + + /** + * Set font of button. + * + * @param typeFace New font. + */ + public void setTypeFace(Typeface typeFace) { + text.setTypeface(typeFace); + subText.setTypeface(typeFace); + } + + /** + * Set the string of the text. + * + * @param textString The new string. + */ + public void setText(String textString) { + this.textString = textString; + if (text != null) text.setText(textString); + } + + /** + * Set the string of the sub text. + * + * @param subTextString The new string. + */ + public void setSubText(String subTextString) { + this.subTextString = subTextString; + if (subText != null) subText.setText(subTextString); + } + + /** + * Set the visibility of sub textview. + * + * @param visibility The visibility. + */ + public void setSubTextVisibility(int visibility) { + if (visibility == GONE) { + text.setGravity(Gravity.CENTER); + } else { + text.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM); + } + subText.setVisibility(visibility); + } + + /** + * Perform the click effect. + * + * @param event MotionEvent. + * @return + */ + @Override + public boolean dispatchTouchEvent(MotionEvent event) { + switch(event.getAction()){ + case MotionEvent.ACTION_DOWN: + if (onPressListener != null) onPressListener.onPress(textString); + clickEffectAnimator.cancel(); + clickEffect.setAlpha(1); + break; + case MotionEvent.ACTION_UP: + clickEffectAnimator.start(); + break; + default:break; + } + + return super.dispatchTouchEvent(event); + } + + /** + * Clear the animation. + */ + public void clearAnimation() { + if (clickEffect.getAlpha() == 1) { + clickEffectAnimator.cancel(); + clickEffectAnimator.start(); + } + } + + public interface OnPressListener { + void onPress(String string); + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/BlurLockView.java b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/BlurLockView.java new file mode 100644 index 0000000..3cb8a58 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/BlurLockView.java @@ -0,0 +1,869 @@ +package com.cpm.lorealbaautomation.blurlockview; + +import android.animation.Animator; +import android.animation.AnimatorListenerAdapter; +import android.animation.ObjectAnimator; +import android.animation.ValueAnimator; +import android.app.Activity; +import android.content.Context; +import android.content.res.Resources; +import android.graphics.Point; +import android.graphics.Typeface; +import androidx.core.content.ContextCompat; +import android.util.AttributeSet; +import android.view.Display; +import android.view.LayoutInflater; +import android.view.MotionEvent; +import android.view.View; +import android.widget.FrameLayout; +import android.widget.LinearLayout; +import android.widget.TextView; + +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.blurlockview.Directions.HideType; +import com.cpm.lorealbaautomation.blurlockview.Directions.ShowType; +import com.cpm.lorealbaautomation.blurlockview.Eases.EaseType; + +import java.util.Stack; + +/** + * Created by Weiping on 2016/3/16. + */ +public class BlurLockView extends FrameLayout + implements + BigButtonView.OnPressListener, + SmallButtonView.OnPressListener { + + private final char CHARS[][] = { + {'1', '2', '3', '4', '5', '6', '7', '8', '9', '0'}, + {'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P'}, + { 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L' }, + { 'Z', 'X', 'C', 'V', 'B', 'N', 'M' } + }; + + private Password type = Password.NUMBER; + + private int passwordLength = 4; + private String correctPassword = null; + private int incorrectInputTimes = 0; + private Typeface typeface; + + private boolean animationIsPlaying = false; + + public boolean isIs_Password_Check_Mode() { + return is_Password_Check_Mode; + } + + public void setIs_Password_Check_Mode(boolean is_Password_Check_Mode) { + this.is_Password_Check_Mode = is_Password_Check_Mode; + } + + private boolean is_Password_Check_Mode = false; + + private Stack passwordStack = null; + + private TextView title; + private Indicator indicator; + + private BigButtonView[] bigButtonViews; + private SmallButtonView[][] smallButtonViews; + private BlurView mBlurView; + private TextView leftButton; + private TextView rightButton; + + private OnLeftButtonClickListener onLeftButtonClickListener; + private OnPasswordInputListener onPasswordInputListener; + + public BlurLockView(Context context) { + this(context, null); + } + + public BlurLockView(Context context, AttributeSet attrs) { + super(context, attrs); + + init(); + } + + /** + * Init. + */ + private void init() { + // number password + LayoutInflater.from(getContext()).inflate(R.layout.number_lock_view, this, true); + + bigButtonViews = new BigButtonView[10]; + bigButtonViews[0] = (BigButtonView)findViewById(R.id.button_0); + bigButtonViews[1] = (BigButtonView)findViewById(R.id.button_1); + bigButtonViews[2] = (BigButtonView)findViewById(R.id.button_2); + bigButtonViews[3] = (BigButtonView)findViewById(R.id.button_3); + bigButtonViews[4] = (BigButtonView)findViewById(R.id.button_4); + bigButtonViews[5] = (BigButtonView)findViewById(R.id.button_5); + bigButtonViews[6] = (BigButtonView)findViewById(R.id.button_6); + bigButtonViews[7] = (BigButtonView)findViewById(R.id.button_7); + bigButtonViews[8] = (BigButtonView)findViewById(R.id.button_8); + bigButtonViews[9] = (BigButtonView)findViewById(R.id.button_9); + + String[] texts = getResources().getStringArray(R.array.default_big_button_text); + String[] subTexts = getResources().getStringArray(R.array.default_big_button_sub_text); + for (int i = 0; i < 10; i++) { + bigButtonViews[i].setOnPressListener(this); + bigButtonViews[i].setText(texts[i]); + //bigButtonViews[i].setSubText(subTexts[i]); + } + + bigButtonViews[0].setSubTextVisibility(View.GONE); + bigButtonViews[1].setSubTextVisibility(View.INVISIBLE); + + // text password + smallButtonViews = new SmallButtonView[4][10]; + + // get screen width + Display display = ((Activity)getContext()).getWindowManager().getDefaultDisplay(); + Point size = new Point(); + display.getSize(size); + int width = size.x; + + int buttonHorizontalMargin = 6; + int buttonVerticalMargin = 24; + int buttonWidth = (width - 11 * buttonHorizontalMargin) / 10; + + // add buttons to lines + LinearLayout line1 = (LinearLayout)findViewById(R.id.line_1); + for (int i = 0; i < 10; i++) { + smallButtonViews[0][i] = new SmallButtonView(getContext()); + smallButtonViews[0][i].setOnPressListener(this); + smallButtonViews[0][i].setText(CHARS[0][i] + ""); + smallButtonViews[0][i].setWidth(buttonWidth); + smallButtonViews[0][i].setHeight(buttonWidth); + + LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( + buttonWidth, + buttonWidth + ); + if (i == 0) + params.setMargins(buttonHorizontalMargin, buttonVerticalMargin / 2, buttonHorizontalMargin / 2, buttonVerticalMargin / 2); + else if (i == 9) + params.setMargins(buttonHorizontalMargin / 2, buttonVerticalMargin / 2, buttonHorizontalMargin, buttonVerticalMargin / 2); + else + params.setMargins(buttonHorizontalMargin / 2, buttonVerticalMargin / 2, buttonHorizontalMargin / 2, buttonVerticalMargin / 2); + line1.addView(smallButtonViews[0][i], params); + } + + LinearLayout line2 = (LinearLayout)findViewById(R.id.line_2); + for (int i = 0; i < 10; i++) { + smallButtonViews[1][i] = new SmallButtonView(getContext()); + smallButtonViews[1][i].setOnPressListener(this); + smallButtonViews[1][i].setText(CHARS[1][i] + ""); + smallButtonViews[1][i].setWidth(buttonWidth); + smallButtonViews[1][i].setHeight(buttonWidth); + + LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( + buttonWidth, + buttonWidth + ); + if (i == 0) + params.setMargins(buttonHorizontalMargin, buttonVerticalMargin / 2, buttonHorizontalMargin / 2, buttonVerticalMargin / 2); + else if (i == 9) + params.setMargins(buttonHorizontalMargin / 2, buttonVerticalMargin / 2, buttonHorizontalMargin, buttonVerticalMargin / 2); + else + params.setMargins(buttonHorizontalMargin / 2, buttonVerticalMargin / 2, buttonHorizontalMargin / 2, buttonVerticalMargin / 2); + line2.addView(smallButtonViews[1][i], params); + } + + LinearLayout line3 = (LinearLayout)findViewById(R.id.line_3); + for (int i = 0; i < 9; i++) { + smallButtonViews[2][i] = new SmallButtonView(getContext()); + smallButtonViews[2][i].setOnPressListener(this); + smallButtonViews[2][i].setText(CHARS[2][i] + ""); + smallButtonViews[2][i].setWidth(buttonWidth); + smallButtonViews[2][i].setHeight(buttonWidth); + + LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( + buttonWidth, + buttonWidth + ); + + if (i == 0) + params.setMargins(buttonHorizontalMargin, buttonVerticalMargin / 2, buttonHorizontalMargin / 2, buttonVerticalMargin / 2); + else if (i == 8) + params.setMargins(buttonHorizontalMargin / 2, buttonVerticalMargin / 2, buttonHorizontalMargin, buttonVerticalMargin / 2); + else + params.setMargins(buttonHorizontalMargin / 2, buttonVerticalMargin / 2, buttonHorizontalMargin / 2, buttonVerticalMargin / 2); + line3.addView(smallButtonViews[2][i], params); + } + + LinearLayout line4 = (LinearLayout)findViewById(R.id.line_4); + for (int i = 0; i < 7; i++) { + smallButtonViews[3][i] = new SmallButtonView(getContext()); + smallButtonViews[3][i].setOnPressListener(this); + smallButtonViews[3][i].setText(CHARS[3][i] + ""); + smallButtonViews[3][i].setWidth(buttonWidth); + smallButtonViews[3][i].setHeight(buttonWidth); + + LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( + buttonWidth, + buttonWidth + ); + + if (i == 0) + params.setMargins(buttonHorizontalMargin, buttonVerticalMargin / 2, buttonHorizontalMargin / 2, buttonVerticalMargin / 2); + else if (i == 6) + params.setMargins(buttonHorizontalMargin / 2, buttonVerticalMargin / 2, buttonHorizontalMargin, buttonVerticalMargin / 2); + else + params.setMargins(buttonHorizontalMargin / 2, buttonVerticalMargin / 2, buttonHorizontalMargin / 2, buttonVerticalMargin / 2); + line4.addView(smallButtonViews[3][i], params); + } + + passwordStack = new Stack<>(); + + mBlurView = (BlurView)findViewById(R.id.blurview); + mBlurView.setOnClickListener(new OnClickListener() { + @Override + public void onClick(View v) { + + } + }); + + Resources resources = getResources(); + + indicator = (Indicator)findViewById(R.id.indicator); + indicator.setPasswordLength(passwordLength); + + title = (TextView)findViewById(R.id.title); + title.setTextColor(ContextCompat.getColor(getContext(), R.color.default_title_text_color)); + title.setTextSize(resources.getInteger(R.integer.default_title_text_size)); + + leftButton = (TextView)findViewById(R.id.left_button); + leftButton.setTextColor(ContextCompat.getColor(getContext(), R.color.default_left_button_text_color)); + leftButton.setTextSize(resources.getInteger(R.integer.default_left_button_text_size)); + leftButton.setOnClickListener(new OnClickListener() { + @Override + public void onClick(View v) { + if (onLeftButtonClickListener != null) onLeftButtonClickListener.onClick(); + } + }); + + rightButton = (TextView)findViewById(R.id.right_button); + rightButton.setTextColor(ContextCompat.getColor(getContext(), R.color.default_right_button_text_color)); + rightButton.setTextSize(resources.getInteger(R.integer.default_right_button_text_size)); + rightButton.setOnClickListener(new OnClickListener() { + @Override + public void onClick(View v) { + if (passwordStack.size() > 0) { + passwordStack.pop(); + indicator.delete(); + if (onPasswordInputListener != null){ + StringBuilder nowPassword = new StringBuilder(""); + for (String s : passwordStack) { + nowPassword.append(s); + } + onPasswordInputListener.clear(nowPassword.toString()); + } + + + } + } + }); + } + + /** + * Show the text keyboard smoothly or not. + * + * @param smoothly Smoothly or not. + */ + private void showText(boolean smoothly) { + if (animationIsPlaying) return; + animationIsPlaying = true; + if (smoothly) { + ObjectAnimator.ofFloat(findViewById(R.id.layout_123), "alpha", 1f, 0f) + .setDuration(500).start(); + ObjectAnimator.ofFloat(findViewById(R.id.layout_456), "alpha", 1f, 0f) + .setDuration(500).start(); + ObjectAnimator.ofFloat(findViewById(R.id.layout_789), "alpha", 1f, 0f) + .setDuration(500).start(); + ObjectAnimator.ofFloat(findViewById(R.id.button_0), "alpha", 1f, 0f) + .setDuration(500).start(); + ObjectAnimator showAnimator = + ObjectAnimator.ofFloat(findViewById(R.id.text_layout), "alpha", 0f, 1f); + showAnimator.setDuration(500).addListener(new AnimatorListenerAdapter() { + @Override + public void onAnimationStart(Animator animation) { + super.onAnimationStart(animation); + findViewById(R.id.text_layout).setVisibility(VISIBLE); + } + + @Override + public void onAnimationEnd(Animator animation) { + super.onAnimationEnd(animation); + findViewById(R.id.layout_123).setVisibility(INVISIBLE); + findViewById(R.id.layout_456).setVisibility(INVISIBLE); + findViewById(R.id.layout_789).setVisibility(INVISIBLE); + findViewById(R.id.button_0).setVisibility(INVISIBLE); + animationIsPlaying = false; + } + }); + showAnimator.start(); + } else { + findViewById(R.id.layout_123).setVisibility(INVISIBLE); + findViewById(R.id.layout_456).setVisibility(INVISIBLE); + findViewById(R.id.layout_789).setVisibility(INVISIBLE); + findViewById(R.id.button_0).setVisibility(INVISIBLE); + findViewById(R.id.text_layout).setVisibility(VISIBLE); + animationIsPlaying = false; + } + } + + /** + * Show the number keyboard smoothly or not. + * + * @param smoothly Smoothly or not. + */ + private void showNumber(boolean smoothly) { + if (animationIsPlaying) return; + animationIsPlaying = true; + if (smoothly) { + ObjectAnimator.ofFloat(findViewById(R.id.layout_123), "alpha", 0f, 1f) + .setDuration(500).start(); + ObjectAnimator.ofFloat(findViewById(R.id.layout_456), "alpha", 0f, 1f) + .setDuration(500).start(); + ObjectAnimator.ofFloat(findViewById(R.id.layout_789), "alpha", 0f, 1f) + .setDuration(500).start(); + ObjectAnimator.ofFloat(findViewById(R.id.button_0), "alpha", 0f, 1f) + .setDuration(500).start(); + ObjectAnimator showAnimator = + ObjectAnimator.ofFloat(findViewById(R.id.text_layout), "alpha", 1f, 0f); + showAnimator.setDuration(500).addListener(new AnimatorListenerAdapter() { + @Override + public void onAnimationStart(Animator animation) { + super.onAnimationStart(animation); + findViewById(R.id.layout_123).setVisibility(VISIBLE); + findViewById(R.id.layout_456).setVisibility(VISIBLE); + findViewById(R.id.layout_789).setVisibility(VISIBLE); + findViewById(R.id.button_0).setVisibility(VISIBLE); + } + + @Override + public void onAnimationEnd(Animator animation) { + super.onAnimationEnd(animation); + findViewById(R.id.text_layout).setVisibility(INVISIBLE); + animationIsPlaying = false; + } + }); + showAnimator.start(); + } else { + findViewById(R.id.layout_123).setVisibility(VISIBLE); + findViewById(R.id.layout_456).setVisibility(VISIBLE); + findViewById(R.id.layout_789).setVisibility(VISIBLE); + findViewById(R.id.button_0).setVisibility(VISIBLE); + findViewById(R.id.text_layout).setVisibility(INVISIBLE); + animationIsPlaying = false; + } + } + + /** + * Set the view that need to be blurred. + * + * @param blurredView The view. + */ + public void setBlurredView(View blurredView) { + mBlurView.setBlurredView(blurredView); + } + + /** + * Set the listener. + * + * @param onLeftButtonClickListener Listener. + */ + public void setOnLeftButtonClickListener(OnLeftButtonClickListener onLeftButtonClickListener) { + this.onLeftButtonClickListener = onLeftButtonClickListener; + } + + /** + * Set the listener. + * + * @param onPasswordInputListener Listener. + */ + public void setOnPasswordInputListener(OnPasswordInputListener onPasswordInputListener) { + this.onPasswordInputListener = onPasswordInputListener; + } + + /** + * From the button views. + * + * @param string The string from button views. + */ + @Override + public void onPress(String string) { + if (correctPassword == null) { + throw new RuntimeException("The correct password has NOT been set!"); + } + if (passwordStack.size() >= passwordLength) return; + passwordStack.push(string); + indicator.add(); + StringBuilder nowPassword = new StringBuilder(""); + for (String s : passwordStack) { + nowPassword.append(s); + } + String nowPasswordString = nowPassword.toString(); + if (correctPassword.equals(nowPasswordString)) { + // correct password + if (onPasswordInputListener != null) + onPasswordInputListener.correct(nowPasswordString); + } else { + if (correctPassword.length() > nowPasswordString.length()) { + // input right now + if (onPasswordInputListener != null) + onPasswordInputListener.input(nowPasswordString); + } else { + // incorrect password + if (onPasswordInputListener != null) + onPasswordInputListener.incorrect(nowPasswordString); + if(is_Password_Check_Mode){ + // perform the clear animation + incorrectInputTimes++; + indicator.clear(); + passwordStack.clear(); + } + } + } + } + + /** + * Prevent click 2 or above buttons at the same time. + * + * @param event + * @return + */ + @Override + public boolean dispatchTouchEvent(MotionEvent event) { + if (event.getPointerCount() > 1) { + if (Password.NUMBER.equals(type)) { + for (int i = 0; i < bigButtonViews.length; i++) bigButtonViews[i].clearAnimation(); + } else if (Password.TEXT.equals(type)) { + for (int i = 0; i < smallButtonViews.length; i++) { + for (int j = 0; j < smallButtonViews[i].length; j++) { + if (smallButtonViews[i][j] != null) smallButtonViews[i][j].clearAnimation(); + } + } + } + return true; + } + return super.dispatchTouchEvent(event); + } + + /** + * Set big buttons' background. + * + * @param id + */ + public void setBigButtonViewsBackground(int id) { + for (int i = 0; i < 10; i++) bigButtonViews[i].setBackground(id); + } + + /** + * Set big buttons' click effect. + * + * @param id + */ + public void setBigButtonViewsClickEffect(int id) { + for (int i = 0; i < 10; i++) bigButtonViews[i].setEffect(id); + } + + /** + * Set the click effect duration. + * + * @param duration + */ + public void setBigButtonViewsClickEffectDuration(int duration) { + for (int i = 0; i < 10; i++) bigButtonViews[i].setEffectDuration(duration); + } + + /** + * Set small buttons' background. + * + * @param id + */ + public void setSmallButtonViewsBackground(int id) { + for (int i = 0; i < smallButtonViews.length; i++) + for (int j = 0; j < smallButtonViews[i].length; j++) + if (smallButtonViews[i][j] != null) + smallButtonViews[i][j].setBackground(id); + } + + /** + * Set small buttons' click effect. + * + * @param id + */ + public void setSmallButtonViewsClickEffect(int id) { + for (int i = 0; i < smallButtonViews.length; i++) + for (int j = 0; j < smallButtonViews[i].length; j++) + if (smallButtonViews[i][j] != null) + smallButtonViews[i][j].setEffect(id); + } + + /** + * Set the click effect duration. + * + * @param duration + */ + public void setSmallButtonViewsClickEffectDuration(int duration) { + for (int i = 0; i < smallButtonViews.length; i++) + for (int j = 0; j < smallButtonViews[i].length; j++) + if (smallButtonViews[i][j] != null) + smallButtonViews[i][j].setEffectDuration(duration); + } + + /** + * Set all the fonts. + * + * @param typeface + */ + public void setTypeface(Typeface typeface) { + this.typeface = typeface; + if (type.equals(Password.NUMBER)) { + for (int i = 0; i < 10; i++) bigButtonViews[i].setTypeFace(typeface); + } else if (type.equals(Password.TEXT)) { + for (int i = 0; i < smallButtonViews.length; i++) + for (int j = 0; j < smallButtonViews[i].length; j++) + if (smallButtonViews[i][j] != null) + smallButtonViews[i][j].setTypeFace(typeface); + } + title.setTypeface(typeface); + leftButton.setTypeface(typeface); + rightButton.setTypeface(typeface); + } + + /** + * Set all the text color. + * + * @param color + */ + public void setTextColor(int color) { + if (type.equals(Password.NUMBER)) { + for (int i = 0; i < 10; i++) { + bigButtonViews[i].setTextColor(color); + bigButtonViews[i].setSubTextColor(color); + } + } else if (type.equals(Password.TEXT)) { + for (int i = 0; i < smallButtonViews.length; i++) + for (int j = 0; j < smallButtonViews[i].length; j++) + if (smallButtonViews[i][j] != null) + smallButtonViews[i][j].setTextColor(color); + } + title.setTextColor(color); + leftButton.setTextColor(color); + rightButton.setTextColor(color); + } + + /** + * Set the length of the password. + * Default length is 4. + * + * @param passwordLength + */ + public void setPasswordLength(int passwordLength) { + this.passwordLength = passwordLength; + indicator.setPasswordLength(passwordLength); + passwordStack.clear(); + correctPassword = null; + } + + /** + * Get the password type. + * + * @return + */ + public Password getType() { + return type; + } + + /** + * Set the password type. + * + * @param type Number or text. + */ + public void setType(Password type, boolean smoothly) { + if (animationIsPlaying) return; + this.type = type; + indicator.clear(); + passwordStack.clear(); + if (Password.NUMBER.equals(type)) { + showNumber(smoothly); + } else if (Password.TEXT.equals(type)) { + showText(smoothly); + } + } + + /** + * Set the title text. + * + * @param string + */ + public void setTitle(String string) { + title.setText(string); + } + + /** + * Set the text of left button. + * + * @param string + */ + public void setLeftButton(String string) { + leftButton.setText(string); + } + + /** + * Set the text of right button. + * + * @param string + */ + public void setRightButton(String string) { + rightButton.setText(string); + } + + /** + * Set the target password. + * + * @param correctPassword The target password. + */ + public void setCorrectPassword(String correctPassword) { + setPasswordLength(correctPassword.length()); + this.correctPassword = correctPassword; + } + + /** + * You can use this to reset the incorrect input times. + * + * @param incorrectInputTimes The incorrect input times. + */ + public void setIncorrectInputTimes(int incorrectInputTimes) { + this.incorrectInputTimes = incorrectInputTimes; + } + + /** + * Return the incorrect input times. + * + * @return Incorrect input times. + */ + public int getIncorrectInputTimes() { + return incorrectInputTimes; + } + + /** + * Invalidate the blur view. + */ + public void update() { + mBlurView.invalidate(); + } + + /** + * Show this BlurLockView. + * + * @param duration Duration, in ms. + * @param showType Direction, in ShowType. + * @param easeType Ease type, in EaseType. + */ + public void show(int duration, ShowType showType, EaseType easeType) { + if (animationIsPlaying) return; + animationIsPlaying = true; + indicator.clear(); + passwordStack.clear(); + ObjectAnimator animator = null; + setVisibility(VISIBLE); + if (showType.equals(ShowType.FROM_TOP_TO_BOTTOM)) { + animator = ObjectAnimator.ofFloat(this, "translationY", + getTranslationY() - getHeight(), + getTranslationY()); + } else if (showType.equals(ShowType.FROM_RIGHT_TO_LEFT)) { + animator = ObjectAnimator.ofFloat(this, "translationX", + getTranslationX() + getWidth(), + getTranslationX()); + } else if (showType.equals(ShowType.FROM_BOTTOM_TO_TOP)) { + animator = ObjectAnimator.ofFloat(this, "translationY", + getTranslationY() + getHeight(), + getTranslationY()); + } else if (showType.equals(ShowType.FROM_LEFT_TO_RIGHT)) { + animator = ObjectAnimator.ofFloat(this, "translationX", + getTranslationX() - getWidth(), + getTranslationX()); + } else if (showType.equals(ShowType.FADE_IN)) { + animator = ObjectAnimator.ofFloat(this, "alpha", + 0, + 1); + } + animator.setDuration(duration); + animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { + @Override + public void onAnimationUpdate(ValueAnimator animation) { + update(); + } + }); + animator.addListener(new AnimatorListenerAdapter() { + @Override + public void onAnimationEnd(Animator animation) { + super.onAnimationEnd(animation); + animationIsPlaying = false; + } + }); + animator.setInterpolator(InterpolatorFactory.getInterpolator(easeType)); + animator.start(); + } + + /** + * Hide this BlurLockView. + * + * @param duration Duration, in ms. + * @param hideType Direction, in HideType. + * @param easeType Ease type, in EaseType. + */ + public void hide(int duration, HideType hideType, EaseType easeType) { + if (animationIsPlaying) return; + animationIsPlaying = true; + ObjectAnimator animator = null; + final float originalX = getTranslationX(); + final float originalY = getTranslationY(); + if (hideType.equals(HideType.FROM_TOP_TO_BOTTOM)) { + animator = ObjectAnimator.ofFloat(this, "translationY", + getTranslationY(), + getTranslationY() + getHeight()); + } else if (hideType.equals(HideType.FROM_RIGHT_TO_LEFT)) { + animator = ObjectAnimator.ofFloat(this, "translationX", + getTranslationX(), + getTranslationX() - getWidth()); + } else if (hideType.equals(HideType.FROM_BOTTOM_TO_TOP)) { + animator = ObjectAnimator.ofFloat(this, "translationY", + getTranslationY(), + getTranslationY() - getHeight()); + } else if (hideType.equals(HideType.FROM_LEFT_TO_RIGHT)) { + animator = ObjectAnimator.ofFloat(this, "translationX", + getTranslationX(), + getTranslationX() + getWidth()); + } else if (hideType.equals(HideType.FADE_OUT)) { + animator = ObjectAnimator.ofFloat(this, "alpha", + 1, + 0); + } + animator.setDuration(duration); + animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { + @Override + public void onAnimationUpdate(ValueAnimator animation) { + update(); + } + }); + animator.addListener(new AnimatorListenerAdapter() { + @Override + public void onAnimationEnd(Animator animation) { + super.onAnimationEnd(animation); + setVisibility(INVISIBLE); + setTranslationX(originalX); + setTranslationY(originalY); + setAlpha(1); + animationIsPlaying = false; + } + }); + animator.setInterpolator(InterpolatorFactory.getInterpolator(easeType)); + animator.start(); + } + + public interface OnPasswordInputListener { + void correct(String inputPassword); + void incorrect(String inputPassword); + void input(String inputPassword); + void clear(String remainingPassword); + } + + public interface OnLeftButtonClickListener { + void onClick(); + } + + /** + * Get the title. + * @return + */ + public TextView getTitle() { + return title; + } + + /** + * Get the left button. + * @return + */ + public TextView getLeftButton() { + return leftButton; + } + + /** + * Get the right button. + * @return + */ + public TextView getRightButton() { + return rightButton; + } + + /** + * Get the numbers. + * @return + */ + public BigButtonView[] getBigButtonViews() { + return bigButtonViews; + } + + /** + * Get the texts. + * @return + */ + public SmallButtonView[][] getSmallButtonViews() { + return smallButtonViews; + } + + /** + * Set the blur radius. + */ + public void setBlurRadius(int blurRadius) { + mBlurView.setBlurRadius(blurRadius); + update(); + } + + /** + * Get the blur radius. + * @return + */ + public int getBlurRadius() { + return mBlurView.getBlurRadius(); + } + + /** + * Set the downsample factor. + * @param downsampleFactor + */ + public void setDownsampleFactor(int downsampleFactor) { + mBlurView.setDownsampleFactor(downsampleFactor); + update(); + } + + /** + * Get the downsample factor. + * @return + */ + public int getDownsampleFactor() { + return mBlurView.getDownsampleFactor(); + } + + /** + * Set the overlay color. + * @param color + */ + public void setOverlayColor(int color) { + mBlurView.setOverlayColor(color); + update(); + } + + /** + * Get the overlay color. + * @return + */ + public int getOverlayColor() { + return mBlurView.getmOverlayColor(); + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/BlurView.java b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/BlurView.java new file mode 100644 index 0000000..046d6df --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/BlurView.java @@ -0,0 +1,194 @@ +package com.cpm.lorealbaautomation.blurlockview; + +import android.content.Context; +import android.content.res.Resources; +import android.content.res.TypedArray; +import android.graphics.Bitmap; +import android.graphics.Canvas; +import android.graphics.Color; +import android.graphics.drawable.ColorDrawable; +import android.renderscript.Allocation; +import android.renderscript.Element; +import android.renderscript.RenderScript; +import android.renderscript.ScriptIntrinsicBlur; +import android.util.AttributeSet; +import android.view.View; + +import com.cpm.lorealbaautomation.R; + + +/** + * Created by Weiping on 2016/3/16. + */ +public class BlurView extends View { + + private int mBlurRadius; + private int mDownsampleFactor; + private int mOverlayColor; + + private View mBlurredView; + private int mBlurredViewWidth, mBlurredViewHeight; + + private boolean mDownsampleFactorChanged; + private Bitmap mBitmapToBlur, mBlurredBitmap; + private Canvas mBlurringCanvas; + private RenderScript mRenderScript; + private ScriptIntrinsicBlur mBlurScript; + private Allocation mBlurInput, mBlurOutput; + + public BlurView(Context context) { + this(context, null); + } + + public BlurView(Context context, AttributeSet attrs) { + super(context, attrs); + + final Resources res = getResources(); + final int defaultBlurRadius = res.getInteger(R.integer.default_blur_radius); + final int defaultDownsampleFactor = res.getInteger(R.integer.default_downsample_factor); + final int defaultOverlayColor = res.getColor(R.color.default_overlay_color); + + initializeRenderScript(context); + + TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.BlurView); + setBlurRadius(a.getInt(R.styleable.BlurView_blurRadius, defaultBlurRadius)); + setDownsampleFactor(a.getInt(R.styleable.BlurView_downsampleFactor, + defaultDownsampleFactor)); + setOverlayColor(a.getColor(R.styleable.BlurView_overlayColor, defaultOverlayColor)); + a.recycle(); + } + + public void setBlurredView(View blurredView) { + mBlurredView = blurredView; + } + + @Override + protected void onDraw(Canvas canvas) { + super.onDraw(canvas); + if (mBlurredView != null) { + if (prepare()) { + // If the background of the blurred view is a color drawable, we use it to clear + // the blurring canvas, which ensures that edges of the child views are blurred + // as well; otherwise we clear the blurring canvas with a transparent color. + if (mBlurredView.getBackground() != null && mBlurredView.getBackground() instanceof ColorDrawable) { + mBitmapToBlur.eraseColor(((ColorDrawable) mBlurredView.getBackground()).getColor()); + } else { + mBitmapToBlur.eraseColor(Color.TRANSPARENT); + } + + int[] mBlurredViewXY = new int[2]; + mBlurredView.getLocationOnScreen(mBlurredViewXY); + int[] mBlurringViewXY = new int[2]; + getLocationOnScreen(mBlurringViewXY); + + mBlurredView.draw(mBlurringCanvas); + blur(); + + canvas.save(); + + // modify here to get the correct bitmap when the blurring view is in a parent + canvas.translate(mBlurredViewXY[0] - mBlurringViewXY[0], mBlurredViewXY[1] - mBlurringViewXY[1]); + canvas.scale(mDownsampleFactor, mDownsampleFactor); + canvas.drawBitmap(mBlurredBitmap, 0, 0, null); + canvas.restore(); + } + canvas.drawColor(mOverlayColor); + } + } + + public void setBlurRadius(int radius) { + mBlurRadius = radius; + mBlurScript.setRadius(mBlurRadius); + } + + public int getBlurRadius() { + return mBlurRadius; + } + + public void setDownsampleFactor(int factor) { + if (factor <= 0) { + throw new IllegalArgumentException("Downsample factor must be greater than 0."); + } + + if (mDownsampleFactor != factor) { + mDownsampleFactor = factor; + mDownsampleFactorChanged = true; + } + } + + public int getDownsampleFactor() { + return mDownsampleFactor; + } + + public void setOverlayColor(int color) { + mOverlayColor = color; + } + + public int getmOverlayColor() { + return mOverlayColor; + } + + private void initializeRenderScript(Context context) { + mRenderScript = RenderScript.create(context); + mBlurScript = ScriptIntrinsicBlur.create(mRenderScript, Element.U8_4(mRenderScript)); + } + + protected boolean prepare() { + final int width = mBlurredView.getWidth(); + final int height = mBlurredView.getHeight(); + + if (mBlurringCanvas == null || mDownsampleFactorChanged + || mBlurredViewWidth != width || mBlurredViewHeight != height) { + mDownsampleFactorChanged = false; + + mBlurredViewWidth = width; + mBlurredViewHeight = height; + + int scaledWidth = width / mDownsampleFactor; + int scaledHeight = height / mDownsampleFactor; + + // The following manipulation is to avoid some RenderScript artifacts at the edge. + scaledWidth = scaledWidth - scaledWidth % 4 + 4; + scaledHeight = scaledHeight - scaledHeight % 4 + 4; + + if (mBlurredBitmap == null + || mBlurredBitmap.getWidth() != scaledWidth + || mBlurredBitmap.getHeight() != scaledHeight) { + mBitmapToBlur = Bitmap.createBitmap(scaledWidth, scaledHeight, + Bitmap.Config.ARGB_8888); + if (mBitmapToBlur == null) { + return false; + } + + mBlurredBitmap = Bitmap.createBitmap(scaledWidth, scaledHeight, + Bitmap.Config.ARGB_8888); + if (mBlurredBitmap == null) { + return false; + } + } + + mBlurringCanvas = new Canvas(mBitmapToBlur); + mBlurringCanvas.scale(1f / mDownsampleFactor, 1f / mDownsampleFactor); + mBlurInput = Allocation.createFromBitmap(mRenderScript, mBitmapToBlur, + Allocation.MipmapControl.MIPMAP_NONE, Allocation.USAGE_SCRIPT); + mBlurOutput = Allocation.createTyped(mRenderScript, mBlurInput.getType()); + } + return true; + } + + protected void blur() { + mBlurInput.copyFrom(mBitmapToBlur); + mBlurScript.setInput(mBlurInput); + mBlurScript.forEach(mBlurOutput); + mBlurOutput.copyTo(mBlurredBitmap); + } + + @Override + protected void onDetachedFromWindow() { + super.onDetachedFromWindow(); + if (mRenderScript != null) { + mRenderScript.destroy(); + } + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Directions/HideType.java b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Directions/HideType.java new file mode 100644 index 0000000..089f48b --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Directions/HideType.java @@ -0,0 +1,20 @@ +package com.cpm.lorealbaautomation.blurlockview.Directions; + +/** + * Created by Weiping on 2016/3/17. + */ +public enum HideType { + + FROM_TOP_TO_BOTTOM(0), + FROM_RIGHT_TO_LEFT(1), + FROM_BOTTOM_TO_TOP(2), + FROM_LEFT_TO_RIGHT(3), + FADE_OUT(4); + + int type; + + HideType(int type) { + this.type = type; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Directions/ShowType.java b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Directions/ShowType.java new file mode 100644 index 0000000..2977e20 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Directions/ShowType.java @@ -0,0 +1,20 @@ +package com.cpm.lorealbaautomation.blurlockview.Directions; + +/** + * Created by Weiping on 2016/3/17. + */ +public enum ShowType { + + FROM_TOP_TO_BOTTOM(0), + FROM_RIGHT_TO_LEFT(1), + FROM_BOTTOM_TO_TOP(2), + FROM_LEFT_TO_RIGHT(3), + FADE_IN(4); + + int type; + + ShowType(int type) { + this.type = type; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Dot.java b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Dot.java new file mode 100644 index 0000000..339d90a --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Dot.java @@ -0,0 +1,87 @@ +package com.cpm.lorealbaautomation.blurlockview; + +import android.animation.ObjectAnimator; +import android.content.Context; +import android.util.AttributeSet; +import android.view.LayoutInflater; +import android.view.View; +import android.widget.FrameLayout; + +import com.cpm.lorealbaautomation.R; + + +/** + * Created by Weiping on 2016/3/17. + */ +public class Dot extends FrameLayout { + + private View selected; + private View unselected; + + private ObjectAnimator selectedAnimator; + private ObjectAnimator unselectedAnimator; + + private boolean isSelected = false; + + public Dot(Context context) { + this(context, null); + } + + public Dot(Context context, AttributeSet attrs) { + super(context, attrs); + + LayoutInflater.from(context).inflate(R.layout.dot_view, this, true); + + selected = findViewById(R.id.selected); + unselected = findViewById(R.id.unselected); + + clear(); + } + + /** + * Set this dot to selected or not. + * + * @param isSelected Selected or not. + */ + public void setSelected(boolean isSelected) { + if (!(this.isSelected ^ isSelected)) return; + this.isSelected = isSelected; + if (isSelected) { + // change to selected + selected.setAlpha(0); + unselected.setAlpha(1); + if (selectedAnimator != null) selectedAnimator.cancel(); + if (unselectedAnimator != null) unselectedAnimator.cancel(); + + selectedAnimator = ObjectAnimator.ofFloat(selected, "alpha", 0f, 1f); + selectedAnimator.setDuration(300); + selectedAnimator.start(); + + unselectedAnimator = ObjectAnimator.ofFloat(unselected, "alpha", 1f, 0f); + unselectedAnimator.setDuration(300); + unselectedAnimator.start(); + } else { + // change to unselected + selected.setAlpha(1); + unselected.setAlpha(0); + if (selectedAnimator != null) selectedAnimator.cancel(); + if (unselectedAnimator != null) unselectedAnimator.cancel(); + + selectedAnimator = ObjectAnimator.ofFloat(selected, "alpha", 1f, 0f); + selectedAnimator.setDuration(300); + selectedAnimator.start(); + + unselectedAnimator = ObjectAnimator.ofFloat(unselected, "alpha", 0f, 1f); + unselectedAnimator.setDuration(300); + unselectedAnimator.start(); + } + } + + /** + * Clear the dot. + */ + public void clear() { + selected.setAlpha(0); + unselected.setAlpha(1); + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/CubicBezier.java b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/CubicBezier.java new file mode 100644 index 0000000..0f17951 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/CubicBezier.java @@ -0,0 +1,82 @@ +package com.cpm.lorealbaautomation.blurlockview.Eases; + +import android.graphics.PointF; + +/** + * Created by Weiping on 2016/3/3. + */ +public abstract class CubicBezier { + + private PointF start; + private PointF end; + private PointF a = new PointF(); + private PointF b = new PointF(); + private PointF c = new PointF(); + + /** + * init the 4 values of the cubic-bezier + * @param startX x of start + * @param startY y of start + * @param endX x of end + * @param endY y of end + */ + public void init(float startX, float startY, float endX, float endY) { + setStart(new PointF(startX, startY)); + setEnd(new PointF(endX, endY)); + } + + public void init(double startX, double startY, double endX, double endY) { + init((float) startX, (float) startY, (float) endX, (float) endY); + } + + public float getOffset(float offset) { + return getBezierCoordinateY(getXForTime(offset)); + } + + private float getBezierCoordinateY(float time) { + c.y = 3 * start.y; + b.y = 3 * (end.y - start.y) - c.y; + a.y = 1 - c.y - b.y; + return time * (c.y + time * (b.y + time * a.y)); + } + + private float getXForTime(float time) { + float x = time; + float z; + for (int i = 1; i < 14; i++) { + z = getBezierCoordinateX(x) - time; + if (Math.abs(z) < 1e-3) { + break; + } + x -= z / getXDerivate(x); + } + return x; + } + + private float getXDerivate(float t) { + return c.x + t * (2 * b.x + 3 * a.x * t); + } + + private float getBezierCoordinateX(float time) { + c.x = 3 * start.x; + b.x = 3 * (end.x - start.x) - c.x; + a.x = 1 - c.x - b.x; + return time * (c.x + time * (b.x + time * a.x)); + } + + public PointF getStart() { + return start; + } + + public void setStart(PointF start) { + this.start = start; + } + + public PointF getEnd() { + return end; + } + + public void setEnd(PointF end) { + this.end = end; + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseInBack.java b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseInBack.java new file mode 100644 index 0000000..7c26030 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseInBack.java @@ -0,0 +1,14 @@ +package com.cpm.lorealbaautomation.blurlockview.Eases; + + +/** + * Created by Weiping on 2016/3/3. + */ + +public class EaseInBack extends CubicBezier { + + public EaseInBack() { + init(0.6, -0.28, 0.735, 0.045); + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseInBounce.java b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseInBounce.java new file mode 100644 index 0000000..03a4d68 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseInBounce.java @@ -0,0 +1,32 @@ +package com.cpm.lorealbaautomation.blurlockview.Eases; + +/** + * Created by Weiping on 2016/3/3. + */ + +public class EaseInBounce extends CubicBezier { + + public EaseInBounce() { + + } + + public float getOffset(float t) { + float b = 0; + float c = 1; + float d = 1; + return c - easeOutBounce(d-t, 0, c, d) + b; + } + + private float easeOutBounce(float t, float b, float c, float d) { + if ((t/=d) < (1/2.75f)) { + return c*(7.5625f*t*t) + b; + } else if (t < (2/2.75f)) { + return c*(7.5625f*(t-=(1.5f/2.75f))*t + .75f) + b; + } else if (t < (2.5/2.75)) { + return c*(7.5625f*(t-=(2.25f/2.75f))*t + .9375f) + b; + } else { + return c*(7.5625f*(t-=(2.625f/2.75f))*t + .984375f) + b; + } + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseInCirc.java b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseInCirc.java new file mode 100644 index 0000000..544c224 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseInCirc.java @@ -0,0 +1,14 @@ +package com.cpm.lorealbaautomation.blurlockview.Eases; + + +/** + * Created by Weiping on 2016/3/3. + */ + +public class EaseInCirc extends CubicBezier { + + public EaseInCirc() { + init(0.6, 0.04, 0.98, 0.335); + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseInCubic.java b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseInCubic.java new file mode 100644 index 0000000..7ca40fa --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseInCubic.java @@ -0,0 +1,14 @@ +package com.cpm.lorealbaautomation.blurlockview.Eases; + + +/** + * Created by Weiping on 2016/3/3. + */ + +public class EaseInCubic extends CubicBezier { + + public EaseInCubic() { + init(0.55, 0.055, 0.675, 0.19); + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseInElastic.java b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseInElastic.java new file mode 100644 index 0000000..d2fd905 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseInElastic.java @@ -0,0 +1,24 @@ +package com.cpm.lorealbaautomation.blurlockview.Eases; + +/** + * Created by Weiping on 2016/3/3. + */ + +public class EaseInElastic extends CubicBezier { + + public EaseInElastic() { + + } + + public float getOffset(float t) { + float b = 0; + float c = 1; + float d = 1; + if (t==0) return b; if ((t/=d)==1) return b+c; + float p=d*.3f; + float a=c; + float s=p/4; + return -(a*(float) Math.pow(2,10*(t-=1)) * (float) Math.sin( (t*d-s)*(2*(float) Math.PI)/p )) + b; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseInExpo.java b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseInExpo.java new file mode 100644 index 0000000..63f66ef --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseInExpo.java @@ -0,0 +1,14 @@ +package com.cpm.lorealbaautomation.blurlockview.Eases; + + +/** + * Created by Weiping on 2016/3/3. + */ + +public class EaseInExpo extends CubicBezier { + + public EaseInExpo() { + init(0.95, 0.05, 0.795, 0.035); + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseInOutBack.java b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseInOutBack.java new file mode 100644 index 0000000..43d69aa --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseInOutBack.java @@ -0,0 +1,14 @@ +package com.cpm.lorealbaautomation.blurlockview.Eases; + + +/** + * Created by Weiping on 2016/3/3. + */ + +public class EaseInOutBack extends CubicBezier { + + public EaseInOutBack() { + init(0.68, -0.55, 0.265, 1.55); + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseInOutBounce.java b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseInOutBounce.java new file mode 100644 index 0000000..4bf298f --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseInOutBounce.java @@ -0,0 +1,39 @@ +package com.cpm.lorealbaautomation.blurlockview.Eases; + +/** + * Created by Weiping on 2016/3/3. + */ + +public class EaseInOutBounce extends CubicBezier { + + public EaseInOutBounce() { + + } + + public float getOffset(float t) { + float b = 0; + float c = 1; + float d = 1; + if (t < d / 2) + return easeInBounce(t * 2, 0, c, d) * .5f + b; + else + return easeOutBounce(t * 2 - d, 0, c, d) * .5f + c * .5f + b; + } + + private float easeInBounce(float t, float b, float c, float d) { + return c - easeOutBounce(d - t, 0, c, d) + b; + } + + private float easeOutBounce(float t, float b, float c, float d) { + if ((t/=d) < (1/2.75f)) { + return c*(7.5625f*t*t) + b; + } else if (t < (2/2.75f)) { + return c*(7.5625f*(t-=(1.5f/2.75f))*t + .75f) + b; + } else if (t < (2.5/2.75)) { + return c*(7.5625f*(t-=(2.25f/2.75f))*t + .9375f) + b; + } else { + return c*(7.5625f*(t-=(2.625f/2.75f))*t + .984375f) + b; + } + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseInOutCirc.java b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseInOutCirc.java new file mode 100644 index 0000000..969e820 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseInOutCirc.java @@ -0,0 +1,14 @@ +package com.cpm.lorealbaautomation.blurlockview.Eases; + + +/** + * Created by Weiping on 2016/3/3. + */ + +public class EaseInOutCirc extends CubicBezier { + + public EaseInOutCirc() { + init(0.785, 0.135, 0.15, 0.86); + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseInOutCubic.java b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseInOutCubic.java new file mode 100644 index 0000000..15d20b4 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseInOutCubic.java @@ -0,0 +1,14 @@ +package com.cpm.lorealbaautomation.blurlockview.Eases; + + +/** + * Created by Weiping on 2016/3/3. + */ + +public class EaseInOutCubic extends CubicBezier { + + public EaseInOutCubic() { + init(0.645, 0.045, 0.355, 1); + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseInOutElastic.java b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseInOutElastic.java new file mode 100644 index 0000000..26faea3 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseInOutElastic.java @@ -0,0 +1,25 @@ +package com.cpm.lorealbaautomation.blurlockview.Eases; + +/** + * Created by Weiping on 2016/3/3. + */ + +public class EaseInOutElastic extends CubicBezier { + + public EaseInOutElastic() { + + } + + public float getOffset(float t) { + float b = 0; + float c = 1; + float d = 1; + if (t==0) return b; if ((t/=d/2)==2) return b+c; + float p=d*(.3f*1.5f); + float a=c; + float s=p/4; + if (t < 1) return -.5f*(a*(float) Math.pow(2,10*(t-=1)) * (float) Math.sin( (t*d-s)*(2*(float) Math.PI)/p )) + b; + return a*(float) Math.pow(2,-10*(t-=1)) * (float) Math.sin( (t*d-s)*(2*(float) Math.PI)/p )*.5f + c + b; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseInOutExpo.java b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseInOutExpo.java new file mode 100644 index 0000000..f973547 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseInOutExpo.java @@ -0,0 +1,14 @@ +package com.cpm.lorealbaautomation.blurlockview.Eases; + + +/** + * Created by Weiping on 2016/3/3. + */ + +public class EaseInOutExpo extends CubicBezier { + + public EaseInOutExpo() { + init(1, 0, 0, 1); + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseInOutQuad.java b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseInOutQuad.java new file mode 100644 index 0000000..9c0d18d --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseInOutQuad.java @@ -0,0 +1,14 @@ +package com.cpm.lorealbaautomation.blurlockview.Eases; + + +/** + * Created by Weiping on 2016/3/3. + */ + +public class EaseInOutQuad extends CubicBezier { + + public EaseInOutQuad() { + init(0.455, 0.03, 0.515, 0.955); + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseInOutQuart.java b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseInOutQuart.java new file mode 100644 index 0000000..84e8140 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseInOutQuart.java @@ -0,0 +1,14 @@ +package com.cpm.lorealbaautomation.blurlockview.Eases; + + +/** + * Created by Weiping on 2016/3/3. + */ + +public class EaseInOutQuart extends CubicBezier { + + public EaseInOutQuart() { + init(0.77, 0, 0.175, 1); + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseInOutQuint.java b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseInOutQuint.java new file mode 100644 index 0000000..5076542 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseInOutQuint.java @@ -0,0 +1,14 @@ +package com.cpm.lorealbaautomation.blurlockview.Eases; + + +/** + * Created by Weiping on 2016/3/3. + */ + +public class EaseInOutQuint extends CubicBezier { + + public EaseInOutQuint() { + init(0.86, 0, 0.07, 1); + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseInOutSine.java b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseInOutSine.java new file mode 100644 index 0000000..413e6f8 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseInOutSine.java @@ -0,0 +1,13 @@ +package com.cpm.lorealbaautomation.blurlockview.Eases; + +/** + * Created by Weiping on 2016/3/3. + */ + +public class EaseInOutSine extends CubicBezier { + + public EaseInOutSine() { + init(0.445, 0.05, 0.55, 0.95); + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseInQuad.java b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseInQuad.java new file mode 100644 index 0000000..1eec4f1 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseInQuad.java @@ -0,0 +1,13 @@ +package com.cpm.lorealbaautomation.blurlockview.Eases; + +/** + * Created by Weiping on 2016/3/3. + */ + +public class EaseInQuad extends CubicBezier { + + public EaseInQuad() { + init(0.55, 0.085, 0.68, 0.53); + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseInQuart.java b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseInQuart.java new file mode 100644 index 0000000..0c13666 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseInQuart.java @@ -0,0 +1,12 @@ +package com.cpm.lorealbaautomation.blurlockview.Eases; +/** + * Created by Weiping on 2016/3/3. + */ + +public class EaseInQuart extends CubicBezier { + + public EaseInQuart() { + init(0.895, 0.03, 0.685, 0.22); + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseInQuint.java b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseInQuint.java new file mode 100644 index 0000000..a516eae --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseInQuint.java @@ -0,0 +1,14 @@ +package com.cpm.lorealbaautomation.blurlockview.Eases; + + +/** + * Created by Weiping on 2016/3/3. + */ + +public class EaseInQuint extends CubicBezier { + + public EaseInQuint() { + init(0.755, 0.05, 0.855, 0.06); + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseInSine.java b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseInSine.java new file mode 100644 index 0000000..d88d2e3 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseInSine.java @@ -0,0 +1,14 @@ +package com.cpm.lorealbaautomation.blurlockview.Eases; + + +/** + * Created by Weiping on 2016/3/3. + */ + +public class EaseInSine extends CubicBezier { + + public EaseInSine() { + init(0.47, 0, 0.745, 0.715); + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseOutBack.java b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseOutBack.java new file mode 100644 index 0000000..5f04faf --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseOutBack.java @@ -0,0 +1,14 @@ +package com.cpm.lorealbaautomation.blurlockview.Eases; + + +/** + * Created by Weiping on 2016/3/3. + */ + +public class EaseOutBack extends CubicBezier { + + public EaseOutBack() { + init(0.175, 0.885, 0.32, 1.275); + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseOutBounce.java b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseOutBounce.java new file mode 100644 index 0000000..03d8cbc --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseOutBounce.java @@ -0,0 +1,27 @@ +package com.cpm.lorealbaautomation.blurlockview.Eases; +/** + * Created by Weiping on 2016/3/3. + */ + +public class EaseOutBounce extends CubicBezier { + + public EaseOutBounce() { + + } + + public float getOffset(float t) { + float b = 0; + float c = 1; + float d = 1; + if ((t/=d) < (1/2.75f)) { + return c*(7.5625f*t*t) + b; + } else if (t < (2/2.75f)) { + return c*(7.5625f*(t-=(1.5f/2.75f))*t + .75f) + b; + } else if (t < (2.5/2.75)) { + return c*(7.5625f*(t-=(2.25f/2.75f))*t + .9375f) + b; + } else { + return c*(7.5625f*(t-=(2.625f/2.75f))*t + .984375f) + b; + } + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseOutCirc.java b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseOutCirc.java new file mode 100644 index 0000000..a5933dd --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseOutCirc.java @@ -0,0 +1,14 @@ +package com.cpm.lorealbaautomation.blurlockview.Eases; + + +/** + * Created by Weiping on 2016/3/3. + */ + +public class EaseOutCirc extends CubicBezier { + + public EaseOutCirc() { + init(0.075, 0.82, 0.165, 1); + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseOutCubic.java b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseOutCubic.java new file mode 100644 index 0000000..81e8c4f --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseOutCubic.java @@ -0,0 +1,13 @@ +package com.cpm.lorealbaautomation.blurlockview.Eases; + +/** + * Created by Weiping on 2016/3/3. + */ + +public class EaseOutCubic extends CubicBezier { + + public EaseOutCubic() { + init(0.215, 0.61, 0.355, 1); + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseOutElastic.java b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseOutElastic.java new file mode 100644 index 0000000..8c76dad --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseOutElastic.java @@ -0,0 +1,25 @@ +package com.cpm.lorealbaautomation.blurlockview.Eases; + + +/** + * Created by Weiping on 2016/3/3. + */ + +public class EaseOutElastic extends CubicBezier { + + public EaseOutElastic() { + + } + + public float getOffset(float t) { + float b = 0; + float c = 1; + float d = 1; + if (t==0) return b; if ((t/=d)==1) return b+c; + float p=d*.3f; + float a=c; + float s=p/4; + return (a*(float) Math.pow(2,-10*t) * (float) Math.sin( (t*d-s)*(2*(float) Math.PI)/p ) + c + b); + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseOutExpo.java b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseOutExpo.java new file mode 100644 index 0000000..37662bc --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseOutExpo.java @@ -0,0 +1,13 @@ +package com.cpm.lorealbaautomation.blurlockview.Eases; + +/** + * Created by Weiping on 2016/3/3. + */ + +public class EaseOutExpo extends CubicBezier { + + public EaseOutExpo() { + init(0.19, 1, 0.22, 1); + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseOutQuad.java b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseOutQuad.java new file mode 100644 index 0000000..035a3de --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseOutQuad.java @@ -0,0 +1,13 @@ +package com.cpm.lorealbaautomation.blurlockview.Eases; + +/** + * Created by Weiping on 2016/3/3. + */ + +public class EaseOutQuad extends CubicBezier { + + public EaseOutQuad() { + init(0.25, 0.46, 0.45, 0.94); + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseOutQuart.java b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseOutQuart.java new file mode 100644 index 0000000..04ea2fe --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseOutQuart.java @@ -0,0 +1,14 @@ +package com.cpm.lorealbaautomation.blurlockview.Eases; + + +/** + * Created by Weiping on 2016/3/3. + */ + +public class EaseOutQuart extends CubicBezier { + + public EaseOutQuart() { + init(0.165, 0.84, 0.44, 1); + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseOutQuint.java b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseOutQuint.java new file mode 100644 index 0000000..958ce89 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseOutQuint.java @@ -0,0 +1,14 @@ +package com.cpm.lorealbaautomation.blurlockview.Eases; + + +/** + * Created by Weiping on 2016/3/3. + */ + +public class EaseOutQuint extends CubicBezier { + + public EaseOutQuint() { + init(0.23, 1, 0.32, 1); + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseOutSine.java b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseOutSine.java new file mode 100644 index 0000000..720c68d --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseOutSine.java @@ -0,0 +1,13 @@ +package com.cpm.lorealbaautomation.blurlockview.Eases; + +/** + * Created by Weiping on 2016/3/3. + */ + +public class EaseOutSine extends CubicBezier { + + public EaseOutSine() { + init(0.39, 0.575, 0.565, 1); + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseType.java b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseType.java new file mode 100644 index 0000000..41e8e5c --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/EaseType.java @@ -0,0 +1,70 @@ +package com.cpm.lorealbaautomation.blurlockview.Eases; + +/** + * Created by Weiping on 2016/3/3. + */ + +public enum EaseType { + + EaseInSine(EaseInSine.class), + EaseOutSine(EaseOutSine.class), + EaseInOutSine(EaseInOutSine.class), + + EaseInQuad(EaseInQuad.class), + EaseOutQuad(EaseOutQuad.class), + EaseInOutQuad(EaseInOutQuad.class), + + EaseInCubic(EaseInCubic.class), + EaseOutCubic(EaseOutCubic.class), + EaseInOutCubic(EaseInOutCubic.class), + + EaseInQuart(EaseInQuart.class), + EaseOutQuart(EaseOutQuart.class), + EaseInOutQuart(EaseInOutQuart.class), + + EaseInQuint(EaseInQuint.class), + EaseOutQuint(EaseOutQuint.class), + EaseInOutQuint(EaseInOutQuint.class), + + EaseInExpo(EaseInExpo.class), + EaseOutExpo(EaseOutExpo.class), + EaseInOutExpo(EaseInOutExpo.class), + + EaseInCirc(EaseInCirc.class), + EaseOutCirc(EaseOutCirc.class), + EaseInOutCirc(EaseInOutCirc.class), + + EaseInBack(EaseInBack.class), + EaseOutBack(EaseOutBack.class), + EaseInOutBack(EaseInOutBack.class), + + EaseInElastic(EaseInElastic.class), + EaseOutElastic(EaseOutElastic.class), + EaseInOutElastic(EaseInOutElastic.class), + + EaseInBounce(EaseInBounce.class), + EaseOutBounce(EaseOutBounce.class), + EaseInOutBounce(EaseInOutBounce.class), + + Linear(Linear.class); + + private Class easingType; + + /** + * ease animation helps to make the movement more real + * @param easingType + */ + EaseType(Class easingType) { + this.easingType = easingType; + } + + public float getOffset(float offset) { + try { + return ((CubicBezier) easingType.getConstructor().newInstance()).getOffset(offset); + } catch (Exception e) { + e.fillInStackTrace(); + throw new Error("CubicBezier init error."); + } + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/Linear.java b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/Linear.java new file mode 100644 index 0000000..2ffc06f --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Eases/Linear.java @@ -0,0 +1,13 @@ +package com.cpm.lorealbaautomation.blurlockview.Eases; + +/** + * Created by Weiping on 2016/3/3. + */ + +public class Linear extends CubicBezier { + + public Linear() { + init(0, 0, 1, 1); + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Indicator.java b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Indicator.java new file mode 100644 index 0000000..c9b13dd --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Indicator.java @@ -0,0 +1,69 @@ +package com.cpm.lorealbaautomation.blurlockview; + +import android.content.Context; +import android.util.AttributeSet; +import android.widget.LinearLayout; + +import com.cpm.lorealbaautomation.R; + + +/** + * Created by Weiping on 2016/3/17. + */ +public class Indicator extends LinearLayout { + + private Dot[] dots; + private int number = 0; + + public Indicator(Context context) { + super(context); + } + + public Indicator(Context context, AttributeSet attrs) { + super(context, attrs); + } + + public void setPasswordLength(int length) { + removeAllViews(); + dots = new Dot[length]; + + for(int i = 0; i < length; i++) { + Dot view = new Dot(getContext()); + + view.setBackgroundResource(R.drawable.indicator_background); + + LayoutParams params = new LayoutParams( + 30, + 30 + ); + params.setMargins(20, 10, 20, 10); + addView(view, params); + dots[i] = view; + } + } + + /** + * Add a dot. + */ + public void add() { + if (number == dots.length) return; + dots[number++].setSelected(true); + } + + /** + * Delete a dot. + */ + public void delete() { + if (number == 0) return; + dots[--number].setSelected(false); + } + + /** + * Clear all dots. + */ + public void clear() { + number = 0; + for (int i = 0; i < dots.length; i++) dots[i].setSelected(false); + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/InterpolatorFactory.java b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/InterpolatorFactory.java new file mode 100644 index 0000000..5a8c5bb --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/InterpolatorFactory.java @@ -0,0 +1,31 @@ +package com.cpm.lorealbaautomation.blurlockview; + +import android.view.animation.Interpolator; + +import com.cpm.lorealbaautomation.blurlockview.Eases.EaseType; + + +/** + * Created by Weiping on 2016/3/17. + */ +public class InterpolatorFactory { + + public static BLVInterpolator getInterpolator(EaseType easeType) { + return new BLVInterpolator(easeType); + } + + public static class BLVInterpolator implements Interpolator { + + private EaseType easeType; + + public BLVInterpolator(EaseType easeType) { + this.easeType = easeType; + } + + @Override + public float getInterpolation(float input) { + return easeType.getOffset(input); + } + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Password.java b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Password.java new file mode 100644 index 0000000..d6ad6e7 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/Password.java @@ -0,0 +1,17 @@ +package com.cpm.lorealbaautomation.blurlockview; + +/** + * Created by Weiping on 2016/3/17. + */ +public enum Password { + + NUMBER(0), + TEXT(1); + + private int type; + + private Password(int type) { + this.type = type; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/SmallButtonView.java b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/SmallButtonView.java new file mode 100644 index 0000000..a10c733 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/blurlockview/SmallButtonView.java @@ -0,0 +1,194 @@ +package com.cpm.lorealbaautomation.blurlockview; + +import android.animation.ObjectAnimator; +import android.content.Context; +import android.content.res.Resources; +import android.graphics.Typeface; +import androidx.core.content.ContextCompat; +import android.util.AttributeSet; +import android.util.TypedValue; +import android.view.LayoutInflater; +import android.view.MotionEvent; +import android.view.View; +import android.view.ViewGroup; +import android.widget.FrameLayout; +import android.widget.TextView; + +import com.cpm.lorealbaautomation.R; + +/** + * Created by Weiping on 2016/3/16. + */ + +public class SmallButtonView extends FrameLayout { + + private FrameLayout frameLayout; + private View clickEffect; + private TextView text; + private String textString = ""; + private ObjectAnimator clickEffectAnimator; + private int duration = 500; + private OnPressListener onPressListener; + + public SmallButtonView(Context context) { + this(context, null); + } + + public SmallButtonView(Context context, AttributeSet attrs) { + super(context, attrs); + + LayoutInflater.from(context).inflate(R.layout.small_button_view, this, true); + + Resources resources = getResources(); + + frameLayout = (FrameLayout)findViewById(R.id.frame_layout); + + text = (TextView)findViewById(R.id.text); + text.setText(textString); + text.setTextColor(ContextCompat.getColor(context, R.color.default_small_button_text_color)); + text.setTextSize(resources.getInteger(R.integer.default_small_button_text_size)); + + clickEffect = findViewById(R.id.click_effect); + clickEffect.setAlpha(0); + clickEffectAnimator = ObjectAnimator.ofFloat(clickEffect, "alpha", 1f, 0f); + clickEffectAnimator.setDuration(duration); + } + + /** + * Set the listener, for returning what happened to BlurLockView. + * + * @param onPressListener OnPressListener. + */ + public void setOnPressListener(OnPressListener onPressListener) { + this.onPressListener = onPressListener; + } + + /** + * Set the width of the button. + * + * @param width Width, in pixels. + */ + public void setWidth(int width) { + ViewGroup.LayoutParams layoutParams = frameLayout.getLayoutParams(); + layoutParams.width = width; + frameLayout.setLayoutParams(layoutParams); + layoutParams = clickEffect.getLayoutParams(); + layoutParams.width = width; + clickEffect.setLayoutParams(layoutParams); + } + + /** + * Set the height of the button. + * + * @param height Height, in pixels. + */ + public void setHeight(int height) { + ViewGroup.LayoutParams layoutParams = frameLayout.getLayoutParams(); + layoutParams.height = height; + frameLayout.setLayoutParams(layoutParams); + layoutParams = clickEffect.getLayoutParams(); + layoutParams.height = height; + clickEffect.setLayoutParams(layoutParams); + } + + /** + * Set the resource of background. + * + * @param resourceId ResourceId. + */ + public void setBackground(int resourceId) { + frameLayout.setBackgroundResource(resourceId); + } + + /** + * Set the resource of click effect. + * + * @param resourceId ResourceId. + */ + public void setEffect(int resourceId) { + clickEffect.setBackgroundResource(resourceId); + } + + /** + * Set the duration of the effect. + * + * @param duration Duration, in ms. + */ + public void setEffectDuration(int duration) { + this.duration = duration; + } + + /** + * Set the text size of the main text. + * + * @param size Text size, in sp. + */ + public void setTextSize(int size) { + text.setTextSize(TypedValue.COMPLEX_UNIT_SP, size); + } + + /** + * Set the text color of main text. + * + * @param color Color. + */ + public void setTextColor(int color) { + text.setTextColor(color); + } + + /** + * Set font of button. + * + * @param typeFace New font. + */ + public void setTypeFace(Typeface typeFace) { + text.setTypeface(typeFace); + } + + /** + * Set the string of the text. + * + * @param textString The new string. + */ + public void setText(String textString) { + this.textString = textString; + if (text != null) text.setText(textString); + } + + /** + * Perform the click effect. + * + * @param event MotionEvent. + * @return + */ + @Override + public boolean dispatchTouchEvent(MotionEvent event) { + switch(event.getAction()){ + case MotionEvent.ACTION_DOWN: + if (onPressListener != null) onPressListener.onPress(textString); + clickEffectAnimator.cancel(); + clickEffect.setAlpha(1); + break; + case MotionEvent.ACTION_UP: + clickEffectAnimator.start(); + break; + default:break; + } + + return super.dispatchTouchEvent(event); + } + + /** + * Clear the animation. + */ + public void clearAnimation() { + if (clickEffect.getAlpha() == 1) { + clickEffectAnimator.cancel(); + clickEffectAnimator.start(); + } + } + + public interface OnPressListener { + void onPress(String string); + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/breakmanagement/BreakManagementActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/breakmanagement/BreakManagementActivity.java new file mode 100644 index 0000000..57f4db2 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/breakmanagement/BreakManagementActivity.java @@ -0,0 +1,432 @@ +package com.cpm.lorealbaautomation.breakmanagement; + +import android.annotation.SuppressLint; +import android.app.AlertDialog; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.SharedPreferences; + +import androidx.annotation.NonNull; +import androidx.appcompat.app.AppCompatActivity; + +import android.os.Bundle; + +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; +import androidx.appcompat.widget.Toolbar; + +import android.util.Log; +import android.view.LayoutInflater; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; +import android.widget.AdapterView; +import android.widget.ArrayAdapter; +import android.widget.Button; +import android.widget.Spinner; +import android.widget.TextView; + +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.constant.AlertandMessages; +import com.cpm.lorealbaautomation.constant.CommonFunctions; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.download.Downloader; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterBreak; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Date; +import java.util.List; + +public class BreakManagementActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemSelectedListener { + ArrayList breakmanageList = new ArrayList<>(); + ArrayList insertedBreakList = new ArrayList<>(); + MasterBreak masterBreakObject = new MasterBreak(); + ArrayAdapter break_managemntAdapter; + String CounterId, visit_date, username, loginTym = "", breakType = "", breakId = "0", startTym = "", endTym = ""; + private SharedPreferences preferences; + private SharedPreferences.Editor editor = null; + Button promotion_btn_first, promotion_btn_second; + TextView txt_login_Tym, txt_start_Tym; + RecyclerView recycl_break_managemnt; + Spinner spin_break_Type; + boolean clicked_flag = false, flag_update = false; + Lorealba_Database db; + AlertDialog.Builder alert; + Context context; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_break_management); + context = this; + db = new Lorealba_Database(context); + db.open(); + Toolbar toolbar = findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + if (!CommonFunctions.isTablet(context)) { + toolbar.setTitleTextAppearance(context, R.style.changestext_sizefor_mobile); + } + getSupportActionBar().setHomeButtonEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + iduserinterface(); + setTitle("Break Management -" + username); + ////update device time from server time............. + if (CommonFunctions.checkNetIsAvailable(context)) { + CommonFunctions.GetServerTym(context, username, db); + } + } + + + @SuppressLint("SetTextI18n") + private void iduserinterface() { + preferences = PrefHelper.getPrefs(context); + editor = preferences.edit(); + CounterId = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + username = preferences.getString(CommonString.KEY_USERNAME, ""); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + txt_login_Tym = (TextView) findViewById(R.id.txt_login_Tym); + txt_start_Tym = (TextView) findViewById(R.id.txt_start_Tym); + spin_break_Type = (Spinner) findViewById(R.id.spin_break_Type); + //for demo btn + promotion_btn_first = (Button) findViewById(R.id.posm_btn_first); + promotion_btn_second = (Button) findViewById(R.id.posm_btn_second); + recycl_break_managemnt = (RecyclerView) findViewById(R.id.recycl_break_managemnt); + + promotion_btn_first.setOnClickListener(this); + promotion_btn_second.setOnClickListener(this); + db.open(); + loginTym = db.get_baLoginTym(visit_date, username).getUserLoginTym(); + loginTym = CommonFunctions.setTimeFormat(loginTym); + txt_login_Tym.setText("Login Time - " + loginTym); + calculate_spin(); + db.open(); + calcalate_list_data(true); + } + + @Override + protected void onResume() { + super.onResume(); + db.open(); + } + + @SuppressLint({"SetTextI18n", "UseCompatLoadingForDrawables"}) + private void calcalate_list_data(boolean flag) { + db.open(); + insertedBreakList = db.getBreakManagementList(CounterId, visit_date, username, null); + if (insertedBreakList.size() > 0) { + for (int k = 0; k < insertedBreakList.size(); k++) { + if (insertedBreakList.get(k).getEndTym().equals("")) { + masterBreakObject = insertedBreakList.get(k); + startTym = masterBreakObject.getStartTym(); + txt_start_Tym.setText("Start Time - " + startTym); + flag_update = true; + + promotion_btn_first.setBackgroundColor(getResources().getColor(R.color.green)); + promotion_btn_first.setTextColor(getResources().getColor(R.color.white)); + promotion_btn_second.setBackgroundDrawable(getResources().getDrawable(R.drawable.round_btn_color_primary)); + promotion_btn_second.setTextColor(getResources().getColor(R.color.grayfor_login)); + + break; + } + } + + recycl_break_managemnt.setAdapter(new ValueAdapter(context, insertedBreakList)); + recycl_break_managemnt.setLayoutManager(new LinearLayoutManager(context)); + + + if (flag_update) { + if (flag) { + for (int k = 0; k < breakmanageList.size(); k++) { + if (breakmanageList.get(k).getBreakType().equalsIgnoreCase(masterBreakObject.getBreakType())) { + spin_break_Type.setSelection(k + 1); + spin_break_Type.setEnabled(false); + promotion_btn_first.setEnabled(false); + + break; + } + } + + } + } + } + + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + if (id == android.R.id.home) { + if (clicked_flag) { + AlertDialog.Builder builder = new AlertDialog.Builder(context).setMessage(CommonString.ONBACK_ALERT_MESSAGE).setCancelable(false).setPositiveButton("Ok", + (dialog, id1) -> { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + BreakManagementActivity.this.finish(); + }).setNegativeButton("Cancel", (dialog, id12) -> dialog.cancel()); + AlertDialog alert = builder.create(); + alert.show(); + } else { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + BreakManagementActivity.this.finish(); + } + } + + + return super.onOptionsItemSelected(item); + } + + @Override + public void onBackPressed() { + if (clicked_flag) { + AlertDialog.Builder builder = new AlertDialog.Builder(context).setMessage(CommonString.ONBACK_ALERT_MESSAGE).setCancelable(false).setPositiveButton("Ok", + (dialog, id) -> { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + BreakManagementActivity.this.finish(); + }).setNegativeButton("Cancel", (dialog, id) -> dialog.cancel()); + AlertDialog alert = builder.create(); + alert.show(); + } else { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + BreakManagementActivity.this.finish(); + } + } + + + @SuppressLint("NonConstantResourceId") + @Override + public void onClick(View view) { + if (view.getId() == R.id.posm_btn_first) { + if (spin_break_Type.getSelectedItemId() == 0) { + AlertandMessages.showToastMsg(context, "Please Select Break Type"); + } else if (!startTym.isEmpty()) { + AlertandMessages.showToastMsg(context, "Already Take a Break"); + } else { + alert = new AlertDialog.Builder(context).setTitle(R.string.parinaam).setMessage("Are you sure you want to Take a Break ?").setCancelable(false).setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { + @SuppressLint({"SetTextI18n", "UseCompatLoadingForDrawables"}) + @Override + public void onClick(DialogInterface dialogInterface, int i) { + // hh:mm a will print hours in 12hrs clock, mins and AM/PM (e.g. 02:30 PM) + startTym = getTime(); + txt_start_Tym.setText("Start Time - " + startTym); + promotion_btn_first.setBackgroundColor(getResources().getColor(R.color.green)); + + promotion_btn_first.setTextColor(getResources().getColor(R.color.white)); + promotion_btn_second.setBackgroundDrawable(getResources().getDrawable(R.drawable.round_btn_color_primary)); + promotion_btn_second.setTextColor(getResources().getColor(R.color.grayfor_login)); + + masterBreakObject = new MasterBreak(); + masterBreakObject.setLoginTym(loginTym); + masterBreakObject.setBreakType(breakType); + masterBreakObject.setBreakId(Integer.valueOf(breakId)); + masterBreakObject.setStartTym(startTym); + masterBreakObject.setEndTym(""); + masterBreakObject.setTotalDuration(""); + db.open(); + db.insertBreakManagement(username, visit_date, CounterId, masterBreakObject); + clicked_flag = false; + calcalate_list_data(true); + } + }).setNegativeButton(android.R.string.cancel, (dialogInterface, i) -> dialogInterface.dismiss()); + + alert.show(); + } + + } else if (view.getId() == R.id.posm_btn_second) { + if (masterBreakObject != null && masterBreakObject.getStartTym().equals("")) { + AlertandMessages.showToastMsg(context, "No Break."); + } else { + alert = new AlertDialog.Builder(context).setTitle(R.string.parinaam).setMessage("Are you sure you want to End The Break ?").setCancelable(false).setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { + @SuppressLint("UseCompatLoadingForDrawables") + @Override + public void onClick(DialogInterface dialogInterface, int i) { + endTym = getTime(); + promotion_btn_first.setBackgroundDrawable(getResources().getDrawable(R.drawable.round_btn_color_primary)); + promotion_btn_first.setTextColor(getResources().getColor(R.color.grayfor_login)); + promotion_btn_second.setBackgroundDrawable(getResources().getDrawable(R.drawable.round_btn_color_primary)); + promotion_btn_second.setTextColor(getResources().getColor(R.color.grayfor_login)); + db.open(); + masterBreakObject.setEndTym(endTym); + masterBreakObject.setTotalDuration(calculateTotalDuration() + ""); + masterBreakObject.setTransId(CommonFunctions.getUUID(context)); + db.open(); + db.update_break_management(CounterId, visit_date, username, masterBreakObject); + //download service + Intent intent = new Intent(context, Downloader.class); + intent.putExtra(CommonString.KEY_Break_Mangemennt, masterBreakObject); + Downloader.enqueueWork(context, intent); + AlertandMessages.showToastMsg(context, "Break End Successfully."); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + BreakManagementActivity.this.finish(); + + } + + }).setNegativeButton(android.R.string.cancel, (dialogInterface, i) -> dialogInterface.dismiss()); + + alert.show(); + } + } + + } + + private void calculate_spin() { + db.open(); + breakmanageList = db.getmasterBreak(); + break_managemntAdapter = new ArrayAdapter<>(context, R.layout.spinner_custom_item); + break_managemntAdapter.add("- Select Break Type -"); + + for (int i = 0; i < breakmanageList.size(); i++) { + break_managemntAdapter.add(breakmanageList.get(i).getBreakType()); + } + + spin_break_Type.setAdapter(break_managemntAdapter); + break_managemntAdapter.setDropDownViewResource(R.layout.spinner_custom_item); + spin_break_Type.setOnItemSelectedListener(this); + } + + @Override + public void onItemSelected(AdapterView adapterView, View view, int pos, long l) { + if (pos != 0) { + clicked_flag = true; + breakType = breakmanageList.get(pos - 1).getBreakType(); + breakId = breakmanageList.get(pos - 1).getBreakId().toString(); + if (breakType.equalsIgnoreCase("Lunch Break")) { + if (!validatefor_lunch()) { + AlertandMessages.showToastMsg(context, "Only One Time Lunch Break Allowed"); + spin_break_Type.setSelection(0); + breakType = ""; + breakId = "0"; + } + } else if (breakType.equalsIgnoreCase("Tea Break")) { + if (validatefor_tea() == 2) { + AlertandMessages.showToastMsg(context, "Only Two Time Tea Break Allowed"); + spin_break_Type.setSelection(0); + breakType = ""; + breakId = "0"; + } + } + } else { + breakType = ""; + breakId = "0"; + + } + } + + @Override + public void onNothingSelected(AdapterView adapterView) { + + } + + public class ValueAdapter extends RecyclerView.Adapter { + LayoutInflater inflator; + List data; + + public ValueAdapter(Context context, List data) { + inflator = LayoutInflater.from(context); + this.data = data; + } + + + @NonNull + @Override + public ValueAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) { + View view = inflator.inflate(R.layout.break_management_list, parent, false); + return new ValueAdapter.MyViewHolder(view); + } + + @Override + public void onBindViewHolder(final ValueAdapter.MyViewHolder holder, final int position) { + final MasterBreak current = data.get(position); + + holder.txt_breakType.setText(current.getBreakType()); + holder.txt_breakType.setId(position); + + holder.startTym.setText(current.getStartTym()); + holder.startTym.setId(position); + + holder.endTym.setText(current.getEndTym()); + holder.endTym.setId(position); + + holder.totalDuration.setText(current.getTotalDuration()); + holder.totalDuration.setId(position); + + } + + + @Override + public int getItemCount() { + return data.size(); + } + + class MyViewHolder extends RecyclerView.ViewHolder { + TextView txt_breakType, startTym, endTym, totalDuration; + + public MyViewHolder(View itemView) { + super(itemView); + txt_breakType = (TextView) itemView.findViewById(R.id.txt_breakType); + startTym = (TextView) itemView.findViewById(R.id.startTym); + endTym = (TextView) itemView.findViewById(R.id.endTym); + totalDuration = (TextView) itemView.findViewById(R.id.totalDuration); + } + } + + } + + private String getTime() { + Calendar currnetDateTime = Calendar.getInstance(); + @SuppressLint("SimpleDateFormat") SimpleDateFormat df = new SimpleDateFormat("hh:mm a"); + return df.format(currnetDateTime.getTime()); + } + + private String calculateTotalDuration() { + @SuppressLint("SimpleDateFormat") SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh:mm a"); + int days = 0, hours = 0, min = 0; + try { + Date date1 = simpleDateFormat.parse(startTym); + Date date2 = simpleDateFormat.parse(endTym); + assert date2 != null; + assert date1 != null; + long difference = date2.getTime() - date1.getTime(); + days = (int) (difference / (1000 * 60 * 60 * 24)); + hours = (int) ((difference - (1000 * 60 * 60 * 24 * days)) / (1000 * 60 * 60)); + min = (int) (difference - (1000 * 60 * 60 * 24 * days) - (1000 * 60 * 60 * hours)) / (1000 * 60); + hours = (hours < 0 ? -hours : hours); + Log.i("======= Hours", " :: " + hours); + } catch (ParseException e) { + e.fillInStackTrace(); + } + return hours + ":" + min; + } + + private boolean validatefor_lunch() { + String str = "Lunch"; + boolean flag = true; + if (insertedBreakList.size() > 0) { + for (int k = 0; k < insertedBreakList.size(); k++) { + if (!insertedBreakList.get(k).getEndTym().equals("") && insertedBreakList.get(k).getBreakType().equalsIgnoreCase(str)) { + flag = false; + break; + } + } + } + return flag; + } + + private int validatefor_tea() { + String str = "Tea"; + int count = 0; + if (insertedBreakList.size() > 0) { + for (int k = 0; k < insertedBreakList.size(); k++) { + if (!insertedBreakList.get(k).getEndTym().equals("") && insertedBreakList.get(k).getBreakType().equalsIgnoreCase(str)) { + count++; + } + } + } + return count; + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/bulkInsert/DBContract.java b/app/src/main/java/com/cpm/lorealbaautomation/bulkInsert/DBContract.java new file mode 100644 index 0000000..563c3e5 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/bulkInsert/DBContract.java @@ -0,0 +1,45 @@ +package com.cpm.lorealbaautomation.bulkInsert; + +import android.content.ContentResolver; +import android.content.ContentUris; +import android.net.Uri; +import android.provider.BaseColumns; + +import com.cpm.lorealbaautomation.BuildConfig; + +public class DBContract { + /*Content Authority its a name for the content provider, is convenient to use the + package app name to be unique on the device */ + public static final String CONTENT_AUTHORITY = BuildConfig.APPLICATION_ID; + + //Use CONTENT_AUTHORITY to create all the database URI's that + // the app will use to link the content provider. + public static final Uri BASE_CONTENT_URI = Uri.parse("content://" + CONTENT_AUTHORITY); + + /*the name of the uri that can be the same as the name of your table. + this will translate to content://com.yourdomain.yourapp/user/ as a valid URI + */ + public static final String PATH_USER = "User"; + + // To prevent someone from accidentally instantiating the contract class, + // give it an empty constructor. + public DBContract() { + } + + //Intern class that defines the user table + public static final class UserEntry implements BaseColumns { + public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon(). + appendPath(PATH_USER).build(); + + public static final String CONTENT_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE + "/" + CONTENT_AUTHORITY + "/" + PATH_USER; + + //Name of the table + public static final String TABLE_NAME = "User"; + //Columns of the user table + public static final String COLUMN_Name = "Name"; + public static final String COLUMN_Password = "Password"; + public static Uri buildUri(long id) { + return ContentUris.withAppendedId(CONTENT_URI, id); + } + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/bulkInsert/DBHelper.java b/app/src/main/java/com/cpm/lorealbaautomation/bulkInsert/DBHelper.java new file mode 100644 index 0000000..fcd7efc --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/bulkInsert/DBHelper.java @@ -0,0 +1,46 @@ +package com.cpm.lorealbaautomation.bulkInsert; + +import android.content.Context; +import android.database.sqlite.SQLiteDatabase; +import android.database.sqlite.SQLiteOpenHelper; + +public class DBHelper extends SQLiteOpenHelper { + //if you change the schema of the database, you must increment this number + private static final int DATABASE_VERSION=1; + static final String DATABASE_NAME="mydatabase.db"; + private static DBHelper mInstance=null; + public static DBHelper getInstance(Context ctx){ + if(mInstance==null){ + mInstance= new DBHelper(ctx.getApplicationContext()); + } + return mInstance; + } + + public DBHelper(Context context){ + super(context,DATABASE_NAME,null,DATABASE_VERSION); + } + + public int GetDatabase_Version() { + return DATABASE_VERSION; + } + + @Override + public void onCreate(SQLiteDatabase sqLiteDatabase){ +//Create the table users + final String SQL_CREATE_TABLE_USERS="CREATE TABLE "+ DBContract.UserEntry.TABLE_NAME+ " ("+ + DBContract.UserEntry._ID+" INTEGER PRIMARY KEY, "+ + DBContract.UserEntry.COLUMN_Name+" TEXT , "+ + DBContract.UserEntry.COLUMN_Password+" TEXT "+ + " ); "; + + sqLiteDatabase.execSQL(SQL_CREATE_TABLE_USERS); + + } + + @Override + public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) { + sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + DBContract.UserEntry.TABLE_NAME); + } + +} + diff --git a/app/src/main/java/com/cpm/lorealbaautomation/bulkInsert/DBProvider.java b/app/src/main/java/com/cpm/lorealbaautomation/bulkInsert/DBProvider.java new file mode 100644 index 0000000..a2ab83d --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/bulkInsert/DBProvider.java @@ -0,0 +1,164 @@ +package com.cpm.lorealbaautomation.bulkInsert; + +import android.content.ContentProvider; +import android.content.ContentValues; +import android.content.Context; +import android.content.UriMatcher; +import android.database.Cursor; +import android.database.sqlite.SQLiteDatabase; +import android.net.Uri; + +public class DBProvider extends ContentProvider { + private static final UriMatcher sUriMatcher = buildUriMatcher(); + private DBHelper mDBHelper; + private Context mContext; + static final int USER = 100; + + static UriMatcher buildUriMatcher() { + + final UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH); + final String authority = DBContract.CONTENT_AUTHORITY; + + matcher.addURI(authority, DBContract.PATH_USER, USER); + + return matcher; + } + + @Override + public boolean onCreate() { + mDBHelper = new DBHelper(getContext()); + return false; + } + + public void PeaberryProvider(Context context) { + mDBHelper = DBHelper.getInstance(context); + mContext = context; + } + + @Override + public String getType(Uri uri) { + // determine what type of Uri is + final int match = sUriMatcher.match(uri); + + switch (match) { + case USER: + return DBContract.UserEntry.CONTENT_TYPE; + + default: + throw new UnsupportedOperationException("Uri unknown: " + uri); + } + } + + @Override + public Cursor query(Uri uri, String[] projection, String selection, String[] + selectionArgs, String sortOrder) { + Cursor retCursor; + try { + switch (sUriMatcher.match(uri)) { + case USER: { + retCursor = mDBHelper.getReadableDatabase().query( + DBContract.UserEntry.TABLE_NAME, + projection, + selection, + selectionArgs, + null, + null, + sortOrder + ); + break; + } + default: + throw new UnsupportedOperationException("Uri unknown: " + uri); + } + } catch (Exception ex) { + //test("Cursor", ex.toString()); + } finally { + mDBHelper.close(); + } + return null; + } + + @Override + public Uri insert(Uri uri, ContentValues values) { + final SQLiteDatabase db = mDBHelper.getWritableDatabase(); + final int match = sUriMatcher.match(uri); + Uri returnUri; + try { + + switch (match) { + case USER: { + long _id = db.insert(DBContract.UserEntry.TABLE_NAME, null, values); + if (_id > 0) + returnUri = DBContract.UserEntry.buildUri(_id); + else + throw new android.database.SQLException("Error at inserting row in " + uri); + break; + } + default: + throw new UnsupportedOperationException("Uri unknown: " + uri); + } + mContext.getContentResolver().notifyChange(uri, null); + return returnUri; + } catch (Exception ex) { + //test("Insert", ex.toString()); + db.close(); + } finally { + db.close(); + } + return null; + } + + @Override + public int delete(Uri uri, String selection, String[] selectionArgs) { + try (SQLiteDatabase db = DBHelper.getInstance(mContext).getWritableDatabase()) { + final int match = sUriMatcher.match(uri); + int deletedRows; + if (null == selection) selection = "1"; + try { + switch (match) { + case USER: + deletedRows = db.delete( + DBContract.UserEntry.TABLE_NAME, selection, selectionArgs); + break; + default: + throw new UnsupportedOperationException("Uri unknown: " + uri); + } + if (deletedRows != 0) { + mContext.getContentResolver().notifyChange(uri, null); + } + return deletedRows; + } catch (Exception ex) { + //test("Insert", ex.toString()); + } finally { + db.close(); + } + } + return 0; + } + + @Override + public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { + final SQLiteDatabase db = mDBHelper.getWritableDatabase(); + final int match = sUriMatcher.match(uri); + int updatedRows; + try { + switch (match) { + case USER: + updatedRows = db.update(DBContract.UserEntry.TABLE_NAME, values, selection, selectionArgs); + break; + default: + throw new UnsupportedOperationException("Uri unknown: " + uri); + } + if (updatedRows != 0) { + mContext.getContentResolver().notifyChange(uri, null); + } + return updatedRows; + } catch (Exception ex) { + //test("Update", ex.toString()); + } finally { + db.close(); + } + + return -1; + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/competitionoffer/CompetitionOfferActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/competitionoffer/CompetitionOfferActivity.java new file mode 100644 index 0000000..003ef70 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/competitionoffer/CompetitionOfferActivity.java @@ -0,0 +1,1534 @@ +package com.cpm.lorealbaautomation.competitionoffer; + +import static com.cpm.lorealbaautomation.constant.CommonFunctions.getCurrentTime; +import static com.cpm.lorealbaautomation.dailyactivity.StoreImageActivity.convertBitmap; + +import androidx.annotation.NonNull; +import androidx.appcompat.app.AlertDialog; +import androidx.appcompat.app.AppCompatActivity; +import androidx.appcompat.widget.Toolbar; +import androidx.core.content.ContextCompat; +import androidx.core.widget.NestedScrollView; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; + +import android.annotation.SuppressLint; +import android.app.DatePickerDialog; +import android.app.Dialog; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.graphics.Color; +import android.graphics.Typeface; +import android.graphics.drawable.ColorDrawable; +import android.os.Build; +import android.os.Bundle; +import android.text.Editable; +import android.text.InputType; +import android.text.TextWatcher; +import android.util.DisplayMetrics; +import android.util.Log; +import android.util.TypedValue; +import android.view.Gravity; +import android.view.LayoutInflater; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; +import android.view.Window; +import android.view.WindowManager; +import android.widget.AdapterView; +import android.widget.ArrayAdapter; +import android.widget.Button; +import android.widget.EditText; +import android.widget.ImageView; +import android.widget.LinearLayout; +import android.widget.Spinner; +import android.widget.TextView; +import android.widget.Toast; + +import com.google.android.material.floatingactionbutton.FloatingActionButton; +import com.google.gson.Gson; +import com.google.zxing.integration.android.IntentIntegrator; +import com.google.zxing.integration.android.IntentResult; +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.constant.AlertandMessages; +import com.cpm.lorealbaautomation.constant.CommonFunctions; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.databinding.CompetitionOfferBaDetailBinding; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.gettersetter.BaTenureDetail; +import com.cpm.lorealbaautomation.gettersetter.MasterCompetitionOffer; +import com.cpm.lorealbaautomation.gettersetter.MasterCompetitionOfferSaleRange; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterCompetitionOfferGet; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterCompetitionOfferSet; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterCompetitionProductType; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterCompetitionPromoType; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterCompetitonBrandWiseNuance; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.File; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Calendar; +import java.util.Collections; +import java.util.Date; +import java.util.List; +import java.util.Objects; + +public class CompetitionOfferActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemSelectedListener { + Lorealba_Database db; + Context context; + SharedPreferences preferences; + String counter_id, visit_date, username, _pathforcheck, _path; + double tvapercent = 0.0; + double avgtarget = 0.0; + double avgofftake = 0.0; + ArrayAdapter companyAdapter, nuanceAdapter, promoTypeAdapter, comOfferSetAdapter, comOfferGetAdapter, dataForMonthAdapter, productTypeAdapter, + compOfferSaleAdapter, spinBuyTypeAdapter, spinbuyTypeInputAdapter, spingetTypeInputAdapter; + ArrayList companies, nuances = new ArrayList<>(); + ArrayList competitionPromoTypes = new ArrayList<>(); + ArrayList competitionOfferSaleRange = new ArrayList<>(); + ArrayList competitionOfferSets = new ArrayList<>(); + ArrayList competitionOfferGets = new ArrayList<>(); + ArrayList productTypes = new ArrayList<>(); + ArrayList competitionOfferType, competitionBuyType, competitionBuyTypeInput, competitionGetTypeInput = new ArrayList<>(); + ArrayList insertList = new ArrayList<>(); + ImageView img_FromDate, img_toDate, imgComoOffer, img_button_yes, img_button_no; + Spinner spinCompany, spinNuance, spinPromoType, spinBuy, spinPromoGet, spinProductType, spinDataforMonth, spingwp; + EditText edtPromotionDetails, edtBuyQTY, edtGetQTY, avgOfftakeET, tvapercentET, avgTargetET; + NestedScrollView scroll_view; + TextView tvFromDate, tvToDate; + CompOfferAdapter compOfferAdapter; + FloatingActionButton btn_add, fab_save; + RecyclerView recyclCompDetails; + LinearLayout ll_hide; + + String compofferdata = "", spinbuyTypedata = "", spinbuyTypeInputData = "", spingetTypeInputData = "", counterData = "", noOfBa = "", saleRange = "", gwpstatus = ""; + int compOfferId = 0, spinbuyTypeId = 0, spinbuyTypeInputId = 0, spingetTypeInputId = 0, saleRangeId = 0; + EditText edtNewLaunchMrp; + String gwpAvailable = ""; + + + String company = "", nounce_str = "", promoType = "", compOfferset = "", compOfferGet = "", + present_or_not = "", img_comp_offer = "", productType = "", img_gwp = ""; + int companyId = 0, nuanceId = 0, promoTypeId = 0, compOfferSetId = 0, compOfferGetId = 0, productTypeId = 0; + boolean ischanged = false, compOfferaddflag = false, ShowProductTypeDropdown = true; + int mYear, mMonth, mDay; + DatePickerDialog dpd; + Calendar c; + private final List> allBAEditTexts = new ArrayList<>(); + + //New Competition Offer Module + + String[] noofcounter = {"Select", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"}; + String[] noofba = {"Select", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"}; + String[] spngwpdata = {"Select", "Yes", "No"}; + Spinner spincounter, spinba, spinmonthlysale, spinbuyType, spinbuytypeinput, spinGetTypeInput; + + LinearLayout containerBAViews; + ImageView gwpIV; + + @SuppressLint("SetTextI18n") + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_competition_offer); + context = this; + db = new Lorealba_Database(context); + getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); + validateUIData(); + SetSpinnerData(); + setDataToListView(); + String couter_code = preferences.getString(CommonString.KEY_COUNTER_CODE, ""); + TextView txt_counter_code = (TextView) findViewById(R.id.txt_counter_code); + txt_counter_code.setText("Counter Code - " + couter_code + " / Id - " + counter_id); + } + + private void validateUIData() { + preferences = PrefHelper.getPrefs(context); + counter_id = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + username = preferences.getString(CommonString.KEY_USERNAME, ""); + containerBAViews = findViewById(R.id.containerBAViews); + gwpIV = findViewById(R.id.gwpIV); + spingwp = findViewById(R.id.spingwp); + + Toolbar toolbar = findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + Objects.requireNonNull(getSupportActionBar()).setHomeButtonEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + + if (!CommonFunctions.isTablet(context)) { + toolbar.setTitleTextAppearance(context, R.style.changestext_sizefor_mobile); + } + + setTitle("Competition Intelligence - " + visit_date); + scroll_view = (NestedScrollView) findViewById(R.id.scroll_view); + img_button_yes = (ImageView) findViewById(R.id.img_button_yes); + img_button_no = (ImageView) findViewById(R.id.img_button_no); + imgComoOffer = (ImageView) findViewById(R.id.imgComoOffer); + img_FromDate = (ImageView) findViewById(R.id.img_FromDate); + img_toDate = (ImageView) findViewById(R.id.img_toDate); + + avgTargetET = findViewById(R.id.avgTargetET); + avgOfftakeET = findViewById(R.id.avgOfftakeET); + tvapercentET = findViewById(R.id.tvapercentET); + + spinPromoType = (Spinner) findViewById(R.id.spinPromoType); + spinPromoGet = (Spinner) findViewById(R.id.spinPromoGet); + spinCompany = (Spinner) findViewById(R.id.spinCompany); + spinNuance = (Spinner) findViewById(R.id.spinNuance); + spinBuy = (Spinner) findViewById(R.id.spinBuy); + spinDataforMonth = (Spinner) findViewById(R.id.spinDataforMonth); + //New Ravi + spincounter = (Spinner) findViewById(R.id.spincounter); + spinba = (Spinner) findViewById(R.id.spinba); + spinmonthlysale = (Spinner) findViewById(R.id.spinmonthlysale); + spinbuyType = (Spinner) findViewById(R.id.spinbuyType); + spinbuytypeinput = (Spinner) findViewById(R.id.spinbuytypeinput); + spinGetTypeInput = (Spinner) findViewById(R.id.spinGetTypeInput); + edtNewLaunchMrp = (EditText) findViewById(R.id.edtNewLaunchMrp); + // + + spinDataforMonth = (Spinner) findViewById(R.id.spinDataforMonth); + spinDataforMonth = (Spinner) findViewById(R.id.spinDataforMonth); + + tvToDate = (TextView) findViewById(R.id.tvToDate); + tvFromDate = (TextView) findViewById(R.id.tvFromDate); + edtPromotionDetails = (EditText) findViewById(R.id.edtPromotionDetails); + edtBuyQTY = (EditText) findViewById(R.id.edtBuyQTY); + edtGetQTY = (EditText) findViewById(R.id.edtGetQTY); + edtBuyQTY.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL + | InputType.TYPE_NUMBER_FLAG_SIGNED); + edtGetQTY.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL + | InputType.TYPE_NUMBER_FLAG_SIGNED); + btn_add = (FloatingActionButton) findViewById(R.id.btn_add); + fab_save = (FloatingActionButton) findViewById(R.id.fab_save); + + recyclCompDetails = (RecyclerView) findViewById(R.id.recyclCompDetails); + ll_hide = (LinearLayout) findViewById(R.id.ll_hide); + + img_FromDate.setOnClickListener(this); + img_toDate.setOnClickListener(this); + imgComoOffer.setOnClickListener(this); + gwpIV.setOnClickListener(this); + img_button_yes.setOnClickListener(this); + img_button_no.setOnClickListener(this); + fab_save.setOnClickListener(this); + btn_add.setOnClickListener(this); + + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { + scroll_view.setOnScrollChangeListener((View.OnScrollChangeListener) (v, scrollX, scrollY, oldScrollX, oldScrollY) -> { + if (scrollY > oldScrollY) { + fab_save.hide(); + } else { + fab_save.show(); + } + }); + } + } + + public void SetSpinnerData() { + ArrayAdapter counter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, noofcounter); + counter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); + spincounter.setAdapter(counter); + + ArrayAdapter baAdapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, noofba); + baAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); + spinba.setAdapter(baAdapter); + + ArrayAdapter spingwpAdapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, spngwpdata); + baAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); + spingwp.setAdapter(spingwpAdapter); + + spincounter.setOnItemSelectedListener(this); + spinba.setOnItemSelectedListener(this); + spingwp.setOnItemSelectedListener(this); + + db.open(); + companies = db.getcompanies(false, 0); + companyAdapter = new ArrayAdapter<>(context, android.R.layout.simple_spinner_item); + companyAdapter.add("- Select -"); + for (int i = 0; i < companies.size(); i++) { + companyAdapter.add(companies.get(i).getCompetitionBrand()); + } + + spinCompany.setAdapter(companyAdapter); + companyAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); + spinCompany.setOnItemSelectedListener(this); + + dataForMonthAdapter = new ArrayAdapter<>(context, android.R.layout.simple_spinner_item); + dataForMonthAdapter.add("- Select -"); + for (int i = 0; i < getYearForExpiry().size(); i++) { + dataForMonthAdapter.add(getYearForExpiry().get(i)); + } + + spinDataforMonth.setAdapter(dataForMonthAdapter); + dataForMonthAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); + spinDataforMonth.setOnItemSelectedListener(this); + + //for Sale Range + db.open(); + competitionOfferSaleRange = db.getCompOfferSaleRange(); + //test("salerangesize", String.valueOf(competitionOfferSaleRange.size())); + compOfferSaleAdapter = new ArrayAdapter<>(context, android.R.layout.simple_spinner_item); + compOfferSaleAdapter.add("- Select -"); + for (int i = 0; i < competitionOfferSaleRange.size(); i++) { + compOfferSaleAdapter.add(competitionOfferSaleRange.get(i).getSaleRange()); + } + spinmonthlysale.setAdapter(compOfferSaleAdapter); + compOfferSaleAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); + spinmonthlysale.setOnItemSelectedListener(this); + + ///for brand + db.open(); + competitionOfferSets = db.getComOfferSet(); + comOfferSetAdapter = new ArrayAdapter<>(context, android.R.layout.simple_spinner_item); + comOfferSetAdapter.add("- Select -"); + for (int i = 0; i < competitionOfferSets.size(); i++) { + comOfferSetAdapter.add(competitionOfferSets.get(i).getCompetitionOfferSet()); + } + + spinBuy.setAdapter(comOfferSetAdapter); + comOfferSetAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); + spinBuy.setOnItemSelectedListener(this); + //compoffer + db.open(); + competitionOfferType = db.getCompOfferType(true, false, false, false, 0, 0, 0); + //test("compoffersize", String.valueOf(competitionOfferType.size())); + promoTypeAdapter = new ArrayAdapter<>(context, android.R.layout.simple_spinner_item); + promoTypeAdapter.add("- Select -"); + for (int i = 0; i < competitionOfferType.size(); i++) { + promoTypeAdapter.add(competitionOfferType.get(i).getCompOffer()); + } + spinPromoType.setAdapter(promoTypeAdapter); + promoTypeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); + spinPromoType.setOnItemSelectedListener(this); + } + + @Override + public void onClick(View v) { + int id = v.getId(); + + if (id == R.id.imgComoOffer) { + _pathforcheck = counter_id + "-CompOfferImg-" + username + "_" + visit_date.replace("/", "") + + "_" + getCurrentTime().replace(":", "") + ".jpg"; + _path = CommonString.getImagesFolder(context) + _pathforcheck; + CommonFunctions.startAnncaCameraActivity(context, _path, null, false, CommonString.CAMERA_FACE_REAR); + + } else if (id == R.id.gwpIV) { + _pathforcheck = counter_id + "-Gwp_CompOfferImg-" + username + "_" + visit_date.replace("/", "") + + "_" + getCurrentTime().replace(":", "") + ".jpg"; + _path = CommonString.getImagesFolder(context) + _pathforcheck; + CommonFunctions.startAnncaCameraActivity(context, _path, null, false, CommonString.CAMERA_FACE_REAR); + + } else if (id == R.id.img_FromDate) { + c = Calendar.getInstance(); + mYear = c.get(Calendar.YEAR); + mMonth = c.get(Calendar.MONTH); + mDay = c.get(Calendar.DAY_OF_MONTH); + dpd = new DatePickerDialog(context, (view, year, monthOfYear, dayOfMonth) -> { + String current_monthFromDate = (monthOfYear + 1 < 10) ? "0" + (monthOfYear + 1) : String.valueOf(monthOfYear + 1); + String daysFromDate = (dayOfMonth < 10) ? "0" + dayOfMonth : String.valueOf(dayOfMonth); + String dob = current_monthFromDate + "/" + daysFromDate + "/" + year; + tvFromDate.setText(dob); + }, mYear, mMonth, mDay); + dpd.show(); + + } else if (id == R.id.img_toDate) { + if (tvFromDate.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Select From Date"); + } else { + c = Calendar.getInstance(); + mYear = c.get(Calendar.YEAR); + mMonth = c.get(Calendar.MONTH); + mDay = c.get(Calendar.DAY_OF_MONTH); + dpd = new DatePickerDialog(context, (view, year, monthOfYear, dayOfMonth) -> { + String current_month = (monthOfYear + 1 < 10) ? "0" + (monthOfYear + 1) : String.valueOf(monthOfYear + 1); + String days = (dayOfMonth < 10) ? "0" + dayOfMonth : String.valueOf(dayOfMonth); + String dob = current_month + "/" + days + "/" + year; + tvToDate.setText(dob); + }, mYear, mMonth, mDay); + + try { + @SuppressLint("SimpleDateFormat") SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy"); + Date d = sdf.parse(tvFromDate.getText().toString()); + assert d != null; + dpd.getDatePicker().setMinDate(d.getTime()); + } catch (ParseException e) { + e.fillInStackTrace(); + } + + dpd.show(); + } + + } else if (id == R.id.img_button_yes) { + db.open(); + if (db.isCompOffersFilled(visit_date, counter_id)) { + AlertandMessages.showToastMsg(context, "Some data already uploaded,you cannot select 'Available'."); + } else { + if (insertList.size() > 0) { + if (insertList.get(0).getKeyId() == null && insertList.get(0).getPresent_str().equals("0")) { + insertList.clear(); + } + } + ischanged = true; + present_or_not = "1"; + img_button_yes.setImageResource(R.mipmap.available); + img_button_no.setImageResource(R.mipmap.not_available_grey); + ll_hide.setVisibility(View.VISIBLE); + recyclCompDetails.setVisibility(View.VISIBLE); + } + + } else if (id == R.id.img_button_no) { + db.open(); + if (db.isCompOffersFilled(visit_date, counter_id)) { + AlertandMessages.showToastMsg(context, "Some data already uploaded,you cannot select 'Not Available'."); + } else { + insertList.clear(); + call_not_present(); + } + + } else if (id == R.id.btn_add) { + try { + if (validation()) { + @SuppressLint("NotifyDataSetChanged") AlertDialog.Builder builder4 = new AlertDialog.Builder(context) + .setTitle(getString(R.string.parinaam)) + .setMessage("Are you sure you want to add ?") + .setCancelable(false) + .setPositiveButton("Yes", (dialog, dialogId) -> { + compOfferaddflag = true; + List tenureDetailsnew = getBaTenureDetailList(); + MasterCompetitonBrandWiseNuance compOffer = new MasterCompetitonBrandWiseNuance(); + compOffer.setPresent_str("1"); + compOffer.setDateOfMonth(spinDataforMonth.getSelectedItem().toString()); + compOffer.setCompetitionBrandId(companyId); + compOffer.setCompetitionBrand(company); + compOffer.setCompetitionNuanceId(nuanceId); + compOffer.setCompetitionNuance(nounce_str); + compOffer.setPromoType(compofferdata); + compOffer.setPromoTypeId(compOfferId); + compOffer.setBuyType(spinbuyTypedata); + compOffer.setBuyTypeId(spinbuyTypeId); + compOffer.setBuyTypeInput(spinbuyTypeInputData); + compOffer.setBuyTypeInputId(spinbuyTypeInputId); + compOffer.setGetTypeInput(spingetTypeInputData); + compOffer.setGetTypeInputId(spingetTypeInputId); + compOffer.setCounter(counterData); + compOffer.setNoOfBa(noOfBa); + compOffer.setGwpAvailable(gwpAvailable); + compOffer.setSaleRange(saleRange); + compOffer.setFromDate(tvFromDate.getText().toString()); + compOffer.setToDate(tvToDate.getText().toString()); + compOffer.setCompOfferImg(img_comp_offer); + compOffer.setGwpImage(img_gwp); + compOffer.setCompPromDetail(CommonFunctions.removed_special_char(edtPromotionDetails)); + compOffer.setNewLaunchMrp(CommonFunctions.removed_special_char(edtNewLaunchMrp)); + compOffer.setAvgtarget(CommonFunctions.removed_special_char(avgTargetET)); + compOffer.setAvgOfftake(CommonFunctions.removed_special_char(avgOfftakeET)); + compOffer.setTvapercent(CommonFunctions.removed_special_char(tvapercentET)); + compOffer.setBaTenureDetailList(tenureDetailsnew); + insertList.add(compOffer); + + compOfferAdapter = new CompOfferAdapter(context, insertList); + recyclCompDetails.setVisibility(View.VISIBLE); + recyclCompDetails.setAdapter(compOfferAdapter); + recyclCompDetails.setLayoutManager(new LinearLayoutManager(context)); + compOfferAdapter.notifyDataSetChanged(); + compOfferaddflag = true; + clear_all_field(); + dialog.dismiss(); + AlertandMessages.showToastMsg(context, "Data has been added"); + }) + .setNegativeButton("No", (dialog, dialogId) -> dialog.dismiss()); + AlertDialog alert = builder4.create(); + alert.show(); + } + } catch (Exception e) { + e.fillInStackTrace(); + } + + } else if (id == R.id.fab_save) { + if (compOfferaddflag && insertList.size() > 0) { + AlertDialog.Builder builder4 = new AlertDialog.Builder(context) + .setTitle(getString(R.string.parinaam)) + .setMessage(getString(R.string.alertsaveData)) + .setCancelable(false) + .setPositiveButton("Yes", (dialog, dialogId) -> { + db.open(); + long l = db.insertCompOffers(username, counter_id, visit_date, getfillderedList(insertList), CommonFunctions.getUUID(context)); + if (l > 0) { + CommonFunctions.call_upload(context); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + AlertandMessages.showToastMsg(context, "Data Saved Successfully"); + CompetitionOfferActivity.this.finish(); + } else { + AlertandMessages.showToastMsg(context, "Data Not Saved."); + } + dialog.dismiss(); + }) + .setNegativeButton("No", (dialog, dialogId) -> dialog.dismiss()); + builder4.show(); + } else { + AlertandMessages.showToastMsg(context, "Please Add First"); + } + } + } + + private void jsondatainsert() throws JSONException { + db.open(); + ArrayList compOffers = db.getInsertedCompOffers(visit_date, counter_id, "0", false); + JSONArray topUpArray = new JSONArray(); + if (compOffers.size() > 0) { + topUpArray = new JSONArray(); + Gson gson = new Gson(); + db.open(); + for (int j = 0; j < compOffers.size(); j++) { + JSONObject obj = new JSONObject(); + obj.put("MID", "0"); + obj.put("Counter_id", counter_id); + obj.put("UserId", compOffers.get(j).get_userId()); + obj.put("TransId", "0"); + + if (compOffers.get(j).getPresent_str().equals("1")) { + String baInfoJson = gson.toJson(compOffers.get(j).getBaTenureDetailList()); + JSONArray baListJsonArray = new JSONArray(baInfoJson); + for (int i = 0; i < baListJsonArray.length(); i++) { + JSONObject baObj = baListJsonArray.getJSONObject(i); + baObj.put("KeyID", compOffers.get(j).getKeyId()); // Add keyid + } + obj.put("Present", compOffers.get(j).getPresent_str()); + if (compOffers.get(j).getGwpAvailable().equalsIgnoreCase("1")) { + obj.put("GWP_Available", 1); + } else { + obj.put("GWP_Available", 0); + } + obj.put("GWP_Image", compOffers.get(j).getGwpImage()); + obj.put("DataForMonth", compOffers.get(j).getDateOfMonth()); + obj.put("KeyID", compOffers.get(j).getKeyId()); + obj.put("CompBrandId", compOffers.get(j).getCompetitionBrandId()); + obj.put("NuanceId", compOffers.get(j).getCompetitionNuanceId()); + obj.put("CompOfferId", compOffers.get(j).getPromoTypeId()); + obj.put("FromDate", compOffers.get(j).getFromDate()); + obj.put("ToDate", compOffers.get(j).getToDate()); + obj.put("CompBuyTypeId", compOffers.get(j).getBuyTypeId()); + obj.put("CompSetId", compOffers.get(j).getBuyTypeInputId()); + obj.put("CompGetId", compOffers.get(j).getGetTypeInputId()); + obj.put("SaleRange", compOffers.get(j).getSaleRange()); + obj.put("NoOfBa", compOffers.get(j).getNoOfBa()); + obj.put("NumOfCounter", compOffers.get(j).getCounter()); + obj.put("NewLaunchMrp", compOffers.get(j).getNewLaunchMrp()); + obj.put("PromoDetails", compOffers.get(j).getCompPromDetail()); + obj.put("CompOfferImg", compOffers.get(j).getCompOfferImg()); + obj.put("AvgTarget", compOffers.get(j).getAvgtarget()); + obj.put("AvgOfftake", compOffers.get(j).getAvgOfftake()); + obj.put("TvaPercentage", compOffers.get(j).getTvapercent()); + obj.put("BAListData", baListJsonArray); + } else { + JSONArray balistdata = new JSONArray(); + obj.put("Present", 0); + obj.put("KeyID", 0); + obj.put("DataForMonth", ""); + obj.put("CompBrandId", 0); + obj.put("NuanceId", 0); + obj.put("CompOfferId", 0); + obj.put("FromDate", ""); + obj.put("ToDate", ""); + obj.put("PromoDetails", ""); + obj.put("CompOfferImg", ""); + obj.put("CompBuyTypeId", 0); + obj.put("CompSetId", 0); + obj.put("CompGetId", 0); + obj.put("SaleRange", ""); + obj.put("NoOfBa", 0); + obj.put("NumOfCounter", 0); + obj.put("NewLaunchMrp", 0); + obj.put("AvgTarget", 0); + obj.put("AvgOfftake", 0); + obj.put("GWP_Image", ""); + obj.put("GWP_Available", 0); + obj.put("TvaPercentage", 0); + obj.put("BAListData", balistdata); + } + + topUpArray.put(obj); + } + String complete_json_str = topUpArray.toString(); + //test("complete_json_str",complete_json_str); + } + } + + private List getBaTenureDetailList() { + List baList = new ArrayList<>(); + + for (List fields : allBAEditTexts) { + String tenure = fields.get(0).getText().toString().trim(); + String experience = fields.get(1).getText().toString().trim(); + String ctc = fields.get(2).getText().toString().trim(); + String regular = fields.get(3).getText().toString().trim(); + String topUp = fields.get(4).getText().toString().trim(); + + // You can validate here too if needed + if (tenure.isEmpty() || experience.isEmpty() || ctc.isEmpty() || regular.isEmpty() || topUp.isEmpty()) { + fields.get(0).requestFocus(); // optional: focus on first field of group + //Toast.makeText(this, "Please fill all BA fields", Toast.LENGTH_SHORT).show(); + return null; + } + BaTenureDetail detail = new BaTenureDetail(); + detail.setTenure(tenure); + detail.setExperience(experience); + detail.setCtc(ctc); + detail.setRegularIncentive(regular); + detail.setTopUpIncentive(topUp); + baList.add(detail); + } + return baList; + } + + @SuppressLint("NonConstantResourceId") + @Override + public void onItemSelected(AdapterView parent, View view, int position, long _id) { + int id = parent.getId(); + if (id == R.id.spinCompany) { + if (position != 0) { + companyId = companies.get(position - 1).getCompetitionBrandId(); + company = companies.get(position - 1).getCompetitionBrand(); + + db.open(); + nuances = db.getcompanies(true, companyId); + nuanceAdapter = new ArrayAdapter<>(context, android.R.layout.simple_spinner_item); + nuanceAdapter.add("- Select -"); + for (int i = 0; i < nuances.size(); i++) { + nuanceAdapter.add(nuances.get(i).getCompetitionNuance()); + } + + spinNuance.setAdapter(nuanceAdapter); + nuanceAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); + spinNuance.setOnItemSelectedListener(this); + } else { + company = ""; + companyId = 0; + } + + } else if (id == R.id.spinNuance) { + if (position != 0) { + nuanceId = nuances.get(position - 1).getCompetitionNuanceId(); + nounce_str = nuances.get(position - 1).getCompetitionNuance(); + } else { + nounce_str = ""; + nuanceId = 0; + } + + } else if (id == R.id.spincounter) { + if (position != 0) { + counterData = spincounter.getSelectedItem().toString(); + } else { + counterData = ""; + } + + } else if (id == R.id.spinba) { + if (position != 0) { + noOfBa = spinba.getSelectedItem().toString(); + generateBAViews(Integer.parseInt(noOfBa)); + containerBAViews.setVisibility(View.VISIBLE); + } else { + noOfBa = ""; + containerBAViews.setVisibility(View.GONE); + } + + } else if (id == R.id.spingwp) { + if (position != 0) { + gwpstatus = spingwp.getSelectedItem().toString(); + if (gwpstatus.equals("Yes")) { + gwpAvailable = "1"; + gwpIV.setVisibility(View.VISIBLE); + } else { + gwpAvailable = "0"; + gwpIV.setVisibility(View.GONE); + } + } else { + gwpstatus = ""; + gwpAvailable = ""; + gwpIV.setVisibility(View.GONE); + } + + } else if (id == R.id.spinmonthlysale) { + if (position != 0) { + saleRange = competitionOfferSaleRange.get(position - 1).getSaleRange(); + } else { + saleRange = ""; + } + + } else if (id == R.id.spinPromoType) { + if (position != 0) { + compofferdata = competitionOfferType.get(position - 1).getCompOffer(); + compOfferId = competitionOfferType.get(position - 1).getCompOfferId(); + db.open(); + competitionBuyType = db.getCompOfferType(false, true, false, false, compOfferId, 0, 0); + spinBuyTypeAdapter = new ArrayAdapter<>(context, android.R.layout.simple_spinner_item); + spinBuyTypeAdapter.add("- Select -"); + for (int i = 0; i < competitionBuyType.size(); i++) { + spinBuyTypeAdapter.add(competitionBuyType.get(i).getCompBuyType()); + } + spinbuyType.setAdapter(spinBuyTypeAdapter); + spinBuyTypeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); + spinbuyType.setOnItemSelectedListener(this); + } else { + compOfferId = 0; + compofferdata = ""; + } + + } else if (id == R.id.spinbuyType) { + if (position != 0) { + spinbuyTypedata = competitionBuyType.get(position - 1).getCompBuyType(); + spinbuyTypeId = competitionBuyType.get(position - 1).getCompBuyTypeId(); + db.open(); + competitionBuyTypeInput = db.getCompOfferType(false, false, true, false, compOfferId, spinbuyTypeId, 0); + spinbuyTypeInputAdapter = new ArrayAdapter<>(context, android.R.layout.simple_spinner_item); + spinbuyTypeInputAdapter.add("- Select -"); + for (int i = 0; i < competitionBuyTypeInput.size(); i++) { + spinbuyTypeInputAdapter.add(competitionBuyTypeInput.get(i).getCompSetName()); + } + spinbuytypeinput.setAdapter(spinbuyTypeInputAdapter); + spinbuyTypeInputAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); + spinbuytypeinput.setOnItemSelectedListener(this); + } else { + spinbuyTypeId = 0; + spinbuyTypedata = ""; + } + + } else if (id == R.id.spinbuytypeinput) { + if (position != 0) { + spinbuyTypeInputData = competitionBuyTypeInput.get(position - 1).getCompSetName(); + spinbuyTypeInputId = competitionBuyTypeInput.get(position - 1).getCompSetId(); + + db.open(); + competitionGetTypeInput = db.getCompOfferType(false, false, false, true, compOfferId, spinbuyTypeId, spinbuyTypeInputId); + spingetTypeInputAdapter = new ArrayAdapter<>(context, android.R.layout.simple_spinner_item); + spingetTypeInputAdapter.add("- Select -"); + for (int i = 0; i < competitionGetTypeInput.size(); i++) { + spingetTypeInputAdapter.add(competitionGetTypeInput.get(i).getCompGetName()); + } + spinGetTypeInput.setAdapter(spingetTypeInputAdapter); + spingetTypeInputAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); + spinGetTypeInput.setOnItemSelectedListener(this); + } else { + spinbuyTypeInputId = 0; + spinbuyTypeInputData = ""; + } + + } else if (id == R.id.spinGetTypeInput) { + if (position != 0) { + spingetTypeInputData = competitionGetTypeInput.get(position - 1).getCompGetName(); + spingetTypeInputId = competitionGetTypeInput.get(position - 1).getCompGetId(); + } else { + spingetTypeInputId = 0; + spingetTypeInputData = ""; + } + + } else if (id == R.id.spinBuy) { + if (position != 0) { + compOfferSetId = competitionOfferSets.get(position - 1).getCompetitionOfferSetId(); + compOfferset = competitionOfferSets.get(position - 1).getCompetitionOfferSet(); + db.open(); + competitionOfferGets = db.getComOfferGet(compOfferSetId); + comOfferGetAdapter = new ArrayAdapter<>(context, android.R.layout.simple_spinner_item); + comOfferGetAdapter.add("- Select -"); + for (int i = 0; i < competitionOfferGets.size(); i++) { + comOfferGetAdapter.add(competitionOfferGets.get(i).getCompetitionOfferGet()); + } + + spinPromoGet.setAdapter(comOfferGetAdapter); + spinPromoGet.setOnItemSelectedListener(this); + comOfferGetAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); + } else { + compOfferSetId = 0; + compOfferset = ""; + } + + } else if (id == R.id.spinPromoGet) { + if (position != 0) { + compOfferGetId = competitionOfferGets.get(position - 1).getCometitionOfferGetId(); + compOfferGet = competitionOfferGets.get(position - 1).getCompetitionOfferGet(); + ShowProductTypeDropdown = competitionOfferGets.get(position - 1).getShowProductTypeDropdown(); + if (ShowProductTypeDropdown) { + spinProductType.setEnabled(true); + spinProductType.setClickable(true); + spinProductType.setBackgroundColor(getResources().getColor(R.color.white)); + } else { + spinProductType.setEnabled(false); + spinProductType.setClickable(false); + spinProductType.setBackgroundColor(getResources().getColor(R.color.grey_background)); + } + } else { + compOfferGet = ""; + compOfferGetId = 0; + ShowProductTypeDropdown = true; + spinProductType.setEnabled(true); + spinProductType.setClickable(true); + spinProductType.setBackgroundColor(getResources().getColor(R.color.white)); + } + + } + + + } + + @SuppressLint("SetTextI18n") + private void generateBAViews(int count) { + containerBAViews.removeAllViews(); // Clear existing views + allBAEditTexts.clear(); + for (int i = 1; i <= count; i++) { + TextView title = new TextView(this); + title.setText("BA-" + i); + title.setTextSize(14); + title.setTextColor(Color.BLACK); + title.setTypeface(null, Typeface.BOLD); + int padding = (int) TypedValue.applyDimension( + TypedValue.COMPLEX_UNIT_DIP, 5, getResources().getDisplayMetrics()); + title.setPadding(padding, padding, padding, padding); + + EditText tenure = createEditText("Tenure with the Brand"); + EditText experience = createEditText("Experience with Beauty"); + EditText ctc = createEditText("CTC"); + EditText regularIncentive = createEditText("Avg Regular Incentive/month"); + EditText topUpIncentive = createEditText("Avg Top-up Incentive/month"); + + List baFields = Arrays.asList(tenure, experience, ctc, regularIncentive, topUpIncentive); + allBAEditTexts.add(baFields); + + containerBAViews.addView(title); + for (EditText editText : baFields) containerBAViews.addView(editText); + } + + } + + private EditText createEditText(String hint) { + EditText editText = new EditText(this); + editText.setHint(hint); + editText.setInputType(InputType.TYPE_CLASS_NUMBER); + LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( + LinearLayout.LayoutParams.MATCH_PARENT, + LinearLayout.LayoutParams.WRAP_CONTENT + ); + + editText.setBackground(ContextCompat.getDrawable(this, R.drawable.rouded_corner_edittaxt)); + // Optional: padding inside EditText + int padding = (int) TypedValue.applyDimension( + TypedValue.COMPLEX_UNIT_DIP, 12, getResources().getDisplayMetrics()); + editText.setPadding(padding, padding, padding, padding); + + int margin = (int) TypedValue.applyDimension( + TypedValue.COMPLEX_UNIT_DIP, 5, editText.getResources().getDisplayMetrics()); + params.setMargins(margin, margin, margin, margin); + + editText.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12); + editText.setTextColor(Color.BLACK); + editText.setHintTextColor(Color.BLACK); + editText.setLayoutParams(params); + return editText; + } + + @Override + public void onNothingSelected(AdapterView parent) { + + } + + private static ArrayList getYearForExpiry() { + ArrayList years = new ArrayList<>(); + Calendar prevYear, calendar; + try { + prevYear = Calendar.getInstance(); + prevYear.add(Calendar.YEAR, 0); + + calendar = Calendar.getInstance(); + calendar.add(Calendar.MONTH, 0); + int month = calendar.get(Calendar.MONTH); + years.add(0, theMonth(month) + " - " + prevYear.get(Calendar.YEAR)); + prevYear = Calendar.getInstance(); + prevYear.add(Calendar.YEAR, 0); + + calendar = Calendar.getInstance(); + calendar.add(Calendar.MONTH, -1); + month = calendar.get(Calendar.MONTH); + years.add(1, theMonth(month) + " - " + prevYear.get(Calendar.YEAR)); + + prevYear = Calendar.getInstance(); + prevYear.add(Calendar.YEAR, 0); + calendar = Calendar.getInstance(); + calendar.add(Calendar.MONTH, -2); + month = calendar.get(Calendar.MONTH); + + years.add(2, theMonth(month) + " - " + prevYear.get(Calendar.YEAR)); + + } catch (Exception e) { + e.fillInStackTrace(); + } + + return years; + } + + + public static String theMonth(int month) { + String[] monthNames = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}; + return monthNames[month]; + } + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data); + if (result == null) { + switch (resultCode) { + case 0: + Log.i("MakeMachine", "User cancelled"); + break; + case -1: + try { + if (_pathforcheck != null && !_pathforcheck.isEmpty()) { + if (new File(CommonString.getImagesFolder(context) + _pathforcheck).exists()) { + convertBitmap(CommonString.getImagesFolder(context) + _pathforcheck); + if (_pathforcheck.contains("-CompOfferImg-")) { + imgComoOffer.setImageResource(R.mipmap.camera_bsd); + img_comp_offer = _pathforcheck; + _pathforcheck = ""; + } else if (_pathforcheck.contains("-Gwp_CompOfferImg-")) { + gwpIV.setImageResource(R.mipmap.camera_bsd); + img_gwp = _pathforcheck; + _pathforcheck = ""; + } + } + } + } catch (Exception e) { + e.fillInStackTrace(); + } + break; + } + } else + super.onActivityResult(requestCode, resultCode, data); + } + + private void call_not_present() { + try { + present_or_not = "0"; + img_button_no.setImageResource(R.mipmap.not_available); + img_button_yes.setImageResource(R.mipmap.available_grey); + ll_hide.setVisibility(View.GONE); + recyclCompDetails.setVisibility(View.GONE); + + MasterCompetitonBrandWiseNuance compOffer = new MasterCompetitonBrandWiseNuance(); + compOffer.setPresent_str("0"); + compOffer.setDateOfMonth(""); + compOffer.setCompetitionBrandId(0); + compOffer.setCompetitionBrand(""); + compOffer.setCompetitionNuanceId(0); + compOffer.setCompetitionNuance(""); + compOffer.setPromoType(""); + compOffer.setPromoTypeId(0); + compOffer.setCompOfferGet(""); + compOffer.setCompOfferGetId(0); + compOffer.setCompOfferset(""); + compOffer.setCompOffersetId(0); + compOffer.setFromDate(""); + compOffer.setToDate(""); + compOffer.setCompOfferImg(""); + compOffer.setCompPromDetail(""); + insertList.add(compOffer); + compOfferaddflag = true; + clear_all_field(); + } catch (Exception e) { + e.fillInStackTrace(); + } + } + + private void clear_all_field() { + tvFromDate.setText(""); + tvToDate.setText(""); + edtBuyQTY.setText("0"); + edtGetQTY.setText("0"); + spinCompany.setSelection(0); + spinNuance.setSelection(0); + spinPromoType.setSelection(0); + allBAEditTexts.clear(); + containerBAViews.setVisibility(View.GONE); + + spincounter.setSelection(0); + spingwp.setSelection(0); + spinba.setSelection(0); + spinmonthlysale.setSelection(0); + spinbuyType.setSelection(0); + spinbuytypeinput.setSelection(0); + spinGetTypeInput.setSelection(0); + spinDataforMonth.setSelection(0); + edtPromotionDetails.setText(""); + edtNewLaunchMrp.setText(""); + avgTargetET.setText(""); + avgOfftakeET.setText(""); + tvapercentET.setText("0.0"); + edtPromotionDetails.setHint("Competition New Launch"); + company = ""; + + counterData = ""; + noOfBa = ""; + gwpAvailable = ""; + saleRange = ""; + spinbuyTypedata = ""; + compofferdata = ""; + spinbuyTypeInputData = ""; + spingetTypeInputData = ""; + nounce_str = ""; + promoType = ""; + compOfferset = ""; + compOfferGet = ""; + companyId = 0; + nuanceId = 0; + promoTypeId = 0; + compOfferSetId = 0; + compOfferGetId = 0; + img_comp_offer = ""; + img_gwp = ""; + compOfferId = 0; + spinbuyTypeId = 0; + spinbuyTypeInputId = 0; + spingetTypeInputId = 0; + imgComoOffer.setImageResource(R.mipmap.camera_bs); + gwpIV.setImageResource(R.mipmap.camera_bs); + } + + private boolean validation() { + boolean flag; + if (present_or_not.equals("")) { + AlertandMessages.showToastMsg(context, "Please Select Competition Intelligence 'Available' OR 'Not Available'"); + flag = false; + } else if (present_or_not.equals("1")) { + List tenureDetails = getBaTenureDetailList(); + if (spinDataforMonth.getSelectedItemId() == 0) { + AlertandMessages.showToastMsg(context, "Please Select Data For Month"); + flag = false; + } else if (spinCompany.getSelectedItemId() == 0) { + AlertandMessages.showToastMsg(context, "Please Select Company"); + flag = false; + } else if (spincounter.getSelectedItemPosition() == 0) { + AlertandMessages.showToastMsg(context, "Please Select No. Of Counters"); + flag = false; + } else if (spinba.getSelectedItemPosition() == 0) { + AlertandMessages.showToastMsg(context, "Please Select No. Of Ba's"); + flag = false; + } else if (tenureDetails == null) { + AlertandMessages.showToastMsg(context, "Please Fill All Ba's Field"); + flag = false; + } else if (spinNuance.getSelectedItemId() == 0) { + AlertandMessages.showToastMsg(context, "Please Select Nuance/Sub Category"); + flag = false; + } else if (spinmonthlysale.getSelectedItemId() == 0) { + AlertandMessages.showToastMsg(context, "Please Select Monthly Sale"); + flag = false; + } else if (spinPromoType.getSelectedItemId() == 0) { + AlertandMessages.showToastMsg(context, "Please Select Competition Intelligence"); + flag = false; + } else if (spinbuyType.getSelectedItemId() == 0) { + AlertandMessages.showToastMsg(context, "Please Select Competition Buy Type"); + flag = false; + } else if (spinbuytypeinput.getSelectedItemId() == 0) { + AlertandMessages.showToastMsg(context, "Please Select Competition Buy Type Input"); + flag = false; + } else if (spinGetTypeInput.getSelectedItemId() == 0) { + AlertandMessages.showToastMsg(context, "Please Select Competition Get Type Input"); + flag = false; + } else if (avgTargetET.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter Average Target"); + flag = false; + } else if (avgOfftakeET.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter Average Offtake"); + flag = false; + } else if (tvFromDate.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Select From Date"); + flag = false; + } else if (tvToDate.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Select To Date"); + flag = false; + } else if (spingwp.getSelectedItemPosition() == 0) { + AlertandMessages.showToastMsg(context, "Please Select Gwp Available Or Not"); + flag = false; + } else if (gwpAvailable.equalsIgnoreCase("1") && img_gwp.equals("")) { + AlertandMessages.showToastMsg(context, "Please Capture Gwp Image"); + flag = false; + } else if (img_comp_offer.equals("")) { + AlertandMessages.showToastMsg(context, "Please Capture Competition Intelligence Details"); + flag = false; + } else { + flag = true; + } + } else { + flag = true; + } + return flag; + } + + private class CompOfferAdapter extends RecyclerView.Adapter { + final LayoutInflater inflator; + Context context; + ArrayList insertedlist_Data; + + CompOfferAdapter(Context context, ArrayList insertedlist_Data) { + inflator = LayoutInflater.from(context); + this.context = context; + this.insertedlist_Data = insertedlist_Data; + } + + @Override + public int getItemCount() { + return insertedlist_Data.size(); + } + + @NonNull + @Override + public CompOfferAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { + View view = inflator.inflate(R.layout.item_comp_offer, parent, false); + return new MyViewHolder(view); + } + + @SuppressLint({"NotifyDataSetChanged", "SetTextI18n"}) + @Override + public void onBindViewHolder(@NonNull final MyViewHolder holder, @SuppressLint("RecyclerView") final int position) { + final MasterCompetitonBrandWiseNuance current = insertedlist_Data.get(position); + + if (current.getKeyId() != null && !current.getStatus().equals("") + && !current.getStatus().equalsIgnoreCase(CommonString.KEY_N)) { + holder.remove.setImageResource(R.mipmap.upload_tick); + holder.remove.setId(position); + holder.remove.setVisibility(View.VISIBLE); + holder.deleteBT.setVisibility(View.GONE); + } else { + holder.remove.setVisibility(View.GONE); + holder.deleteBT.setVisibility(View.VISIBLE); + } + + holder.viewbainfoBT.setOnClickListener(v -> { + if (current.getBaTenureDetailList() != null && !current.getBaTenureDetailList().isEmpty()) { + new BaDetailsDailog(context, current).show(); + } else { + Toast.makeText(context, getResources().getText(R.string.balist_data_not_available), Toast.LENGTH_SHORT).show(); + } + }); + + holder.deleteBT.setOnClickListener(v -> { + if (current.getKeyId() == null) { + AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle(getString(R.string.parinaam)); + builder.setMessage("Are you sure you want to Delete ?") + .setCancelable(false) + .setPositiveButton("Yes", (dialog, id) -> { + deleteImageIfExist(current); + insertedlist_Data.remove(position); + if (insertedlist_Data.size() > 0) { + compOfferAdapter = new CompOfferAdapter(context, insertedlist_Data); + recyclCompDetails.setAdapter(compOfferAdapter); + compOfferAdapter.notifyDataSetChanged(); + } + notifyDataSetChanged(); + }) + .setNegativeButton("No", + (dialog, id) -> dialog.dismiss()); + AlertDialog alert = builder.create(); + alert.show(); + } else if (current.getStatus().equalsIgnoreCase(CommonString.KEY_N)) { + AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle(getString(R.string.parinaam)); + builder.setMessage("Are you sure you want to Delete ?") + .setCancelable(false) + .setPositiveButton("Yes", (dialog, id) -> { + deleteImageIfExist(current); + db.open(); + db.deleteCompOffers(counter_id, visit_date, current.getKeyId()); + insertedlist_Data.remove(position); + if (insertedlist_Data.size() > 0) { + compOfferAdapter = new CompOfferAdapter(context, insertedlist_Data); + recyclCompDetails.setAdapter(compOfferAdapter); + compOfferAdapter.notifyDataSetChanged(); + } + notifyDataSetChanged(); + dialog.dismiss(); + }) + .setNegativeButton("No", + (dialog, id) -> dialog.dismiss()); + AlertDialog alert = builder.create(); + alert.show(); + } + }); + + holder.tvCompany.setText("Company > " + current.getCompetitionBrand()); + holder.tvCompany.setId(position); + + holder.tvNuance.setText("Nuance > " + current.getCompetitionNuance()); + holder.tvNuance.setId(position); + + holder.tvCounter.setText("Counter > " + current.getCounter()); + holder.tvCounter.setId(position); + + holder.tvBa.setText("No. Of Ba > " + current.getNoOfBa()); + holder.tvBa.setId(position); + + holder.tvSale.setText("SaleRange > " + current.getSaleRange()); + holder.tvSale.setId(position); + + holder.tvPromoType.setText("Type > " + current.getPromoType()); + holder.tvPromoType.setId(position); + + holder.tvBuyType.setText("BuyType > " + current.getBuyType()); + holder.tvBuyType.setId(position); + + holder.tvOfferSet.setText("Buy > " + current.getBuyTypeInput()); + holder.tvOfferSet.setId(position); + + holder.tvOfferGet.setText("Get > " + current.getGetTypeInput()); + holder.tvOfferGet.setId(position); + + holder.tvFromDatee.setText("From Date > " + current.getFromDate()); + holder.tvFromDatee.setId(position); + + holder.tvToDatee.setText("To Date > " + current.getToDate()); + holder.tvToDatee.setId(position); + + holder.avgtargetTV.setText("Avg Target > " + current.getAvgtarget()); + holder.avgtargetTV.setId(position); + + holder.avgofftakeTV.setText("Avg Offtake > " + current.getAvgOfftake()); + holder.avgofftakeTV.setId(position); + + holder.tvaperTV.setText("TVA Percent > " + current.getTvapercent()); + holder.tvaperTV.setId(position); + + if (current.getGwpAvailable().equalsIgnoreCase("0")) { + holder.gwpavailableTV.setText("GWP Available > " + "No"); + holder.gwpavailableTV.setId(position); + } else if (current.getGwpAvailable().equalsIgnoreCase("1")) { + holder.gwpavailableTV.setText("GWP Available > " + "Yes"); + holder.gwpavailableTV.setId(position); + } + + holder.remove.setId(position); + holder.deleteBT.setId(position); + } + + class MyViewHolder extends RecyclerView.ViewHolder { + TextView tvCompany, tvNuance, tvPromoType, tvOfferSet, tvOfferGet, tvFromDatee, tvToDatee, + tvCounter, tvBa, tvSale, tvBuyType, avgtargetTV, avgofftakeTV, tvaperTV, gwpavailableTV; + Button viewbainfoBT, deleteBT; + ImageView remove; + + public MyViewHolder(View convertView) { + super(convertView); + gwpavailableTV = convertView.findViewById(R.id.gwpavailableTV); + tvCompany = (TextView) convertView.findViewById(R.id.tvCompany); + tvNuance = (TextView) convertView.findViewById(R.id.tvNuance); + tvPromoType = (TextView) convertView.findViewById(R.id.tvPromoType); + tvOfferSet = (TextView) convertView.findViewById(R.id.tvOfferSet); + tvOfferGet = (TextView) convertView.findViewById(R.id.tvOfferGet); + tvFromDatee = (TextView) convertView.findViewById(R.id.tvFromDatee); + tvToDatee = (TextView) convertView.findViewById(R.id.tvToDatee); + tvCounter = (TextView) convertView.findViewById(R.id.tvCounter); + tvBa = (TextView) convertView.findViewById(R.id.tvBa); + tvSale = (TextView) convertView.findViewById(R.id.tvSale); + tvBuyType = (TextView) convertView.findViewById(R.id.tvBuyType); + avgtargetTV = (TextView) convertView.findViewById(R.id.avgtargetTV); + avgofftakeTV = (TextView) convertView.findViewById(R.id.avgofftakeTV); + tvaperTV = (TextView) convertView.findViewById(R.id.tvaperTV); + remove = (ImageView) convertView.findViewById(R.id.imgDelete); + viewbainfoBT = convertView.findViewById(R.id.viewbainfoBT); + deleteBT = convertView.findViewById(R.id.deleteBT); + + } + } + } + + private void deleteImageIfExist(MasterCompetitonBrandWiseNuance obj) { + try { + File file = new File(CommonString.getImagesFolder(context) + obj.getCompOfferImg()); + if (file.exists()) file.delete(); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + @SuppressLint("NotifyDataSetChanged") + public void setDataToListView() { + try { + db.open(); + insertList = db.getInsertedCompOffers(visit_date, counter_id, null, false); + if (!insertList.isEmpty()) { + try { + if (insertList.get(0).getPresent_str().equals("1")) { + img_button_yes.setImageResource(R.mipmap.available); + present_or_not = "1"; + img_button_no.setImageResource(R.mipmap.not_available_grey); + recyclCompDetails.setVisibility(View.VISIBLE); + ll_hide.setVisibility(View.VISIBLE); + Collections.reverse(insertList); + compOfferAdapter = new CompOfferAdapter(context, insertList); + recyclCompDetails.setAdapter(compOfferAdapter); + recyclCompDetails.setLayoutManager(new LinearLayoutManager(context)); + compOfferAdapter.notifyDataSetChanged(); + } else if (insertList.size() > 0 && insertList.get(0).getPresent_str().equals("0")) { + img_button_no.setImageResource(R.mipmap.not_available); + img_button_yes.setImageResource(R.mipmap.available_grey); + present_or_not = "0"; + recyclCompDetails.setVisibility(View.GONE); + ll_hide.setVisibility(View.GONE); + } else { + img_button_no.setImageResource(R.mipmap.not_available_grey_); + img_button_yes.setImageResource(R.mipmap.available_grey_); + recyclCompDetails.setVisibility(View.GONE); + ll_hide.setVisibility(View.GONE); + present_or_not = ""; + } + + } catch (Exception e) { + e.fillInStackTrace(); + } + } + + } catch (Exception e) { + e.fillInStackTrace(); + } + } + + private ArrayList getfillderedList(ArrayList insertList) { + ArrayList filterData = new ArrayList<>(); + if (insertList.size() > 0) { + for (int k = 0; k < insertList.size(); k++) { + if (insertList.get(k).getKeyId() == null) { + filterData.add(insertList.get(k)); + } + } + } + return filterData; + } + + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + if (id == android.R.id.home) { + if (ischanged) { + android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(context) + .setMessage(CommonString.ONBACK_ALERT_MESSAGE).setCancelable(false).setPositiveButton("Ok", + (dialog, id1) -> { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + CompetitionOfferActivity.this.finish(); + }).setNegativeButton("Cancel", (dialog, id12) -> dialog.cancel()); + android.app.AlertDialog alert = builder.create(); + alert.show(); + } else { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + CompetitionOfferActivity.this.finish(); + } + } + return super.onOptionsItemSelected(item); + } + + @Override + public void onBackPressed() { + if (ischanged) { + android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(context).setMessage(CommonString.ONBACK_ALERT_MESSAGE).setCancelable(false).setPositiveButton("Ok", + (dialog, id) -> { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + CompetitionOfferActivity.this.finish(); + }).setNegativeButton("Cancel", (dialog, id) -> dialog.cancel()); + android.app.AlertDialog alert = builder.create(); + alert.show(); + } else { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + CompetitionOfferActivity.this.finish(); + } + } + + @Override + protected void onResume() { + super.onResume(); + avgOfftakeET.addTextChangedListener(new TextWatcher() { + @Override + public void beforeTextChanged(CharSequence s, int start, int count, int after) { + + } + @Override + public void onTextChanged(CharSequence charSequence, int start, int before, int after) { + // Only calculate percentage when both fields are not empty + } + + @Override + public void afterTextChanged(Editable editable) { + if (!avgTargetET.getText().toString().isEmpty() && !avgOfftakeET.getText().toString().isEmpty()) { + avgtarget = Double.parseDouble(avgTargetET.getText().toString()); + avgofftake = Double.parseDouble(avgOfftakeET.getText().toString()); + tvapercent = (avgofftake / avgtarget) * 100; + tvapercent = Math.round(tvapercent * 10.0) / 10.0; + tvapercentET.setText(String.valueOf(tvapercent)); + } else { + // If either field is empty, set percentage to 0 + tvapercent = 0.0; + tvapercentET.setText("0.0"); + } + // This method is called after the text has changed. + // You can leave it empty if you don't need to do anything after the change. + } + }); + + avgTargetET.addTextChangedListener(new TextWatcher() { + @Override + public void beforeTextChanged(CharSequence s, int start, int count, int after) { + + } + + @Override + public void onTextChanged(CharSequence charSequence, int start, int before, int after) { + // Only calculate percentage when both fields are not empty + } + + @Override + public void afterTextChanged(Editable editable) { + if (!avgTargetET.getText().toString().isEmpty() && !avgOfftakeET.getText().toString().isEmpty()) { + avgtarget = Double.parseDouble(avgTargetET.getText().toString()); + avgofftake = Double.parseDouble(avgOfftakeET.getText().toString()); + tvapercent = (avgofftake / avgtarget) * 100; + tvapercent = Math.round(tvapercent * 10.0) / 10.0; + tvapercentET.setText(String.valueOf(tvapercent)); + } else { + // If either field is empty, set percentage to 0 + tvapercent = 0.0; + tvapercentET.setText("0.0"); + } + // This method is called after the text has changed. + // You can leave it empty if you don't need to do anything after the change. + } + }); + } + + private class BaDetailsDailog extends Dialog { + Context context; + MasterCompetitonBrandWiseNuance current; + + public BaDetailsDailog(Context context, MasterCompetitonBrandWiseNuance current) { + super(context); + this.context = context; + this.current = current; + } + + @SuppressLint({"SetTextI18n", "DefaultLocale"}) + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + requestWindowFeature(Window.FEATURE_NO_TITLE); + com.cpm.lorealbaautomation.databinding.CompetitionOfferBaDetailBinding binding = CompetitionOfferBaDetailBinding.inflate(getLayoutInflater()); + setContentView(binding.getRoot()); + Objects.requireNonNull(getWindow()).setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); + binding.closeDialog.setOnClickListener(v -> dismiss()); + Window window = getWindow(); + if (window != null) { + DisplayMetrics displayMetrics = new DisplayMetrics(); + window.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics); + // int dialogWidthDp = 320; + /* int dialogWidthDp = displayMetrics.widthPixels; + float scale = context.getResources().getDisplayMetrics().density; + int dialogWidthPx = (int) (dialogWidthDp * scale + 0.9f);*/ + int screenWidth = displayMetrics.widthPixels; + int dialogWidth = (int) (screenWidth * 0.9); + + window.setLayout(dialogWidth, ViewGroup.LayoutParams.WRAP_CONTENT); + window.setGravity(Gravity.CENTER); + window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); + } + + + if (current.getBaTenureDetailList() != null) { + int i = 0; + List baList = current.getBaTenureDetailList(); + int total = baList.size(); + for (BaTenureDetail detail : baList) { + // Create parent LinearLayout (horizontal) + LinearLayout horizontalLayout = new LinearLayout(context); + horizontalLayout.setOrientation(LinearLayout.HORIZONTAL); + // Optional: set padding, background, etc. + horizontalLayout.setPadding(10, 10, 10, 20); + // Set layout params for horizontal layout + + // Create first TextView + TextView tv1 = new TextView(context); + tv1.setText( + "Tenure with the Brand : " + "\n" + + "Experience with the beauty : " + "\n" + + "CTC : " + "\n" + + "Avg Regular incentive per month : " + "\n" + + "Avg Top-up incentive per month : " + ); + tv1.setTextSize(13); + tv1.setLineSpacing(10f, 1.0f); + tv1.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD)); + tv1.setTextColor(Color.BLACK); + // Set weight for equal spacing + LinearLayout.LayoutParams tvParams1 = new LinearLayout.LayoutParams( + 0, ViewGroup.LayoutParams.WRAP_CONTENT, 2.5f // width=0, weight=1 + ); + // tvParams1.setMargins(8, 0, 8, 0); + tv1.setPadding(10, 0, 0, 0); + tv1.setLayoutParams(tvParams1); + // Create second TextView + TextView tv2 = new TextView(context); + tv2.setText( + detail.getTenure() + "\n" + + detail.getExperience() + "\n" + + detail.getCtc() + "\n" + + detail.getRegularIncentive() + "\n" + + detail.getTopUpIncentive() + ); + tv2.setTextSize(13); + tv2.setLineSpacing(10f, 1.0f); + tv2.setTextColor(Color.BLACK); + horizontalLayout.addView(tv1); + + LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams( + ViewGroup.LayoutParams.MATCH_PARENT, + ViewGroup.LayoutParams.WRAP_CONTENT + ); + horizontalLayout.setLayoutParams(layoutParams); + + LinearLayout.LayoutParams tvParams2 = new LinearLayout.LayoutParams( + 0, ViewGroup.LayoutParams.WRAP_CONTENT, 1.0f // width=0, weight=1 + ); + //tvParams2.setMargins(8, 0, 8, 0); + // tv2.setPadding(0, 0, 8, 0); + tv2.setLayoutParams(tvParams2); + // Add TextViews to horizontal layout + horizontalLayout.addView(tv2); + + // Finally add horizontal layout to your main container + binding.baListContainer.addView(horizontalLayout); + // binding.baListContainer.addView(divider); + if (i != total - 1) { + View divider = new View(context); + LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( + ViewGroup.LayoutParams.MATCH_PARENT, + 2 + ); + params.setMargins(10, 10, 10, 10); // You can reduce bottom here if needed + divider.setLayoutParams(params); + divider.setBackgroundColor(Color.LTGRAY); + binding.baListContainer.addView(divider); + } + i++; // Increment manually + } + } + } + + @SuppressLint("SetTextI18n") + @Override + protected void onStart() { + super.onStart(); + setCancelable(true); + } + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/constant/AlertandMessages.java b/app/src/main/java/com/cpm/lorealbaautomation/constant/AlertandMessages.java new file mode 100644 index 0000000..a0869f6 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/constant/AlertandMessages.java @@ -0,0 +1,113 @@ +package com.cpm.lorealbaautomation.constant; + +import android.app.Activity; +import android.app.AlertDialog; +import android.content.Context; + +import com.google.android.material.snackbar.Snackbar; +import com.cpm.lorealbaautomation.download.DownloadActivity; + +import android.content.Intent; +import android.widget.Toast; + +import java.util.Objects; + + +/** + * Created by jeevanp on 14-12-2017. + */ + +public class AlertandMessages { + public static final String MESSAGE_SOCKETEXCEPTION = "Network Communication Failure. Check Your Network Connection"; + public static void showAlert(final Activity activity, String str, final Boolean activityFinish) { + try { + AlertDialog.Builder builder = new AlertDialog.Builder(activity); + builder.setTitle("Parinaam"); + builder.setMessage(str).setCancelable(false) + .setPositiveButton(android.R.string.ok, (dialog, id) -> { + if (activityFinish) { + activity.finish(); + } else { + dialog.dismiss(); + } + + }); + AlertDialog alert = builder.create(); + alert.show(); + } catch (Exception e) { + e.fillInStackTrace(); + } + } + + public static void showAlertfordatanotSyncedcompeletetly(final Activity activity, String str, final Boolean activityFinish) { + try { + AlertDialog.Builder builder = new AlertDialog.Builder(activity); + builder.setTitle("Parinaam"); + builder.setMessage(str).setCancelable(false) + .setPositiveButton(android.R.string.ok, (dialog, id) -> { + if (activityFinish) { + activity.finish(); + activity.startActivity(new Intent(activity, DownloadActivity.class).putExtra(CommonString.TAG_FROM, 1)); + } else { + dialog.dismiss(); + } + + }); + AlertDialog alert = builder.create(); + alert.show(); + } catch (Exception e) { + e.fillInStackTrace(); + } + } + + + public static void showAlertlogin(final Activity activity, String str) { + try { + AlertDialog.Builder builder = new AlertDialog.Builder(activity); + builder.setTitle("Parinaam"); + builder.setMessage(str).setCancelable(false) + .setPositiveButton(android.R.string.ok, (dialog, id) -> dialog.dismiss()); + AlertDialog alert = builder.create(); + alert.show(); + } catch (Exception e) { + e.fillInStackTrace(); + } + } + + public static void showAlertCounterlogin(final Activity activity, String str) { + try { + AlertDialog.Builder builder = new AlertDialog.Builder(activity); + builder.setTitle("Parinaam"); + builder.setMessage(str).setCancelable(false) + .setPositiveButton(android.R.string.ok, (dialog, id) -> { + dialog.dismiss(); + activity.finish(); + + + }); + AlertDialog alert = builder.create(); + alert.show(); + } catch (Exception e) { + e.fillInStackTrace(); + } + } + + + public static void showToastMsg(Context context, String message) { + Toast.makeText(context, message, Toast.LENGTH_LONG).show(); + } + + public static void showSnackbarMsg(Context context, String message) { + Snackbar.make(Objects.requireNonNull(((Activity) context).getCurrentFocus()), message, Snackbar.LENGTH_SHORT).show(); + } + + public void backpressedAlert(final Activity activity) { + final AlertDialog.Builder builder = new AlertDialog.Builder(activity); + builder.setTitle("Alert"); + builder.setMessage("Do you want to exit? Filled data will be lost").setCancelable(false) + .setPositiveButton("Ok", (dialog, id) -> activity.finish()); + builder.setNegativeButton("Cancel", (dialog, which) -> dialog.dismiss()); + AlertDialog alert = builder.create(); + alert.show(); + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/constant/CommonFunctions.java b/app/src/main/java/com/cpm/lorealbaautomation/constant/CommonFunctions.java new file mode 100644 index 0000000..130250c --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/constant/CommonFunctions.java @@ -0,0 +1,755 @@ +package com.cpm.lorealbaautomation.constant; + +import android.Manifest; +import android.annotation.SuppressLint; +import android.app.Activity; +import android.app.Dialog; +import android.app.ProgressDialog; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.content.pm.PackageManager; +import android.content.res.Configuration; +import android.graphics.Bitmap; +import android.graphics.BitmapFactory; +import android.graphics.Canvas; +import android.graphics.Color; +import android.graphics.Matrix; +import android.graphics.Paint; +import android.graphics.PorterDuff; +import android.graphics.PorterDuffXfermode; +import android.graphics.Rect; +import android.graphics.RectF; +import android.net.ConnectivityManager; +import android.net.NetworkInfo; +import android.os.Handler; + +import androidx.core.app.ActivityCompat; +import androidx.fragment.app.Fragment; + +import android.text.TextUtils; +import android.util.Patterns; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewTreeObserver; +import android.view.Window; +import android.view.inputmethod.InputMethodManager; +import android.widget.Button; +import android.widget.EditText; +import android.widget.ImageView; +import android.widget.TextView; + +import com.google.firebase.crashlytics.FirebaseCrashlytics; +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.gsonGetterSetter.ProductMaster; +import com.cpm.lorealbaautomation.retrofit.DownloadAllDatawithRetro; +import com.cpm.lorealbaautomation.upload.UploadKeyData; + +import org.json.JSONObject; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Date; +import java.util.Locale; +import java.util.UUID; + +import io.github.memfis19.annca.Annca; +import io.github.memfis19.annca.internal.configuration.AnncaConfiguration; + +/** + * Created by jeevanp on 2/16/2017. + */ + +public class CommonFunctions { + public static boolean checkNetIsAvailable(Context context) { + ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); + NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); + return activeNetwork != null && activeNetwork.isConnectedOrConnecting(); + } + + public static boolean isValidEmail(CharSequence target) { + return !TextUtils.isEmpty(target) && Patterns.EMAIL_ADDRESS.matcher(target).matches(); + } + + public static void startAnncaCameraActivity(final Context context, final String path, Fragment fragment, final boolean showGrid, final int cameraFace) { + if (context != null) { + final AnncaConfiguration.Builder dialogDemo = getBuilder((Activity) context, fragment, cameraFace); + final Dialog dialog = new Dialog(context); + dialog.setContentView(R.layout.view_horizontal_camera); + dialog.setCancelable(false); + if (!dialog.isShowing()) { + dialog.show(); + } + new Handler().postDelayed(() -> { + if (dialog.isShowing()) { + dialog.dismiss(); + } + if (ActivityCompat.checkSelfPermission(context, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { + return; + } + new Annca(dialogDemo.build()).launchCamera(path, showGrid, cameraFace); + }, 1000); + } + + } + + private static AnncaConfiguration.Builder getBuilder(Activity context, Fragment fragment, int cameraFace) { + final AnncaConfiguration.Builder dialogDemo; + if (fragment == null) { + dialogDemo = new AnncaConfiguration.Builder(context, CommonString.CAPTURE_MEDIA); + } else { + dialogDemo = new AnncaConfiguration.Builder(fragment, CommonString.CAPTURE_MEDIA); + } + dialogDemo.setMediaAction(AnncaConfiguration.MEDIA_ACTION_PHOTO); + dialogDemo.setCameraFace(cameraFace); + dialogDemo.setMediaResultBehaviour(AnncaConfiguration.PREVIEW); + return dialogDemo; + } + + public static void setScaledImage(ImageView imageView, final String path) { + final ImageView iv = imageView; + ViewTreeObserver viewTreeObserver = iv.getViewTreeObserver(); + viewTreeObserver.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { + public boolean onPreDraw() { + iv.getViewTreeObserver().removeOnPreDrawListener(this); + int imageViewHeight = iv.getMeasuredHeight(); + int imageViewWidth = iv.getMeasuredWidth(); + iv.setImageBitmap(decodeSampledBitmapFromPath(path, imageViewWidth, imageViewHeight)); + return true; + } + }); + } + + private static Bitmap decodeSampledBitmapFromPath(String path, int reqWidth, int reqHeight) { + // First decode with inJustDecodeBounds = true to check dimensions + final BitmapFactory.Options options = new BitmapFactory.Options(); + options.inJustDecodeBounds = true; + //BitmapFactory.decodeResource(res, resId, options); + BitmapFactory.decodeFile(path, options); + // Calculate inSampleSize + options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); + // Decode bitmap with inSampleSize set + options.inJustDecodeBounds = false; + return BitmapFactory.decodeFile(path, options); + } + + private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { + // Raw height and width of image_icon + final int height = options.outHeight; + final int width = options.outWidth; + int inSampleSize = 1; + if (height > reqHeight || width > reqWidth) { + final int halfHeight = height / 2; + final int halfWidth = width / 2; + // Calculate the largest inSampleSize value that is a power of 2 and keeps both + // height and width larger than the requested height and width. + while ((halfHeight / inSampleSize) > reqHeight && (halfWidth / inSampleSize) > reqWidth) { + inSampleSize *= 2; + } + } + + return inSampleSize; + } + + public static String getCurrentTimeHHMMSS() { + Calendar m_cal = Calendar.getInstance(); + return m_cal.get(Calendar.HOUR_OF_DAY) + "" + m_cal.get(Calendar.MINUTE) + "" + m_cal.get(Calendar.SECOND); + } + + + public static String setMetadataAtImages(String store_Nm, String store_Id, String type, String userId) { + return "Store Name : " + store_Nm + " | Store Id : " + store_Id + " " + " | Merchandiser Id : " + userId + " | Image Type : " + type; + } + + + public static String setMetadataAtImagesforwindow(String store_Nm, String store_Id, String window_cd, String type, String userId) { + return "Store Name : " + store_Nm + " | Store Id : " + store_Id + " " + " | Window Id : " + window_cd + " | Merchandiser Id : " + userId + " | Image Type : " + type; + } + + public static String setMetadataAtImagesforvisitorstorewise(String store_Nm, String store_Id, String visitor_nm, String type, String userId) { + return "Store Name : " + store_Nm + " | Store Id : " + store_Id + " " + " | Visitor Name : " + visitor_nm + " | Merchandiser Id : " + userId + " | Image Type : " + type; + } + + public static String setMetadataAtImagesforvisitor(String visitor_nm, String type, String userId) { + return "Visitor Name : " + visitor_nm + " | Merchandiser Id : " + userId + " | Image Type : " + type; + } + + public static String setMetadataAtImagesdpreporting(String type, String userId) { + String ss = "Merchandiser Id : " + userId + " | Image Type : " + type; + return ss; + } + + + public static Bitmap addMetadataAndTimeStampToImage(Context context, final String path, String metadata, String visit_date) { + Bitmap bmp1 = BitmapFactory.decodeFile(path); + @SuppressLint("InflateParams") View view = LayoutInflater.from(context).inflate(R.layout.preview_image, null); + view.layout(0, 0, bmp1.getWidth(), bmp1.getHeight()); + Bitmap bmp = getViewBitmap(view, bmp1, path, metadata, visit_date); + try { + bmp.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(new File(path))); + return bmp; + } catch (FileNotFoundException e) { + // TODO Auto-generated catch block + e.fillInStackTrace(); + FirebaseCrashlytics.getInstance().recordException(e); + return bmp1; + } + } + + @SuppressLint("SetTextI18n") + public static Bitmap getViewBitmap(View view, Bitmap bmp, String path, String metadata, String visit_date) { + //Get the dimensions of the view so we can re-layout the view at its current size + @SuppressLint("SimpleDateFormat") SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss"); + String dateTime = sdf.format(Calendar.getInstance().getTime()); + String copm = dateTime; + ImageView temp_img = (ImageView) view.findViewById(R.id.temp_img); + TextView storeM = (TextView) view.findViewById(R.id.storeM); + int copleteValue = 0; + try { + copm = copm.replaceAll("[- ]", " "); + String[] items = copm.split(":"); + String seconds = items[2]; + int lastIndex; + lastIndex = Integer.parseInt(seconds); + int day = Integer.parseInt(visit_date.substring(3, 5)); + int a = Integer.parseInt("10") * Integer.parseInt("40"); + a = a + day; + lastIndex = lastIndex * 2; + copleteValue = a + lastIndex; + } catch (NumberFormatException e) { + FirebaseCrashlytics.getInstance().recordException(e); + e.fillInStackTrace(); + } + + //timestamp on image_icon + Bitmap dest = Bitmap.createBitmap(bmp.getWidth(), bmp.getHeight(), Bitmap.Config.ARGB_8888); + Canvas cs = new Canvas(dest); + Paint tPaint = new Paint(); + tPaint.setTextSize(27); + tPaint.setColor(Color.RED); + tPaint.setStyle(Paint.Style.FILL_AND_STROKE); + cs.drawBitmap(bmp, 0f, 0f, null); + float height_ = tPaint.measureText("yY"); + cs.drawText(dateTime + "[" + "10" + "] " + (copleteValue), 20f, height_ + 15f, tPaint); + try { + dest.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(new File(path))); + } catch (FileNotFoundException e) { + FirebaseCrashlytics.getInstance().recordException(e); + // TODO Auto-generated catch block + e.fillInStackTrace(); + } + + storeM.setText(metadata + " | Date : " + dateTime + "[" + "10" + "] " + (copleteValue)); + bmp = BitmapFactory.decodeFile(path); + temp_img.setImageBitmap(bmp); + int width = bmp.getWidth(); + int height = bmp.getHeight(); + int measuredWidth = View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY); + int measuredHeight = View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY); + //Cause the view to re-layout + view.measure(measuredWidth, measuredHeight); + view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight()); + //Create a bitmap backed Canvas to draw the view into + Bitmap b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); + Canvas c = new Canvas(b); + view.draw(c); + return b; + } + + public static String getCurrentTime() { + Calendar calendar = Calendar.getInstance(); + @SuppressLint("SimpleDateFormat") SimpleDateFormat mdformat = new SimpleDateFormat("HH:mm:ss"); + return mdformat.format(calendar.getTime()); + } + + public static String getCurrentTime_only() { + Calendar calendar = Calendar.getInstance(); + @SuppressLint("SimpleDateFormat") SimpleDateFormat mdformat = new SimpleDateFormat("HH:mm:ss"); + return mdformat.format(calendar.getTime()); + } + + public static String getUUID(Context context) { + SharedPreferences preferences = PrefHelper.getPrefs(context); + String counter_id = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + return counter_id + "_" + UUID.randomUUID().toString(); + } + + public static boolean isTablet(Context context) { + boolean xlarge = ((context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == 4); + boolean large = ((context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE); + return (xlarge || large); + } + + public static void show_image_preview(Context context, String img_name) { + final Bitmap bmp = BitmapFactory.decodeFile(CommonString.getImagesFolder(context) + img_name); + final Dialog dialog = new Dialog(context); + //setting custom layout---------------------------- to dialog + dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); + dialog.setContentView(R.layout.custom_dialog_preview); + Button cancel_btn = (Button) dialog.findViewById(R.id.cancel_btn); + ImageView img_addit = (ImageView) dialog.findViewById(R.id.img_addit); + img_addit.setImageBitmap(bmp); + cancel_btn.setOnClickListener(v -> dialog.dismiss()); + dialog.show(); + } + + public static String convert24to12(String loginTym) { + String strTym = ""; + try { + @SuppressLint("SimpleDateFormat") SimpleDateFormat simpleDate = new SimpleDateFormat("HH"); + Date date = simpleDate.parse(loginTym); + assert date != null; + simpleDate.format(date); + Calendar calander = Calendar.getInstance(); + @SuppressLint("SimpleDateFormat") SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh"); + strTym = simpleDateFormat.format(calander.getTime()); + } catch (Exception e) { + e.fillInStackTrace(); + } + return strTym; + } + + public static String setTimeFormat(String start_dt) { + //test("xxxd" + start_dt); + String newvalue = ""; + try { + if (!start_dt.isEmpty()) { + String s[] = start_dt.split(":"); + //test("time-----------------" + s[0] + "parseint" + Integer.parseInt(s[0])); + int t = Integer.parseInt(s[0]); + //test("vv....." + t); + if (t < 12) { + s[0] = Integer.valueOf(s[0]).toString(); + if (Integer.parseInt(s[0]) < 10 && s[0].length() == 0) { + newvalue = "0" + s[0] + ":" + s[1] + ":" + s[2]; + } else { + newvalue = s[0] + ":" + s[1] + ":" + s[2]; + } + //test("value..." + newvalue); + } else { + int time = Integer.parseInt(s[0]) - 12; + if (time < 10) { + newvalue = "0" + time + ":" + s[1] + ":" + s[2]; + } else { + newvalue = "0" + time + ":" + s[1] + ":" + s[2]; + } + + //test("value..." + newvalue); + } + } + } catch (NumberFormatException e) { + e.fillInStackTrace(); + } + + return newvalue; + } + + public static File saveBitmapToFile(File file) { + File file2 = file; + try { + int inWidth = 0; + int inHeight = 0; + InputStream in = new FileInputStream(file2); + // decode image size (decode metadata only, not the whole image) + BitmapFactory.Options options = new BitmapFactory.Options(); + options.inJustDecodeBounds = true; + BitmapFactory.decodeStream(in, null, options); + in.close(); + in = null; + // save width and height + inWidth = options.outWidth; + inHeight = options.outHeight; + // decode full image pre-resized + in = new FileInputStream(file2); + options = new BitmapFactory.Options(); + // calc rought re-size (this is no exact resize) + options.inSampleSize = Math.max(inWidth / 800, inHeight / 500); + // decode full image + Bitmap roughBitmap = BitmapFactory.decodeStream(in, null, options); + if (roughBitmap == null) { + return null; + } + // calc exact destination size + Matrix m = new Matrix(); + RectF inRect = new RectF(0, 0, roughBitmap.getWidth(), roughBitmap.getHeight()); + RectF outRect = new RectF(0, 0, 800, 500); + m.setRectToRect(inRect, outRect, Matrix.ScaleToFit.CENTER); + float[] values = new float[9]; + m.getValues(values); + // resize bitmap + Bitmap resizedBitmap = Bitmap.createScaledBitmap(roughBitmap, (int) (roughBitmap.getWidth() * values[0]), (int) (roughBitmap.getHeight() * values[4]), true); + // save image + try { + FileOutputStream out = new FileOutputStream(file2); + resizedBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out); + } catch (Exception e) { + //test("Image", e.toString(), e); + } + } catch (IOException e) { + //test("Image", e.toString(), e); + return file2; + } + return file; + } + + public static Bitmap getResizedBitmap(Bitmap image, int maxSize) { + int width = 0, height = 0; + try { + if (image != null) { + width = image.getWidth(); + height = image.getHeight(); + + if (maxSize != 0 && width != 0 && height != 0) { + float bitmapRatio = (float) width / (float) height; + if (bitmapRatio > 1) { + width = maxSize; + height = (int) (width / bitmapRatio); + } else { + height = maxSize; + width = (int) (height * bitmapRatio); + } + } + + } + } catch (Exception e) { + e.fillInStackTrace(); + } + assert image != null; + return Bitmap.createScaledBitmap(image, width, height, true); + } + + public static Bitmap getCroppedBitmap(Bitmap bitmap) { + Bitmap output = null; + + try { + if (bitmap != null) { + if (bitmap.getWidth() > bitmap.getHeight()) { + output = Bitmap.createBitmap(bitmap.getHeight(), bitmap.getHeight(), Bitmap.Config.ARGB_8888); + } else { + output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getWidth(), Bitmap.Config.ARGB_8888); + } + + Canvas canvas = new Canvas(output); + final int color = 0xff424242; + final Paint paint = new Paint(); + final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()); + + float r = 0; + if (bitmap.getWidth() > bitmap.getHeight()) { + r = (float) bitmap.getHeight() / 2; + } else { + r = (float) bitmap.getWidth() / 2; + } + paint.setAntiAlias(true); + canvas.drawARGB(0, 0, 0, 0); + paint.setColor(color); + canvas.drawCircle(r, r, r, paint); + paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN)); + canvas.drawBitmap(bitmap, rect, rect, paint); + + } + } catch (Exception e) { + e.fillInStackTrace(); + } + + return output; + } + + @SuppressLint("SetTextI18n") + public static void show_incurrect_device_tym(final Context context, String serverTym) { + if (context != null) { + final Dialog dialog = new Dialog(context); + //setting custom layout---------------------------- to dialog + dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); + dialog.setContentView(R.layout.dialog_incurrect_tym); + dialog.setCancelable(false); + Button cancel_btn = (Button) dialog.findViewById(R.id.cancel_btn); + TextView txt_serverTym = (TextView) dialog.findViewById(R.id.txt_serverTym); + txt_serverTym.setText("Server Time : " + serverTym); + + cancel_btn.setOnClickListener(v -> { + context.startActivity(new Intent(android.provider.Settings.ACTION_DATE_SETTINGS)); + dialog.dismiss(); + }); + dialog.show(); + } + } + + public static void delete_old_imge_from_folder(Context context, String visit_date, Lorealba_Database db) { + db.open(); + try { + if (db.CheckPreviousProduct(visit_date)) { + File f = new File(CommonString.getImagesFolder(context)); + final File[] file = f.listFiles(); + if (file != null && file.length > 0) { + String filename = ""; + for (File value : file) { + filename = value.getName(); + if (filename.contains("_counter_img_one_") || filename.contains("_counter_img_two_") || filename.contains("_cp_img_one_") || filename.contains("_cp_img_two_") || filename.contains("_groomed_img_mrng_") || filename.contains("_groomed_img_noon_") || filename.contains("_groomed_img_evning_")) { + File originalFile = new File(CommonString.getImagesFolder(context) + value.getName()); + if (originalFile.isFile() && originalFile.exists()) + originalFile.delete(); + } + } + } + } + } catch (Exception e) { + e.fillInStackTrace(); + } + } + + public static void GetServerTym(Context context, String user_name, Lorealba_Database db) { + try { + ArrayList keysList = new ArrayList<>(); + ArrayList jsonList = new ArrayList<>(); + ArrayList KeyNames = new ArrayList<>(); + keysList.add("ServerTime"); + for (int i = 0; i < keysList.size(); i++) { + JSONObject jsonObject = new JSONObject(); + jsonObject.put("Downloadtype", keysList.get(i)); + jsonObject.put("Username", user_name); + jsonObject.put("Param1", ""); + jsonObject.put("Param2", ""); + jsonList.add(jsonObject.toString()); + KeyNames.add(keysList.get(i)); + } + + if (!jsonList.isEmpty()) { + ProgressDialog pd = new ProgressDialog(context); + DownloadAllDatawithRetro downloadData = new DownloadAllDatawithRetro(context, db, pd, CommonString.TAG_FROM_CURRENT); + downloadData.listSize = jsonList.size(); + downloadData.downloadDataUniversalBa(jsonList, KeyNames, 0, CommonString.DOWNLOAD_ALL_SERVICE); + } + + } catch (Exception e) { + e.fillInStackTrace(); + } + } + + + public static String removeFirstChar(String s) { + String str = ""; + try { + str = s.substring(1); + } catch (Exception e) { + e.fillInStackTrace(); + return str; + } + + return str; + } + + public static void call_upload(Context context) { + if (checkNetIsAvailable(context)) { + context.startActivity(new Intent(context, UploadKeyData.class).putExtra(CommonString.TAG_OBJECT, "1")); + } + } + + public static boolean checkincomplete_upload_data(String visit_date, String counter_id, Lorealba_Database db, boolean previous_date) { + boolean status = true; + try { + if (!db.getBaProfileListData(visit_date, counter_id, previous_date).isEmpty()) { + status = false; + } else if (!db.getCounterProfileListData(visit_date, counter_id, previous_date).isEmpty()) { + status = false; + } else if (!db.getme_quiz_from(visit_date, counter_id, previous_date).isEmpty()) { + status = false; + } else if (!db.getgroomingdata(counter_id, visit_date, previous_date).isEmpty()) { + status = false; + } else if (!db.getba_counterimgList(counter_id, visit_date, previous_date).isEmpty()) { + status = false; + } + } catch (Exception e) { + e.fillInStackTrace(); + } + return status; + } + + public static String removed_special_char(EditText common_edt) { + String value_edt = ""; + try { + if (common_edt.getText().toString().contains("[/;(!@#$%^&*?)\"]")) { + value_edt = common_edt.getText().toString().trim().replaceAll("[/;(!@#$%^&*?)\"]", ""); + } else { + value_edt = common_edt.getText().toString().trim(); + } + + } catch (Exception e) { + e.fillInStackTrace(); + } + + return value_edt; + } + + public static int mod(int x, int y) { + int result = 0; + try { + result = x % y; + if (result < 0) result += y; + } catch (Exception e) { + e.fillInStackTrace(); + } + return result; + } + + + public String getCountOfDays(String fromDate, String toDate) { + SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy", Locale.getDefault()); + Date createdConvertedDate = null, expireCovertedDate = null, todayWithZeroTime = null; + try { + createdConvertedDate = dateFormat.parse(fromDate); + expireCovertedDate = dateFormat.parse(toDate); + + Date today = new Date(); + + todayWithZeroTime = dateFormat.parse(dateFormat.format(today)); + } catch (ParseException e) { + e.fillInStackTrace(); + } + + int cYear = 0, cMonth = 0, cDay = 0; + + assert createdConvertedDate != null; + if (createdConvertedDate.after(todayWithZeroTime)) { + Calendar cCal = Calendar.getInstance(); + cCal.setTime(createdConvertedDate); + cYear = cCal.get(Calendar.YEAR); + cMonth = cCal.get(Calendar.MONTH); + cDay = cCal.get(Calendar.DAY_OF_MONTH); + + } else { + Calendar cCal = Calendar.getInstance(); + assert todayWithZeroTime != null; + cCal.setTime(todayWithZeroTime); + cYear = cCal.get(Calendar.YEAR); + cMonth = cCal.get(Calendar.MONTH); + cDay = cCal.get(Calendar.DAY_OF_MONTH); + } + + Calendar eCal = Calendar.getInstance(); + assert expireCovertedDate != null; + eCal.setTime(expireCovertedDate); + + int eYear = eCal.get(Calendar.YEAR); + int eMonth = eCal.get(Calendar.MONTH); + int eDay = eCal.get(Calendar.DAY_OF_MONTH); + + Calendar date1 = Calendar.getInstance(); + Calendar date2 = Calendar.getInstance(); + + date1.clear(); + date1.set(cYear, cMonth, cDay); + date2.clear(); + date2.set(eYear, eMonth, eDay); + + long diff = date2.getTimeInMillis() - date1.getTimeInMillis(); + + float dayCount = (float) diff / (24 * 60 * 60 * 1000); + + return ((int) dayCount + " Days"); + } + + public static void hideKeyboard(Activity activity) { + InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE); + //Find the currently focused view, so we can grab the correct window token from it. + View view = activity.getCurrentFocus(); + //If no view currently has focus, create a new one, just so we can grab a window token from it + if (view == null) { + view = new View(activity); + } + if (imm.isAcceptingText()) imm.hideSoftInputFromWindow(view.getWindowToken(), 0); + } + + public static String capitalizeFirstLetter(String input) { + if (input == null || input.isEmpty()) { + return input; + } + return input.substring(0, 1).toUpperCase() + input.substring(1).toLowerCase(); + } + + public static void dismissKeyboard(View view) { + try { + if (view != null) { + InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); + imm.hideSoftInputFromWindow(view.getWindowToken(), 0); + } + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + public static ArrayList getFilters() { + ArrayList listSubAxe = new ArrayList<>(); + try { + ProductMaster obj = new ProductMaster(); + obj.setSubAxeName("Axe"); + listSubAxe.add(obj); + + obj = new ProductMaster(); + obj.setSubAxeName("Sub Axe"); + listSubAxe.add(obj); + + obj = new ProductMaster(); + obj.setSubAxeName("Signature"); + listSubAxe.add(obj); + + obj = new ProductMaster(); + obj.setSubAxeName("Sub Brand"); + listSubAxe.add(obj); + + obj = new ProductMaster(); + obj.setSubAxeName("Brand"); + listSubAxe.add(obj); + + obj = new ProductMaster(); + obj.setSubAxeName("Product"); + listSubAxe.add(obj); + } catch (Exception ignored) { + } + + return listSubAxe; + } + + public static String formatDate(String inputDate) { + // Check if the device supports java.time (API 26+) + if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) { + // Input date format (MM/dd/yyyy) + DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("MM/dd/yyyy", Locale.ENGLISH); + // Desired output date format (MMMM dd, yyyy) + DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("MMM dd, yyyy", Locale.ENGLISH); + + // Parse the input date string + LocalDate date = LocalDate.parse(inputDate, inputFormatter); + + // Return formatted date + return date.format(outputFormatter); + + } else { + // For older Android versions (below API 26) + SimpleDateFormat inputFormat = new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH); + SimpleDateFormat outputFormat = new SimpleDateFormat("MMM dd, yyyy", Locale.ENGLISH); + try { + // Parse the input date string + Date date = inputFormat.parse(inputDate); + // Format the date to the desired output + assert date != null; + return outputFormat.format(date); + } catch (ParseException e) { + e.fillInStackTrace(); + return null; // Return null if parsing fails + } + } + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/constant/CommonString.java b/app/src/main/java/com/cpm/lorealbaautomation/constant/CommonString.java new file mode 100644 index 0000000..d2854cc --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/constant/CommonString.java @@ -0,0 +1,1287 @@ +package com.cpm.lorealbaautomation.constant; + +import android.content.Context; + +import com.cpm.lorealbaautomation.utils.AppUtils; + +/** + * Created by jeevanp on 14-12-2017. + */ +public class CommonString { + public static final String BACKUP_FOLDER_NAME = "LorealBa_Backup"; + public static final String IMAGE_FOLDER_NAME = "LorealBa_Images"; + public static final String PROFILE_FOLDER_NAME = "LorealProfile"; + public static final String LorealPromo_Folder = "LorealPromoOffers"; + public static final String LorealBaApkFolder = "LorealBaApkFolder"; + + public static String getLorealBaApkFolder(Context context) { + return AppUtils.getInternalDirectory(context, LorealBaApkFolder).getAbsolutePath() + "/"; + } + + public static String getImagesFolder(Context context) { + return AppUtils.getInternalDirectory(context, IMAGE_FOLDER_NAME).getAbsolutePath() + "/"; + } + + public static String getProfileFolder(Context context) { + return AppUtils.getInternalDirectory(context, PROFILE_FOLDER_NAME).getAbsolutePath() + "/"; + } + + public static String getPromosFolder(Context context) { + return AppUtils.getInternalDirectory(context, LorealPromo_Folder).getAbsolutePath() + "/"; + } + + public static String getBackupFolder(Context context) { + return AppUtils.getInternalDirectory(context, BACKUP_FOLDER_NAME).getAbsolutePath() + "/"; + } + + //preference + public static final String KEY_DB_NAME = "LorealBaNew"; + public static final int KEY_DB_NAME_iD = 2; + public static final String KEY_LOGIN_DATA = "login_data"; + public static final String TAG_FROM = "FROM"; + public static final int TIMEOUT = 180; + public static final String TAG_MODE = "MODE"; + public static final String TAG_FROM_BA = "BA"; + public static final String MODE_FROM_BA_LOGIN = "BA LOGIN"; + public static final String MODE_FROM_ME_LOGIN = "ME LOGIN"; + public static final String MODE_FROM_TBA_LOGIN = "TBA LOGIN"; + public static final String TAG_FROM_ME = "ME"; + public static final String TAG_FROM_TBA = "TBA"; + public static final String KEY_USERNAME = "USERNAME"; + public static final String KEY_PASSWORD_CHANGE = "PASSWORD_CHANGE"; + public static final String KEY_PROMO_ID = "PromoId"; + public static final String KEY_USER_LOGINTIME = "LoginTime"; + public static final String KEY_COUNTER_ID = "COUNTER_ID"; + public static final String KEY_COUNTER_CODE = "COUNTER_CODE"; + public static final String KEY_PASSWORD = "PASSWORD"; + public static final String KEY_MPIN = "MPIN"; + public static final String KEY_STATUS = "STATUS"; + public static final String KEY_INCORRECT_TSTOCK_SUMMERY = "TSTOCK_SUMMERY"; + public static final String KEY_MY_KNOWLEDGE_URL = "https://lba.parinaam.in/WebView/ViewContent?Counter_Id="; + public static final String KEY_DATE = "DATE"; + public static final String KEY_D = "D"; + public static final String KEY_U = "U"; + public static final String KEY_VALUE = "Value"; + public static final String KEY_TOTAL_AMOUNT = "Total_Amount"; + public static final String ADD_NEW_ITEM_FROM_OPTION = "2"; + public static final String KEY_DISABLE_EDIT_MODE = "1"; + public static final String KEY_ENABLE_EDIT_MODE = "0"; + public static final String KEY_BID = "BID"; + + public static String URL = "https://lba.parinaam.in/webservice/Loginservice.svc/"; + public static String URLGORIMAG = "https://lba.parinaam.in/webservice/Imageupload.asmx/"; + public static final int CAPTURE_MEDIA = 131; + public static final String KEY_PATH = "PATH"; + public static final String KEY_VERSION = "APP_VERSION"; + public static final String KEY_TEMP_DB_VERSION = "DbVerCode"; + public static final String KEY_SUCCESS = "Success"; + public static final String KEY_FAILURE = "Failure"; + public static final String TAG_OBJECT = "OBJECT"; + public static final String MESSAGE_INTERNET_NOT_AVALABLE = "No Internet Connection.Please Check Your Network Connection"; + public static final String MESSAGE_EXCEPTION = "Problem Occured : Report The Problem To Parinaam "; + public static final String MESSAGE_SOCKETEXCEPTION = "Network Communication Failure. Please Check Your Network Connection"; + public static final String MESSAGE_NO_RESPONSE_SERVER = "Server Not Responding.Please try again."; + public static final String MESSAGE_INVALID_JSON = "Problem Occured while parsing Json : invalid json data"; + public static final String KEY_DOWNLOAD_INDEX = "download_Index"; + public static final int TAG_FROM_CURRENT = 1; + public static final int DOWNLOAD_ALL_SERVICE = 2; + public static final String ONBACK_ALERT_MESSAGE = "Unsaved data will be lost - Do you want to continue?"; + public static final String UPLOAD_PONBACK_ALERT_MESSAGE = "Uploading process will be Stopped - Do you want to continue?"; + public static final String KEY_USER_TYPE = "RIGHTNAME"; + public static final String KEY_USER_Checkout = "UserCheckout"; + public static final String KEY_CHECKOUT_IMAGE = "CHECKOUT_IMAGE"; + public static final String KEY_VISIT_DATE = "Visit_Date"; + public static final String KEY_NEW_PRODUCT = "NEW_PRODUCT"; + public static final String KEY_LATITUDE = "LATITUDE"; + public static final String KEY_LONGITUDE = "LONGITUDE"; + public static final String KEY_REASON_ID = "REASON_ID"; + public static final String KEY_REASON = "REASON"; + public static final String KEY_IMAGE = "STORE_IMAGE"; + public static final String KEY_COVERAGE_REMARK = "REMARK"; + public static final String KEY_USER_ID = "User_Id"; + public static final String KEY_ACTIVITY = "ACTIVITY"; + public static final String KEY_DASHBOARD_REFRESH_TIME = "DASHBOARD_REFRESH_TIME"; + public static final String KEY_SKIN_GENIUS_URL = "SKIN_GENIUS_URL"; + public static final String KEY_D2D_ARS_URL = "D2D_ARS_URL"; + public static final String KEY_FIRST_DOWNLOAD_TsTOCK = "FIRST_DOWNLOAD_TsTOCK"; + public static final String KEY_SKIN_MAYBELLINE_URL = "SKIN_MAYBELLINE_URL"; + public static final String KEY_ID = "ID"; + public static final String KEY_RECCEPT_NUMBER = "RECCEPT_COUNT"; + public static final String KEY_COUNTER_NAME = "COUNTER_NAME"; + public static final String KEY_SKIN_GENIUS_UPLOADTYM = "SKIN_GENIUS_UPLOADTYM"; + public static final String TABLE_NOTIFICATION_DATA = "Notification_Data"; + public static final String TABLE_NOTIFICATION_USER = "Notification_User_Table"; + public static final String KEY_TITLE = "Title"; + public static final String KEY_BODY = "Body"; + public static final String KEY_TYPE = "Message_Type"; + public static final int PERMISSION_ALL = 99; + public static final String TABLE_COVERAGE_DATA = "COVERAGE_DATA"; + public static final String Key_Download_Status = "Download_Status"; + public static final String MESSAGE_CHANGED = "Invalid UserId Or Password / Password Has Been Changed."; + public static final String MESSAGE_LOGIN_NO_DATA = "Data mapping error."; + public static final String Table_Sale_Tracking = "SALE_TRACKING_TABLE"; + public static final String Table_Applyeid_Promotion = "APPLYED_PROMOTION_TABLE"; + + public static final String TABLE_INSERT_HEADER_STOCK_DATA = "DR_STOCK_HEADER_DATA"; + public static final String TABLE_INSERT_HEADER_TESTER_DATA = "DR_TESTER_HEADER_DATA"; + public static final String TABLE_INSERT_HEADER_ME_SALE_DATA = "DR_ME_SALE_HEADER_DATA"; + public static final String TABLE_INSERT_HEADER_SAMPLE_DATA = "DR_SAMPLE_HEADER_DATA"; + public static final String TABLE_INSERT_HEADER_DAMAGED_DATA = "DR_DAMAGED_HEADER_DATA"; + public static final String TABLE_INSERT_HEADER_SUGGESTED_STOCK_DATA = "DR_SUGGESTED_STOCK_HEADER_DATA"; + public static final String TABLE_INSERT_HEADER_GWP_DATA = "DR_GWP_HEADER_DATA"; + + public static final String TABLE_INSERT_INWARD_STOCK_HEADER_DATA = "DR_INWARD_STOCK_HEADER_DATA"; + public static final String TABLE_INSERT_INWARD_STOCK_CHILD_DATA = "DR_INWARD_STOCK_CHILD_DATA"; + public static final String KEY_COMMON_ID = "Common_Id"; + + public static final String T_StockSummary = "T_StockSummary"; + public static final String KEY_TABLE_T_CounterInvoice = "T_CounterInvoice"; + public static final String KEY_SaleableBalance = "SaleableBalance"; + public static final String KEY_TesterBalance = "TesterBalance"; + public static final String KEY_SampleBalance = "SampleBalance"; + public static final String KEY_SALEABLE_IN = "SaleableIn"; + public static final String KEY_TESTER_IN = "TesterIn"; + public static final String KEY_SAMPLE_IN = "SampleIn"; + public static final String KEY_GWP_IN = "GwpIn"; + public static final String KEY_GWP_BALANCE = "GwpBalance"; + public static final String KEY_CounterProfile = "CounterProfile"; + public static final String KEY_BaProfile = "BaProfile"; + public static final String KEY_BaProfile_list = "BaProfile_list"; + public static final String KEY_VisibilityEliment = "VisibilityEliment"; + public static final String TABLE_BA_SURVEY_CHILD_DATA = "Table_BA_Survey_Child_Data"; + public static final String TABLE_BA_SURVEY_HEADER_DATA = "Table_BA_Survey_Header_Data"; + + public static final String TABLE_COUNTER_SURVEY_CHILD_DATA = "Table_Counter_Survey_Child_Data"; + public static final String TABLE_COUNTER_SURVEY_HEADER_DATA = "Table_Counter_Survey_Header_Data"; + + public static String KEY_Survey_Id = "Survey_Id"; + public static String KEY_Survey_Name = "Survey_Name"; + public static String KEY_Survey_Type = "Survey_Type"; + public static String KEY_Survey_Question = "Survey_Question"; + public static String KEY_Survey_Question_Id = "Survey_Question_Id"; + public static String KEY_Correct_Answer_Id = "Correct_Answer_Id"; + public static String KEY_Image_Allow = "Image_Allow"; + public static String KEY_Question_Type = "Question_Type"; + public static String KEY_Survey_Question_Image = "Survey_Question_Image"; + public static String KEY_Correct_Answer = "Question_Correct_Answer"; + + public static final String CREATE_TABLE_BA_SURVEY_CHILD_DATA = "CREATE TABLE IF NOT EXISTS " + + TABLE_BA_SURVEY_CHILD_DATA + " (" + + "KEY_ID" + " INTEGER PRIMARY KEY AUTOINCREMENT ," + + CommonString.KEY_COMMON_ID + " INTEGER," + + CommonString.KEY_BID + " INTEGER," + + CommonString.KEY_COUNTER_ID + " INTEGER," + + CommonString.KEY_Survey_Id + " INTEGER," + + CommonString.KEY_Survey_Question + " VARCHAR," + + CommonString.KEY_Survey_Question_Id + " INTEGER," + + CommonString.KEY_Correct_Answer_Id + " INTEGER," + + CommonString.KEY_Image_Allow + " VARCHAR," + + CommonString.KEY_Question_Type + " VARCHAR," + + CommonString.KEY_Survey_Question_Image + " VARCHAR," + + CommonString.KEY_UPLOAD_STATUS + " VARCHAR," + + CommonString.KEY_Correct_Answer + " VARCHAR)"; + + + public static final String CREATE_TABLE_BA_SURVEY_HEADER_DATA = "CREATE TABLE IF NOT EXISTS " + + TABLE_BA_SURVEY_HEADER_DATA + " (" + + "KEY_ID" + " INTEGER PRIMARY KEY AUTOINCREMENT ," + + CommonString.KEY_COUNTER_ID + " INTEGER," + + CommonString.KEY_BID + " INTEGER," + + CommonString.KEY_VISIT_DATE + " VARCHAR," + + CommonString.KEY_Survey_Type + " VARCHAR," + + CommonString.KEY_Survey_Id + " INTEGER," + + CommonString.KEY_UPLOAD_STATUS + " VARCHAR," + + CommonString.KEY_Survey_Name + " VARCHAR" + ")"; + + + public static final String KEY_MID = "MID"; + + public static final String CREATE_TABLE_COUNTER_SURVEY_CHILD_DATA = "CREATE TABLE IF NOT EXISTS " + + TABLE_COUNTER_SURVEY_CHILD_DATA + + " (" + "KEY_ID" + " INTEGER PRIMARY KEY AUTOINCREMENT ," + + CommonString.KEY_COMMON_ID + " INTEGER," + + CommonString.KEY_MID + " INTEGER," + + CommonString.KEY_COUNTER_ID + " INTEGER," + + CommonString.KEY_Survey_Id + " VARCHAR," + + CommonString.KEY_Survey_Question + " VARCHAR," + + CommonString.KEY_Survey_Question_Id + " INTEGER," + + CommonString.KEY_Correct_Answer_Id + " INTEGER," + + CommonString.KEY_Image_Allow + " VARCHAR," + + CommonString.KEY_Question_Type + " VARCHAR," + + CommonString.KEY_Survey_Question_Image + " VARCHAR," + + CommonString.KEY_UPLOAD_STATUS + " VARCHAR," + + CommonString.KEY_Correct_Answer + " VARCHAR" + ")"; + + + public static final String CREATE_TABLE_COUNTER_SURVEY_HEADER_DATA = "CREATE TABLE IF NOT EXISTS " + + TABLE_COUNTER_SURVEY_HEADER_DATA + + " (" + "KEY_ID" + " INTEGER PRIMARY KEY AUTOINCREMENT ," + + CommonString.KEY_COUNTER_ID + " INTEGER," + + CommonString.KEY_MID + " INTEGER," + + CommonString.KEY_VISIT_DATE + " VARCHAR," + + CommonString.KEY_Survey_Type + " VARCHAR," + + CommonString.KEY_Survey_Id + " INTEGER," + + CommonString.KEY_UPLOAD_STATUS + " VARCHAR," + + CommonString.KEY_Survey_Name + " VARCHAR" + ")"; + + + public static final String CREATE_TABLE_FOCUS_PRODUCT_OPENINGHEADER_DATA = "CREATE TABLE IF NOT EXISTS " + + TABLE_INSERT_HEADER_STOCK_DATA + " (" + KEY_ID + + " INTEGER PRIMARY KEY AUTOINCREMENT ," + + "AxeName" + " VARCHAR, " + + KEY_VISIT_DATE + " VARCHAR," + + "COMMONID" + " INTEGER," + + CommonString.KEY_COUNTER_ID + " INTEGER," + + "BrandName" + " VARCHAR," + + "ImagePath" + " VARCHAR," + + "SignatureName" + " VARCHAR," + + "NuanceName" + " VARCHAR," + + "SubAxeName" + " VARCHAR)"; + + + public static final String TABLE_STORE_STOCK_CHILD_DATA = "DR_STOCK_CHILD_DATA"; + public static final String TABLE_STORE_STOCK_CHILD_ME_SALE_DATA = "DR_ME_SALE_CHILD_DATA"; + public static final String CREATE_TABLE_FIRST_TIME_STOCK_DATA = "CREATE TABLE IF NOT EXISTS " + + TABLE_STORE_STOCK_CHILD_DATA + " (" + "Common_Id" + + " INTEGER ," + + "AxeName" + " VARCHAR, " + + CommonString.KEY_COUNTER_ID + " INTEGER, " + + KEY_VISIT_DATE + " VARCHAR," + + "ProductId" + " INTEGER, " + + "ProductName" + " VARCHAR, " + + "STOCK" + " INTEGER, " + + "STOCK_RECEIVED" + " INTEGER, " + + "BrandName" + " VARCHAR," + + "SignatureName" + " VARCHAR," + + "Mrp" + " INTEGER, " + + "REASON_ID" + " INTEGER, " + + "REASON" + " VARCHAR, " + + "SubAxeName" + " VARCHAR)"; + + public static final String CREATE_TABLE_STORE_STOCK_CHILD_ME_SALE_DATA = "CREATE TABLE IF NOT EXISTS " + + TABLE_STORE_STOCK_CHILD_ME_SALE_DATA + " (" + + "Common_Id" + " INTEGER ," + + "AxeName" + " VARCHAR, " + + "USER_ID" + " VARCHAR, " + + CommonString.KEY_COUNTER_ID + " INTEGER, " + + KEY_VISIT_DATE + " VARCHAR," + + "ProductId" + " INTEGER, " + + "ProductName" + " VARCHAR, " + + "NuanceName" + " VARCHAR, " + + "UploadStatus" + " VARCHAR, " + + "UNIQUE_CODE" + " VARCHAR, " + + "STOCK" + " INTEGER, " + + "STOCK_RECEIVED" + " INTEGER, " + + "BrandName" + " VARCHAR," + + "SubBrandName" + " VARCHAR," + + "SignatureName" + " VARCHAR," + + "ReferenceName" + " VARCHAR," + + "ImagePath" + " VARCHAR," + + "Mrp" + " INTEGER, " + + "EanCode" + " VARCHAR, " + + "SubAxeName" + " VARCHAR)"; + + public static String IS_PASSWORD_CHECK = "IS_PASSWORD_CHECK"; + public static String MPIN = "MPIN"; + public static final int CHANGE_PASSWORD_SERVICE = 12; + public static final int FORGOT_PASSWORD_SERVICE = 13; + public static final String TABLE_User_Login = "User_login"; + public static final String TABLE_COUNTER_IMAGE_DATA = "Table_Counter_Image"; + public static final String TABLE_GROOMED_IMAGE_DATA = "Table_Groomed_Image"; + public static final int UPLOAD_DEVICE_TOKEN_DETAILS = 1; + + public static final String CREATE_TABLE_User_Login = "CREATE TABLE IF NOT EXISTS " + + TABLE_User_Login + " (" + KEY_ID + + " INTEGER PRIMARY KEY AUTOINCREMENT ," + KEY_PASSWORD + + " VARCHAR,USER_ID VARCHAR, " + + KEY_VISIT_DATE + " VARCHAR," + + KEY_IMAGE + " VARCHAR," + + KEY_USER_LOGINTIME + " VARCHAR," + + KEY_USER_TYPE + " VARCHAR," + + KEY_USER_Checkout + " INTEGER," + + KEY_MPIN + " VARCHAR)"; + + + public static final String CREATE_TABLE_COUNTER_IMAGE_DATA = "CREATE TABLE IF NOT EXISTS " + + TABLE_COUNTER_IMAGE_DATA + " (" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT ," + + KEY_COUNTER_ID + " INTEGER, " + + KEY_USER_ID + " VARCHAR," + + KEY_VISIT_DATE + " VARCHAR," + + KEY_USER_TYPE + " VARCHAR," + + "Pre_Setup_Img_One" + " VARCHAR," + + "Pre_Setup_Img_Two" + " VARCHAR," + + "Post_Setup_Img_One" + " VARCHAR," + + "UNIQUE_CODE" + " VARCHAR, " + + "UPLOAD_STATUS" + " VARCHAR, " + + "Counter_Img_One" + " VARCHAR, " + + "Counter_Img_Two" + " VARCHAR, " + + "Post_Setup_Img_Two" + " VARCHAR)"; + + + public static final String CREATE_TABLE_GROOMED_IMAGE_DATA = "CREATE TABLE IF NOT EXISTS " + + TABLE_GROOMED_IMAGE_DATA + " (" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT ," + + KEY_COUNTER_ID + " INTEGER, " + + KEY_USER_ID + " VARCHAR," + + KEY_VISIT_DATE + " VARCHAR," + + "Mornning_groomed_img" + " VARCHAR," + + "Mornning_groomed_time" + " VARCHAR," + + "Noon_groomed_img" + " VARCHAR," + + "Noon_groomed_time" + " VARCHAR," + + "Evening_groomed_img" + " VARCHAR," + + "UNIQUE_CODE" + " VARCHAR, " + + "UPLOAD_STATUS" + " VARCHAR, " + + "Evening_groomed_time" + " VARCHAR)"; + + public static final String CREATE_TABLE_COVERAGE_DATA = "CREATE TABLE IF NOT EXISTS " + + TABLE_COVERAGE_DATA + " (" + KEY_ID + + " INTEGER PRIMARY KEY AUTOINCREMENT ," + KEY_COUNTER_ID + + " INTEGER,USER_ID VARCHAR, " + + KEY_VISIT_DATE + " VARCHAR," + + KEY_LATITUDE + " VARCHAR," + KEY_LONGITUDE + " VARCHAR," + + KEY_IMAGE + " VARCHAR," + + KEY_CHECKOUT_IMAGE + " VARCHAR," + + KEY_REASON_ID + " INTEGER," + + KEY_COVERAGE_REMARK + " VARCHAR," + + KEY_COUNTER_NAME + " VARCHAR," + + KEY_REASON + " VARCHAR)"; + + public static final String TABLE_TRANSACTION_DATA = "TABLE_TRANSACTION_DATA"; + public static final String TABLE_TRANSACTION_WISE_MASTER_TABLE = "DR_TABLE_TRANSACTION_WISE_MASTER"; + public static final String TABLE_RETURNTO_DISTRIBUTOR_DATA = "TABLE_RETURNTO_DISTRIBUTOR"; + public static final String KEY_UUID = "UUID_ID"; + public static final String KEY_STOCK = "STOCK"; + public static final String KEY_ProductId = "ProductId"; + public static final String KEY_STOCK_TYPE = "STOCK_TYPE"; + public static final String KEY_ENTRY_TYPE = "ENTRY_TYPE"; + public static final String KEY_MASTER_TRANSACTION_ID = "MASTER_TRANSACTION_ID"; + + public static final String CREATE_TABLE_TRANSACTION_DATA = "CREATE TABLE IF NOT EXISTS " + + TABLE_TRANSACTION_DATA + " (" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT ," + + KEY_UUID + " INTEGER, " + + CommonString.KEY_COUNTER_ID + " INTEGER, " + + KEY_USER_ID + " VARCHAR," + + KEY_VISIT_DATE + " VARCHAR," + + KEY_STOCK_TYPE + " VARCHAR," + + KEY_ProductId + " INTEGER," + + KEY_STATUS + " VARCHAR," + + KEY_REASON_ID + " INTEGER," + + KEY_ENTRY_TYPE + " VARCHAR," + + KEY_MASTER_TRANSACTION_ID + " INTEGER," + + KEY_IMAGE + " VARCHAR," + + KEY_STOCK + " VARCHAR)"; + + public static final String CREATE_TABLE_TRANSACTION_WISE_DATA = "CREATE TABLE IF NOT EXISTS " + + TABLE_TRANSACTION_WISE_MASTER_TABLE + " (" + KEY_MASTER_TRANSACTION_ID + " INTEGER PRIMARY KEY AUTOINCREMENT ," + + KEY_UUID + " INTEGER, " + + CommonString.KEY_COUNTER_ID + " INTEGER, " + + KEY_USER_ID + " VARCHAR," + + KEY_VISIT_DATE + " VARCHAR," + + KEY_ENTRY_TYPE + " VARCHAR," + + KEY_STATUS + " VARCHAR," + + KEY_STOCK_TYPE + " VARCHAR)"; + + public static final String CREATE_TABLE_RETURNTO_DISTRIBUTOR_DATA = "CREATE TABLE IF NOT EXISTS " + + TABLE_RETURNTO_DISTRIBUTOR_DATA + " (" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT ," + + KEY_MASTER_TRANSACTION_ID + " INTEGER, " + + KEY_UUID + " VARCHAR, " + + KEY_COUNTER_ID + " INTEGER, " + + KEY_USER_ID + " VARCHAR," + + KEY_VISIT_DATE + " VARCHAR," + + KEY_STOCK_TYPE + " VARCHAR," + + KEY_ProductId + " INTEGER," + + KEY_STATUS + " VARCHAR," + + KEY_STOCK + " INTEGER)"; + + public static final String KEY_READ_STATUS = "Read_Status"; + public static final String CREATE_TABLE_NOTIFICATION_DATA = "CREATE TABLE IF NOT EXISTS " + + TABLE_NOTIFICATION_DATA + + " (" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT ," + + KEY_BODY + " INTEGER, " + + KEY_TITLE + " VARCHAR," + + KEY_VISIT_DATE + " VARCHAR," + + KEY_TYPE + " VARCHAR," + + KEY_COUNTER_ID + " INTEGER," + + KEY_READ_STATUS + " VARCHAR," + + KEY_PATH + " VARCHAR)"; + + public static final String CREATE_TABLE_NOTIFICATION_USER = "CREATE TABLE IF NOT EXISTS " + + TABLE_NOTIFICATION_USER + + " (" + KEY_ID + " INTEGER," + + KEY_VISIT_DATE + " VARCHAR," + + KEY_COUNTER_ID + " INTEGER," + + KEY_USER_ID + " VARCHAR)"; + + + public static final String KEY_USER_NAME = "USER_ID"; + //Tester + public static final String CREATE_TABLE_TESTER_HEADER_DATA = "CREATE TABLE IF NOT EXISTS " + + TABLE_INSERT_HEADER_TESTER_DATA + " (" + KEY_ID + + " INTEGER PRIMARY KEY AUTOINCREMENT ," + + "AxeName" + " VARCHAR, " + + KEY_VISIT_DATE + " VARCHAR," + + "COMMONID" + " INTEGER," + + CommonString.KEY_COUNTER_ID + " INTEGER," + + "BrandName" + " VARCHAR," + + "ImagePath" + " VARCHAR," + + "SignatureName" + " VARCHAR," + + "NuanceName" + " VARCHAR," + + "SubAxeName" + " VARCHAR)"; + + public static final String CREATE_TABLE_INSERT_HEADER_ME_SALE_DATA = "CREATE TABLE IF NOT EXISTS " + + TABLE_INSERT_HEADER_ME_SALE_DATA + " (" + KEY_ID + + " INTEGER PRIMARY KEY AUTOINCREMENT ," + + "AxeName" + " VARCHAR, " + + "USER_ID" + " VARCHAR, " + + KEY_VISIT_DATE + " VARCHAR," + + CommonString.KEY_COUNTER_ID + " INTEGER," + + "BrandName" + " VARCHAR," + + "UploadStatus" + " VARCHAR," + + "UNIQUE_CODE" + " VARCHAR," + + "ImagePath" + " VARCHAR," + + "SignatureName" + " VARCHAR," + + "NuanceName" + " VARCHAR," + + "SubAxeName" + " VARCHAR)"; + + + public static final String TABLE_TESTER_CHILD_DATA = "DR_TESTER_CHILD_DATA"; + public static final String CREATE_TABLE_FIRST_TIME_TESTER_DATA = "CREATE TABLE IF NOT EXISTS " + + TABLE_TESTER_CHILD_DATA + " (" + "Common_Id" + + " INTEGER ," + + "AxeName" + " VARCHAR, " + + KEY_VISIT_DATE + " VARCHAR," + + "ProductId" + " INTEGER, " + + "ProductName" + " VARCHAR, " + + "STOCK" + " INTEGER, " + + "STOCK_RECEIVED" + " INTEGER, " + + "BrandName" + " VARCHAR," + + "Mrp" + " INTEGER, " + + "SubAxeName" + " VARCHAR)"; + + //SAMPLE-------------------------- + public static final String CREATE_TABLE_SAMPLE_HEADER_DATA = "CREATE TABLE IF NOT EXISTS " + + TABLE_INSERT_HEADER_SAMPLE_DATA + " (" + KEY_ID + + " INTEGER PRIMARY KEY AUTOINCREMENT ," + + "AxeName" + " VARCHAR, " + + KEY_VISIT_DATE + " VARCHAR," + + "COMMONID" + " INTEGER," + + CommonString.KEY_COUNTER_ID + " INTEGER," + + "BrandName" + " VARCHAR," + + "ImagePath" + " VARCHAR," + + "SignatureName" + " VARCHAR," + + "NuanceName" + " VARCHAR," + + "SubAxeName" + " VARCHAR)"; + + public static final String TABLE_SAMPLE_CHILD_DATA = "DR_SAMPLE_CHILD_DATA"; + public static final String CREATE_TABLE_FIRST_TIME_SAMPLE_DATA = "CREATE TABLE IF NOT EXISTS " + + TABLE_SAMPLE_CHILD_DATA + " (" + "Common_Id" + + " INTEGER ," + + "AxeName" + " VARCHAR, " + + KEY_VISIT_DATE + " VARCHAR," + + "ProductId" + " INTEGER, " + + "ProductName" + " VARCHAR, " + + "STOCK" + " INTEGER, " + + "STOCK_RECEIVED" + " INTEGER, " + + "BrandName" + " VARCHAR," + + "Mrp" + " INTEGER, " + + "SubAxeName" + " VARCHAR)"; + + //DAMAGED ----------------------------- + public static final String CREATE_TABLE_DAMAGED_HEADER_DATA = "CREATE TABLE IF NOT EXISTS " + + TABLE_INSERT_HEADER_DAMAGED_DATA + " (" + KEY_ID + + " INTEGER PRIMARY KEY AUTOINCREMENT ," + + "AxeName" + " VARCHAR, " + + KEY_VISIT_DATE + " VARCHAR," + + "COMMONID" + " INTEGER," + + CommonString.KEY_COUNTER_ID + " INTEGER," + + "BrandName" + " VARCHAR," + + "ImagePath" + " VARCHAR," + + "SignatureName" + " VARCHAR," + + "SubAxeName" + " VARCHAR)"; + + + public static final String TABLE_DAMAGED_CHILD_DATA = "DR_DAMAGED_CHILD_DATA"; + public static final String CREATE_TABLE_FIRST_TIME_DAMAGED_DATA = "CREATE TABLE IF NOT EXISTS " + + TABLE_DAMAGED_CHILD_DATA + " (" + "Common_Id" + + " INTEGER ," + + "AxeName" + " VARCHAR, " + + KEY_VISIT_DATE + " VARCHAR," + + KEY_COUNTER_ID + " INTEGER," + + "ProductId" + " INTEGER, " + + "ProductName" + " VARCHAR, " + + "STOCK" + " INTEGER, " + + "STOCK_RECEIVED" + " INTEGER, " + + "BrandName" + " VARCHAR," + + "Mrp" + " INTEGER, " + + "ImagePath" + " VARCHAR," + + "SubAxeName" + " VARCHAR)"; + + //SUGGESTED_STOCK ----------------------------- + public static final String CREATE_TABLE_SUGGESTED_STOCK_HEADER_DATA = "CREATE TABLE IF NOT EXISTS " + + TABLE_INSERT_HEADER_SUGGESTED_STOCK_DATA + " (" + KEY_ID + + " INTEGER PRIMARY KEY AUTOINCREMENT ," + + "AxeName" + " VARCHAR, " + + KEY_VISIT_DATE + " VARCHAR," + + "COMMONID" + " INTEGER," + + CommonString.KEY_COUNTER_ID + " INTEGER," + + "BrandName" + " VARCHAR," + + "ImagePath" + " VARCHAR," + + "SubAxeName" + " VARCHAR)"; + + + public static final String TABLE_SUGGESTED_STOCK_CHILD_DATA = "DR_SUGGESTED_STOCK_CHILD_DATA"; + public static final String CREATE_TABLE_FIRST_TIME_SUGGESTED_STOCK_DATA = "CREATE TABLE IF NOT EXISTS " + + TABLE_SUGGESTED_STOCK_CHILD_DATA + " (" + "Common_Id" + + " INTEGER ," + + "AxeName" + " VARCHAR, " + + KEY_VISIT_DATE + " VARCHAR," + + "ProductId" + " INTEGER, " + + "ProductName" + " VARCHAR, " + + "STOCK" + " INTEGER, " + + "STOCK_RECEIVED" + " INTEGER, " + + "BrandName" + " VARCHAR," + + "Mrp" + " INTEGER, " + + "SubAxeName" + " VARCHAR)"; + + //usk + public static final String Table_visibilisty = "VISIBILITY_TABLE"; + public static final String CREATE_TABLE_VIISBILITY_DATA = "CREATE TABLE IF NOT EXISTS " + + Table_visibilisty + " (" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT ," + + KEY_UUID + " VARCHAR, " + + KEY_MASTER_TRANSACTION_ID + " INTEGER, " + + KEY_COUNTER_ID + " INTEGER, " + + KEY_USER_ID + " VARCHAR," + + KEY_VISIT_DATE + " VARCHAR," + + KEY_STATUS + " VARCHAR," + + "VISIBILITY_EXIST" + " VARCHAR," + + "VISIBILITY_IMG" + " VARCHAR," + + "Posm" + " VARCHAR," + + "PosmId" + " INTEGER," + + "PosmTypeId" + " INTEGER," + + "Resion" + " VARCHAR," + + "Resion_id" + " INTEGER," + + "RefImage" + " VARCHAR)"; + + public static final String Key_For_Pos_Enable_With_Showing_Invoice = "Pos_Enable"; + public static final String Key_For_Consumer_Update = "Consumer_Update"; + public static final String KEY_STORE_NAME = "STORE_NAME"; + public static final String KEY_STORE_ADDRESS = "STORE_ADDEESS"; + + public static final String KEY_SaleableStatus = "SaleableStatus"; + public static final String KEY_TesterStatus = "TesterStatus"; + public static final String KEY_SampleStatus = "SampleStatus"; + public static final String KEY_GwpStatus = "GwpStatus"; + + //For filters + public static final String Signature = "Signature"; + public static final String Brand = "Brand"; + public static final String SubBrand = "SubBrand"; + public static final String Reference = "Reference"; + + + public static final String TABLE_AUDIT_DATA_SAVE = "AUDIT_BA_PROFILE"; + public static final String CREATE_TABLE_AUDIT_DATA_SAVE = "CREATE TABLE IF NOT EXISTS " + + TABLE_AUDIT_DATA_SAVE + " (" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT ," + + KEY_USER_ID + " VARCHAR," + + KEY_VISIT_DATE + " VARCHAR," + + KEY_STATUS + " VARCHAR," + + "QUESTION_ID" + " INTEGER," + + "QUESTION" + " VARCHAR," + + "ANSWER" + " VARCHAR," + + "ANS_CAM_IMAGE" + " VARCHAR," + + "CAMERA_ALLOW" + " VARCHAR," + + "ANSWER_ID" + " INTEGER," + + "CATEGORY_ID" + " INTEGER," + + "OTHERS_TVALUE" + " VARCHAR," + + "ANSWER_TYPE" + " VARCHAR)"; + + public static final String Key_For_Reciept_Count = "Reciept_Count"; + public static final String Table_Consumer_Return = "CONSUMER_RETURN_TABLE"; + public static final String Create_Table_Consumer_Return = "CREATE TABLE IF NOT EXISTS " + + Table_Consumer_Return + " (" + + KEY_MASTER_TRANSACTION_ID + " INTEGER, " + + KEY_RECCEPT_NUMBER + " INTEGER ," + + KEY_COUNTER_ID + " INTEGER, " + + KEY_VISIT_DATE + " VARCHAR, USER_ID VARCHAR, " + + "UNIQUE_CODE" + " VARCHAR, " + + "PRODUCT_ID" + " INTEGER, " + + "PRODUCT" + " VARCHAR, " + + "QUANTITY" + " INTEGER, " + + "ACTUAL_QTY" + " INTEGER, " + + "PRODUCT_RATE" + " INTEGER, " + + "TOTAL_PRICE" + " DOUBLE, " + + "REASON_ID" + " INTEGER, " + + "REASON" + " VARCHAR, " + + "UPLOAD_STATUS" + " VARCHAR, " + + "EAN_CODE" + " VARCHAR)"; + + + public static final String Table_Consumer_Return_Replace_Product = "CONSUMER_RETURN_REPL_PRODUCT_TABLE"; + public static final String Create_Table_Consumer_Return_Replace_Product = "CREATE TABLE IF NOT EXISTS " + + Table_Consumer_Return_Replace_Product + " (" + KEY_RECCEPT_NUMBER + + " INTEGER ," + KEY_COUNTER_ID + " INTEGER, " + + KEY_VISIT_DATE + " VARCHAR, USER_ID VARCHAR, " + + "UNIQUE_CODE" + " VARCHAR, " + + "PRODUCT_ID" + " INTEGER, " + + "PRODUCT" + " VARCHAR, " + + "QUANTITY" + " INTEGER, " + + "PRODUCT_RATE" + " INTEGER, " + + "UPLOAD_STATUS" + " VARCHAR, " + + "EAN_CODE" + " VARCHAR)"; + + public static final String Table_Leave_Management = "LEAVE_MANAGEMENT_TABLE"; + public static final String Create_Table_Leave_Management = "CREATE TABLE IF NOT EXISTS " + + Table_Leave_Management + " (" + KEY_ID + + " INTEGER PRIMARY KEY AUTOINCREMENT ," + + KEY_MASTER_TRANSACTION_ID + " INTEGER, " + + "UNIQUE_CODE" + " VARCHAR, " + + KEY_COUNTER_ID + " INTEGER, " + + KEY_VISIT_DATE + " VARCHAR, USER_ID VARCHAR, " + + "Request_Date" + " VARCHAR, " + + "From_Date" + " VARCHAR, " + + "Upload_From_Date" + " VARCHAR, " + + "To_Date" + " VARCHAR, " + + "Upload_To_Date" + " VARCHAR, " + + "LeaveReason" + " VARCHAR, " + + "UPLOAD_STATUS" + " VARCHAR, " + + "One_Day_Leave" + " VARCHAR, " + + "LeaveType" + " VARCHAR, " + + "LeaveTypeId" + " INTEGER, " + + "Leave_Status" + " VARCHAR)"; + + public static final String Table_Break_Management = "BREAK_MANAGEMENT_TABLE"; + public static final String Create_Table_Break_Management = "CREATE TABLE IF NOT EXISTS " + + Table_Break_Management + " (" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT ," + + KEY_MASTER_TRANSACTION_ID + " INTEGER, " + + "UNIQUE_CODE" + " VARCHAR, " + + KEY_COUNTER_ID + " INTEGER, " + + KEY_VISIT_DATE + " VARCHAR, USER_ID VARCHAR, " + + "LoginTym" + " VARCHAR, " + + "BreakType" + " VARCHAR, " + + "StartTym" + " VARCHAR, " + + "EndTym" + " VARCHAR, " + + "TotalDuration" + " VARCHAR, " + + "UPLOAD_STATUS" + " VARCHAR, " + + "BreakId" + " INTEGER)"; + + public static final String KEY_SKU_CONFIRMATION_CHECK = "Sku_Confirmation_Check"; + public static final String KEY_MRP = "MRP"; + public static final String KEY_Product = "Product"; + public static final String KEY_INVOICE_QTY = "Invoice_Qty"; + public static final String KEY_ACTUAL_QTY = "Actual_Qty"; + public static final String KEY_INVOICE_NUMBER = "InvoiceNo"; + public static final String KEY_INVOICE_ID = "InvId"; + public static final String KEY_INVOICE_DATE = "InvoiceDate"; + public static final String KEY_INVOICE_TYPE = "InvoiceType"; + public static final String KEY_SOURCE = "Source"; + + public static final String CREATE_TABLE_INWARD_STOCK_HEADER_DATA = "CREATE TABLE IF NOT EXISTS " + + TABLE_INSERT_INWARD_STOCK_HEADER_DATA + " (" + KEY_ID + + " INTEGER PRIMARY KEY AUTOINCREMENT ," + + KEY_VISIT_DATE + " VARCHAR," + + CommonString.KEY_COUNTER_ID + " INTEGER," + + CommonString.KEY_USER_ID + " VARCHAR," + + CommonString.KEY_INVOICE_NUMBER + " VARCHAR," + + CommonString.KEY_INVOICE_DATE + " VARCHAR," + + CommonString.KEY_INVOICE_TYPE + " VARCHAR," + + "SubBrandName" + " VARCHAR, " + + "BrandName" + " VARCHAR," + + "SignatureName" + " VARCHAR," + + "SubAxeName" + " VARCHAR," + + "ReferenceName" + " VARCHAR)"; + + + public static final String KEY_INVOICE_STATUS = "Invoice_Status"; + public static final String KEY_TRANSACTION_ID = "Transaction_Id"; + public static final String TABLE_INSERT_INWARD_STOCK_TRANSACTION = "DR_INWARD_STOCK_TRANSACTION"; + + public static final String CREATE_TABLE_INWARD_STOCK_CHILD_DATA = "CREATE TABLE IF NOT EXISTS " + + TABLE_INSERT_INWARD_STOCK_CHILD_DATA + " (" + KEY_ID + + " INTEGER PRIMARY KEY AUTOINCREMENT ," + + KEY_VISIT_DATE + " VARCHAR," + + CommonString.KEY_COMMON_ID + " INTEGER," + + CommonString.KEY_SKU_CONFIRMATION_CHECK + " VARCHAR," + + CommonString.KEY_COUNTER_ID + " INTEGER," + + CommonString.KEY_USER_ID + " VARCHAR," + + CommonString.KEY_MRP + " VARCHAR," + + CommonString.KEY_INVOICE_ID + " INTEGER," + + CommonString.KEY_REASON_ID + " INTEGER," + + CommonString.KEY_ProductId + " INTEGER," + + CommonString.KEY_Product + " VARCHAR," + + CommonString.KEY_INVOICE_NUMBER + " VARCHAR," + + CommonString.KEY_INVOICE_TYPE + " VARCHAR," + + CommonString.KEY_INVOICE_QTY + " INTEGER," + + CommonString.KEY_ACTUAL_QTY + " INTEGER," + + CommonString.KEY_INVOICE_STATUS + " VARCHAR," + + "SubBrandName" + " VARCHAR, " + + "BrandName" + " VARCHAR," + + "SignatureName" + " VARCHAR," + + "SubAxeName" + " VARCHAR," + + "ReferenceName" + " VARCHAR)"; + + public static final String KEY_UPLOAD_STATUS = "Upload_Status"; + public static final String KEY_INVOICE_IMG = "Invoice_Img"; + public static final String CREATE_TABLE_INWARD_STOCK_TRANSACTION = "CREATE TABLE IF NOT EXISTS " + + TABLE_INSERT_INWARD_STOCK_TRANSACTION + " (" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT ," + + KEY_MASTER_TRANSACTION_ID + " INTEGER," + + KEY_VISIT_DATE + " VARCHAR," + + KEY_NEW_PRODUCT + " INTEGER," + + CommonString.KEY_SKU_CONFIRMATION_CHECK + " VARCHAR," + + CommonString.KEY_COUNTER_ID + " INTEGER," + + CommonString.KEY_USER_ID + " VARCHAR," + + CommonString.KEY_MRP + " INTEGER," + + CommonString.KEY_INVOICE_ID + " VARCHAR," + + CommonString.KEY_REASON_ID + " VARCHAR," + + CommonString.KEY_ProductId + " INTEGER," + + CommonString.KEY_INVOICE_NUMBER + " VARCHAR," + + CommonString.KEY_INVOICE_DATE + " VARCHAR," + + CommonString.KEY_INVOICE_TYPE + " VARCHAR," + + CommonString.KEY_INVOICE_QTY + " INTEGER," + + CommonString.KEY_ACTUAL_QTY + " INTEGER," + + CommonString.KEY_INVOICE_STATUS + " VARCHAR," + + CommonString.KEY_TRANSACTION_ID + " VARCHAR," + + CommonString.KEY_SOURCE + " VARCHAR," + + CommonString.KEY_UPLOAD_STATUS + " VARCHAR)"; + + + public static final String TABLE_COUNTER_PROFILE_DATA = "COUNTER_PROFILE_DATA"; + public static final String CREATE_TABLE_COUNTER_PROFILE_SAVE = "CREATE TABLE IF NOT EXISTS " + + TABLE_COUNTER_PROFILE_DATA + " (" + + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT ," + + KEY_UUID + " VARCHAR," + + KEY_USER_ID + " VARCHAR," + + CommonString.KEY_COUNTER_ID + " INTEGER," + + KEY_VISIT_DATE + " VARCHAR," + + KEY_STATUS + " VARCHAR," + + KEY_USER_TYPE + " VARCHAR," + + "IMAGE1" + " VARCHAR," + + "IMAGE2" + " VARCHAR," + + "COUNTER_AGEING" + " VARCHAR," + + "HIGHT" + " DOUBLE," + + "WIDTH" + " DOUBLE," + + "SETUP_DATE" + " VARCHAR," + + "COUNTER_TYPE" + " VARCHAR)"; + + public static final String TABLE_BA_PROFILE_DATA = "BA_PROFILE_DATA"; + public static final String CREATE_TABLE_BA_PROFILE_DATAE_SAVE = "CREATE TABLE IF NOT EXISTS " + + TABLE_BA_PROFILE_DATA + " (" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT ," + + KEY_USER_ID + " VARCHAR, " + + KEY_VISIT_DATE + " VARCHAR, " + + KEY_USER_TYPE + " VARCHAR," + + KEY_STATUS + " VARCHAR," + + "ADDRESS" + " VARCHAR," + + "LOCATION" + " VARCHAR," + + "LANDMARK" + " VARCHAR," + + "DOB" + " VARCHAR," + + "MOBILE_NO" + " VARCHAR," + + "EMAIL_ADDRESS" + " VARCHAR," + + CommonString.KEY_COUNTER_ID + " INTEGER," + + "PROFILE_IMAGE" + " VARCHAR," + + "INSTAGRAM_ADDRESS" + " VARCHAR)"; + + // neeraj database + public static final String TABLE_INSERT_MANUAL_INWARD_TRANSACTION = "DR_MANUAL_INWARD_TRANSACTION"; + public static final String KEY_COUNTER_CONFIRM = "CounterConfirm"; + public static final String KEY_DRAFT_STATUS = "Draft_Status"; + public static final String KEY_VIEW_MODE = "View_Mode"; + + public static final String CREATE_TABLE_MANUAL_INWARD_TRANSACTION = "CREATE TABLE IF NOT EXISTS " + + TABLE_INSERT_MANUAL_INWARD_TRANSACTION + " (" + KEY_ID + + " INTEGER PRIMARY KEY AUTOINCREMENT ," + + KEY_MASTER_TRANSACTION_ID + " INTEGER," + + KEY_VISIT_DATE + " VARCHAR," + + CommonString.KEY_COUNTER_ID + " INTEGER," + + CommonString.KEY_USER_ID + " VARCHAR," + + KEY_NEW_PRODUCT + " INTEGER," + + CommonString.KEY_MRP + " INTEGER," + + CommonString.KEY_INVOICE_ID + " VARCHAR," + + CommonString.KEY_REASON_ID + " VARCHAR," + + CommonString.KEY_Product + " VARCHAR," + + CommonString.KEY_ProductId + " INTEGER," + + CommonString.KEY_INVOICE_NUMBER + " VARCHAR," + + CommonString.KEY_INVOICE_DATE + " VARCHAR," + + CommonString.KEY_INVOICE_TYPE + " VARCHAR," + + CommonString.KEY_INVOICE_QTY + " INTEGER," + + CommonString.KEY_ACTUAL_QTY + " INTEGER," + + CommonString.KEY_INVOICE_STATUS + " VARCHAR," + + CommonString.KEY_TRANSACTION_ID + " VARCHAR," + + CommonString.KEY_COUNTER_CONFIRM + " VARCHAR," + + CommonString.KEY_TOTAL_AMOUNT + " VARCHAR," + + CommonString.KEY_VIEW_MODE + " VARCHAR," + + CommonString.KEY_SKU_CONFIRMATION_CHECK + " VARCHAR," + + CommonString.KEY_SOURCE + " VARCHAR," + + CommonString.KEY_UPLOAD_STATUS + " VARCHAR," + + CommonString.KEY_INVOICE_IMG + " VARCHAR," + + CommonString.KEY_DRAFT_STATUS + " VARCHAR)"; + + //SAMPLE-------------------------- + public static final String CREATE_TABLE_GWP_HEADER_DATA = "CREATE TABLE IF NOT EXISTS " + + TABLE_INSERT_HEADER_GWP_DATA + " (" + KEY_ID + + " INTEGER PRIMARY KEY AUTOINCREMENT ," + + "AxeName" + " VARCHAR, " + + KEY_VISIT_DATE + " VARCHAR," + + "COMMONID" + " INTEGER," + + CommonString.KEY_COUNTER_ID + " INTEGER," + + "BrandName" + " VARCHAR," + + "ImagePath" + " VARCHAR," + + "SignatureName" + " VARCHAR," + + "SubAxeName" + " VARCHAR)"; + + public static final String TABLE_GWP_CHILD_DATA = "DR_GWP_CHILD_DATA"; + public static final String CREATE_TABLE_FIRST_TIME_GWP_DATA = "CREATE TABLE IF NOT EXISTS " + + TABLE_GWP_CHILD_DATA + " (" + "Common_Id" + " INTEGER ," + + "AxeName" + " VARCHAR, " + + CommonString.KEY_COUNTER_ID + " INTEGER," + + KEY_VISIT_DATE + " VARCHAR," + + "ProductId" + " INTEGER, " + + "ProductName" + " VARCHAR, " + + "STOCK" + " INTEGER, " + + "STOCK_RECEIVED" + " INTEGER, " + + "BrandName" + " VARCHAR," + + "Mrp" + " INTEGER, " + + "ImagePath" + " VARCHAR," + + "SubAxeName" + " VARCHAR)"; + + public static final String KEY_COMPLETE = "COMPLETE"; + public static final String KEY_DRAFT = "DRAFT"; + public static final String KEY_REGULAR = "Regular_Stock"; + public static final String KEY_Y = "Y"; + public static final String KEY_N = "N"; + public static final String KEY_JSON = "JSON"; + + public static final String Table_Sale_Tracking_Header_Data = "SALE_TRACKING_HEADER_TABLE"; + public static final String Create_Table_Sale_Tracking_Header_Data = "CREATE TABLE IF NOT EXISTS " + + Table_Sale_Tracking_Header_Data + " (" + KEY_RECCEPT_NUMBER + + " INTEGER PRIMARY KEY AUTOINCREMENT ," + + KEY_MASTER_TRANSACTION_ID + " INTEGER, " + + KEY_COUNTER_ID + " INTEGER, " + + KEY_VISIT_DATE + " VARCHAR, USER_ID VARCHAR, " + + "BUYER_NAME" + " VARCHAR, " + + "CONTACT_NUMBER" + " VARCHAR, " + + "EMAIL_ID" + " VARCHAR, " + + "AGE" + " VARCHAR, " + + "SKIN_TYPE" + " VARCHAR, " + + "GENDER" + " VARCHAR, " + + "DEMO_GIVEN" + " VARCHAR, " + + "PRODUCT_SOLD" + " VARCHAR, " + + "SKIN_GENIUS" + " VARCHAR, " + + "MAYBELLINE_VTO" + " VARCHAR, " + + "PER_TIMING" + " VARCHAR, " + + KEY_STORE_NAME + " VARCHAR, " + + "STORE_ADDRESS" + " VARCHAR, " + + "UPLOAD_STATUS" + " VARCHAR, " + + "POS_SALE_FLAG" + " VARCHAR, " + + "TERMCONDITION_FLAG" + " VARCHAR, " + + "CONSUMER_NOSALE_IMG" + " VARCHAR, " + + "SOURCEOFSALES" + " VARCHAR, " + + "UNIQUE_CODE" + " VARCHAR, " + + KEY_USER_TYPE + " VARCHAR)"; + + + public static final String Table_Makeover_Capture = "MAKEOVER_CAPTURE_TABLE"; + public static final String Create_Table_Makeover_Capture = "CREATE TABLE IF NOT EXISTS " + + Table_Makeover_Capture + " (" + CommonString.KEY_ID + + " INTEGER PRIMARY KEY AUTOINCREMENT ," + + KEY_MASTER_TRANSACTION_ID + " INTEGER, " + + KEY_COUNTER_ID + " INTEGER, " + + KEY_VISIT_DATE + " VARCHAR, USER_ID VARCHAR, " + + "BUYER_NAME" + " VARCHAR, " + + "CONTACT_NUMBER" + " VARCHAR, " + + "EMAIL_ID" + " VARCHAR, " + + "AGE" + " VARCHAR, " + + "SKIN_TYPE" + " VARCHAR, " + + "LOOk" + " VARCHAR, " + + "GENDER" + " VARCHAR, " + + "BEFORE_MAKEOVER_IMG" + " VARCHAR, " + + "AFTER_MAKEOVER_IMG" + " VARCHAR, " + + "UPLOAD_STATUS" + " VARCHAR, " + + "TERMCONDITION_FLAG" + " VARCHAR, " + + "FEEDBACK" + " VARCHAR, " + + "POS_SALE_FLAG" + " VARCHAR, " + + "UNIQUE_CODE" + " VARCHAR)"; + + public static final String Create_Table_Sale_Tracking = "CREATE TABLE IF NOT EXISTS " + + Table_Sale_Tracking + + " (" + + KEY_MASTER_TRANSACTION_ID + " INTEGER," + + KEY_RECCEPT_NUMBER + " INTEGER," + + KEY_COUNTER_ID + " INTEGER, " + + KEY_VISIT_DATE + " VARCHAR, USER_ID VARCHAR, " + + "EMAIL_ID" + " VARCHAR, " + + "AGE" + " VARCHAR, " + + "SKIN_TYPE" + " VARCHAR, " + + "DEMO_GIVEN" + " VARCHAR, " + + "PRODUCT_SOLD" + " VARCHAR, " + + "SOURCEOFSALES" + " VARCHAR, " + + "SKIN_GENIUS" + " VARCHAR, " + + "MAYBELLINE_VTO" + " VARCHAR, " + + KEY_STORE_NAME + " VARCHAR, " + + "STORE_ADDRESS" + " VARCHAR, " + + "CONTACT_NUMBER" + " VARCHAR, " + + "PRODUCT_ID" + " INTEGER, " + + "PRODUCT" + " VARCHAR, " + + "SKU_TYPE" + " VARCHAR, " + + "QUANTITY" + " INTEGER, " + + "PRODUCT_RATE" + " INTEGER, " + + "TOTAL_AMOUNT" + " INTEGER, " + + "BUYER_NAME" + " VARCHAR, " + + "POS_SALE_FLAG" + " VARCHAR, " + + "GENDER" + " VARCHAR, " + + "PER_TIMING" + " VARCHAR, " + + "DISCOUNT" + " DOUBLE, " + + "ACTUAL_PRICE" + " DOUBLE, " + + "DISCOUNTED_VALUE" + " DOUBLE, " + + "UNIQUE_CODE" + " VARCHAR, " + + "UPLOAD_STATUS" + " VARCHAR, " + + "TERMCONDITION_FLAG" + " VARCHAR, " + + "INVOICE_TYPE" + " VARCHAR, " + + "CONSUMER_NOSALE_IMG" + " VARCHAR, " + + "PROMOTION" + " VARCHAR, " + + "PROMOTION_ID" + " INTEGER, " + + "PROMOTION_FLAG" + " INTEGER, " + + "PROMO_TYPE" + " VARCHAR, " + + "EAN_CODE" + " VARCHAR, " + + KEY_USER_TYPE + " VARCHAR)"; + + + public static final String Create_Table_Applyed_Promotion = "CREATE TABLE IF NOT EXISTS " + + Table_Applyeid_Promotion + " (" + + KEY_MASTER_TRANSACTION_ID + " INTEGER," + + KEY_RECCEPT_NUMBER + " INTEGER," + + KEY_COUNTER_ID + " INTEGER, " + + KEY_VISIT_DATE + " VARCHAR, USER_ID VARCHAR, " + + "UNIQUE_CODE" + " VARCHAR, " + + "PROMOTION_FLAG" + " INTEGER, " + + "PROMO_TYPE" + " VARCHAR, " + + "INVOICE_TYPE" + " VARCHAR, " + + "PROMOTION" + " VARCHAR, " + + "PROMOTION_ID" + " INTEGER, " + + "PROMO_PRODUCT_ID" + " INTEGER, " + + "PROMO_PRODUCT" + " VARCHAR, " + + "EAN_CODE" + " VARCHAR, " + + "PROMO_PRODUCT_QTY" + " INTEGER, " + + "PROMO_PRODUCT_MRP" + " INTEGER, " + + "PROMO_DISCOUNT" + " INTEGER, " + + KEY_USER_TYPE + " VARCHAR)"; + + public static final String Table_PromoApplyeidOnProduct = "DR_PROMOAPPLYED_PRODUCT"; + public static final String Create_Table_PromoApplyeidOnProduct = "CREATE TABLE IF NOT EXISTS " + + Table_PromoApplyeidOnProduct + " (" + + KEY_COMMON_ID + " INTEGER," + + KEY_MASTER_TRANSACTION_ID + " INTEGER," + + KEY_RECCEPT_NUMBER + " INTEGER," + + KEY_COUNTER_ID + " INTEGER, " + + KEY_VISIT_DATE + " VARCHAR, USER_ID VARCHAR, " + + "UNIQUE_CODE" + " VARCHAR, " + + "PROMOTION_FLAG" + " INTEGER, " + + "PROMO_TYPE" + " VARCHAR, " + + "INVOICE_TYPE" + " VARCHAR, " + + "PROMOTION" + " VARCHAR, " + + "PROMOTION_ID" + " INTEGER, " + + "PRODUCT_ID" + " INTEGER, " + + "PRODUCT" + " VARCHAR, " + + "EAN_CODE" + " VARCHAR, " + + "PRODUCT_QTY" + " INTEGER, " + + "DISCOUNT" + " DOUBLE, " + + "MRP" + " INTEGER, " + + KEY_USER_TYPE + " VARCHAR)"; + + public static final String KEY_LEAVE_Mangemennt = "Leave_Management"; + public static final String KEY_ME_QUIZ = "ME_QUIZ"; + public static final String KEY_RETAIL_EXCELLENCE = "RETAIL_EXCELLENCE"; + public static final String KEY_Me_MakeOver_Capture = "Me_MakeOver_Capture"; + public static final String KEY_Break_Mangemennt = "Break_Management"; + public static final String KEY_Consumer_Object = "Consumer_Object"; + public static final String KEY_BA_Counter_Image = "Ba_Counter_Image"; + public static final String KEY_Me_Counter_Image = "Me_Counter_Image"; + + public static final String Table_Consumer_Return_Header_Data = "CONSUMER_RETURN_HEADER_TABLE"; + public static final String Create_Table_Consumer_Return_Header_Data = "CREATE TABLE IF NOT EXISTS " + + Table_Consumer_Return_Header_Data + " (" + KEY_RECCEPT_NUMBER + + " INTEGER PRIMARY KEY AUTOINCREMENT ," + + KEY_MASTER_TRANSACTION_ID + " INTEGER, " + + KEY_COUNTER_ID + " INTEGER, " + + KEY_VISIT_DATE + " VARCHAR, USER_ID VARCHAR, " + + KEY_STORE_NAME + " VARCHAR, " + + "STORE_ADDRESS" + " VARCHAR, " + + "BUYER_NAME" + " VARCHAR, " + + "BILL_NO" + " VARCHAR, " + + "CONTACT_NUMBER" + " VARCHAR, " + + "EMAIL" + " VARCHAR, " + + "INVOICE_IMG" + " VARCHAR, " + + "GENDER" + " VARCHAR, " + + "UPLOAD_STATUS" + " VARCHAR, " + + "UNIQUE_CODE" + " VARCHAR)"; + + public static final String SALEABLE = "SALEABLE"; + public static final String ME_SALE = "ME_SALE"; + public static final String TESTER = "TESTER"; + public static final String SAMPLE = "SAMPLE"; + public static final String GWP = "GWP"; + public static final String DAMAGE = "DAMAGE"; + public static final String RETURNTO_DB = "RETURNTO_DB"; + public static final String INWARD_DMS_NEW_SKU = "INWARD_DMS_NEW_SKU"; + public static final String INWARD_DMS = "INWARD_DMS"; + public static final String MANUALINWARD_DMS = "MANUALINWARD_DMS"; + public static final String MANUALINWARD_DMS_NEWPRODUCT = "MANUALINWARD_DMS_NEWPRODUCT"; + public static final String CONSUMERSALE = "CONSUMERSALE"; + public static final String SKINGENIUS = "SKINGENIUS"; + public static final String OPEN_SKINGENIUS = "OPEN_SKINGENIUS"; + public static final String OPEN_MAYBELLINE = "OPEN_MAYBELLINE"; + public static final String CONSUMERRETURN = "CONSUMERRETURN"; + public static final String LEAVE_MANAGEMENT = "LEAVEMANAGEMENT"; + public static final String BREAK_MANAGEMENT = "BREAKMANAGEMENT"; + public static final String VISIBILITY = "VISIBILITY"; + public static final String MAKEOVER_CAPTURE = "MAKEOVER"; + public static final String COMP_OFFERS = "COMP_OFFERS"; + public static final String ba_message = "Unable to sync with server"; + public static final String Key_For_Disable_POS_And_Save = "Disable_Pos"; + public static final String KEY_Groomed_Image = "Groomed_Image_Object"; + + public static final int CAMERA_FACE_FRONT = 0x6; + public static final int CAMERA_FACE_REAR = 0x7; + public static final String TAG_HEADER_OBJECT = "HOBJECT"; + public static final String TAG_FOR_RETURN = "RETURN"; + public static final String FLAG_FOR_TERMCONDITION = "termcondition"; + public static final String KEY_UPLOADIMAGE = "uploadimage"; + + public static final String KEY_SaleableDamage = "SaleableDamage"; + public static final String KEY_Update_Visit_Date = "Updated_Date"; + + public static final String Table_ME_QUIZ = "ME_QUIZ_TABLE"; + public static final String Table_Retail_Excellence_Header = "DR_Retail_Excellence_Header"; + public static final String Table_Retail_Excellence_Child = "DR_Retail_Excellence_Child"; + + public static final String Create_Table_Retail_Excellence_Header = "CREATE TABLE IF NOT EXISTS " + + Table_Retail_Excellence_Header + " (" + + CommonString.KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT ," + + KEY_COUNTER_ID + " INTEGER, " + + KEY_VISIT_DATE + " VARCHAR, " + + "USER_ID" + " VARCHAR, " + + "ItemCategoryId" + " INTEGER, " + + "ItemCategoryName" + " VARCHAR, " + + "UPLOAD_STATUS" + " VARCHAR, " + + "UNIQUE_CODE" + " VARCHAR)"; + public static final String Create_Table_Retail_Excellence_Child = "CREATE TABLE IF NOT EXISTS " + + Table_Retail_Excellence_Child + " (" + + CommonString.KEY_COMMON_ID + " INTEGER ," + + KEY_COUNTER_ID + " INTEGER, " + + KEY_VISIT_DATE + " VARCHAR," + + "USER_ID" + " VARCHAR, " + + "ItemCategoryId" + " INTEGER, " + + "ItemCategoryName" + " VARCHAR, " + + "ItemId" + " INTEGER, " + + "ItemName" + " VARCHAR, " + + "UPLOAD_STATUS" + " VARCHAR, " + + "Answer" + " VARCHAR, " + + "UNIQUE_CODE" + " VARCHAR)"; + + public static final String Create_Table_ME_QUIZ = "CREATE TABLE IF NOT EXISTS " + + Table_ME_QUIZ + " (" + CommonString.KEY_ID + + " INTEGER PRIMARY KEY AUTOINCREMENT ," + KEY_COUNTER_ID + + " INTEGER, " + + KEY_VISIT_DATE + " VARCHAR, USER_ID VARCHAR, " + + "QuizName" + " VARCHAR, " + + "QuizId" + " INTEGER, " + + "CATEGORY" + " VARCHAR, " + + + "CATEGORY_Id" + " INTEGER, " + + "QUESTION" + " VARCHAR, " + + "QUESTION_Id" + " INTEGER, " + + "QUESTION_TYPE" + " VARCHAR, " + + "ANSWER" + " VARCHAR, " + + "ANSWER_Id" + " INTEGER, " + + "IMAGE_STR" + " VARCHAR, " + + "IMAGE_ALLOW" + " INTEGER, " + + "UPLOAD_STATUS" + " VARCHAR, " + + "UNIQUE_CODE" + " VARCHAR)"; + + public static final String Table_ME_QUIZ_MULTI_ANSWER = "ME_QUIZ_MULTI_ANS_TABLE"; + public static final String Create_Table_ME_QUIZ_MULTI_ANSWER = "CREATE TABLE IF NOT EXISTS " + + Table_ME_QUIZ_MULTI_ANSWER + " (" + CommonString.KEY_COMMON_ID + + " INTEGER ," + KEY_COUNTER_ID + + " INTEGER, " + + KEY_VISIT_DATE + " VARCHAR, USER_ID VARCHAR, " + + "QuizName" + " VARCHAR, " + + "QuizId" + " INTEGER, " + + "CATEGORY_Id" + " INTEGER, " + + "QUESTION_Id" + " INTEGER, " + + "QUESTION_TYPE" + " VARCHAR, " + + "IS_SELECTED" + " INTEGER, " + + "ANSWER" + " VARCHAR, " + + "ANSWER_Id" + " INTEGER)"; + + public static final String Table_Temp_Consumer_Sale = "Temp_Consumer_Sale"; + public static final String Create_Table_Temp_Consumer_Sale = "CREATE TABLE IF NOT EXISTS " + + Table_Temp_Consumer_Sale + " (" + CommonString.KEY_ID + + " INTEGER PRIMARY KEY AUTOINCREMENT ," + KEY_COUNTER_ID + + " INTEGER, " + KEY_VISIT_DATE + " VARCHAR, USER_ID VARCHAR, " + + "ProductId" + " INTEGER, " + + "Quantity" + " INTEGER, " + + "Amount" + " INTEGER)"; + + + public static final String Table_Temp_Temp_Promo_AplyDefinition = "Temp_Promo_AplyDefinition"; + public static final String Create_Table_Temp_Temp_Promo_AplyDefinition = "CREATE TABLE IF NOT EXISTS " + + Table_Temp_Temp_Promo_AplyDefinition + " (" + CommonString.KEY_ID + + " INTEGER PRIMARY KEY AUTOINCREMENT ," + KEY_COUNTER_ID + + " INTEGER, " + KEY_VISIT_DATE + " VARCHAR, USER_ID VARCHAR, " + + "PromoId" + " INTEGER, " + + "ProductId" + " INTEGER, " + + "Quantity" + " INTEGER, " + + "Rate" + " INTEGER, " + + "Qualified_Status" + " VARCHAR)"; + + public static final String Table_Temp_Temp_Promo_AplyDefinitionfor_and = "Temp_Promo_AplyDefinitionfor_and"; + public static final String Create_Table_Temp_Temp_Promo_AplyDefinitionfor_and = "CREATE TABLE IF NOT EXISTS " + + Table_Temp_Temp_Promo_AplyDefinitionfor_and + " (" + CommonString.KEY_ID + + " INTEGER PRIMARY KEY AUTOINCREMENT ," + KEY_COUNTER_ID + + " INTEGER, " + KEY_VISIT_DATE + " VARCHAR, USER_ID VARCHAR, " + + "MasterId" + " INTEGER, " + + "PromoId" + " INTEGER, " + + "ProductId" + " INTEGER, " + + "Quantity" + " INTEGER, " + + "Rate" + " INTEGER, " + + "Qualified_Status" + " VARCHAR)"; + + + public static final String Table_Temp_Image = "Temp_Image"; + public static final String Create_Table_Temp_Image = "CREATE TABLE IF NOT EXISTS " + + Table_Temp_Image + " (" + CommonString.KEY_ID + + " INTEGER PRIMARY KEY AUTOINCREMENT ," + + KEY_VISIT_DATE + " VARCHAR, " + + "ImageName" + " VARCHAR)"; + + + public static final String Table_Temp_Sale = "Temp_Sale"; + public static final String Create_Table_Temp_Sale = "CREATE TABLE IF NOT EXISTS " + + Table_Temp_Sale + " (" + CommonString.KEY_ID + + " INTEGER PRIMARY KEY AUTOINCREMENT ," + KEY_COUNTER_ID + + " INTEGER, " + KEY_VISIT_DATE + " VARCHAR, " + + "ProductId" + " INTEGER, " + + "Product_Type" + " VARCHAR, " + + "Quantity" + " INTEGER)"; + + public static final String Table_Skin_Genius_Table = "SKIN_GENIUS_TABLE"; + public static final String Create_Table_Skin_Genius_Table = "CREATE TABLE IF NOT EXISTS " + + Table_Skin_Genius_Table + " (" + KEY_RECCEPT_NUMBER + + " INTEGER PRIMARY KEY AUTOINCREMENT ," + + KEY_MASTER_TRANSACTION_ID + " INTEGER, " + + KEY_COUNTER_ID + " INTEGER, " + + KEY_VISIT_DATE + " VARCHAR, USER_ID VARCHAR, " + + "SKIN_GENIUS_IMG" + " VARCHAR, " + + "UPLOAD_STATUS" + " VARCHAR, " + + "CAPTURED_TIME" + " VARCHAR, " + + "UNIQUE_CODE" + " VARCHAR)"; + + + public static final String Table_Open_Skin_Genius_Table = "OPEN_SKIN_GENIUS_TABLE"; + public static final String Create_Table_Open_Skin_Genius_Table = "CREATE TABLE IF NOT EXISTS " + + Table_Open_Skin_Genius_Table + " (" + KEY_RECCEPT_NUMBER + + " INTEGER PRIMARY KEY AUTOINCREMENT ," + + KEY_MASTER_TRANSACTION_ID + " INTEGER, " + + KEY_COUNTER_ID + " INTEGER, " + + KEY_VISIT_DATE + " VARCHAR, USER_ID VARCHAR, " + + "OPENSKIN_GENIUS_COUNT" + " INTEGER, " + + "UPLOAD_STATUS" + " VARCHAR, " + + "UNIQUE_CODE" + " VARCHAR)"; + + + public static final String Table_Open_Maybelline_Table = "OPEN_MAYBELLINE_TABLE"; + public static final String Create_Table_Open_Mabelline_Table = "CREATE TABLE IF NOT EXISTS " + + Table_Open_Maybelline_Table + " (" + KEY_RECCEPT_NUMBER + + " INTEGER PRIMARY KEY AUTOINCREMENT ," + + KEY_MASTER_TRANSACTION_ID + " INTEGER, " + + KEY_COUNTER_ID + " INTEGER, " + + KEY_VISIT_DATE + " VARCHAR, USER_ID VARCHAR, " + + "OPEN_MAYBELLINE_COUNT" + " INTEGER, " + + "UPLOAD_STATUS" + " VARCHAR, " + + "UNIQUE_CODE" + " VARCHAR)"; + + + public static final String Table_Temp_Promotion_OffSameProduct = "Temp_Promotion_OffSameProduct"; + public static final String Create_Table_Temp_Promotion_OffSameProduct = "CREATE TABLE IF NOT EXISTS " + + Table_Temp_Promotion_OffSameProduct + " (" + CommonString.KEY_ID + + " INTEGER PRIMARY KEY AUTOINCREMENT ," + KEY_COUNTER_ID + + " INTEGER, " + KEY_VISIT_DATE + " VARCHAR, USER_ID VARCHAR, " + + "PromoId" + " INTEGER, " + + "ProductId" + " INTEGER, " + + "Quantity" + " INTEGER, " + + "Rate" + " INTEGER)"; + + + public static final String TABLE_COMP_OFFERS = "DR_COMP_OFFERS"; + public static final String CREATE_TABLE_COMP_OFFERS = "CREATE TABLE IF NOT EXISTS " + + TABLE_COMP_OFFERS + " (" + + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT ," + + KEY_UUID + " VARCHAR, " + + KEY_MASTER_TRANSACTION_ID + " INTEGER, " + + KEY_COUNTER_ID + " INTEGER, " + + KEY_USER_ID + " VARCHAR," + + KEY_VISIT_DATE + " VARCHAR," + + KEY_STATUS + " VARCHAR," + + "PRESENT" + " VARCHAR," + + "DATA_FOR_MONTH" + " VARCHAR," + + "COMPANY" + " VARCHAR," + + "COMPANY_ID" + " INTEGER," + + "NUANCE" + " VARCHAR," + + "NUANCE_ID" + " INTEGER," + + "PROMOTYPE" + " VARCHAR," + + "PROMOTYPE_ID" + " INTEGER," + + "NUM_COUNTER" + " INTEGER," + + "NO_OF_BA" + " INTEGER," + + "SALE_RANGE" + " VARCHAR," + + "COMP_OFFER" + " VARCHAR," + + "COMP_OFFER_ID" + " INTEGER," + + "COMP_BUY_TYPE" + " VARCHAR," + + "COMP_BUY_TYPE_ID" + " INTEGER," + + "COMP_BUY_TYPE_INPUT_ID" + " INTEGER," + + "COMP_BUY_TYPE_INPUT" + " VARCHAR," + + "COMP_GET_TYPE_INPUT_ID" + " INTEGER," + + "COMP_GET_TYPE_INPUT" + " VARCHAR," + + "COMP_NEW_LAUNCH_MRP" + " VARCHAR," + + "COMPOFFERSET_QTY" + " INTEGER," + + "COMPOFFERSET" + " VARCHAR," + + "COMPOFFERSET_ID" + " INTEGER," + + "COMPOFFERGET_QTY" + " INTEGER," + + "COMPOFFERGET" + " VARCHAR," + + "COMPOFFERGET_ID" + " INTEGER," + + "FROM_DATE" + " VARCHAR," + + "TO_DATE" + " VARCHAR," + + "PRODUCTTYPE" + " VARCHAR," + + "PRODUCTTYPE_ID" + " INTEGER," + + "AVG_TARGET" + " VARCHAR," + + "AVG_OFFTAKE" + " VARCHAR," + + "TVA_PER" + " VARCHAR," + + "BA_INFO_LIST" + " VARCHAR," + + "PROMO_DETAILS" + " VARCHAR," + + "GWP_AVAILABLE" + " VARCHAR," + + "GWP_IMAGE" + " VARCHAR," + + "PROMO_IMG" + " VARCHAR)"; + + public static final String TABLE_STORE_GEOTAGGING = "DR_STOREGEO_TAG"; + public static final String CREATE_TABLE_STORE_GEOTAGGING = "CREATE TABLE IF NOT EXISTS " + + TABLE_STORE_GEOTAGGING + + " (" + + "KEY_ID" + + " INTEGER PRIMARY KEY AUTOINCREMENT ," + + KEY_USERNAME + + " VARCHAR," + + "STORE_ID" + + " INTEGER," + + KEY_COUNTER_ID + + " INTEGER," + + "BiD" + + " INTEGER," + + "LATITUDE" + + " VARCHAR," + + "LONGITUDE" + + " VARCHAR," + + "GEOTAG" + + " VARCHAR," + + "GEO_IMG" + " VARCHAR)"; + +} + + + + diff --git a/app/src/main/java/com/cpm/lorealbaautomation/constant/FileUtils.java b/app/src/main/java/com/cpm/lorealbaautomation/constant/FileUtils.java new file mode 100644 index 0000000..1a904e2 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/constant/FileUtils.java @@ -0,0 +1,212 @@ +package com.cpm.lorealbaautomation.constant; + +import android.content.ContentUris; +import android.content.Context; +import android.database.Cursor; +import android.database.DatabaseUtils; +import android.net.Uri; +import android.os.Environment; +import android.provider.DocumentsContract; +import android.provider.MediaStore; + +import java.io.File; + +public class FileUtils { + //replace this with your authority + public static final String AUTHORITY = "com.ianhanniballake.localstorage.documents"; + + private FileUtils() { + } //private constructor to enforce Singleton pattern + + /** + * TAG for log messages. + */ + private static final boolean DEBUG = false; // Set to true to enable logging + + + /** + * @return Whether the URI is a local one. + */ + public static boolean isLocal(String url) { + if (url != null && !url.startsWith("http://") && !url.startsWith("https://")) { + return true; + } + return false; + } + + + public static boolean isLocalStorageDocument(Uri uri) { + return AUTHORITY.equals(uri.getAuthority()); + } + + /** + * @param uri The Uri to check. + * @return Whether the Uri authority is ExternalStorageProvider. + * @author paulburke + */ + public static boolean isExternalStorageDocument(Uri uri) { + return "com.android.externalstorage.documents".equals(uri.getAuthority()); + } + + /** + * @param uri The Uri to check. + * @return Whether the Uri authority is DownloadsProvider. + * @author paulburke + */ + public static boolean isDownloadsDocument(Uri uri) { + return "com.android.providers.downloads.documents".equals(uri.getAuthority()); + } + + /** + * @param uri The Uri to check. + * @return Whether the Uri authority is MediaProvider. + * @author paulburke + */ + public static boolean isMediaDocument(Uri uri) { + return "com.android.providers.media.documents".equals(uri.getAuthority()); + } + + /** + * @param uri The Uri to check. + * @return Whether the Uri authority is Google Photos. + */ + public static boolean isGooglePhotosUri(Uri uri) { + return "com.google.android.apps.photos.content".equals(uri.getAuthority()); + } + + /** + * Get the value of the data column for this Uri. This is useful for + * MediaStore Uris, and other file-based ContentProviders. + * + * @param context The context. + * @param uri The Uri to query. + * @param selection (Optional) Filter used in the query. + * @param selectionArgs (Optional) Selection arguments used in the query. + * @return The value of the _data column, which is typically a file path. + * @author paulburke + */ + public static String getDataColumn(Context context, Uri uri, String selection, + String[] selectionArgs) { + + Cursor cursor = null; + final String column = "_data"; + final String[] projection = { + column + }; + + try { + cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, + null); + if (cursor != null && cursor.moveToFirst()) { + if (DEBUG) + DatabaseUtils.dumpCursor(cursor); + + final int column_index = cursor.getColumnIndexOrThrow(column); + return cursor.getString(column_index); + } + } finally { + if (cursor != null) + cursor.close(); + } + return null; + } + + /** + * Get a file path from a Uri. This will get the the path for Storage Access + * Framework Documents, as well as the _data field for the MediaStore and + * other file-based ContentProviders.
+ *
+ * Callers should check whether the path is local before assuming it + * represents a local file. + * + * @param context The context. + * @param uri The Uri to query. + * @author paulburke + * @see #isLocal(String) + * @see #getFile(Context, Uri) + */ + public static String getPath(final Context context, final Uri uri) { + // DocumentProvider + if (DocumentsContract.isDocumentUri(context, uri)) { + // LocalStorageProvider + if (isLocalStorageDocument(uri)) { + // The path is the id + return DocumentsContract.getDocumentId(uri); + } + // ExternalStorageProvider + else if (isExternalStorageDocument(uri)) { + final String docId = DocumentsContract.getDocumentId(uri); + final String[] split = docId.split(":"); + final String type = split[0]; + + if ("primary".equalsIgnoreCase(type)) { + return Environment.getExternalStorageDirectory() + "/" + split[1]; + } + + // TODO handle non-primary volumes + } + // DownloadsProvider + else if (isDownloadsDocument(uri)) { + final String id = DocumentsContract.getDocumentId(uri); + final Uri contentUri = ContentUris.withAppendedId( + Uri.parse("content://downloads/public_downloads"), Long.parseLong(id)); + return getDataColumn(context, contentUri, null, null); + } + // MediaProvider + else if (isMediaDocument(uri)) { + final String docId = DocumentsContract.getDocumentId(uri); + final String[] split = docId.split(":"); + final String type = split[0]; + + Uri contentUri = null; + if ("image".equals(type)) { + contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; + } else if ("video".equals(type)) { + contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI; + } else if ("audio".equals(type)) { + contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; + } + + final String selection = "_id=?"; + final String[] selectionArgs = new String[]{ + split[1] + }; + + return getDataColumn(context, contentUri, selection, selectionArgs); + } + } + else if ("content".equalsIgnoreCase(uri.getScheme())) { + // Return the remote address + if (isGooglePhotosUri(uri)) + return uri.getLastPathSegment(); + + return getDataColumn(context, uri, null, null); + } + // File + else if ("file".equalsIgnoreCase(uri.getScheme())) { + return uri.getPath(); + } + + return null; + } + + /** + * Convert Uri into File, if possible. + * + * @return file A local file that the Uri was pointing to, or null if the + * Uri is unsupported or pointed to a remote resource. + * @author paulburke + * @see #getPath(Context, Uri) + */ + public static File getFile(Context context, Uri uri) { + if (uri != null) { + String path = getPath(context, uri); + if (isLocal(path)) { + return new File(path); + } + } + return null; + } + + +} \ No newline at end of file diff --git a/app/src/main/java/com/cpm/lorealbaautomation/constant/HorizontalProgressBar.java b/app/src/main/java/com/cpm/lorealbaautomation/constant/HorizontalProgressBar.java new file mode 100644 index 0000000..85bcaab --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/constant/HorizontalProgressBar.java @@ -0,0 +1,140 @@ +package com.cpm.lorealbaautomation.constant; + +import android.content.Context; +import android.content.res.TypedArray; +import android.graphics.Canvas; +import android.graphics.Color; +import android.graphics.Paint; +import android.util.AttributeSet; +import android.view.View; +import android.view.animation.Animation; +import android.view.animation.LinearInterpolator; +import android.view.animation.Transformation; + +import com.cpm.lorealbaautomation.R; + + +public class HorizontalProgressBar extends View { + // distance between neighbour dot centres + private int mDotStep = 20; + // actual dot radius + private int mDotRadius = 5; + // Bounced Dot Radiuslogin + private int mBigDotRadius = 8; + // to get identified in which position dot has to bounce + private int mDotPosition; + // specify how many dots you need in a progressbar + private static final int MIN_COUNT = 1; + private static final int DEF_COUNT = 10; + private static final int MAX_COUNT = 100; + private int mDotCount = DEF_COUNT; + private static final int MIN_TIMEOUT = 100; + private static final int DEF_TIMEOUT = 500; + private static final int MAX_TIMEOUT = 3000; + private int mTimeout = DEF_TIMEOUT; + private int mDotColor = Color.parseColor("#fd583f"); + public HorizontalProgressBar(Context context) { + super(context); + initDotSize(); + } + + + public HorizontalProgressBar(Context context, AttributeSet attrs) { + super(context, attrs); + initDotSize(); + applyAttrs(context, attrs); + } + + public HorizontalProgressBar(Context context, AttributeSet attrs, int defStyleAttr) { + super(context, attrs, defStyleAttr); + initDotSize(); + applyAttrs(context, attrs); + } + + private void initDotSize() { + final float scale = getResources().getDisplayMetrics().density; + mDotStep = (int)(mDotStep * scale); + mDotRadius = (int)(mDotRadius * scale); + mBigDotRadius = (int)(mBigDotRadius * scale); + } + + private void applyAttrs(Context context, AttributeSet attrs) { + TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.HorizontalProgressBar, 0, 0); + try { + mDotColor = a.getColor(R.styleable.HorizontalProgressBar_color, mDotColor); + mDotCount = a.getInteger(R.styleable.HorizontalProgressBar_count, mDotCount); + mDotCount = Math.min(Math.max(mDotCount, MIN_COUNT), MAX_COUNT); + mTimeout = a.getInteger(R.styleable.HorizontalProgressBar_timeout, mTimeout); + mTimeout = Math.min(Math.max(mTimeout, MIN_TIMEOUT), MAX_TIMEOUT); + } finally { + a.recycle(); + } + } + + //Method to draw your customized dot on the canvas + @Override + protected void onDraw(Canvas canvas) { + super.onDraw(canvas); + if (isShown()) { + Paint paint = new Paint(); + paint.setColor(mDotColor); + createDots(canvas, paint); + } + } + + @Override + protected void onAttachedToWindow() { + super.onAttachedToWindow(); + startAnimation(); + } + + private void createDots(Canvas canvas, Paint paint) { + for (int i = 0; i < mDotCount; i++ ) { + int radius = (i == mDotPosition) ? mBigDotRadius : mDotRadius; + canvas.drawCircle(mDotStep / 2 + (i * mDotStep), mBigDotRadius, radius, paint); + } + } + + @Override + protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { + super.onMeasure(widthMeasureSpec, heightMeasureSpec); + + // MUST CALL THIS + setMeasuredDimension(mDotStep * mDotCount, mBigDotRadius * 2); + } + + private void startAnimation() { + BounceAnimation bounceAnimation = new BounceAnimation(); + bounceAnimation.setDuration(mTimeout); + bounceAnimation.setRepeatCount(Animation.INFINITE); + bounceAnimation.setInterpolator(new LinearInterpolator()); + bounceAnimation.setAnimationListener(new Animation.AnimationListener() { + @Override + public void onAnimationStart(Animation animation) { + } + + @Override + public void onAnimationEnd(Animation animation) { + } + + @Override + public void onAnimationRepeat(Animation animation) { + if (++mDotPosition >= mDotCount) { + mDotPosition = 0; + } + } + }); + startAnimation(bounceAnimation); + } + + + private class BounceAnimation extends Animation { + @Override + protected void applyTransformation(float interpolatedTime, Transformation t) { + super.applyTransformation(interpolatedTime, t); + // call invalidate to redraw your view again + invalidate(); + } + } +} + diff --git a/app/src/main/java/com/cpm/lorealbaautomation/constant/ImageConverter.java b/app/src/main/java/com/cpm/lorealbaautomation/constant/ImageConverter.java new file mode 100644 index 0000000..0e117b4 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/constant/ImageConverter.java @@ -0,0 +1,31 @@ +package com.cpm.lorealbaautomation.constant; + +import android.graphics.Bitmap; +import android.graphics.Canvas; +import android.graphics.Paint; +import android.graphics.PorterDuff; +import android.graphics.PorterDuffXfermode; +import android.graphics.Rect; +import android.graphics.RectF; + +public class ImageConverter { + public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, int pixels) { + Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888); + Canvas canvas = new Canvas(output); + final int color = 0xff424242; + final Paint paint = new Paint(); + final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()); + final RectF rectF = new RectF(rect); + final float roundPx = pixels; + + paint.setAntiAlias(true); + canvas.drawARGB(0, 0, 0, 0); + paint.setColor(color); + canvas.drawRoundRect(rectF, roundPx, roundPx, paint); + + paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN)); + canvas.drawBitmap(bitmap, rect, rect, paint); + + return output; + } +} \ No newline at end of file diff --git a/app/src/main/java/com/cpm/lorealbaautomation/constant/RoundImage.java b/app/src/main/java/com/cpm/lorealbaautomation/constant/RoundImage.java new file mode 100644 index 0000000..46b440e --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/constant/RoundImage.java @@ -0,0 +1,94 @@ +package com.cpm.lorealbaautomation.constant; + +import android.graphics.Bitmap; +import android.graphics.BitmapShader; +import android.graphics.Canvas; +import android.graphics.ColorFilter; +import android.graphics.Paint; +import android.graphics.PixelFormat; +import android.graphics.Rect; +import android.graphics.RectF; +import android.graphics.Shader; +import android.graphics.drawable.Drawable; + +public class RoundImage extends Drawable { + private final Bitmap mBitmap; + private final Paint mPaint; + private final RectF mRectF; + private final int mBitmapWidth=100; + private final int mBitmapHeight=100; + + public RoundImage(Bitmap bitmap) { + mBitmap = bitmap; + mRectF = new RectF(); + mPaint = new Paint(); + mPaint.setAntiAlias(true); + mPaint.setDither(true); + final BitmapShader shader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP); + mPaint.setShader(shader); + +/* mBitmapWidth = mBitmap.getWidth(); + mBitmapHeight = mBitmap.getHeight();*/ + } + + @Override + public void draw(Canvas canvas) { + canvas.drawOval(mRectF, mPaint); + } + + @Override + protected void onBoundsChange(Rect bounds) { + super.onBoundsChange(bounds); + mRectF.set(bounds); + } + + @Override + public void setAlpha(int alpha) { + if (mPaint.getAlpha() != alpha) { + mPaint.setAlpha(alpha); + invalidateSelf(); + } + } + + @Override + public void setColorFilter(ColorFilter cf) { + mPaint.setColorFilter(cf); + } + + @Override + public int getOpacity() { + return PixelFormat.TRANSLUCENT; + } + + @Override + public int getIntrinsicWidth() { + return mBitmapWidth; + } + + @Override + public int getIntrinsicHeight() { + return mBitmapHeight; + } + + public void setAntiAlias(boolean aa) { + mPaint.setAntiAlias(aa); + invalidateSelf(); + } + + @Override + public void setFilterBitmap(boolean filter) { + mPaint.setFilterBitmap(filter); + invalidateSelf(); + } + + @Override + public void setDither(boolean dither) { + mPaint.setDither(dither); + invalidateSelf(); + } + + public Bitmap getBitmap() { + return mBitmap; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/constant/RoundedImageView.java b/app/src/main/java/com/cpm/lorealbaautomation/constant/RoundedImageView.java new file mode 100644 index 0000000..1a2b9e8 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/constant/RoundedImageView.java @@ -0,0 +1,154 @@ +package com.cpm.lorealbaautomation.constant; + +import android.annotation.SuppressLint; +import android.content.Context; +import android.graphics.Bitmap; +import android.graphics.BitmapShader; +import android.graphics.Canvas; +import android.graphics.Color; +import android.graphics.Paint; +import android.graphics.Shader; +import android.graphics.drawable.BitmapDrawable; +import android.util.AttributeSet; +import android.widget.ImageView; + +/** + * Created by desktop-04 on 5/7/16. + */ +@SuppressLint("AppCompatCustomView") +public class RoundedImageView extends ImageView +{ + private int borderWidth = 6; + private int viewWidth; + private int viewHeight; + private Bitmap image; + private Paint paint; + private Paint paintBorder; + private BitmapShader shader; + + public RoundedImageView(Context context) + { + super(context); + setup(); + } + + public RoundedImageView(Context context, AttributeSet attrs) + { + super(context, attrs); + setup(); + } + + public RoundedImageView(Context context, AttributeSet attrs, int defStyle) + { + super(context, attrs, defStyle); + setup(); + } + + private void setup() + { + // init paint + paint = new Paint(); + paint.setAntiAlias(true); + + paintBorder = new Paint(); + setBorderColor( Color.parseColor("#FFFFFF")); + paintBorder.setAntiAlias(true); + this.setLayerType(LAYER_TYPE_SOFTWARE, paintBorder); + paintBorder.setShadowLayer(4.0f, 0.0f, 2.0f, Color.TRANSPARENT); + } + + public void setBorderWidth(int borderWidth) + { + this.borderWidth = borderWidth; + this.invalidate(); + } + + public void setBorderColor(int borderColor) + { + if (paintBorder != null) + paintBorder.setColor(borderColor); + + this.invalidate(); + } + + private void loadBitmap() + { + BitmapDrawable bitmapDrawable = (BitmapDrawable) this.getDrawable(); + + if (bitmapDrawable != null) + image = bitmapDrawable.getBitmap(); + } + + @Override + public void onDraw(Canvas canvas) + { + // load the bitmap + loadBitmap(); + + // init shader + if (image != null) + { + shader = new BitmapShader(Bitmap.createScaledBitmap(image, canvas.getWidth(), canvas.getHeight(), false), Shader.TileMode.CLAMP, Shader.TileMode.CLAMP); + paint.setShader(shader); + int circleCenter = viewWidth / 2; + + // circleCenter is the x or y of the view's center + // radius is the radius in pixels of the cirle to be drawn + // paint contains the shader that will texture the shape + canvas.drawCircle(circleCenter + borderWidth, circleCenter + borderWidth, circleCenter + borderWidth - 4.0f, paintBorder); + canvas.drawCircle(circleCenter + borderWidth, circleCenter + borderWidth, circleCenter - 4.0f, paint); + } + } + + @Override + protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) + { + int width = measureWidth(widthMeasureSpec); + int height = measureHeight(heightMeasureSpec, widthMeasureSpec); + + viewWidth = width - (borderWidth * 2); + viewHeight = height - (borderWidth * 2); + + setMeasuredDimension(width, height); + } + + private int measureWidth(int measureSpec) + { + int result = 0; + int specMode = MeasureSpec.getMode(measureSpec); + int specSize = MeasureSpec.getSize(measureSpec); + + if (specMode == MeasureSpec.EXACTLY) + { + // We were told how big to be + result = specSize; + } + else + { + // Measure the text + result = viewWidth; + } + + return result; + } + + private int measureHeight(int measureSpecHeight, int measureSpecWidth) + { + int result = 0; + int specMode = MeasureSpec.getMode(measureSpecHeight); + int specSize = MeasureSpec.getSize(measureSpecHeight); + + if (specMode == MeasureSpec.EXACTLY) + { + // We were told how big to be + result = specSize; + } + else + { + // Measure the text (beware: ascent is a negative number) + result = viewHeight; + } + + return (result + 2); + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/consumeractivity/ConsumerIntractionDetailActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/consumeractivity/ConsumerIntractionDetailActivity.java new file mode 100644 index 0000000..f53f7af --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/consumeractivity/ConsumerIntractionDetailActivity.java @@ -0,0 +1,289 @@ +package com.cpm.lorealbaautomation.consumeractivity; + +import android.annotation.SuppressLint; +import android.app.AlertDialog; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.os.Bundle; + +import androidx.annotation.NonNull; +import androidx.appcompat.app.AppCompatActivity; +import androidx.cardview.widget.CardView; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; +import androidx.appcompat.widget.Toolbar; + +import android.view.LayoutInflater; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; +import android.widget.ImageView; +import android.widget.TextView; + +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.constant.AlertandMessages; +import com.cpm.lorealbaautomation.constant.CommonFunctions; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.gsonGetterSetter.InvoiceGetterSetter; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +public class ConsumerIntractionDetailActivity extends AppCompatActivity implements View.OnClickListener { + String counter_id, visit_date, username; + private SharedPreferences preferences; + ArrayList invoice_List = new ArrayList<>(); + InvoiceGetterSetter totalsales = new InvoiceGetterSetter(); + ImageView btn_saletra_add_performa; + TextView count_cst, total_sales, discount_value; + Lorealba_Database db; + Context context; + RecyclerView sale_tracking_recycle; + boolean clicked_flag = false; + String from = CommonString.TAG_FROM_BA; + + @SuppressLint("SetTextI18n") + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_consumer_intraction_detail); + from = getIntent().getStringExtra("from"); + context = this; + db = new Lorealba_Database(context); + db.open(); + iduserinterface(); + String couter_code = preferences.getString(CommonString.KEY_COUNTER_CODE, ""); + TextView txt_counter_code = (TextView) findViewById(R.id.txt_counter_code); + txt_counter_code.setText("Counter Code - " + couter_code + " / Id - " + counter_id); + Toolbar toolbar = findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + Objects.requireNonNull(getSupportActionBar()).setHomeButtonEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + if (!CommonFunctions.isTablet(context)) { + toolbar.setTitleTextAppearance(context, R.style.changestext_sizefor_mobile); + } + + setTitle("Consumer Interaction - " + username); + } + + private void iduserinterface() { + preferences = PrefHelper.getPrefs(context); + counter_id = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + username = preferences.getString(CommonString.KEY_USERNAME, ""); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + btn_saletra_add_performa = (ImageView) findViewById(R.id.btn_saletra_add_performa); + sale_tracking_recycle = (RecyclerView) findViewById(R.id.sale_tracking_recycle); + count_cst = (TextView) findViewById(R.id.count_cst); + total_sales = (TextView) findViewById(R.id.total_sales); + discount_value = (TextView) findViewById(R.id.discount_value); + btn_saletra_add_performa.setOnClickListener(this); + } + + @SuppressLint("SetTextI18n") + @Override + protected void onResume() { + super.onResume(); + db = new Lorealba_Database(context); + db.open(); + invoice_List = db.getsalestrackingListusing_group(counter_id, visit_date, null,from); + if (!invoice_List.isEmpty()) { + sale_tracking_recycle.setAdapter(new ValueAdapter(context, invoice_List)); + sale_tracking_recycle.setLayoutManager(new LinearLayoutManager(context)); + } + db.open(); + totalsales = db.getcst_countandtotal_sale_value(visit_date, counter_id, null,from); + db.open(); + ArrayList totaldiscount = db.getcst_totaldiscount(visit_date, counter_id, null,from); + + if (totalsales.getCst_count() != null && !totalsales.getCst_count().equals("0")) { + count_cst.setText(totalsales.getCst_count()); + total_sales.setText(totalsales.getTotal_amount()); + if (!totaldiscount.isEmpty()) { + int total_discount = 0; + for (int k = 0; k < totaldiscount.size(); k++) { + total_discount = total_discount + totaldiscount.get(k).getAplyieddiscountedprice(); + } + discount_value.setText(String.valueOf(total_discount)); + } else { + discount_value.setText("0.0"); + } + } else { + count_cst.setText("0"); + total_sales.setText("0.0"); + discount_value.setText("0.0"); + } + } + @Override + public void onClick(View v) { + if (v.getId() == R.id.btn_saletra_add_performa) { + startActivity(new Intent(context, ConsumerUserDetailsActivity.class).putExtra(CommonString.TAG_MODE, "1").putExtra("from",from)); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + } + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + if (id == android.R.id.home) { + if (clicked_flag) { + AlertDialog.Builder builder = new AlertDialog.Builder(context).setMessage(CommonString.ONBACK_ALERT_MESSAGE).setCancelable(false).setPositiveButton("Ok", + (dialog, id1) -> { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + ConsumerIntractionDetailActivity.this.finish(); + }).setNegativeButton("Cancel", (dialog, id12) -> dialog.cancel()); + AlertDialog alert = builder.create(); + alert.show(); + } else { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + ConsumerIntractionDetailActivity.this.finish(); + } + } + + return super.onOptionsItemSelected(item); + } + + @Override + public void onBackPressed() { + if (clicked_flag) { + AlertDialog.Builder builder = new AlertDialog.Builder(context).setMessage(CommonString.ONBACK_ALERT_MESSAGE).setCancelable(false).setPositiveButton("Ok", + (dialog, id) -> { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + ConsumerIntractionDetailActivity.this.finish(); + }).setNegativeButton("Cancel", (dialog, id) -> dialog.cancel()); + AlertDialog alert = builder.create(); + alert.show(); + } else { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + ConsumerIntractionDetailActivity.this.finish(); + } + } + + private class ValueAdapter extends RecyclerView.Adapter { + LayoutInflater inflator; + List data; + + public ValueAdapter(Context context, List data) { + inflator = LayoutInflater.from(context); + this.data = data; + } + + @NonNull + @Override + public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) { + View view = inflator.inflate(R.layout.details_consumer_list, parent, false); + return new ValueAdapter.MyViewHolder(view); + } + + @SuppressLint("SetTextI18n") + @Override + public void onBindViewHolder(@NonNull final MyViewHolder holder, final int position) { + final InvoiceGetterSetter current = data.get(position); + if (current.isPos_sale_flag()) { + if (!current.getStr_upload_status().isEmpty() && !current.getStr_upload_status().equalsIgnoreCase(CommonString.KEY_N)) { + holder.pos_icon.setImageResource(R.mipmap.upload_tick); + } else { + holder.pos_icon.setImageResource(R.mipmap.not_upload); + } + holder.pos_icon.setVisibility(View.VISIBLE); + holder.pos_icon.setId(position); + } else { + holder.pos_icon.setVisibility(View.VISIBLE); + holder.pos_icon.setId(position); + } + + if (checkdemovalidation(current) && current.getProduct_sold_str().equalsIgnoreCase("No")) { + holder.demo_icon.setVisibility(View.VISIBLE); + holder.demo_icon.setId(position); + holder.sale_icon.setVisibility(View.INVISIBLE); + holder.sale_icon.setId(position); + } else if (!checkdemovalidation(current) && current.getProduct_sold_str().equalsIgnoreCase("Yes")) { + holder.demo_icon.setVisibility(View.INVISIBLE); + holder.demo_icon.setId(position); + holder.sale_icon.setVisibility(View.VISIBLE); + holder.sale_icon.setId(position); + } else if (checkdemovalidation(current) && current.getProduct_sold_str().equalsIgnoreCase("Yes")) { + holder.demo_icon.setVisibility(View.VISIBLE); + holder.demo_icon.setId(position); + holder.sale_icon.setVisibility(View.VISIBLE); + holder.sale_icon.setId(position); + } else { + holder.demo_icon.setVisibility(View.INVISIBLE); + holder.demo_icon.setId(position); + holder.sale_icon.setVisibility(View.INVISIBLE); + holder.sale_icon.setId(position); + } + + holder.sale_trcking_name.setText(current.getCustomer_name() + " - Mobile No. : " + current.getMobile_no()); + holder.sale_trcking_name.setId(position); + + holder.sales_count.setText("Count : " + current.getQuantity()); + holder.sales_count.setId(position); + + holder.sale_total_amount.setText("Total Amount : " + current.getTotal_amount()); + holder.sale_total_amount.setId(position); + + holder.discountedRs.setText("Discounted Rs : " + current.getAplyieddiscountedprice()); + holder.discountedRs.setId(position); + + holder.sale_card.setOnClickListener(v -> { + if (!current.isPos_sale_flag()) { + db.open(); + startActivity(new Intent(context, ConsumerUserDetailsActivity.class) + .putExtra(CommonString.TAG_OBJECT, + db.getsalesTrackingByUserMobile(current.getReccept_count(), current.getMobile_no(), + visit_date, counter_id, current.getUserName())) + .putExtra(CommonString.Key_For_Pos_Enable_With_Showing_Invoice, "1") + .putExtra(CommonString.Key_For_Consumer_Update, "1").putExtra("from",from)); + + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + } else { + db.open(); + if (current.getProduct_sold_str().equalsIgnoreCase("Yes")) { + startActivity(new Intent(context, InvoiceReportProformaActivity.class) + .putExtra(CommonString.TAG_OBJECT, db.getsalesTrackingByUserMobile(current.getReccept_count(), + current.getMobile_no(), visit_date, counter_id, current.getUserName())) + .putExtra(CommonString.Key_For_Disable_POS_And_Save, "1") + .putExtra(CommonString.Key_For_Consumer_Update, "1").putExtra("from",from)); + + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + } else { + AlertandMessages.showToastMsg(context, "Sales Not Found"); + } + } + }); + } + + @Override + public int getItemCount() { + return data.size(); + } + + class MyViewHolder extends RecyclerView.ViewHolder { + TextView sale_trcking_name, sales_count, sale_total_amount, discountedRs; + CardView sale_card; + ImageView pos_icon, demo_icon, sale_icon; + + public MyViewHolder(View itemView) { + super(itemView); + sale_card = (CardView) itemView.findViewById(R.id.sale_card); + sale_trcking_name = (TextView) itemView.findViewById(R.id.sale_trcking_name); + sales_count = (TextView) itemView.findViewById(R.id.sales_count); + sale_total_amount = (TextView) itemView.findViewById(R.id.sale_total_amount); + discountedRs = (TextView) itemView.findViewById(R.id.discountedRs); + pos_icon = (ImageView) itemView.findViewById(R.id.pos_icon); + sale_icon = (ImageView) itemView.findViewById(R.id.sale_icon); + demo_icon = (ImageView) itemView.findViewById(R.id.demo_icon); + } + } + } + + private boolean checkdemovalidation(InvoiceGetterSetter current) { + return current.getDemo_given_str().equalsIgnoreCase("Yes") || current.getSkin_genius_str().equalsIgnoreCase("Yes") || current.getMaybelline_vto_str().equalsIgnoreCase("Yes"); + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/consumeractivity/ConsumerReturnReplaceProductActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/consumeractivity/ConsumerReturnReplaceProductActivity.java new file mode 100644 index 0000000..0e83050 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/consumeractivity/ConsumerReturnReplaceProductActivity.java @@ -0,0 +1,1214 @@ +package com.cpm.lorealbaautomation.consumeractivity; + +import android.annotation.SuppressLint; +import android.app.Activity; +import android.app.AlertDialog; +import android.app.Dialog; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; + +import com.google.android.material.floatingactionbutton.FloatingActionButton; + +import androidx.annotation.NonNull; +import androidx.appcompat.app.AppCompatActivity; + +import android.os.Bundle; + +import androidx.cardview.widget.CardView; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; +import androidx.appcompat.widget.Toolbar; + +import android.text.Editable; +import android.text.TextWatcher; +import android.view.Gravity; +import android.view.LayoutInflater; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; +import android.view.Window; +import android.view.WindowManager; +import android.widget.AdapterView; +import android.widget.ArrayAdapter; +import android.widget.Button; +import android.widget.EditText; +import android.widget.ImageView; +import android.widget.LinearLayout; +import android.widget.Spinner; +import android.widget.TextView; +import android.widget.Toast; + +import com.google.zxing.integration.android.IntentIntegrator; +import com.google.zxing.integration.android.IntentResult; +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.constant.AlertandMessages; +import com.cpm.lorealbaautomation.constant.CommonFunctions; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.gsonGetterSetter.InvoiceGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.ProductMaster; + + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + + +import static com.cpm.lorealbaautomation.constant.CommonFunctions.removeFirstChar; +import static com.cpm.lorealbaautomation.dailyactivity.ConsumerReturnActivity.replace_productList; + + +public class ConsumerReturnReplaceProductActivity extends AppCompatActivity implements View.OnClickListener { + ArrayAdapter dialog_brand_adapter, dialog_sub_brand_adapter, dialog_frenchise_adapter, dialog_sku_adapter; + TextView txt_product_name, txt_return_qty, txt_product_mrp; + EditText edt_scan_code; + Button btn_scan, btn_enter_code, btn_sku_list; + RecyclerView drawer_layout_recycle_store; + MultiPurposeDialog multiPurposeDialog; + InvoiceGetterSetter object, selected_product_mrpObject; + int minteger = 0; + + String counterID, username, visit_date, dialog_brand_Id = "", dialog_sub_brand_Id = "", + dialog_reference_Id = "", product_name = "", product_Id = "0", product_mrp = "0", product_scan_code = "", + bill_no, mobile_no, consumer_name; + private SharedPreferences preferences; + private SharedPreferences.Editor editor = null; + TextView qrcode_text, sku_name, stock_text_value, actual_qty_dialog; + boolean clicked_flag = false, flag_for_filter = false, flag_filter_by_edt = false; + public ArrayList dialog_product_list = new ArrayList<>(); + public ArrayList dialog_product_using_searchlist = new ArrayList<>(); + FloatingActionButton save_fab; + LinearLayout rl_actual_qty; + Lorealba_Database db; + Context context; + int current_total = 0; + + @SuppressLint("SetTextI18n") + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_consumer_return_replace_product); + context = this; + ((ConsumerReturnReplaceProductActivity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); + Toolbar toolbar = findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + if (!CommonFunctions.isTablet(context)) { + toolbar.setTitleTextAppearance(context, R.style.changestext_sizefor_mobile); + } + + Objects.requireNonNull(getSupportActionBar()).setHomeButtonEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + iduserinterface(); + setTitle("Replace Product - " + username); + + String couter_code = preferences.getString(CommonString.KEY_COUNTER_CODE, ""); + TextView txt_counter_code = (TextView) findViewById(R.id.txt_counter_code); + txt_counter_code.setText("Counter Code - " + couter_code + " / Id - " + counterID); + } + + @SuppressLint("SetTextI18n") + private void iduserinterface() { + db = new Lorealba_Database(context); + db.open(); + preferences = PrefHelper.getPrefs(context); + editor = preferences.edit(); + counterID = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + username = preferences.getString(CommonString.KEY_USERNAME, ""); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + txt_product_name = (TextView) findViewById(R.id.txt_product_name); + txt_return_qty = (TextView) findViewById(R.id.txt_return_qty); + txt_product_mrp = (TextView) findViewById(R.id.txt_product_mrp); + save_fab = (FloatingActionButton) findViewById(R.id.save_fab); + + btn_scan = (Button) findViewById(R.id.btn_scan); + btn_enter_code = (Button) findViewById(R.id.btn_enter_code); + btn_sku_list = (Button) findViewById(R.id.btn_sku_list); + drawer_layout_recycle_store = (RecyclerView) findViewById(R.id.drawer_layout_recycle_store); + db.open(); + btn_scan.setOnClickListener(this); + btn_enter_code.setOnClickListener(this); + btn_sku_list.setOnClickListener(this); + save_fab.setOnClickListener(this); + db.open(); + dialog_product_list = db.getproduct_masterlist("T_StockSummary", visit_date, counterID, null); + selected_product_mrpObject = (InvoiceGetterSetter) getIntent().getSerializableExtra(CommonString.TAG_OBJECT); + if (selected_product_mrpObject != null && selected_product_mrpObject.getTotal_replace_product_value() != 0) { + txt_return_qty.setText("Return Total Rs. : " + selected_product_mrpObject.getTotal_replace_product_value()); + txt_product_mrp.setText("Current Total Rs. : 0"); + } + + + if (!replace_productList.isEmpty()) { + drawer_layout_recycle_store.setAdapter(new ValueAdapter(context, replace_productList)); + drawer_layout_recycle_store.setLayoutManager(new LinearLayoutManager(context)); + txt_product_mrp.setText("Current Total Rs. : " + calculate_total_consume(replace_productList)); + } + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + if (id == android.R.id.home) { + if (clicked_flag) { + AlertDialog.Builder builder = new AlertDialog.Builder(context).setMessage(CommonString.ONBACK_ALERT_MESSAGE).setCancelable(false).setPositiveButton("Ok", + (dialog, id12) -> { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + ConsumerReturnReplaceProductActivity.this.finish(); + }).setNegativeButton("Cancel", (dialog, id1) -> dialog.cancel()); + AlertDialog alert = builder.create(); + alert.show(); + } else { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + ConsumerReturnReplaceProductActivity.this.finish(); + } + } + + return super.onOptionsItemSelected(item); + } + + @Override + public void onBackPressed() { + if (clicked_flag) { + AlertDialog.Builder builder = new AlertDialog.Builder(context).setMessage(CommonString.ONBACK_ALERT_MESSAGE).setCancelable(false).setPositiveButton("Ok", + (dialog, id) -> { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + ConsumerReturnReplaceProductActivity.this.finish(); + }).setNegativeButton("Cancel", (dialog, id) -> dialog.cancel()); + AlertDialog alert = builder.create(); + alert.show(); + } else { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + ConsumerReturnReplaceProductActivity.this.finish(); + } + } + + @SuppressLint("NonConstantResourceId") + @Override + public void onClick(View view) { + + if (view.getId() == R.id.btn_scan) { + ((ConsumerReturnReplaceProductActivity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); + show_proforma_dialog(context, true); + + } else if (view.getId() == R.id.btn_enter_code) { + ((ConsumerReturnReplaceProductActivity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); + show_proforma_dialog(context, false); + + } else if (view.getId() == R.id.btn_sku_list) { + ((ConsumerReturnReplaceProductActivity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); + show_dialog_forsku_categorywise(context); + + } else if (view.getId() == R.id.save_fab) { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + ConsumerReturnReplaceProductActivity.this.finish(); + } + + } + + + @SuppressLint("SetTextI18n") + private void show_proforma_dialog(final Context context, final boolean flag_for_rl) { + minteger = 0; + final MultiPurposeDialog multiPurposeDialog = new MultiPurposeDialog(context); + multiPurposeDialog.requestWindowFeature(Window.FEATURE_NO_TITLE); + multiPurposeDialog.setContentView(R.layout.custom_bar_code_dialog); + multiPurposeDialog.setCancelable(false); + WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); + lp.copyFrom(Objects.requireNonNull(multiPurposeDialog.getWindow()).getAttributes()); + lp.width = WindowManager.LayoutParams.MATCH_PARENT; + lp.height = WindowManager.LayoutParams.WRAP_CONTENT; + lp.gravity = Gravity.CENTER; + multiPurposeDialog.getWindow().setAttributes(lp); + multiPurposeDialog.setCancelable(false); + +//for actual Quantity form Tstock_Summery + rl_actual_qty = (LinearLayout) multiPurposeDialog.findViewById(R.id.rl_actual_qty); + actual_qty_dialog = (TextView) multiPurposeDialog.findViewById(R.id.actual_qty_dialog); + + LinearLayout rl_bar_code = (LinearLayout) multiPurposeDialog.findViewById(R.id.rl_bar_code); + LinearLayout RL_scan_code = (LinearLayout) multiPurposeDialog.findViewById(R.id.RL_scan_code); + Button check_exist_sku = (Button) multiPurposeDialog.findViewById(R.id.check_exist_sku); + TextView txt_bar_code = multiPurposeDialog.findViewById(R.id.txt_bar_code); + TextView txt_enterbar_code = multiPurposeDialog.findViewById(R.id.txt_enterbar_code); + LinearLayout rl_quantity = (LinearLayout) multiPurposeDialog.findViewById(R.id.rl_quantity); + final RecyclerView recycl_mutliennter_qty = (RecyclerView) multiPurposeDialog.findViewById(R.id.recycl_mutliennter_qty); + recycl_mutliennter_qty.setVisibility(View.GONE); + rl_quantity.setVisibility(View.VISIBLE); + + sku_name = multiPurposeDialog.findViewById(R.id.sku_name); + if (flag_for_rl) { + RL_scan_code.setVisibility(View.GONE); + rl_bar_code.setVisibility(View.VISIBLE); + txt_bar_code.setVisibility(View.VISIBLE); + txt_enterbar_code.setVisibility(View.GONE); + } else { + rl_bar_code.setVisibility(View.GONE); + txt_bar_code.setVisibility(View.GONE); + RL_scan_code.setVisibility(View.VISIBLE); + txt_enterbar_code.setVisibility(View.VISIBLE); + } + + qrcode_text = (TextView) multiPurposeDialog.findViewById(R.id.qrcode_text); + edt_scan_code = (EditText) multiPurposeDialog.findViewById(R.id.edt_scan_code); + final Button stock_img_minus = (Button) multiPurposeDialog.findViewById(R.id.stock_img_minus); + Button stock_img_plus = (Button) multiPurposeDialog.findViewById(R.id.stock_img_plus); + stock_text_value = (TextView) multiPurposeDialog.findViewById(R.id.stock_text_value); + + ImageView img_bar_code = (ImageView) multiPurposeDialog.findViewById(R.id.img_bar_code); + ImageView cancet_btn = (ImageView) multiPurposeDialog.findViewById(R.id.cancet_btn); + final ImageView btn_add = (ImageView) multiPurposeDialog.findViewById(R.id.btn_add); + btn_add.setVisibility(View.VISIBLE); + + stock_img_plus.setOnClickListener(v -> { + if (!product_Id.equals("0")) { + db.open(); + if (db.getActualSaleableStock(product_Id, null, visit_date, counterID, null).getStock() == 0) { + AlertandMessages.showToastMsg(context, "Stock for this Product is Zero. Cannot allow to add this Product"); + } else { + minteger = minteger + 1; + db.open(); + if (db.getActualSaleableStock(product_Id, null, visit_date, counterID, null).getStock() != 0 && minteger > db.getActualSaleableStock(product_Id, null, visit_date, counterID, null).getStock()) { + minteger = minteger - 1; + AlertandMessages.showToastMsg(context, "Stock Low. Please reduce sale quantity below or equal to the stock value"); + } else { + int val = calculate_total() + (minteger * (Integer.parseInt(product_mrp))); + stock_text_value.setText("" + minteger); + } + } + } + }); + + stock_img_minus.setOnClickListener(v -> { + if (minteger == 0) { + AlertandMessages.showToastMsg(context, "Product quantity should not be less than Zero"); + } else { + minteger = minteger - 1; + stock_text_value.setText("" + minteger); + } + }); + + cancet_btn.setOnClickListener(v -> { + multiPurposeDialog.dismiss(); + sku_name.setText(""); + stock_text_value.setText(""); + qrcode_text.setText(""); + product_scan_code = ""; + product_name = ""; + product_mrp = ""; + product_Id = "0"; + sku_name.setVisibility(View.GONE); + }); + + check_exist_sku.setOnClickListener(v -> { + if (!flag_for_rl && edt_scan_code.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter Bar Code"); + } else { + db.open(); + if (db.getsku_fromproductusing_eancode(edt_scan_code.getText().toString(), true, visit_date, counterID, null).isEmpty()) { + edt_scan_code.setText(""); + AlertandMessages.showToastMsg(context, "Invalid Bar Code.Please try again"); + } else { + db.open(); + show_dialog_forsku(context, db.getsku_fromproductusing_eancode(edt_scan_code.getText().toString(), true, visit_date, counterID, null), rl_actual_qty, actual_qty_dialog); + } + } + }); + + + btn_add.setOnClickListener(v -> { + db.open(); + if (db.getActualSaleableStock(product_Id, null, visit_date, counterID, null).getStock() == 0) { + AlertandMessages.showToastMsg(context, "Stock for this Product is Zero. Cannot allow to add this Product"); + multiPurposeDialog.cancel(); + stock_text_value.setText(""); + qrcode_text.setText(""); + edt_scan_code.setText(""); + product_scan_code = ""; + product_name = ""; + product_mrp = ""; + product_Id = "0"; + sku_name.setText(""); + sku_name.setVisibility(View.GONE); + + } else { + if (flag_for_rl && qrcode_text.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Scan Bar Code"); + } else if (!flag_for_rl && edt_scan_code.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter Bar Code "); + } else if (stock_text_value.getText().toString().equals("0")) { + AlertandMessages.showToastMsg(context, "Please add Atleast One Product Quantity "); + } else { + object = new InvoiceGetterSetter(); + if (checkduplicate_entry()) { + if (!flag_for_rl) { + product_scan_code = edt_scan_code.getText().toString(); + db.open(); + if (db.getsku_fromproductusing_eancode(product_scan_code, true, visit_date, counterID, null).isEmpty()) { + AlertandMessages.showToastMsg(context, "Product not found "); + } else { + minteger = 0; + multiPurposeDialog.cancel(); + + // get selected radio button from radioGroup + object = new InvoiceGetterSetter(); + object.setCustomer_name(consumer_name); + object.setConsumer_return_bill_no(bill_no); + object.setMobile_no(mobile_no); + object.setProduct_rate(product_mrp); + object.setProduct(product_name); + object.setProduct_Id(product_Id); + object.setScan_ean_code_or_enterd_ean_code(product_scan_code); + object.setQuantity(stock_text_value.getText().toString()); + replace_productList.add(object); + txt_product_mrp.setText("Current Total Rs. : " + calculate_total_consume(replace_productList)); + + stock_text_value.setText(""); + qrcode_text.setText(""); + edt_scan_code.setText(""); + product_scan_code = ""; + product_name = ""; + product_mrp = ""; + product_Id = "0"; + sku_name.setText(""); + sku_name.setVisibility(View.GONE); + drawer_layout_recycle_store.setAdapter(new ValueAdapter(context, replace_productList)); + drawer_layout_recycle_store.setLayoutManager(new LinearLayoutManager(context)); + } + } else { + multiPurposeDialog.cancel(); + minteger = 0; + // get selected radio button from radioGroup + object = new InvoiceGetterSetter(); + object.setCustomer_name(consumer_name); + object.setConsumer_return_bill_no(bill_no); + object.setMobile_no(mobile_no); + object.setProduct_rate(product_mrp); + object.setProduct(product_name); + object.setProduct_Id(product_Id); + object.setScan_ean_code_or_enterd_ean_code(product_scan_code); + object.setQuantity(stock_text_value.getText().toString()); + replace_productList.add(object); + txt_product_mrp.setText("Current Total Rs. : " + calculate_total_consume(replace_productList)); + sku_name.setText(""); + stock_text_value.setText(""); + qrcode_text.setText(""); + product_scan_code = ""; + product_name = ""; + product_mrp = ""; + product_Id = "0"; + sku_name.setVisibility(View.GONE); + drawer_layout_recycle_store.setAdapter(new ValueAdapter(context, replace_productList)); + drawer_layout_recycle_store.setLayoutManager(new LinearLayoutManager(context)); + } + } + } + } + }); + + img_bar_code.setOnClickListener(v -> openScanner()); + multiPurposeDialog.show(); + } + + public class MultiPurposeDialog extends Dialog { + public MultiPurposeDialog(Context context) { + super(context); + // DIALOG USER_INTERFACE TEMPLATE + WindowManager.LayoutParams wmLayoutParams = Objects.requireNonNull(getWindow()).getAttributes(); + wmLayoutParams.gravity = Gravity.CENTER; + getWindow().setAttributes(wmLayoutParams); + setTitle(null); + setCancelable(false); + setOnCancelListener(null); + LinearLayout layout = new LinearLayout(context); + layout.setOrientation(LinearLayout.VERTICAL); + } + } + + private int calculate_total_consume(ArrayList invoice_List) { + int total_INR_value = 0; + if (!invoice_List.isEmpty()) { + for (int k = 0; k < invoice_List.size(); k++) { + int quantity = Integer.parseInt(invoice_List.get(k).getQuantity()); + int amount = Integer.parseInt((invoice_List.get(k).getProduct_rate())); + amount = amount * quantity; + invoice_List.get(k).setTotal_amount("" + amount); + total_INR_value = total_INR_value + Integer.parseInt(invoice_List.get(k).getTotal_amount()); + + } + } + + return total_INR_value; + } + + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data); + if (result != null) { + if (result.getContents() == null) { + //test("ScanActivity", "Cancelled scan"); + Toast.makeText(this, "Cancelled", Toast.LENGTH_SHORT).show(); + } else { + + db.open(); + ArrayList productList = db.getsku_fromproductusing_eancode(result.getContents(), true, visit_date, counterID, null); + + if (productList.isEmpty()) { + db.open(); + productList = db.getsku_fromproductusing_eancode(removeFirstChar(result.getContents()), true, visit_date, counterID, null); + } + + if (!productList.isEmpty()) { + show_dialog_forsku(context, productList, rl_actual_qty, actual_qty_dialog); + sku_name.setText(productList.get(0).getProductName()); + sku_name.setVisibility(View.VISIBLE); + stock_text_value.setText("0"); + minteger = 0; + } else { + minteger = 0; + product_name = ""; + product_scan_code = ""; + qrcode_text.setText(""); + AlertandMessages.showToastMsg(context, "Unable To Scan Correct Data. Please Try Again."); + } + } + + } else + super.onActivityResult(requestCode, resultCode, data); + } + + private void openScanner() { + IntentIntegrator intentIntegrator = new IntentIntegrator((Activity) context); + intentIntegrator.setBeepEnabled(true); + intentIntegrator.setOrientationLocked(false); + intentIntegrator.setPrompt("Scan the barcode or QR code to get the data"); + intentIntegrator.initiateScan(); + } + + @SuppressLint("SetTextI18n") + private void show_dialog_forsku_categorywise(final Context context) { + minteger = 0; + multiPurposeDialog = new MultiPurposeDialog(context); + multiPurposeDialog.requestWindowFeature(Window.FEATURE_NO_TITLE); + multiPurposeDialog.setContentView(R.layout.custom_sku_list_with_category); + final WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); + lp.copyFrom(multiPurposeDialog.getWindow().getAttributes()); + lp.width = WindowManager.LayoutParams.MATCH_PARENT; + lp.height = WindowManager.LayoutParams.WRAP_CONTENT; + lp.gravity = Gravity.CENTER; + multiPurposeDialog.getWindow().setAttributes(lp); + multiPurposeDialog.setCancelable(false); + + final Spinner dialog_brand_spin = (Spinner) multiPurposeDialog.findViewById(R.id.dialog_brand_spin); + final Spinner dialog_subbrand_spin = (Spinner) multiPurposeDialog.findViewById(R.id.dialog_subbrand_spin); + final Spinner dialog_reference_spin = (Spinner) multiPurposeDialog.findViewById(R.id.dialog_reference_spin); + final Spinner dialog_product_spin = (Spinner) multiPurposeDialog.findViewById(R.id.dialog_product_spin); + final EditText et_search = (EditText) multiPurposeDialog.findViewById(R.id.et_search); + final TextView stock_text_value = (TextView) multiPurposeDialog.findViewById(R.id.stock_text_value); + + final Button stock_img_minus = (Button) multiPurposeDialog.findViewById(R.id.stock_img_minus); + Button stock_img_plus = (Button) multiPurposeDialog.findViewById(R.id.stock_img_plus); + + ImageView cancet_btn = (ImageView) multiPurposeDialog.findViewById(R.id.cancet_btn); + final ImageView btn_add = (ImageView) multiPurposeDialog.findViewById(R.id.btn_add); +//for actual Quantity form Tstock_Summery + rl_actual_qty = (LinearLayout) multiPurposeDialog.findViewById(R.id.rl_actual_qty); + actual_qty_dialog = (TextView) multiPurposeDialog.findViewById(R.id.actual_qty_dialog); + TextView txt_current_invoice_type = (TextView) multiPurposeDialog.findViewById(R.id.txt_current_invoice_type); + + et_search.addTextChangedListener(new TextWatcher() { + @Override + public void beforeTextChanged(CharSequence s, int start, int count, int after) { + + } + + @Override + public void onTextChanged(CharSequence s, int start, int before, int count) { + String text = s.toString(); + setSearchFilter(dialog_product_list, text, dialog_product_spin); + } + + @Override + public void afterTextChanged(Editable s) { + String text = s.toString(); + } + }); + + + db.open(); + validate_spin_ui_data(dialog_brand_spin, dialog_subbrand_spin, dialog_reference_spin, dialog_product_spin, + db.getproductdata_dialog("BrandName", "BrandId", false, "", visit_date, counterID, null), + db.getproductdata_dialog("SubBrandName", "SubBrandId", false, "", visit_date, counterID, null), + db.getproductdata_dialog("ReferenceName", "ReferenceId", false, "", visit_date, counterID, null), + db.getbrand_wise_sku_fromproduct(null, null, visit_date, counterID, null), stock_text_value, actual_qty_dialog, txt_current_invoice_type); + + + cancet_btn.setOnClickListener(v -> multiPurposeDialog.dismiss()); + + + stock_img_minus.setOnClickListener(v -> { + if (minteger == 0) { + AlertandMessages.showToastMsg(context, "Product quantity should not be less than Zero"); + } else { + minteger = minteger - 1; + stock_text_value.setText("" + minteger); + } + }); + + + stock_img_plus.setOnClickListener(v -> { + if (!product_Id.equals("0")) { + db.open(); + if (!product_Id.equals("0")) { + rl_actual_qty.setVisibility(View.VISIBLE); + db.open(); + if (db.getActualSaleableStock(product_Id, "SaleableBalance", visit_date, counterID, null).getStock() == 0) { + AlertandMessages.showToastMsg(context, "Stock for this Product is Zero. Cannot allow to add this Product"); + } else { + minteger = minteger + 1; + db.open(); + if (db.getActualSaleableStock(product_Id, "SaleableBalance", visit_date, counterID, null).getStock() != 0 && minteger > db.getActualSaleableStock(product_Id, "SaleableBalance", visit_date, counterID, null).getStock()) { + minteger = minteger - 1; + AlertandMessages.showToastMsg(context, "Stock Low. Please reduce sale quantity below or equal to the stock value"); + } else { + int val = (calculate_total() + (minteger * (Integer.parseInt(product_mrp)))); + stock_text_value.setText("" + minteger); + } + } + } + } + }); + + + btn_add.setOnClickListener(new View.OnClickListener() { + @SuppressLint("SetTextI18n") + @Override + public void onClick(View v) { + ((ConsumerReturnReplaceProductActivity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); + if (dialog_product_spin.getSelectedItemId() == 0) { + AlertandMessages.showToastMsg(context, "Please Select Product"); + } else if (stock_text_value.getText().toString().equals("0")) { + AlertandMessages.showToastMsg(context, "Please add atleast One Product Quantity "); + } else { + // get selected radio button from radioGroup + object = new InvoiceGetterSetter(); + object.setCustomer_name(consumer_name); + object.setConsumer_return_bill_no(bill_no); + object.setMobile_no(mobile_no); + object.setProduct_rate(product_mrp); + object.setProduct(product_name); + object.setProduct_Id(product_Id); + object.setScan_ean_code_or_enterd_ean_code(product_scan_code); + object.setQuantity(stock_text_value.getText().toString()); + replace_productList.add(object); + txt_product_mrp.setText("Current Total Rs. : " + calculate_total_consume(replace_productList)); + minteger = 0; + stock_text_value.setText("0"); + product_scan_code = ""; + dialog_brand_Id = ""; + dialog_sub_brand_Id = ""; + dialog_reference_Id = ""; + product_name = ""; + product_Id = "0"; + drawer_layout_recycle_store.setAdapter(new ValueAdapter(context, replace_productList)); + drawer_layout_recycle_store.setLayoutManager(new LinearLayoutManager(context)); + multiPurposeDialog.dismiss(); + + } + } + }); + + multiPurposeDialog.show(); + } + + + public void setSearchFilter(ArrayList originalList, String text, Spinner dialog_product_spin) { + flag_filter_by_edt = true; + dialog_sku_adapter = new ArrayAdapter<>(context, R.layout.spinner_custom_item); + dialog_sku_adapter.add("- Select Product -"); + dialog_product_using_searchlist = new ArrayList<>(); + dialog_product_using_searchlist = filterListForProduct_edt(originalList, text); + + if (filterListForProduct_edt(originalList, text).isEmpty()) { + dialog_product_using_searchlist = originalList; + } + + for (int i = 0; i < dialog_product_using_searchlist.size(); i++) { + dialog_sku_adapter.add(dialog_product_using_searchlist.get(i).getProductName() + " - (MRP-" + dialog_product_using_searchlist.get(i).getMrp().toString() + ")"); + } + dialog_product_spin.setAdapter(dialog_sku_adapter); + dialog_sku_adapter.setDropDownViewResource(R.layout.spinner_custom_item); + + dialog_product_spin.invalidate(); + } + + + public ArrayList filterListForProduct_edt(List originalList, String text) { + ArrayList filterList = new ArrayList<>(); + for (ProductMaster object : originalList) { + if (object.getProductName().toLowerCase().contains(text.toLowerCase())) { + filterList.add(object); + } else { + continue; + } + } + + return filterList; + } + + private void + validate_spin_ui_data(final Spinner dialog_brand_spin, final Spinner dialog_sub_brand_spin, + final Spinner dialog_franchise_spin, final Spinner dialog_product_spin, final ArrayList brandList, final ArrayList subbrandList, + final ArrayList referenceList, + final ArrayList productList, final TextView stock_text_value, final TextView actual_qty_dialog, final TextView txt_current_invoice_type) { + + dialog_brand_adapter = new ArrayAdapter<>(this, R.layout.spinner_custom_item); + dialog_brand_adapter.add("- Select Brand -"); + + for (int i = 0; i < brandList.size(); i++) { + dialog_brand_adapter.add(brandList.get(i).getBrandName()); + } + + dialog_brand_spin.setAdapter(dialog_brand_adapter); + + dialog_brand_adapter.setDropDownViewResource(R.layout.spinner_custom_item); + + setSubBrandSpinnerData(subbrandList, dialog_sub_brand_spin); + + setReferenceSpinnerData(referenceList, dialog_franchise_spin); + + setProductSpinnerData(productList, dialog_product_spin); + + dialog_brand_spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { + @Override + public void onItemSelected(AdapterView adapterView, View view, int pos, long l) { + if (pos != 0) { + flag_for_filter = true; + flag_filter_by_edt = false; + dialog_brand_Id = adapterView.getSelectedItem().toString(); + setFilter(FILTER_FOR_BRAND, dialog_product_spin); + + setSubBrandSpinnerData(db.getsub_brand_using_brand_Id(dialog_brand_Id, "SubBrandName", "SubBrandId", "BrandName", null, visit_date, counterID, true, null), dialog_sub_brand_spin); + setReferenceSpinnerData(db.getsub_brand_using_brand_Id(dialog_brand_Id, "ReferenceName", "ReferenceId", "BrandName", null, visit_date, counterID, true, null), dialog_franchise_spin); + } else { + dialog_brand_Id = ""; + if (dialog_brand_spin.getSelectedItemPosition() != 0 || dialog_sub_brand_spin.getSelectedItemPosition() != 0 || + dialog_franchise_spin.getSelectedItemPosition() != 0) { + flag_for_filter = true; + } else { + setFilter(CLEAR_FILTER, dialog_product_spin); + flag_for_filter = false; + } + } + } + + + @Override + public void onNothingSelected(AdapterView adapterView) { + + } + }); + + dialog_sub_brand_spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { + @Override + public void onItemSelected(AdapterView adapterView, View view, int pos, long l) { + if (pos != 0) { + flag_for_filter = true; + flag_filter_by_edt = false; + dialog_sub_brand_Id = adapterView.getSelectedItem().toString(); + setFilter(FILTER_FOR_SUB_BRAND, dialog_product_spin); + setReferenceSpinnerData(db.getsub_brand_using_brand_Id(dialog_sub_brand_Id, "ReferenceName", "ReferenceId", "SubBrandName", null, visit_date, counterID, true, null), dialog_franchise_spin); + } else { + dialog_sub_brand_Id = ""; + if (dialog_brand_spin.getSelectedItemPosition() != 0 || dialog_sub_brand_spin.getSelectedItemPosition() != 0 || + dialog_franchise_spin.getSelectedItemPosition() != 0) { + flag_for_filter = true; + } else { + setFilter(CLEAR_FILTER, dialog_product_spin); + flag_for_filter = false; + } + } + } + + @Override + public void onNothingSelected(AdapterView adapterView) { + + } + }); + + dialog_franchise_spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { + @Override + public void onItemSelected(AdapterView adapterView, View view, int pos, long l) { + if (pos != 0) { + flag_for_filter = true; + flag_filter_by_edt = false; + dialog_reference_Id = adapterView.getSelectedItem().toString(); + setFilter(FILTER_FOR_REFERENCE_NAME, dialog_product_spin); + + } else { + dialog_reference_Id = ""; + if (dialog_brand_spin.getSelectedItemPosition() != 0 || dialog_sub_brand_spin.getSelectedItemPosition() != 0 || + dialog_franchise_spin.getSelectedItemPosition() != 0) { + flag_for_filter = true; + } else { + setFilter(CLEAR_FILTER, dialog_product_spin); + flag_for_filter = false; + } + } + } + + @Override + public void onNothingSelected(AdapterView adapterView) { + + } + }); + + + dialog_product_spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { + @SuppressLint("SetTextI18n") + @Override + public void onItemSelected(AdapterView parent, View view, int position, long id) { + if (position != 0) { + if (flag_filter_by_edt) { + product_name = dialog_product_using_searchlist.get(position - 1).getProductName(); + product_Id = dialog_product_using_searchlist.get(position - 1).getProductId().toString(); + product_mrp = dialog_product_using_searchlist.get(position - 1).getMrp().toString(); + product_scan_code = dialog_product_using_searchlist.get(position - 1).getEanCode(); + stock_text_value.setText("0"); + + stock_text_value.setText("0"); + if (!product_Id.equals("0")) { + rl_actual_qty.setVisibility(View.VISIBLE); + db.open(); + txt_current_invoice_type.setText(R.string.current_stock_saleable); + actual_qty_dialog.setText("" + db.getActualSaleableStock(product_Id, "SaleableBalance", visit_date, counterID, null).getStock()); + } + + minteger = 0; + } else if (flag_for_filter) { + product_name = filterListForReferencename(dialog_product_list, dialog_reference_Id, dialog_brand_Id, dialog_sub_brand_Id).get(position - 1).getProductName(); + product_Id = filterListForReferencename(dialog_product_list, dialog_reference_Id, dialog_brand_Id, dialog_sub_brand_Id).get(position - 1).getProductId().toString(); + product_mrp = filterListForReferencename(dialog_product_list, dialog_reference_Id, dialog_brand_Id, dialog_sub_brand_Id).get(position - 1).getMrp().toString(); + product_scan_code = filterListForReferencename(dialog_product_list, dialog_reference_Id, dialog_brand_Id, dialog_sub_brand_Id).get(position - 1).getEanCode(); + stock_text_value.setText("0"); + if (!product_Id.equals("0")) { + rl_actual_qty.setVisibility(View.VISIBLE); + db.open(); + txt_current_invoice_type.setText(R.string.current_stock_saleable); + actual_qty_dialog.setText("" + db.getActualSaleableStock(product_Id, "SaleableBalance", visit_date, counterID, null).getStock()); + } + minteger = 0; + } else { + product_name = productList.get(position - 1).getProductName(); + product_Id = productList.get(position - 1).getProductId().toString(); + product_mrp = productList.get(position - 1).getMrp().toString(); + product_scan_code = productList.get(position - 1).getEanCode(); + stock_text_value.setText("0"); + if (!product_Id.equals("0")) { + rl_actual_qty.setVisibility(View.VISIBLE); + db.open(); + txt_current_invoice_type.setText(R.string.current_stock_saleable); + actual_qty_dialog.setText("" + db.getActualSaleableStock(product_Id, "SaleableBalance", visit_date, counterID, null).getStock()); + } + minteger = 0; + } + + } else { + stock_text_value.setText("0"); + product_scan_code = ""; + product_mrp = "0"; + product_name = ""; + product_Id = "0"; + minteger = 0; + } + } + + @Override + public void onNothingSelected(AdapterView parent) { + + } + }); + + } + + + private void setSubBrandSpinnerData(ArrayList axeList, Spinner dialog_sub_brand_spin) { + dialog_sub_brand_adapter = new ArrayAdapter<>(this, R.layout.spinner_custom_item); + dialog_sub_brand_adapter.add("- Select Sub Brand -"); + + for (int i = 0; i < axeList.size(); i++) { + dialog_sub_brand_adapter.add(axeList.get(i).getBrandName()); + } + + dialog_sub_brand_spin.setAdapter(dialog_sub_brand_adapter); + dialog_sub_brand_adapter.setDropDownViewResource(R.layout.spinner_custom_item); + + } + + + private void setReferenceSpinnerData(ArrayList referenceList, Spinner dialog_franchise_spin) { + dialog_frenchise_adapter = new ArrayAdapter<>(this, R.layout.spinner_custom_item); + dialog_frenchise_adapter.add("- Select Franchise -"); + + for (int i = 0; i < referenceList.size(); i++) { + dialog_frenchise_adapter.add(referenceList.get(i).getBrandName()); + } + + dialog_franchise_spin.setAdapter(dialog_frenchise_adapter); + dialog_frenchise_adapter.setDropDownViewResource(R.layout.spinner_custom_item); + } + + private void setProductSpinnerData(ArrayList productList, Spinner dialog_product_spin) { + dialog_sku_adapter = new ArrayAdapter<>(this, R.layout.spinner_custom_item); + dialog_sku_adapter.add("- Select Product -"); + + for (int i = 0; i < productList.size(); i++) { + dialog_sku_adapter.add(productList.get(i).getProductName() + " - (MRP-" + productList.get(i).getMrp().toString() + ")"); + } + + dialog_product_spin.setAdapter(dialog_sku_adapter); + dialog_sku_adapter.setDropDownViewResource(R.layout.spinner_custom_item); + } + + + public void setFilter(int filterType, Spinner dialog_spin) { + if (filterType == FILTER_FOR_BRAND) { + dialog_sku_adapter = new ArrayAdapter<>(context, R.layout.spinner_custom_item); + dialog_sku_adapter.add("- Select Product -"); + + for (int i = 0; i < filterListForBrand(dialog_product_list, dialog_brand_Id).size(); i++) { + dialog_sku_adapter.add(filterListForBrand(dialog_product_list, dialog_brand_Id).get(i).getProductName() + " - (MRP-" + filterListForBrand(dialog_product_list, dialog_brand_Id).get(i).getMrp().toString() + ")"); + } + + dialog_spin.setAdapter(dialog_sku_adapter); + dialog_sku_adapter.setDropDownViewResource(R.layout.spinner_custom_item); + + } else if (filterType == FILTER_FOR_SUB_BRAND) { + dialog_sku_adapter = new ArrayAdapter<>(context, R.layout.spinner_custom_item); + dialog_sku_adapter.add("- Select Product -"); + + for (int i = 0; i < filterListForSubBrand(dialog_product_list, dialog_sub_brand_Id, dialog_brand_Id).size(); i++) { + dialog_sku_adapter.add(filterListForSubBrand(dialog_product_list, dialog_sub_brand_Id, dialog_brand_Id).get(i).getProductName() + " - (MRP-" + + filterListForSubBrand(dialog_product_list, dialog_sub_brand_Id, dialog_brand_Id).get(i).getMrp().toString() + ")"); + } + dialog_spin.setAdapter(dialog_sku_adapter); + dialog_sku_adapter.setDropDownViewResource(R.layout.spinner_custom_item); + } else if (filterType == FILTER_FOR_REFERENCE_NAME) { + + dialog_sku_adapter = new ArrayAdapter<>(context, R.layout.spinner_custom_item); + dialog_sku_adapter.add("- Select Product -"); + + for (int i = 0; i < filterListForReferencename(dialog_product_list, dialog_reference_Id, dialog_brand_Id, dialog_sub_brand_Id).size(); i++) { + dialog_sku_adapter.add(filterListForReferencename(dialog_product_list, dialog_reference_Id, dialog_brand_Id, dialog_sub_brand_Id).get(i).getProductName() + + " - (MRP-" + filterListForReferencename(dialog_product_list, dialog_reference_Id, dialog_brand_Id, dialog_sub_brand_Id).get(i).getMrp().toString() + ")"); + } + + dialog_spin.setAdapter(dialog_sku_adapter); + dialog_sku_adapter.setDropDownViewResource(R.layout.spinner_custom_item); + + } else { + dialog_sku_adapter = new ArrayAdapter<>(context, R.layout.spinner_custom_item); + dialog_sku_adapter.add("- Select Product -"); + + for (int i = 0; i < dialog_product_list.size(); i++) { + dialog_sku_adapter.add(dialog_product_list.get(i).getProductName() + " - (MRP-" + dialog_product_list.get(i).getMrp().toString() + ")"); + } + + dialog_spin.setAdapter(dialog_sku_adapter); + dialog_sku_adapter.setDropDownViewResource(R.layout.spinner_custom_item); + } + + dialog_spin.invalidate(); + } + + final int CLEAR_FILTER = 0; + final int FILTER_FOR_BRAND = 1; + final int FILTER_FOR_SUB_BRAND = 2; + final int FILTER_FOR_REFERENCE_NAME = 3; + + public ArrayList filterListForBrand(List originalList, String text) { + ArrayList filterList = new ArrayList<>(); + for (ProductMaster object : originalList) { + if (object.getBrandName().equalsIgnoreCase(text)) { + filterList.add(object); + } else { + continue; + } + } + return filterList; + } + + public ArrayList filterListForSubBrand(List originalList, String sub_brand_name_id, String brand_Id) { + ArrayList filterList = new ArrayList<>(); + for (ProductMaster object : originalList) { + if (sub_brand_name_id.isEmpty() && object.getBrandName().equalsIgnoreCase(brand_Id)) { + filterList.add(object); + } else if (object.getSubBrandName().equalsIgnoreCase(sub_brand_name_id) && (brand_Id.isEmpty() || object.getBrandName().equalsIgnoreCase(brand_Id))) { + filterList.add(object); + } else { + continue; + } + } + + return filterList; + } + + + public ArrayList filterListForReferencename(List originalList, String franchise_Id, String brandName_Id, String sub_brand_name_Id) { + ArrayList filterList = new ArrayList<>(); + for (ProductMaster object : originalList) { + if (sub_brand_name_Id.isEmpty() && object.getBrandName().equalsIgnoreCase(brandName_Id)) { + filterList.add(object); + } else if (franchise_Id.isEmpty() && object.getSubBrandName().equalsIgnoreCase(sub_brand_name_Id)) { + filterList.add(object); + } else if (object.getReferenceName().equalsIgnoreCase(franchise_Id) && (brandName_Id.isEmpty() || object.getBrandName().equalsIgnoreCase(brandName_Id)) && (sub_brand_name_Id.isEmpty() || object.getSubBrandName().equalsIgnoreCase(sub_brand_name_Id))) { + filterList.add(object); + } else { + continue; + } + } + + return filterList; + } + + private class ValueAdapter extends RecyclerView.Adapter { + LayoutInflater inflator; + List data; + + + public ValueAdapter(Context context, List data) { + inflator = LayoutInflater.from(context); + this.data = data; + } + + @NonNull + @Override + public ValueAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) { + View view = inflator.inflate(R.layout.row_adapter_return_consumer, parent, false); + return new ValueAdapter.MyViewHolder(view); + } + + @SuppressLint("SetTextI18n") + @Override + public void onBindViewHolder(final ValueAdapter.MyViewHolder holder, @SuppressLint("RecyclerView") final int position) { + final InvoiceGetterSetter current = data.get(position); + + holder.select_promo_productRl.setVisibility(View.GONE); + holder.select_promo_productRl.setId(position); + + holder.select_productRl.setVisibility(View.VISIBLE); + holder.select_productRl.setId(position); + + if (current.getDiscount() == 0.0 || current.getDiscount() == 0) { + holder.text_item.setText(current.getProduct()); + holder.text_item.setId(position); + } else { + String string = current.getDiscount().toString(); + //test("last character: " + string.substring(string.length() - 1)); + holder.text_item.setText(current.getProduct() + " Discount : " + string.substring(string.length() - 1) + "0%"); + holder.text_item.setId(position); + } + + holder.text_qty.setText(current.getQuantity()); + holder.text_qty.setId(position); + + holder.text_actualqty.setText(current.getActualQty()); + holder.text_actualqty.setId(position); + + holder.txt_amount.setText(current.getProduct_rate()); + holder.txt_amount.setId(position); + + holder.delete_added_product.setOnClickListener(v -> { + @SuppressLint("NotifyDataSetChanged") AlertDialog.Builder builder = new AlertDialog.Builder(context).setMessage("Are you sure you want to Delete ?").setTitle(getString(R.string.password_rules)).setCancelable(false) + .setPositiveButton("Yes", + (dialog, id) -> { + data.remove(position); + notifyDataSetChanged(); + if (!data.isEmpty()) { + ValueAdapter adapter = new ValueAdapter(context, data); + drawer_layout_recycle_store.setAdapter(adapter); + adapter.notifyDataSetChanged(); + } + + txt_product_mrp.setText("Current Total Rs. : " + calculate_total_consume(replace_productList)); + notifyDataSetChanged(); + }) + .setNegativeButton("No", + (dialog, id) -> dialog.cancel()); + AlertDialog alert = builder.create(); + alert.show(); + }); + + } + + @Override + public int getItemCount() { + return data.size(); + } + + class MyViewHolder extends RecyclerView.ViewHolder { + LinearLayout select_productRl, select_promo_productRl; + TextView text_item, text_qty, txt_amount, text_actualqty; + ImageView delete_added_product; + + public MyViewHolder(View itemView) { + super(itemView); + text_item = (TextView) itemView.findViewById(R.id.text_item); + text_qty = (TextView) itemView.findViewById(R.id.text_qty); + txt_amount = (TextView) itemView.findViewById(R.id.txt_amount); + text_actualqty = (TextView) itemView.findViewById(R.id.text_actualqty); + delete_added_product = (ImageView) itemView.findViewById(R.id.delete_added_product); + select_promo_productRl = (LinearLayout) itemView.findViewById(R.id.select_promo_productRl); + select_productRl = (LinearLayout) itemView.findViewById(R.id.select_productRl); + } + } + } + + ////sku scannnnnnnnnnnn + private void show_dialog_forsku(final Context context, ArrayList skuList_with_eancode, + LinearLayout rl_actual_qty, TextView actual_qty_dialog) { + multiPurposeDialog = new MultiPurposeDialog(context); + multiPurposeDialog.requestWindowFeature(Window.FEATURE_NO_TITLE); + multiPurposeDialog.setContentView(R.layout.custom_sku_adapter); + final WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); + lp.copyFrom(Objects.requireNonNull(multiPurposeDialog.getWindow()).getAttributes()); + lp.width = WindowManager.LayoutParams.MATCH_PARENT; + lp.height = WindowManager.LayoutParams.WRAP_CONTENT; + lp.gravity = Gravity.CENTER; + multiPurposeDialog.getWindow().setAttributes(lp); + multiPurposeDialog.setCancelable(false); + TextView sale_trcking_name = (TextView) multiPurposeDialog.findViewById(R.id.sale_trcking_name); + sale_trcking_name.setText(skuList_with_eancode.get(0).getProductName()); + RecyclerView recycl_sku = (RecyclerView) multiPurposeDialog.findViewById(R.id.recycl_sku); + + recycl_sku.setAdapter(new AdapterforSku(context, skuList_with_eancode, multiPurposeDialog, "0", rl_actual_qty, actual_qty_dialog)); + recycl_sku.setLayoutManager(new LinearLayoutManager(context)); + ImageView dismiss_dialog = (ImageView) multiPurposeDialog.findViewById(R.id.dismiss_dialog); + dismiss_dialog.setOnClickListener(v -> multiPurposeDialog.dismiss()); + + multiPurposeDialog.show(); + } + + + private class AdapterforSku extends RecyclerView.Adapter { + LayoutInflater inflator; + List data; + String show_dialog; + MultiPurposeDialog multiPurposeDialog; + LinearLayout rl_actual_qty; + TextView actual_qty_dialog; + + public AdapterforSku(Context context, List data, MultiPurposeDialog multiPurposeDialog, String show_dialog + , LinearLayout rl_actual_qty, TextView actual_qty_dialog) { + inflator = LayoutInflater.from(context); + this.data = data; + this.show_dialog = show_dialog; + this.multiPurposeDialog = multiPurposeDialog; + + this.actual_qty_dialog = actual_qty_dialog; + this.rl_actual_qty = rl_actual_qty; + } + + @Override + public AdapterforSku.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) { + View view = inflator.inflate(R.layout.adapter_custom, parent, false); + return new AdapterforSku.MyViewHolder(view); + } + + + @SuppressLint("SetTextI18n") + @Override + public void onBindViewHolder(@NonNull final AdapterforSku.MyViewHolder holder, final int position) { + final ProductMaster current = data.get(position); + if (show_dialog.equals("1")) { + holder.sale_card.setVisibility(View.VISIBLE); + holder.sale_card.setId(position); + holder.sale_trcking_name.setText("Date : " + current.getVisit_date()); + holder.sale_trcking_name.setId(position); + holder.consumer_recycle.setVisibility(View.VISIBLE); + holder.consumer_recycle.setId(position); + + } else { + holder.sale_card.setVisibility(View.VISIBLE); + holder.sale_card.setId(position); + holder.sale_trcking_name.setText("(MRP - " + current.getMrp().toString() + ")"); + holder.sale_trcking_name.setId(position); + + holder.consumer_recycle.setVisibility(View.GONE); + holder.consumer_recycle.setId(position); + + holder.sale_card.setOnClickListener(new View.OnClickListener() { + @SuppressLint("SetTextI18n") + @Override + public void onClick(View v) { + qrcode_text.setVisibility(View.VISIBLE); + qrcode_text.setText(current.getEanCode()); + product_name = current.getProductName(); + product_Id = current.getProductId().toString(); + product_scan_code = current.getEanCode(); + product_mrp = current.getMrp().toString(); + sku_name.setText(product_name + " Mrp - " + product_mrp); + sku_name.setVisibility(View.VISIBLE); + multiPurposeDialog.dismiss(); + if (!product_Id.equals("0")) { + db.open(); + actual_qty_dialog.setText("" + db.getActualSaleableStock(product_Id, null, visit_date, counterID, null).getStock()); + rl_actual_qty.setVisibility(View.VISIBLE); + } + + } + }); + } + } + + + @Override + public int getItemCount() { + return data.size(); + } + + class MyViewHolder extends RecyclerView.ViewHolder { + TextView sale_trcking_name; + CardView sale_card; + RecyclerView consumer_recycle; + + + public MyViewHolder(View itemView) { + super(itemView); + sale_card = (CardView) itemView.findViewById(R.id.sale_card); + sale_trcking_name = (TextView) itemView.findViewById(R.id.sale_trcking_name); + ////for consumer product + consumer_recycle = (RecyclerView) itemView.findViewById(R.id.consumer_recycle); + } + } + } + + private boolean checkduplicate_entry() { + boolean status = true; + if (replace_productList != null && !replace_productList.isEmpty()) { + for (int k = 0; k < replace_productList.size(); k++) { + if (replace_productList.get(k).getProduct_Id().equals(product_Id) && replace_productList.get(k).getProduct_rate().equals(product_mrp)) { + AlertandMessages.showToastMsg(context, "This product already added "); + status = false; + break; + } + } + } + return status; + } + + private int calculate_total() { + current_total = 0; + if (!replace_productList.isEmpty()) { + for (int k = 0; k < replace_productList.size(); k++) { + current_total = current_total + (Integer.parseInt(replace_productList.get(k).getQuantity()) * Integer.parseInt(replace_productList.get(k).getProduct_rate())); + } + } + + return current_total; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/consumeractivity/ConsumerReturnsHistoryActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/consumeractivity/ConsumerReturnsHistoryActivity.java new file mode 100644 index 0000000..d2118ab --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/consumeractivity/ConsumerReturnsHistoryActivity.java @@ -0,0 +1,248 @@ +package com.cpm.lorealbaautomation.consumeractivity; + +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; + +import androidx.appcompat.app.AppCompatActivity; + +import android.os.Bundle; + +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; +import androidx.appcompat.widget.Toolbar; + +import android.view.LayoutInflater; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; +import android.widget.ImageView; +import android.widget.LinearLayout; +import android.widget.TextView; + +import com.google.firebase.crashlytics.FirebaseCrashlytics; +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.constant.CommonFunctions; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.gsonGetterSetter.InvoiceGetterSetter; +import com.cpm.lorealbaautomation.printer.PrinterActivity; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class ConsumerReturnsHistoryActivity extends AppCompatActivity { + public ArrayList headerList = new ArrayList<>(); + String counter_Id, visit_date, username; + private SharedPreferences preferences; + private SharedPreferences.Editor editor = null; + RecyclerView recycl_history; + Lorealba_Database db; + Context context; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_consumer_returns_history); + context = this; + db = new Lorealba_Database(context); + db.open(); + Toolbar toolbar = findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + getSupportActionBar().setHomeButtonEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + if (!CommonFunctions.isTablet(context)) { + toolbar.setTitleTextAppearance(context, R.style.changestext_sizefor_mobile); + } + + iduserinterface(); + + } + + private void iduserinterface() { + preferences = PrefHelper.getPrefs(context); + editor = preferences.edit(); + counter_Id = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + username = preferences.getString(CommonString.KEY_USERNAME, ""); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + recycl_history = (RecyclerView) findViewById(R.id.recycl_history); + db = new Lorealba_Database(context); + db.open(); + + setTitle("Returns History - " + username); + + setDataToListView(); + } + + + public void setDataToListView() { + try { + db.open(); + headerList = db.getsaleReturnHeaderData(visit_date, counter_Id, username, false, false, null); + if (headerList.size() > 0) { + Collections.reverse(headerList); + recycl_history.setAdapter(new ValueAdapter(context, headerList)); + recycl_history.setLayoutManager(new LinearLayoutManager(context)); + } + + } catch (Exception e) { + FirebaseCrashlytics.getInstance().recordException(e); + //test("Exception when fetching", e.toString()); + } + } + + public class ValueAdapter extends RecyclerView.Adapter { + private LayoutInflater inflator; + List data; + + + public ValueAdapter(Context context, List data) { + inflator = LayoutInflater.from(context); + this.data = data; + } + + @Override + public ValueAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int i) { + View view = inflator.inflate(R.layout.row_returns_history, parent, false); + return new ValueAdapter.MyViewHolder(view); + } + + @Override + public void onBindViewHolder(final ValueAdapter.MyViewHolder holder, final int position) { + final InvoiceGetterSetter current = data.get(position); + + holder.txt_name_with_mobile.setText("Consumer Name : " + current.getCustomer_name() + " Mobile No. : " + current.getMobile_no()); + holder.txt_name_with_mobile.setId(position); + + + holder.text_bill_no.setText("Bill No. : " + current.getConsumer_return_bill_no()); + holder.text_bill_no.setId(position); + db.open(); + ////////////////////get return list from db user and bill wise + holder.return_productList = db.getsalesReturnChildData(current.getReccept_count(), visit_date, counter_Id, username, false); + ////////////////////get replace product list from db user and bill wise + db.open(); + holder.replace_productList = db.getsalesReturnReplaceProduct(current.getReccept_count(), visit_date, counter_Id, username, false); + + if (holder.return_productList.size() > 0) { + holder.sku_list_returns.setAdapter(new ReturnsSkuAdapter(context, holder.return_productList)); + holder.sku_list_returns.setLayoutManager(new LinearLayoutManager(context)); + } + + + if (holder.replace_productList.size() > 0) { + holder.sku_list_replace_product.setAdapter(new ReturnsSkuAdapter(context, holder.replace_productList)); + holder.sku_list_replace_product.setLayoutManager(new LinearLayoutManager(context)); + holder.rl_replace_product.setVisibility(View.VISIBLE); + holder.rl_replace_product.setId(position); + } else { + holder.rl_replace_product.setVisibility(View.GONE); + holder.rl_replace_product.setId(position); + } + + + holder.img_printer.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + startActivity(new Intent(context, PrinterActivity.class).putExtra(CommonString.TAG_OBJECT, holder.return_productList).putExtra(CommonString.TAG_HEADER_OBJECT, current).putExtra(CommonString.TAG_FOR_RETURN, "1")); + } + }); + + } + + @Override + public int getItemCount() { + return data.size(); + } + + class MyViewHolder extends RecyclerView.ViewHolder { + TextView txt_name_with_mobile, text_bill_no; + RecyclerView sku_list_returns, sku_list_replace_product; + LinearLayout rl_printer, rl_replace_product; + ImageView img_printer; + ArrayList return_productList, replace_productList; + + public MyViewHolder(View itemView) { + super(itemView); + txt_name_with_mobile = (TextView) itemView.findViewById(R.id.txt_name_with_mobile); + text_bill_no = (TextView) itemView.findViewById(R.id.text_bill_no); + img_printer = (ImageView) itemView.findViewById(R.id.img_printer); + rl_printer = (LinearLayout) itemView.findViewById(R.id.rl_printer); + sku_list_returns = (RecyclerView) itemView.findViewById(R.id.sku_list_returns); + rl_replace_product = (LinearLayout) itemView.findViewById(R.id.rl_replace_product); + sku_list_replace_product = (RecyclerView) itemView.findViewById(R.id.sku_list_replace_product); + } + } + } + + + public class ReturnsSkuAdapter extends RecyclerView.Adapter { + private LayoutInflater inflator; + List data; + + public ReturnsSkuAdapter(Context context, List data) { + inflator = LayoutInflater.from(context); + this.data = data; + } + + @Override + public MyViewHolder onCreateViewHolder(ViewGroup parent, int i) { + View view = inflator.inflate(R.layout.row_returns_sku, parent, false); + return new MyViewHolder(view); + } + + @Override + public void onBindViewHolder(final ReturnsSkuAdapter.MyViewHolder holder, final int position) { + final InvoiceGetterSetter current = data.get(position); + + holder.product_name.setText("Product : " + current.getProduct()); + holder.product_name.setId(position); + + holder.product_rate.setText("QTY - " + current.getQuantity() + " Rate - " + current.getProduct_rate()); + holder.product_rate.setId(position); + + int total_ammount = Integer.parseInt(current.getQuantity()) * Integer.parseInt(current.getProduct_rate()); + holder.total_ammount_txt.setText("Total Amount - " + total_ammount); + holder.total_ammount_txt.setId(position); + } + + @Override + public int getItemCount() { + return data.size(); + } + + class MyViewHolder extends RecyclerView.ViewHolder { + TextView product_name, product_rate, total_ammount_txt; + + public MyViewHolder(View itemView) { + super(itemView); + product_name = (TextView) itemView.findViewById(R.id.txt_name_with_mobile); + product_rate = (TextView) itemView.findViewById(R.id.text_bill_no); + total_ammount_txt = (TextView) itemView.findViewById(R.id.total_ammount_txt); + } + } + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + if (id == android.R.id.home) { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + ConsumerReturnsHistoryActivity.this.finish(); + } + + + return super.onOptionsItemSelected(item); + } + + @Override + public void onBackPressed() { + super.onBackPressed(); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + ConsumerReturnsHistoryActivity.this.finish(); + + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/consumeractivity/ConsumerUserDetailsActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/consumeractivity/ConsumerUserDetailsActivity.java new file mode 100644 index 0000000..c477bcf --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/consumeractivity/ConsumerUserDetailsActivity.java @@ -0,0 +1,4911 @@ +package com.cpm.lorealbaautomation.consumeractivity; + +import static com.cpm.lorealbaautomation.constant.CommonFunctions.getCurrentTime; +import static com.cpm.lorealbaautomation.constant.CommonFunctions.removeFirstChar; +import static com.cpm.lorealbaautomation.dailyactivity.StoreImageActivity.convertBitmap; + +import android.annotation.SuppressLint; +import android.app.Activity; +import android.app.AlertDialog; +import android.app.Dialog; +import android.app.ProgressDialog; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.SharedPreferences; +import android.graphics.Bitmap; +import android.graphics.drawable.ColorDrawable; +import android.os.AsyncTask; +import android.os.Bundle; +import android.text.Editable; +import android.text.TextWatcher; +import android.util.Log; +import android.view.Gravity; +import android.view.LayoutInflater; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; +import android.view.Window; +import android.view.WindowManager; +import android.webkit.WebView; +import android.webkit.WebViewClient; +import android.widget.AdapterView; +import android.widget.ArrayAdapter; +import android.widget.Button; +import android.widget.CheckBox; +import android.widget.EditText; +import android.widget.ImageView; +import android.widget.LinearLayout; +import android.widget.ProgressBar; +import android.widget.RadioButton; +import android.widget.RadioGroup; +import android.widget.ScrollView; +import android.widget.Spinner; +import android.widget.TextView; +import android.widget.Toast; + +import androidx.annotation.NonNull; +import androidx.appcompat.app.AppCompatActivity; +import androidx.appcompat.widget.Toolbar; +import androidx.cardview.widget.CardView; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; + +import com.google.android.material.floatingactionbutton.FloatingActionButton; +import com.google.gson.Gson; +import com.google.zxing.integration.android.IntentIntegrator; +import com.google.zxing.integration.android.IntentResult; +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.constant.AlertandMessages; +import com.cpm.lorealbaautomation.constant.CommonFunctions; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.gsonGetterSetter.ConsumerSalesHistory; +import com.cpm.lorealbaautomation.gsonGetterSetter.ConsumerTermsConditionAccept; +import com.cpm.lorealbaautomation.gsonGetterSetter.InvoiceGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.JourneyPlan; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterAgeLimit; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterBAProfileGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterPromotion; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterPromotionSetEntityItem; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterPromotionSetProductGroup; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterSkinType; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterSourcesOfSale; +import com.cpm.lorealbaautomation.gsonGetterSetter.ProductMaster; +import com.cpm.lorealbaautomation.retrofit.PostApi; + +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.File; +import java.text.DecimalFormat; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.TimeUnit; + +import okhttp3.MediaType; +import okhttp3.OkHttpClient; +import okhttp3.RequestBody; +import okhttp3.ResponseBody; +import retrofit2.Retrofit; +import retrofit2.converter.gson.GsonConverterFactory; + +public class ConsumerUserDetailsActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemSelectedListener { + String dialog_invoiceType = "Saleable", dialog_brand_Id = "", dialog_sub_brand_Id = "", dialog_reference_Id = "", product_name = "", + product_Id = "0", product_mrp = "0", CounterId, visit_date, + username, perchasing_tym = "", productType = "", str_termCondition = "0", response_term_condition = "", _pathforcheck = "", _path = "", tagmode = ""; + ArrayAdapter dialog_brand_adapter, dialog_sub_brand_adapter, dialog_frenchise_adapter, dialog_sku_adapter, + AgeAdapter, SkinTypeAdapter, sourceofsalesAdapter; + private SharedPreferences preferences; + public ArrayList dialog_product_using_searchlist = new ArrayList<>(); + Lorealba_Database db; + EditText edt_customer, edt_mobile_no; + Button btn_scan, btn_enter_code, btn_sku_list; + RecyclerView drawer_layout_recycle_store; + public ArrayList selected_list = new ArrayList<>(); + public ArrayList dialog_product_list = new ArrayList<>(); + InvoiceGetterSetter object; + String product_scan_code = "", flag_for_consumer_Update = "", Key_For_Pos_Enable_With_Showing_Invoice = "", + skin_genius_str = "", maybelline_vto = "", demo_given_str = "", product_sold_str = "", otp_code = "", str_img_demo_no_sale = "", str_sourceof_sales = ""; + FloatingActionButton fab, draft_fab; + TextView qrcode_text, sku_name, stock_text_value, txt_history, current_total_stock; + EditText edt_scan_code; + CardView card_layout_scan, card_layout_title; + CheckBox mobile_checkbox, no_name_checkbox; + boolean no_name_flag = false, no_mobile_no_flag = false; + ProgressDialog loading; + Context context; + int minteger = 0; + private RadioGroup radioSexGroup; + private RadioButton radioSexButton; + double discount = 0.0; + Button promotion_btn_first, promotion_btn_second, sale_btn_yes, sale_btn_no, skingn_btn_yes, skingn_btn_no, maybelline_btn_yes, maybelline_btn_no; + double total = 0.0; + boolean clicked_flag = false, product_add_flag = false; + int reciept_count = 0; + ///new changes19/08/19 + LinearLayout rl_otp, rl_actual_qty, rl_complete_layout; + EditText edt_otp, edt_email_address; + Spinner spin_age, spin_skin_type; + ScrollView scroll_view; + boolean flag_for_filter = false, flag_for_term_condition = false, flag_filter_by_edt = false; + TextView actual_qty_dialog, rl_term_condition, text_user_nm; + ImageView img_visble; + ArrayList listDataHeader = new ArrayList<>(); + HashMap> listDataChild; + JourneyPlan storeDataObject = new JourneyPlan(); + ArrayList sourceofsaleslist = new ArrayList<>(); + ArrayList ageLimits = new ArrayList<>(); + ArrayList skinTypes = new ArrayList<>(); + ArrayList brandList, subbrandList, referenceList, productList = new ArrayList<>(); + LinearLayout rl_demo_img; + ImageView img_only_demo; + ArrayList selected_promoList = new ArrayList<>(); + ArrayList added_prmo_products = new ArrayList<>(); + ArrayList applyeid_products = new ArrayList<>(); + Spinner spinSourceof_sales; + LinearLayout rlSalesSource; + String from = ""; + + @SuppressLint("SetTextI18n") + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_consumer_user_details); + from = getIntent().getStringExtra("from"); + context = this; + ((ConsumerUserDetailsActivity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); + iduserinterface(); + Toolbar toolbar = findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + if (!CommonFunctions.isTablet(context)) { + toolbar.setTitleTextAppearance(context, R.style.changestext_sizefor_mobile); + } + Objects.requireNonNull(getSupportActionBar()).setHomeButtonEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + setTitle("Consumer Details -" + username); + perchasing_tym = CommonFunctions.getCurrentTime_only(); + String couter_code = preferences.getString(CommonString.KEY_COUNTER_CODE, ""); + TextView txt_counter_code = (TextView) findViewById(R.id.txt_counter_code); + txt_counter_code.setText("Counter Code - " + couter_code + " / Id - " + CounterId); + } + + @SuppressLint({"UseCompatLoadingForDrawables", "SetTextI18n"}) + private void iduserinterface() { + db = new Lorealba_Database(context); + db.open(); + preferences = PrefHelper.getPrefs(context); + CounterId = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + username = preferences.getString(CommonString.KEY_USERNAME, ""); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + scroll_view = (ScrollView) findViewById(R.id.scroll_view); + btn_scan = (Button) findViewById(R.id.btn_scan); + btn_enter_code = (Button) findViewById(R.id.btn_enter_code); + btn_sku_list = (Button) findViewById(R.id.btn_sku_list); + fab = (FloatingActionButton) findViewById(R.id.fab); + draft_fab = (FloatingActionButton) findViewById(R.id.draft_fab); + edt_customer = (EditText) findViewById(R.id.edt_customer); + edt_mobile_no = (EditText) findViewById(R.id.edt_mobile_no); + txt_history = (TextView) findViewById(R.id.txt_history); + current_total_stock = (TextView) findViewById(R.id.txt_total); + drawer_layout_recycle_store = (RecyclerView) findViewById(R.id.drawer_layout_recycle_store); + mobile_checkbox = (CheckBox) findViewById(R.id.mobile_checkbox); + no_name_checkbox = (CheckBox) findViewById(R.id.no_name_checkbox); + card_layout_scan = (CardView) findViewById(R.id.card_layout_scan); + card_layout_title = (CardView) findViewById(R.id.card_layout_title); + //for demo btn + promotion_btn_first = (Button) findViewById(R.id.posm_btn_first); + promotion_btn_second = (Button) findViewById(R.id.posm_btn_second); + sale_btn_yes = (Button) findViewById(R.id.sale_btn_yes); + sale_btn_no = (Button) findViewById(R.id.sale_btn_no); + ////for skin Genius + skingn_btn_yes = (Button) findViewById(R.id.skingn_btn_yes); + skingn_btn_no = (Button) findViewById(R.id.skingn_btn_no); + maybelline_btn_yes = (Button) findViewById(R.id.maybelline_btn_yes); + maybelline_btn_no = (Button) findViewById(R.id.maybelline_btn_no); + radioSexGroup = (RadioGroup) findViewById(R.id.radioGrp); + ///new changes19--08-19 + rl_term_condition = (TextView) findViewById(R.id.rl_term_condition); + text_user_nm = (TextView) findViewById(R.id.text_user_nm); + rl_otp = (LinearLayout) findViewById(R.id.rl_otp); + edt_otp = (EditText) findViewById(R.id.edt_otp); + edt_email_address = (EditText) findViewById(R.id.edt_email_address); + spin_age = (Spinner) findViewById(R.id.spin_age); + spin_skin_type = (Spinner) findViewById(R.id.spin_skin_type); + /////new changwessssssssss + rl_complete_layout = (LinearLayout) findViewById(R.id.rl_complete_layout); + img_visble = (ImageView) findViewById(R.id.img_visble); + rl_demo_img = (LinearLayout) findViewById(R.id.rl_demo_img); + img_only_demo = (ImageView) findViewById(R.id.img_only_demo); + spinSourceof_sales = (Spinner) findViewById(R.id.spinSourceof_sales); + rlSalesSource = (LinearLayout) findViewById(R.id.rlSalesSource); + img_visble.setVisibility(View.GONE); + img_only_demo.setOnClickListener(this); + btn_scan.setOnClickListener(this); + btn_enter_code.setOnClickListener(this); + btn_sku_list.setOnClickListener(this); + fab.setOnClickListener(this); + mobile_checkbox.setOnClickListener(this); + no_name_checkbox.setOnClickListener(this); + txt_history.setOnClickListener(this); + draft_fab.setOnClickListener(this); + promotion_btn_first.setOnClickListener(this); + promotion_btn_second.setOnClickListener(this); + sale_btn_yes.setOnClickListener(this); + sale_btn_no.setOnClickListener(this); + skingn_btn_yes.setOnClickListener(this); + skingn_btn_no.setOnClickListener(this); + maybelline_btn_yes.setOnClickListener(this); + maybelline_btn_no.setOnClickListener(this); + rl_otp.setOnClickListener(this); + img_visble.setOnClickListener(this); + rl_term_condition.setOnClickListener(this); + if (getIntent().getStringExtra(CommonString.TAG_MODE) != null) { + tagmode = getIntent().getStringExtra(CommonString.TAG_MODE); + } + + db.open(); + sourceofsaleslist = db.getsourceofsales(); + db.open(); + ageLimits = db.getAgeLimitMasterData(); + db.open(); + skinTypes = db.getskinTypeMaster(); + storeDataObject = db.getspecific_storenamewith_counter_name(visit_date, CounterId, username); + flag_for_consumer_Update = getIntent().getStringExtra(CommonString.Key_For_Consumer_Update); + selected_list = (ArrayList) getIntent().getSerializableExtra(CommonString.TAG_OBJECT); + Key_For_Pos_Enable_With_Showing_Invoice = getIntent().getStringExtra(CommonString.Key_For_Pos_Enable_With_Showing_Invoice); + adapterforAgeLimit_SkinType(); + getstatusof_termcondition(); + ///calling of age adapter + if (flag_for_consumer_Update != null && flag_for_consumer_Update.equals("1")) { + edt_mobile_no.setEnabled(false); + mobile_checkbox.setEnabled(false); + rl_term_condition.setTextColor(getResources().getColor(R.color.gray)); + rl_term_condition.setEnabled(false); + mobile_checkbox.setEnabled(false); + edt_email_address.setEnabled(false); + } + + if (selected_list != null && !selected_list.isEmpty()) { + username = selected_list.get(0).getUserName(); + edt_customer.setText(selected_list.get(0).getCustomer_name()); + edt_mobile_no.setText(selected_list.get(0).getMobile_no()); + edt_email_address.setText(selected_list.get(0).getConsumer_email_Id()); + reciept_count = selected_list.get(0).getReccept_count(); + str_termCondition = selected_list.get(0).getStr_termcondition(); + /////for radio group + if (selected_list.get(0).getCustomer_gender().equalsIgnoreCase("Male")) { + //radioSexButton + radioSexGroup.check(R.id.radioM); + } else if (selected_list.get(0).getCustomer_gender().equalsIgnoreCase("Female")) { + //radioSexButton + radioSexGroup.check(R.id.radioF); + } else { + radioSexGroup.check(R.id.radio_other); + } + + ///for source of sales + rlSalesSource.setVisibility(View.VISIBLE); + if (!selected_list.get(0).getSourceofSales().isEmpty()) { + str_sourceof_sales = selected_list.get(0).getSourceofSales(); + for (int w = 0; w < sourceofsaleslist.size(); w++) { + if (str_sourceof_sales.equalsIgnoreCase(sourceofsaleslist.get(w).getSourcesOfSale())) { + spinSourceof_sales.setSelection(w + 1); + break; + } + } + } + + //for demo perpose button + if (!selected_list.get(0).getDemo_given_str().isEmpty() && selected_list.get(0).getDemo_given_str().equalsIgnoreCase("Yes")) { + promotion_btn_first.setBackground(getResources().getDrawable(R.drawable.rouded_corner)); + promotion_btn_first.setTextColor(getResources().getColor(R.color.white)); + promotion_btn_second.setBackground(getResources().getDrawable(R.drawable.round_btn_color_primary)); + promotion_btn_second.setTextColor(getResources().getColor(R.color.grayfor_login)); + demo_given_str = "Yes"; + } else { + promotion_btn_second.setBackground(getResources().getDrawable(R.drawable.rouded_corner)); + promotion_btn_second.setTextColor(getResources().getColor(R.color.white)); + promotion_btn_first.setBackground(getResources().getDrawable(R.drawable.round_btn_color_primary)); + promotion_btn_first.setTextColor(getResources().getColor(R.color.grayfor_login)); + demo_given_str = "No"; + } + + /////For Skin Genious + if (!selected_list.get(0).getSkin_genius_str().isEmpty() && selected_list.get(0).getSkin_genius_str().equalsIgnoreCase("Yes")) { + skingn_btn_yes.setBackground(getResources().getDrawable(R.drawable.rouded_corner)); + skingn_btn_yes.setTextColor(getResources().getColor(R.color.white)); + skingn_btn_no.setBackground(getResources().getDrawable(R.drawable.round_btn_color_primary)); + skingn_btn_no.setTextColor(getResources().getColor(R.color.grayfor_login)); + skin_genius_str = "Yes"; + } else { + skingn_btn_no.setBackground(getResources().getDrawable(R.drawable.rouded_corner)); + skingn_btn_no.setTextColor(getResources().getColor(R.color.white)); + skingn_btn_yes.setBackground(getResources().getDrawable(R.drawable.round_btn_color_primary)); + skingn_btn_yes.setTextColor(getResources().getColor(R.color.grayfor_login)); + skin_genius_str = "No"; + } + +/////For Maybelline VTO + if (!selected_list.get(0).getMaybelline_vto_str().isEmpty() && selected_list.get(0).getMaybelline_vto_str().equalsIgnoreCase("Yes")) { + maybelline_btn_yes.setBackground(getResources().getDrawable(R.drawable.rouded_corner)); + maybelline_btn_yes.setTextColor(getResources().getColor(R.color.white)); + maybelline_btn_no.setBackground(getResources().getDrawable(R.drawable.round_btn_color_primary)); + maybelline_btn_no.setTextColor(getResources().getColor(R.color.grayfor_login)); + maybelline_vto = "Yes"; + } else { + maybelline_btn_no.setBackground(getResources().getDrawable(R.drawable.rouded_corner)); + maybelline_btn_no.setTextColor(getResources().getColor(R.color.white)); + maybelline_btn_yes.setBackground(getResources().getDrawable(R.drawable.round_btn_color_primary)); + maybelline_btn_yes.setTextColor(getResources().getColor(R.color.grayfor_login)); + maybelline_vto = "No"; + } + + + if (!selected_list.get(0).getProduct_sold_str().isEmpty() && selected_list.get(0).getProduct_sold_str().equalsIgnoreCase("Yes")) { + sale_btn_yes.setBackground(getResources().getDrawable(R.drawable.rouded_corner)); + sale_btn_yes.setTextColor(getResources().getColor(R.color.white)); + sale_btn_no.setBackground(getResources().getDrawable(R.drawable.round_btn_color_primary)); + sale_btn_no.setTextColor(getResources().getColor(R.color.grayfor_login)); + card_layout_scan.setVisibility(View.VISIBLE); + card_layout_title.setVisibility(View.VISIBLE); + drawer_layout_recycle_store.setVisibility(View.VISIBLE); + product_sold_str = "Yes"; + rl_complete_layout.setVisibility(View.GONE); + img_visble.setVisibility(View.VISIBLE); + text_user_nm.setText(selected_list.get(0).getCustomer_name() + " Customer - " + CommonFunctions.removed_special_char(edt_customer)); + } else { + sale_btn_no.setBackground(getResources().getDrawable(R.drawable.rouded_corner)); + sale_btn_no.setTextColor(getResources().getColor(R.color.white)); + sale_btn_yes.setBackground(getResources().getDrawable(R.drawable.round_btn_color_primary)); + sale_btn_yes.setTextColor(getResources().getColor(R.color.grayfor_login)); + card_layout_scan.setVisibility(View.GONE); + card_layout_title.setVisibility(View.GONE); + drawer_layout_recycle_store.setVisibility(View.GONE); + ///for source of sales + rlSalesSource.setVisibility(View.VISIBLE); + product_sold_str = "No"; + } + + if (!selected_list.get(0).getDemo_given_str().isEmpty() && selected_list.get(0).getDemo_given_str().equalsIgnoreCase("Yes")) { + if (selected_list.get(0).getConsumer_no_saleImg() != null && !selected_list.get(0).getConsumer_no_saleImg().isEmpty()) { + img_only_demo.setImageResource(R.mipmap.camera_bsd); + str_img_demo_no_sale = selected_list.get(0).getConsumer_no_saleImg(); + } + rl_demo_img.setVisibility(View.VISIBLE); + } + + db.open(); + for (int k = 0; k < ageLimits.size(); k++) { + if (selected_list != null && !selected_list.isEmpty() && !selected_list.get(0).getConsumer_age().isEmpty()) { + if (ageLimits.get(k).getAgeLimit().equalsIgnoreCase(selected_list.get(0).getConsumer_age())) { + spin_age.setSelection(k + 1); + break; + } + + } + } + db.open(); + for (int k = 0; k < skinTypes.size(); k++) { + if (selected_list != null && !selected_list.isEmpty() && !selected_list.get(0).getConsumer_skinType().isEmpty()) { + if (skinTypes.get(k).getSkinType().equalsIgnoreCase(selected_list.get(0).getConsumer_skinType())) { + spin_skin_type.setSelection(k + 1); + break; + } + + } + } + + if (selected_list.get(0).getProduct_Id() != null) + drawer_layout_recycle_store.setAdapter(new ValueAdapter(context, selected_list)); + drawer_layout_recycle_store.setLayoutManager(new LinearLayoutManager(context)); + } else { + selected_list = new ArrayList<>(); + promotion_btn_second.setBackground(getResources().getDrawable(R.drawable.rouded_corner)); + promotion_btn_second.setTextColor(getResources().getColor(R.color.white)); + promotion_btn_first.setBackground(getResources().getDrawable(R.drawable.round_btn_color_primary)); + promotion_btn_first.setTextColor(getResources().getColor(R.color.grayfor_login)); + + sale_btn_no.setBackground(getResources().getDrawable(R.drawable.rouded_corner)); + sale_btn_no.setTextColor(getResources().getColor(R.color.white)); + sale_btn_yes.setBackground(getResources().getDrawable(R.drawable.round_btn_color_primary)); + sale_btn_yes.setTextColor(getResources().getColor(R.color.grayfor_login)); + + ///for Sale Genius + skingn_btn_no.setBackground(getResources().getDrawable(R.drawable.rouded_corner)); + skingn_btn_no.setTextColor(getResources().getColor(R.color.white)); + skingn_btn_yes.setBackground(getResources().getDrawable(R.drawable.round_btn_color_primary)); + skingn_btn_yes.setTextColor(getResources().getColor(R.color.grayfor_login)); + + ///for Maybelline VTO + maybelline_btn_no.setBackground(getResources().getDrawable(R.drawable.rouded_corner)); + maybelline_btn_no.setTextColor(getResources().getColor(R.color.white)); + maybelline_btn_yes.setBackground(getResources().getDrawable(R.drawable.round_btn_color_primary)); + maybelline_btn_yes.setTextColor(getResources().getColor(R.color.grayfor_login)); + + maybelline_vto = "No"; + skin_genius_str = "No"; + demo_given_str = "No"; + str_img_demo_no_sale = ""; + product_sold_str = "No"; + rl_demo_img.setVisibility(View.GONE); + img_only_demo.setImageResource(R.mipmap.camera_bs); + ///for source of sales + rlSalesSource.setVisibility(View.VISIBLE); + } + } + + + private boolean checkotp_validation() { + boolean status = true; + if (edt_otp.getText().toString().equals("0000")) { + str_termCondition = "1"; + } else if (edt_otp.getText().toString().equals(otp_code)) { + str_termCondition = "1"; + } else { + status = false; + } + return status; + + } + + private void custom_dialog_for_termand_condition(final Context context) { + minteger = 0; + final MultiPurposeDialog multiDialog = new MultiPurposeDialog(context); + multiDialog.requestWindowFeature(Window.FEATURE_NO_TITLE); + multiDialog.setContentView(R.layout.custom_dialog_for_term_condition); + final WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); + lp.copyFrom(Objects.requireNonNull(multiDialog.getWindow()).getAttributes()); + lp.width = WindowManager.LayoutParams.MATCH_PARENT; + lp.height = WindowManager.LayoutParams.WRAP_CONTENT; + lp.gravity = Gravity.CENTER; + multiDialog.getWindow().setAttributes(lp); + multiDialog.setCancelable(false); + multiDialog.show(); + ///new changes 19 aug + CheckBox checkbox_accept = (CheckBox) multiDialog.findViewById(R.id.checkbox_accept); + CheckBox checkbox_reject = (CheckBox) multiDialog.findViewById(R.id.checkbox_reject); + TextView txt_term_condition = (TextView) multiDialog.findViewById(R.id.txt_term_condition); + WebView webview = (WebView) multiDialog.findViewById(R.id.webview); + webview.loadData(db.getterm_and_condition().getTermsCondition(), "text/html; charset=utf-8", "utf-8"); + if (flag_for_term_condition) { + checkbox_accept.setChecked(true); + } + + db.open(); + txt_term_condition.setText(db.getterm_and_condition().getTermsCondition()); + checkbox_accept.setOnClickListener(v -> { + try { + flag_for_term_condition = true; + if (multiDialog.isShowing()) { + multiDialog.dismiss(); + } + rl_otp.setVisibility(View.VISIBLE); + JSONObject jsonObject = new JSONObject(); + jsonObject.put("MobileNumber", edt_mobile_no.getText().toString()); + getotp_from_mobile_no(jsonObject.toString(), multiDialog); + } catch (JSONException e) { + e.fillInStackTrace(); + } + }); + + checkbox_reject.setOnClickListener(v -> { + if (multiDialog.isShowing()) { + multiDialog.dismiss(); + } + no_mobile_no_flag = true; + flag_for_term_condition = false; + edt_mobile_no.setText("0000000000"); + rl_otp.setVisibility(View.GONE); + edt_mobile_no.setEnabled(false); + mobile_checkbox.setChecked(true); + mobile_checkbox.setEnabled(false); + edt_email_address.setEnabled(false); + edt_email_address.setText(""); + rl_term_condition.setTextColor(getResources().getColor(R.color.gray)); + rl_term_condition.setEnabled(false); + + }); + + multiDialog.show(); + } + + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + if (id == android.R.id.home) { + if (clicked_flag) { + AlertDialog.Builder builder = new AlertDialog.Builder(context).setMessage(CommonString.ONBACK_ALERT_MESSAGE).setCancelable(false).setPositiveButton("Ok", + (dialog, id1) -> { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + ConsumerUserDetailsActivity.this.finish(); + }).setNegativeButton("Cancel", (dialog, id12) -> dialog.cancel()); + AlertDialog alert = builder.create(); + alert.show(); + } else { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + ConsumerUserDetailsActivity.this.finish(); + } + } + + return super.onOptionsItemSelected(item); + } + + @Override + public void onBackPressed() { + if (clicked_flag) { + AlertDialog.Builder builder = new AlertDialog.Builder(context).setMessage(CommonString.ONBACK_ALERT_MESSAGE).setCancelable(false).setPositiveButton("Ok", + (dialog, id) -> { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + ConsumerUserDetailsActivity.this.finish(); + }).setNegativeButton("Cancel", (dialog, id) -> dialog.cancel()); + AlertDialog alert = builder.create(); + alert.show(); + } else { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + ConsumerUserDetailsActivity.this.finish(); + } + } + + + private void calculate_invoice_added_data(ArrayList invoice_List) { + try { + double cCom = 0.0, total_INR_value = 0.0; + for (int k = 0; k < invoice_List.size(); k++) { + if (invoice_List.get(k).getDiscount() != 0.0) { + int quantity = Integer.parseInt(invoice_List.get(k).getQuantity()); + double amount = Double.parseDouble(invoice_List.get(k).getProduct_rate()); + amount = amount * quantity; + invoice_List.get(k).setTotal_amount(String.valueOf(amount)); + cCom = cCom + ((Double.parseDouble(invoice_List.get(k).getTotal_amount())) * invoice_List.get(k).getDiscount()); + } else { + int quantity = Integer.parseInt(invoice_List.get(k).getQuantity()); + double amount = Double.parseDouble(invoice_List.get(k).getProduct_rate()); + amount = amount * quantity; + invoice_List.get(k).setTotal_amount(String.valueOf(amount)); + } + + double amount_ofproduct = ((Double.parseDouble(invoice_List.get(k).getTotal_amount())) * invoice_List.get(k).getDiscount()); + amount_ofproduct = (Double.parseDouble(invoice_List.get(k).getTotal_amount())) - amount_ofproduct; + total_INR_value = total_INR_value + Double.parseDouble(invoice_List.get(k).getTotal_amount()); + String string = invoice_List.get(k).getDiscount().toString(); + if (invoice_List.get(k).getDiscount() == 0.0 || invoice_List.get(k).getDiscount() == 0) { + invoice_List.get(k).setActual_price_per_product((Double.parseDouble(invoice_List.get(k).getTotal_amount()))); + invoice_List.get(k).setDiscounted_value(0.0); + } else { + invoice_List.get(k).setDiscounted_value(((Double.parseDouble(invoice_List.get(k).getTotal_amount())) * invoice_List.get(k).getDiscount())); + invoice_List.get(k).setActual_price_per_product((Double.parseDouble(invoice_List.get(k).getTotal_amount()) - ((Double.parseDouble(invoice_List.get(k).getTotal_amount())) * invoice_List.get(k).getDiscount()))); + } + } + total = total_INR_value - cCom; + } catch (NumberFormatException e) { + e.fillInStackTrace(); + } + } + + + private int calculate_total_consume(ArrayList invoice_List) { + int total_INR_value = 0, off_worth_total = 0, worth_total = 0, OffSameProduct = 0, OffAdditionalProduct = 0, ValueOffAdditionalProduct = 0; + try { + if (!invoice_List.isEmpty()) { + for (int k = 0; k < invoice_List.size(); k++) { + if (!invoice_List.get(k).isPromo_flag()) { + int quantity = Integer.parseInt(invoice_List.get(k).getQuantity()); + int amount = Integer.parseInt((invoice_List.get(k).getProduct_rate())); + amount = amount * quantity; + invoice_List.get(k).setTotal_amount(String.valueOf(amount)); + total_INR_value = total_INR_value + Integer.parseInt(invoice_List.get(k).getTotal_amount()); + } else { + if (invoice_List.get(k).getPromo_type().equalsIgnoreCase("OffProduct")) { + int quantity = Integer.parseInt(invoice_List.get(k).getQuantity()); + int amount = Integer.parseInt((invoice_List.get(k).getProduct_rate())); + amount = amount * quantity; + invoice_List.get(k).setTotal_amount(String.valueOf(amount)); + total_INR_value = total_INR_value + Integer.parseInt(invoice_List.get(k).getTotal_amount()); + total_INR_value = total_INR_value - Integer.parseInt(invoice_List.get(k).getSkuType()); + } else if (invoice_List.get(k).getPromo_type().equalsIgnoreCase("OffWorth") + || invoice_List.get(k).getPromo_type().equalsIgnoreCase("WorthWithProduct")) { + off_worth_total = off_worth_total + Integer.parseInt(invoice_List.get(k).getProduct()); + } else if (invoice_List.get(k).getPromo_type().equalsIgnoreCase("Worth")) { + worth_total = worth_total + Integer.parseInt(invoice_List.get(k).getProduct()); + } else if (invoice_List.get(k).getPromo_type().equalsIgnoreCase("OffSameProduct")) { + OffSameProduct = OffSameProduct + Integer.parseInt(invoice_List.get(k).getProduct()); + } else if (invoice_List.get(k).getPromo_type().equalsIgnoreCase("OffAdditionalProduct")) { + OffAdditionalProduct = OffAdditionalProduct + Integer.parseInt(invoice_List.get(k).getProduct()); + } else if (invoice_List.get(k).getPromo_type().equalsIgnoreCase("ValueOffAdditionalProduct")) { + ValueOffAdditionalProduct = ValueOffAdditionalProduct + Integer.parseInt(invoice_List.get(k).getProduct()); + } + } + } + + total_INR_value = total_INR_value - off_worth_total; + total_INR_value = total_INR_value - worth_total; + total_INR_value = total_INR_value - OffSameProduct; + total_INR_value = total_INR_value - OffAdditionalProduct; + total_INR_value = total_INR_value - ValueOffAdditionalProduct; + } + } catch (NumberFormatException e) { + e.fillInStackTrace(); + } + + return total_INR_value; + } + + @SuppressLint({"NonConstantResourceId", "SetTextI18n", "UseCompatLoadingForDrawables"}) + @Override + public void onClick(View view) { + + if (view.getId() == R.id.img_only_demo) { + _pathforcheck = CounterId + "_ConsumerSimg_" + username + "_" + visit_date.replace("/", "") + "_" + getCurrentTime().replace(":", "") + ".jpg"; + _path = CommonString.getImagesFolder(context) + _pathforcheck; + CommonFunctions.startAnncaCameraActivity(context, _path, null, false, CommonString.CAMERA_FACE_REAR); + } else if (view.getId() == R.id.img_visble) { + if (rl_complete_layout.getVisibility() == View.VISIBLE) { + // Its visible + text_user_nm.setText(getString(R.string.filldetails) + " Customer - " + CommonFunctions.removed_special_char(edt_customer)); + rl_complete_layout.setVisibility(View.GONE); + img_visble.setImageResource(R.mipmap.invisible); + img_visble.setVisibility(View.VISIBLE); + } else { + // Either gone or invisible + rl_complete_layout.setVisibility(View.VISIBLE); + img_visble.setImageResource(R.mipmap.visible); + text_user_nm.setText(getString(R.string.filldetails) + " Customer - " + CommonFunctions.removed_special_char(edt_customer)); + } + + } else if (view.getId() == R.id.rl_term_condition) { + if (checkindex()) { + custom_dialog_for_termand_condition(context); + } + } else if (view.getId() == R.id.txt_history) { + if (edt_mobile_no.getText().toString().isEmpty()) { + txt_history.setEnabled(true); + AlertandMessages.showToastMsg(context, "Please Enter Mobile Number "); + } else if (edt_mobile_no.getText().toString().length() < 10) { + txt_history.setEnabled(true); + AlertandMessages.showToastMsg(context, "Please Enter Atleast 10 Digit Contact Number "); + } else if (checkindex()) { + if (CommonFunctions.checkNetIsAvailable(context)) { + txt_history.setEnabled(false); + try { + JSONObject jsonObject1 = new JSONObject(); + jsonObject1.put("Downloadtype", "Consumer_SalesHistory"); + jsonObject1.put("Username", username); + jsonObject1.put("Param2", edt_email_address.getText().toString()); + jsonObject1.put("Param1", edt_mobile_no.getText().toString()); + loading = ProgressDialog.show(context, "Processing", "Please wait...", false, true); + getpreviousHistory_from_mobile_no(context, loading, jsonObject1.toString()); + } catch (JSONException e) { + e.fillInStackTrace(); + } + } else { + txt_history.setEnabled(true); + AlertandMessages.showToastMsg(context, "Unable To Connect Server. History Data Not Updated"); + } + } + + } else if (view.getId() == R.id.mobile_checkbox) { + clicked_flag = true; + if (mobile_checkbox.isChecked()) { + no_mobile_no_flag = true; + flag_for_term_condition = false; + edt_mobile_no.setText("0000000000"); + rl_otp.setVisibility(View.GONE); + edt_mobile_no.setEnabled(false); + rl_term_condition.setTextColor(getResources().getColor(R.color.gray)); + } else { + edt_mobile_no.setText(""); + no_mobile_no_flag = false; + edt_mobile_no.setEnabled(true); + rl_term_condition.setTextColor(getResources().getColor(R.color.blue)); + } + + } else if (view.getId() == R.id.no_name_checkbox) { + clicked_flag = true; + if (no_name_checkbox.isChecked()) { + no_name_flag = true; + edt_customer.setText("No Name"); + edt_customer.setEnabled(false); + } else { + edt_customer.setText(""); + no_name_flag = false; + edt_customer.setEnabled(true); + } + + } else if (view.getId() == R.id.btn_scan) { + clicked_flag = true; + ((ConsumerUserDetailsActivity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); + if (!no_name_flag && edt_customer.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter Customer Name "); + } else if (!no_mobile_no_flag && edt_mobile_no.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter Mobile Number "); + } else if (!no_mobile_no_flag && edt_mobile_no.getText().toString().length() < 10) { + AlertandMessages.showToastMsg(context, "Please Enter Atleast 10 Digit Contact Number "); + } else if (!edt_email_address.getText().toString().isEmpty() && !CommonFunctions.isValidEmail(edt_email_address.getText().toString())) { + AlertandMessages.showToastMsg(context, "Please Enter Valid Email Id "); + } else if (demo_given_str.isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Select Demo Given "); + } else if (product_sold_str.isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Select Product Sold "); + } else if (str_sourceof_sales.isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Select Source of visit"); + } else if (skin_genius_str.isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Select Skin Genius "); + } else if (maybelline_vto.isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Select Maybelline VTO "); + } else { + show_proforma_dialog(context, true); + } + + } else if (view.getId() == R.id.btn_enter_code) { + clicked_flag = true; + ((ConsumerUserDetailsActivity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); + if (!no_name_flag && edt_customer.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter Customer Name "); + } else if (!no_mobile_no_flag && edt_mobile_no.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter Mobile Number "); + } else if (!no_mobile_no_flag && edt_mobile_no.getText().toString().length() < 10) { + AlertandMessages.showToastMsg(context, "Please Enter Atleast 10 Digit Contact Number "); + } else if (!edt_email_address.getText().toString().isEmpty() && !CommonFunctions.isValidEmail(edt_email_address.getText().toString())) { + AlertandMessages.showToastMsg(context, "Please Enter Valid Email Id "); + } else if (demo_given_str.isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Select Demo Given "); + } else if (product_sold_str.isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Select Product Sold "); + } else if (str_sourceof_sales.isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Select Source of visit"); + } else if (skin_genius_str.isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Select Skin Genius "); + } else if (maybelline_vto.isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Select Maybelline VTO "); + } else { + show_proforma_dialog(context, false); + } + + } else if (view.getId() == R.id.fab) { + ((ConsumerUserDetailsActivity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); + if (!no_name_flag && edt_customer.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter Customer Name "); + } else if (!no_mobile_no_flag && edt_mobile_no.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter Mobile Number "); + } else if (!no_mobile_no_flag && edt_mobile_no.getText().toString().length() < 10) { + AlertandMessages.showToastMsg(context, "Please Enter Atleast 10 Digit Contact Number "); + } else if (checkindex() && rl_term_condition.isEnabled() && otp_code.isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Check Terms & Condition"); + } else if (!edt_email_address.getText().toString().isEmpty() && !CommonFunctions.isValidEmail(edt_email_address.getText().toString())) { + AlertandMessages.showToastMsg(context, "Please Enter Valid Email Id "); + } else if (demo_given_str.isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Select Demo Given "); + } else if (product_sold_str.isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Select Product Sold "); + } else if (str_sourceof_sales.isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Select Source of visit"); + } else if (skin_genius_str.isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Select Skin Genius "); + } else if (maybelline_vto.isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Select Maybelline VTO "); + } else if (product_sold_str.equalsIgnoreCase("Yes") && selected_list.isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Add First "); + } else if (!no_mobile_no_flag && flag_for_term_condition && edt_otp.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter OTP"); + } else if (!no_mobile_no_flag && flag_for_term_condition && !checkotp_validation()) { + AlertandMessages.showToastMsg(context, "Incorrect OTP"); + } else if (checkdemoorskinVTO() && product_sold_str.equalsIgnoreCase("No")) { + AlertandMessages.showToastMsg(context, "You Cannot Save If 'Demo Given' and 'Skin Genius' and 'Maybelline VTO' and 'Product Sale' are 'No'."); + } else { + AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle(R.string.parinaam).setMessage(R.string.alertsaveData); + builder.setPositiveButton(android.R.string.yes, (dialogInterface, i) -> { + try { + dialogInterface.dismiss(); + if (product_sold_str.equalsIgnoreCase("No")) { + selected_list.clear(); + object = new InvoiceGetterSetter(); + object = returnobject(); + + object.setQuantity("0"); + object.setProduct(""); + object.setProduct_Id("0"); + object.setProduct_rate("0"); + object.setDiscount(0.0); + object.setScan_ean_code_or_enterd_ean_code(""); + object.setSkuType(""); + object.setStr_invoiceType(""); + object.setPromo_flag(false); + object.setPromo_type(""); + object.setPromotion_name(""); + object.setPromotion_Id("0"); + selected_list.add(object); + ////prepare products for hashmap.......... + prepareListData(); + long l = calculate_data_insert_data(); + if (l > 0) { + CommonFunctions.call_upload(context); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + ConsumerUserDetailsActivity.this.finish(); + } else { + AlertandMessages.showToastMsg(context, "Data not Saved.Please try again."); + } + + } else { + ///--------Check Promotion-------------- + db.open(); + db.insert_temp_sales_data(visit_date, CounterId, selected_list); + if (check_isPromo() && !product_add_flag) { + drawer_layout_recycle_store.setAdapter(new ValueAdapter(context, selected_list)); + drawer_layout_recycle_store.setLayoutManager(new LinearLayoutManager(context)); + startActivity(new Intent(context, InvoiceReportProformaActivity.class) + .putExtra(CommonString.TAG_OBJECT, selected_list) + .putExtra(CommonString.Key_For_Consumer_Update, flag_for_consumer_Update) + .putExtra(CommonString.Key_For_Reciept_Count, String.valueOf(reciept_count)) + .putExtra(CommonString.FLAG_FOR_TERMCONDITION, str_termCondition) + .putExtra(CommonString.KEY_IMAGE, str_img_demo_no_sale) + .putExtra("from", from)); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + added_prmo_products = new ArrayList(); + } else if (check_isPromo() && product_add_flag) { + AlertandMessages.showToastMsg(context, "Checking Promotion"); + try { + remove_added_promo_index(); + new LoadTask().execute(true); + } catch (Exception e) { + remove_added_promo_index(); + new LoadTask().execute(true); + } + } else { + ////change ,,,,,,,, + AlertandMessages.showToastMsg(context, "Checking Promotion"); + try { + new LoadTask().execute(true); + } catch (Exception e) { + new LoadTask().execute(true); + } + } + } + } catch (Exception e) { + e.fillInStackTrace(); + } + }); + builder.setNegativeButton(android.R.string.cancel, (dialogInterface, i) -> dialogInterface.cancel()); + builder.show(); + } + + } else if (view.getId() == R.id.btn_sku_list) { + clicked_flag = true; + getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); + if (!no_name_flag && edt_customer.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter Customer Name"); + } else if (!no_mobile_no_flag && edt_mobile_no.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter Mobile Number"); + } else if (!no_mobile_no_flag && edt_mobile_no.getText().toString().length() < 10) { + AlertandMessages.showToastMsg(context, "Please Enter Atleast 10 Digit Contact Number "); + } else if (!edt_email_address.getText().toString().isEmpty() && !CommonFunctions.isValidEmail(edt_email_address.getText().toString())) { + AlertandMessages.showToastMsg(context, "Please Enter Valid Email Id "); + } else if (demo_given_str.isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Select Demo Given "); + } else if (product_sold_str.isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Select Product Sold "); + } else if (str_sourceof_sales.isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Select Source of visit"); + } else if (skin_genius_str.isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Select Skin Genius "); + } else if (maybelline_vto.isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Select Maybelline VTO "); + } else { + show_dialog_forsku_categorywise(context); + } + + } else if (view.getId() == R.id.posm_btn_first) { + if (!no_name_flag && edt_customer.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter Customer Name"); + } else if (!no_mobile_no_flag && edt_mobile_no.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter Mobile Number"); + } else if (!no_mobile_no_flag && edt_mobile_no.getText().toString().length() < 10) { + AlertandMessages.showToastMsg(context, "Please Enter Atleast 10 Digit Contact Number "); + } else if (!edt_email_address.getText().toString().isEmpty() && !CommonFunctions.isValidEmail(edt_email_address.getText().toString())) { + AlertandMessages.showToastMsg(context, "Please Enter Valid Email Id "); + } else { + promotion_btn_first.setBackground(getResources().getDrawable(R.drawable.rouded_corner)); + promotion_btn_first.setTextColor(getResources().getColor(R.color.white)); + promotion_btn_second.setBackground(getResources().getDrawable(R.drawable.round_btn_color_primary)); + promotion_btn_second.setTextColor(getResources().getColor(R.color.grayfor_login)); + demo_given_str = "Yes"; + if (response_term_condition.equals("1")) { + rl_demo_img.setVisibility(View.VISIBLE); + } else if (flag_for_term_condition) { + rl_demo_img.setVisibility(View.VISIBLE); + } else { + rl_demo_img.setVisibility(View.GONE); + } + //////open demo image layout + } + + } + + ///for Skin Genius + else if (view.getId() == R.id.skingn_btn_yes) { + if (!no_name_flag && edt_customer.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter Customer Name"); + } else if (!no_mobile_no_flag && edt_mobile_no.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter Mobile Number"); + } else if (!no_mobile_no_flag && edt_mobile_no.getText().toString().length() < 10) { + AlertandMessages.showToastMsg(context, "Please Enter Atleast 10 Digit Contact Number "); + } else if (!edt_email_address.getText().toString().isEmpty() && !CommonFunctions.isValidEmail(edt_email_address.getText().toString())) { + AlertandMessages.showToastMsg(context, "Please Enter Valid Email Id "); + } else { + skingn_btn_yes.setBackground(getResources().getDrawable(R.drawable.rouded_corner)); + skingn_btn_yes.setTextColor(getResources().getColor(R.color.white)); + skingn_btn_no.setBackground(getResources().getDrawable(R.drawable.round_btn_color_primary)); + skingn_btn_no.setTextColor(getResources().getColor(R.color.grayfor_login)); + skin_genius_str = "Yes"; + } + + } + + ///for Maybelline Vto yes + else if (view.getId() == R.id.maybelline_btn_yes) { + if (!no_name_flag && edt_customer.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter Customer Name"); + } else if (!no_mobile_no_flag && edt_mobile_no.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter Mobile Number"); + } else if (!no_mobile_no_flag && edt_mobile_no.getText().toString().length() < 10) { + AlertandMessages.showToastMsg(context, "Please Enter Atleast 10 Digit Contact Number "); + } else if (!edt_email_address.getText().toString().isEmpty() && !CommonFunctions.isValidEmail(edt_email_address.getText().toString())) { + AlertandMessages.showToastMsg(context, "Please Enter Valid Email Id "); + } else { + maybelline_btn_yes.setBackground(getResources().getDrawable(R.drawable.rouded_corner)); + maybelline_btn_yes.setTextColor(getResources().getColor(R.color.white)); + maybelline_btn_no.setBackground(getResources().getDrawable(R.drawable.round_btn_color_primary)); + maybelline_btn_no.setTextColor(getResources().getColor(R.color.grayfor_login)); + maybelline_vto = "Yes"; + } + + } else if (view.getId() == R.id.skingn_btn_no) { + if (!no_name_flag && edt_customer.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter Customer Name"); + } else if (!no_mobile_no_flag && edt_mobile_no.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter Mobile Number"); + } else if (!no_mobile_no_flag && edt_mobile_no.getText().toString().length() < 10) { + AlertandMessages.showToastMsg(context, "Please Enter Atleast 10 Digit Contact Number "); + } else if (!edt_email_address.getText().toString().isEmpty() && !CommonFunctions.isValidEmail(edt_email_address.getText().toString())) { + AlertandMessages.showToastMsg(context, "Please Enter Valid Email Id "); + } else { + skingn_btn_no.setBackground(getResources().getDrawable(R.drawable.rouded_corner)); + skingn_btn_no.setTextColor(getResources().getColor(R.color.white)); + skingn_btn_yes.setBackground(getResources().getDrawable(R.drawable.round_btn_color_primary)); + skingn_btn_yes.setTextColor(getResources().getColor(R.color.grayfor_login)); + skin_genius_str = "No"; + } + + } + + ///Maybelline VTO No + else if (view.getId() == R.id.maybelline_btn_no) { + if (!no_name_flag && edt_customer.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter Customer Name"); + } else if (!no_mobile_no_flag && edt_mobile_no.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter Mobile Number"); + } else if (!no_mobile_no_flag && edt_mobile_no.getText().toString().length() < 10) { + AlertandMessages.showToastMsg(context, "Please Enter Atleast 10 Digit Contact Number "); + } else if (!edt_email_address.getText().toString().isEmpty() && !CommonFunctions.isValidEmail(edt_email_address.getText().toString())) { + AlertandMessages.showToastMsg(context, "Please Enter Valid Email Id "); + } else { + maybelline_btn_no.setBackground(getResources().getDrawable(R.drawable.rouded_corner)); + maybelline_btn_no.setTextColor(getResources().getColor(R.color.white)); + maybelline_btn_yes.setBackground(getResources().getDrawable(R.drawable.round_btn_color_primary)); + maybelline_btn_yes.setTextColor(getResources().getColor(R.color.grayfor_login)); + maybelline_vto = "No"; + } + + } else if (view.getId() == R.id.posm_btn_second) { + if (!no_name_flag && edt_customer.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter Customer Name"); + } else if (!no_mobile_no_flag && edt_mobile_no.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter Mobile Number"); + } else if (!no_mobile_no_flag && edt_mobile_no.getText().toString().length() < 10) { + AlertandMessages.showToastMsg(context, "Please Enter Atleast 10 Digit Contact Number "); + } else if (!edt_email_address.getText().toString().isEmpty() && !CommonFunctions.isValidEmail(edt_email_address.getText().toString())) { + AlertandMessages.showToastMsg(context, "Please Enter Valid Email Id "); + } else { + promotion_btn_second.setBackground(getResources().getDrawable(R.drawable.rouded_corner)); + promotion_btn_second.setTextColor(getResources().getColor(R.color.white)); + promotion_btn_first.setBackground(getResources().getDrawable(R.drawable.round_btn_color_primary)); + promotion_btn_first.setTextColor(getResources().getColor(R.color.grayfor_login)); + + sale_btn_no.setBackground(getResources().getDrawable(R.drawable.rouded_corner)); + sale_btn_no.setTextColor(getResources().getColor(R.color.white)); + sale_btn_yes.setBackground(getResources().getDrawable(R.drawable.round_btn_color_primary)); + sale_btn_yes.setTextColor(getResources().getColor(R.color.grayfor_login)); + + demo_given_str = "No"; + str_img_demo_no_sale = ""; + rl_demo_img.setVisibility(View.GONE); + img_only_demo.setImageResource(R.mipmap.camera_bs); + } + + } else if (view.getId() == R.id.sale_btn_no) { + if (!no_name_flag && edt_customer.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter Customer Name"); + } else if (!no_mobile_no_flag && edt_mobile_no.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter Mobile Number"); + } else if (!no_mobile_no_flag && edt_mobile_no.getText().toString().length() < 10) { + AlertandMessages.showToastMsg(context, "Please Enter Atleast 10 Digit Contact Number "); + } else if (!edt_email_address.getText().toString().isEmpty() && !CommonFunctions.isValidEmail(edt_email_address.getText().toString())) { + AlertandMessages.showToastMsg(context, "Please Enter Valid Email Id "); + } else { + sale_btn_no.setBackground(getResources().getDrawable(R.drawable.rouded_corner)); + sale_btn_no.setTextColor(getResources().getColor(R.color.white)); + sale_btn_yes.setBackground(getResources().getDrawable(R.drawable.round_btn_color_primary)); + sale_btn_yes.setTextColor(getResources().getColor(R.color.grayfor_login)); + card_layout_scan.setVisibility(View.GONE); + card_layout_title.setVisibility(View.GONE); + drawer_layout_recycle_store.setVisibility(View.GONE); + rlSalesSource.setVisibility(View.VISIBLE); + product_sold_str = "No"; + } + + } else if (view.getId() == R.id.sale_btn_yes) { + if (!no_name_flag && edt_customer.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter Customer Name"); + } else if (!no_mobile_no_flag && edt_mobile_no.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter Mobile Number"); + } else if (!no_mobile_no_flag && edt_mobile_no.getText().toString().length() < 10) { + AlertandMessages.showToastMsg(context, "Please Enter Atleast 10 Digit Contact Number "); + } else if (!edt_email_address.getText().toString().isEmpty() && !CommonFunctions.isValidEmail(edt_email_address.getText().toString())) { + AlertandMessages.showToastMsg(context, "Please Enter Valid Email Id "); + } else { + if (flag_for_consumer_Update != null && flag_for_consumer_Update.equals("1")) { + if (selected_list != null && !selected_list.isEmpty()) { + if (selected_list.get(0).getProduct_Id().equals("0")) { + selected_list.clear(); + } + } + } + sale_btn_yes.setBackground(getResources().getDrawable(R.drawable.rouded_corner)); + sale_btn_yes.setTextColor(getResources().getColor(R.color.white)); + sale_btn_no.setBackground(getResources().getDrawable(R.drawable.round_btn_color_primary)); + sale_btn_no.setTextColor(getResources().getColor(R.color.grayfor_login)); + card_layout_scan.setVisibility(View.VISIBLE); + card_layout_title.setVisibility(View.VISIBLE); + drawer_layout_recycle_store.setVisibility(View.VISIBLE); + product_sold_str = "Yes"; + rl_complete_layout.setVisibility(View.VISIBLE); + img_visble.setVisibility(View.VISIBLE); + rlSalesSource.setVisibility(View.VISIBLE); + + } + + } else if (view.getId() == R.id.draft_fab) { + ((ConsumerUserDetailsActivity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); + if (!no_name_flag && edt_customer.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter Customer Name"); + } else if (!no_mobile_no_flag && edt_mobile_no.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter Mobile Number"); + } else if (!no_mobile_no_flag && edt_mobile_no.getText().toString().length() < 10) { + AlertandMessages.showToastMsg(context, "Please Enter Atleast 10 Digit Contact Number"); + } else if (checkindex() && rl_term_condition.isEnabled() && otp_code.isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Check Terms & Condition"); + } else if (!edt_email_address.getText().toString().isEmpty() && !CommonFunctions.isValidEmail(edt_email_address.getText().toString())) { + AlertandMessages.showToastMsg(context, "Please Enter Valid Email Id"); + } else if (demo_given_str.isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Select Demo Given"); + } else if (product_sold_str.isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Select Product Sold"); + } else if (str_sourceof_sales.isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Select Source of visit"); + } else if (skin_genius_str.isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Select Skin Genius "); + } else if (maybelline_vto.isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Select Maybelline VTO "); + } else if (product_sold_str.equalsIgnoreCase("Yes") && selected_list.isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Add First"); + } else if (flag_for_term_condition && edt_otp.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter OTP"); + } else if (flag_for_term_condition && !checkotp_validation()) { + AlertandMessages.showToastMsg(context, "Incorrect OTP"); + } else if (checkdemoorskinVTO() && product_sold_str.equalsIgnoreCase("No")) { + AlertandMessages.showToastMsg(context, "You Cannot Save If 'Demo Given' and 'Skin Genius' and 'Maybelline VTO' and 'Product Sale' are 'No'."); + } else { + AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle(R.string.dialog_title).setMessage(R.string.alertsaveData); + builder.setPositiveButton(android.R.string.yes, (dialogInterface, i) -> { + if (product_sold_str.equalsIgnoreCase("No")) { + selected_list.clear(); + object = new InvoiceGetterSetter(); + object = returnobject(); + object.setQuantity("0"); + object.setProduct(""); + object.setProduct_Id("0"); + object.setProduct_rate("0"); + object.setDiscount(0.0); + object.setScan_ean_code_or_enterd_ean_code(""); + object.setSkuType(""); + object.setStr_invoiceType(""); + ////addd promo column + object.setPromo_flag(false); + object.setPromo_type(""); + object.setPromotion_name(""); + object.setPromotion_Id("0"); + selected_list.add(object); + ////prepare products for hashmap.......... + prepareListData(); + long l = calculate_data_insert_data(); + if (l > 0) { + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + ConsumerUserDetailsActivity.this.finish(); + dialogInterface.dismiss(); + } else { + AlertandMessages.showToastMsg(context, "Data not Saved.Please try again."); + } + } else { + calculate_invoice_added_data(selected_list); + prepareListData(); + long l = calculate_data_insert_data(); + if (l > 0) { + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + ConsumerUserDetailsActivity.this.finish(); + dialogInterface.dismiss(); + } else { + AlertandMessages.showToastMsg(context, "Data not Saved.Please try again."); + } + } + }); + builder.setNegativeButton(android.R.string.cancel, (dialogInterface, i) -> dialogInterface.cancel()); + builder.show(); + + } + } + } + + private boolean checkdemoorskinVTO() { + boolean flag = true; + if (!demo_given_str.isEmpty() && demo_given_str.equalsIgnoreCase("Yes") || !skin_genius_str.isEmpty() && skin_genius_str.equalsIgnoreCase("Yes") || !maybelline_vto.isEmpty() && maybelline_vto.equalsIgnoreCase("Yes")) { + flag = false; + } + return flag; + } + + + private long calculate_data_insert_data() { + long l = 0; + if (flag_for_consumer_Update != null && flag_for_consumer_Update.equals("1")) { + db.open(); + db.deleteconsumersale(visit_date, (reciept_count), username); + db.open(); + if (!checkdemoorskinVTO() && product_sold_str.equalsIgnoreCase("No")) { + l = db.insert_consumer_sales_data(username, visit_date, CounterId, String.valueOf(total), + true, CommonFunctions.getUUID(context), str_termCondition, listDataChild, listDataHeader, + str_img_demo_no_sale, from); + } else { + l = db.insert_consumer_sales_data(username, visit_date, CounterId, String.valueOf(total), + false, CommonFunctions.getUUID(context), str_termCondition, listDataChild, listDataHeader, + str_img_demo_no_sale, from); + } + } else { + db.open(); + if (!checkdemoorskinVTO() && product_sold_str.equalsIgnoreCase("No")) { + l = db.insert_consumer_sales_data(username, visit_date, CounterId, String.valueOf(total), + true, CommonFunctions.getUUID(context), str_termCondition, listDataChild, listDataHeader, + str_img_demo_no_sale, from); + } else { + l = db.insert_consumer_sales_data(username, visit_date, CounterId, String.valueOf(total), + false, CommonFunctions.getUUID(context), str_termCondition, listDataChild, listDataHeader, + str_img_demo_no_sale, from); + } + } + return l; + } + + private void prepareListData() { + listDataHeader = new ArrayList<>(); + listDataChild = new HashMap<>(); + listDataHeader.add(selected_list.get(0)); + listDataHeader.size();// Adding child data + for (int i = 0; i < listDataHeader.size(); i++) { + listDataChild.put(listDataHeader.get(i), selected_list); // Header, Child data + } + } + + + @SuppressLint("SetTextI18n") + private void show_proforma_dialog(final Context context, final boolean flag_for_rl) { + minteger = 0; + final MultiPurposeDialog multiPDialog = new MultiPurposeDialog(context); + multiPDialog.requestWindowFeature(Window.FEATURE_NO_TITLE); + multiPDialog.setContentView(R.layout.custom_bar_code_dialog); + multiPDialog.setCancelable(false); + WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); + lp.copyFrom(Objects.requireNonNull(multiPDialog.getWindow()).getAttributes()); + lp.width = WindowManager.LayoutParams.MATCH_PARENT; + lp.height = WindowManager.LayoutParams.WRAP_CONTENT; + lp.gravity = Gravity.CENTER; + multiPDialog.getWindow().setAttributes(lp); + multiPDialog.setCancelable(false); + multiPDialog.show(); + //for actual Quantity form Tstock_Summery + rl_actual_qty = (LinearLayout) multiPDialog.findViewById(R.id.rl_actual_qty); + actual_qty_dialog = (TextView) multiPDialog.findViewById(R.id.actual_qty_dialog); + + + LinearLayout rl_bar_code = (LinearLayout) multiPDialog.findViewById(R.id.rl_bar_code); + LinearLayout RL_scan_code = (LinearLayout) multiPDialog.findViewById(R.id.RL_scan_code); + Button check_exist_sku = (Button) multiPDialog.findViewById(R.id.check_exist_sku); + TextView txt_bar_code = multiPDialog.findViewById(R.id.txt_bar_code); + TextView txt_enterbar_code = multiPDialog.findViewById(R.id.txt_enterbar_code); + LinearLayout rl_quantity = (LinearLayout) multiPDialog.findViewById(R.id.rl_quantity); + RecyclerView recycl_mutliennter_qty = (RecyclerView) multiPDialog.findViewById(R.id.recycl_mutliennter_qty); + recycl_mutliennter_qty.setVisibility(View.GONE); + rl_quantity.setVisibility(View.VISIBLE); + + sku_name = multiPDialog.findViewById(R.id.sku_name); + if (flag_for_rl) { + RL_scan_code.setVisibility(View.GONE); + rl_bar_code.setVisibility(View.VISIBLE); + txt_bar_code.setVisibility(View.VISIBLE); + txt_enterbar_code.setVisibility(View.GONE); + } else { + rl_bar_code.setVisibility(View.GONE); + txt_bar_code.setVisibility(View.GONE); + RL_scan_code.setVisibility(View.VISIBLE); + txt_enterbar_code.setVisibility(View.VISIBLE); + } + + qrcode_text = (TextView) multiPDialog.findViewById(R.id.qrcode_text); + edt_scan_code = (EditText) multiPDialog.findViewById(R.id.edt_scan_code); + final Button stock_img_minus = (Button) multiPDialog.findViewById(R.id.stock_img_minus); + Button stock_img_plus = (Button) multiPDialog.findViewById(R.id.stock_img_plus); + stock_text_value = (TextView) multiPDialog.findViewById(R.id.stock_text_value); + + ImageView img_bar_code = (ImageView) multiPDialog.findViewById(R.id.img_bar_code); + ImageView cancet_btn = (ImageView) multiPDialog.findViewById(R.id.cancet_btn); + final ImageView btn_add = (ImageView) multiPDialog.findViewById(R.id.btn_add); + btn_add.setVisibility(View.VISIBLE); + + stock_img_plus.setOnClickListener(v -> { + if (!product_Id.equals("0")) { + db.open(); + if (db.getActualSaleableStock(product_Id, null, visit_date, CounterId, from).getStock() == 0) { + AlertandMessages.showToastMsg(context, "Stock for this Product is Zero. Cannot allow to add this Product"); + } else { + minteger = minteger + 1; + db.open(); + if (db.getActualSaleableStock(product_Id, null, visit_date, CounterId, from).getStock() > 0 && minteger > db.getActualSaleableStock(product_Id, null, visit_date, CounterId, from).getStock()) { + minteger = minteger - 1; + AlertandMessages.showToastMsg(context, "Stock Low. Please reduce sale quantity below or equal to the stock value"); + } else { + stock_text_value.setText("" + minteger); + } + } + } + }); + + stock_img_minus.setOnClickListener(v -> { + if (minteger == 0) { + AlertandMessages.showToastMsg(context, "Product quantity should not be less than Zero"); + } else { + minteger = minteger - 1; + stock_text_value.setText("" + minteger); + } + }); + + cancet_btn.setOnClickListener(v -> { + if (multiPDialog.isShowing()) { + multiPDialog.dismiss(); + } + sku_name.setText(""); + stock_text_value.setText(""); + qrcode_text.setText(""); + product_scan_code = ""; + product_name = ""; + product_mrp = ""; + product_Id = "0"; + productType = ""; + discount = 0.0; + sku_name.setVisibility(View.GONE); + }); + + check_exist_sku.setOnClickListener(v -> { + if (!flag_for_rl && edt_scan_code.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter Bar Code"); + } else { + db.open(); + ArrayList productList = db.getsku_fromproductusing_eancode(edt_scan_code.getText().toString(), true, visit_date, CounterId, from); + if (productList.isEmpty()) { + db.open(); + productList = db.getsku_fromproductusing_eancode(removeFirstChar(edt_scan_code.getText().toString()), true, visit_date, CounterId, from); + } + if (productList.isEmpty()) { + edt_scan_code.setText(""); + AlertandMessages.showToastMsg(context, "Invalid Bar Code.Please try again"); + } else { + show_dialog_forsku(context, productList, rl_actual_qty, actual_qty_dialog); + } + } + }); + + + btn_add.setOnClickListener(v -> { + db.open(); + if (db.getActualSaleableStock(product_Id, null, visit_date, CounterId, from).getStock() == 0) { + AlertandMessages.showToastMsg(context, "Stock for this Product is Zero. Cannot allow to add this Product"); + if (multiPDialog.isShowing()) { + multiPDialog.dismiss(); + } + + stock_text_value.setText(""); + qrcode_text.setText(""); + edt_scan_code.setText(""); + product_scan_code = ""; + product_name = ""; + product_mrp = ""; + product_Id = "0"; + productType = ""; + discount = 0.0; + sku_name.setText(""); + sku_name.setVisibility(View.GONE); + + } else { + // get selected radio button from radioGroup + int selectedId = radioSexGroup.getCheckedRadioButtonId(); + // find the radiobutton by returned id + radioSexButton = (RadioButton) findViewById(selectedId); + if (flag_for_rl && qrcode_text.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Scan Bar Code"); + } else if (!flag_for_rl && edt_scan_code.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter Bar Code "); + } else if (stock_text_value.getText().toString().equals("0")) { + AlertandMessages.showToastMsg(context, "Please add Atleast One Product Quantity "); + } else { + if (checkduplicate_entry()) { + if (!flag_for_rl) { + product_scan_code = edt_scan_code.getText().toString(); + db.open(); + if (db.getsku_fromproductusing_eancode(product_scan_code, true, visit_date, CounterId, from).isEmpty()) { + AlertandMessages.showToastMsg(context, "Product not found "); + } else { + minteger = 0; + if (multiPDialog.isShowing()) { + multiPDialog.dismiss(); + } + object = new InvoiceGetterSetter(); + object = returnobject(); + object.setProduct(product_name); + object.setProduct_Id(product_Id); + object.setProduct_rate(product_mrp); + object.setDiscount(discount); + object.setQuantity(stock_text_value.getText().toString()); + object.setSkuType(productType); + object.setStr_invoiceType(dialog_invoiceType); + object.setPromo_flag(false); + object.setPromo_type(""); + object.setPromotion_name(""); + object.setPromotion_Id("0"); + selected_list.add(object); + + current_total_stock.setText("Total : " + calculate_total_consume(selected_list)); + stock_text_value.setText(""); + qrcode_text.setText(""); + edt_scan_code.setText(""); + product_scan_code = ""; + product_name = ""; + product_mrp = ""; + product_Id = "0"; + productType = ""; + discount = 0.0; + sku_name.setText(""); + sku_name.setVisibility(View.GONE); + drawer_layout_recycle_store.setAdapter(new ValueAdapter(context, selected_list)); + drawer_layout_recycle_store.setLayoutManager(new LinearLayoutManager(context)); + product_add_flag = true; + } + } else { + if (multiPDialog.isShowing()) { + multiPDialog.dismiss(); + } + minteger = 0; + object = new InvoiceGetterSetter(); + object = returnobject(); + object.setQuantity(stock_text_value.getText().toString()); + object.setProduct(product_name); + object.setProduct_Id(product_Id); + object.setDiscount(discount); + object.setProduct_rate(product_mrp); + object.setSkuType(productType); + object.setStr_invoiceType(dialog_invoiceType); + object.setPromo_flag(false); + object.setPromo_type(""); + object.setPromotion_name(""); + object.setPromotion_Id("0"); + selected_list.add(object); + + current_total_stock.setText("Total : " + calculate_total_consume(selected_list)); + sku_name.setText(""); + stock_text_value.setText(""); + qrcode_text.setText(""); + product_scan_code = ""; + product_name = ""; + product_mrp = ""; + product_Id = "0"; + productType = ""; + discount = 0.0; + sku_name.setVisibility(View.GONE); + drawer_layout_recycle_store.setAdapter(new ValueAdapter(context, selected_list)); + drawer_layout_recycle_store.setLayoutManager(new LinearLayoutManager(context)); + product_add_flag = true; + } + } + } + } + }); + + img_bar_code.setOnClickListener(v -> openScanner()); + + multiPDialog.show(); + } + + + private void openScanner() { + IntentIntegrator intentIntegrator = new IntentIntegrator((Activity) context); + intentIntegrator.setBeepEnabled(true); + intentIntegrator.setOrientationLocked(false); + intentIntegrator.setPrompt("Scan the barcode or QR code to get the data"); + intentIntegrator.initiateScan(); + } + + private void adapterforAgeLimit_SkinType() { + ///for source of sales + sourceofsalesAdapter = new ArrayAdapter<>(context, R.layout.spinner_custom_item); + sourceofsalesAdapter.add("- Select Source of visit -"); + for (int i = 0; i < sourceofsaleslist.size(); i++) { + sourceofsalesAdapter.add(sourceofsaleslist.get(i).getSourcesOfSale()); + } + spinSourceof_sales.setAdapter(sourceofsalesAdapter); + sourceofsalesAdapter.setDropDownViewResource(R.layout.spinner_custom_item); + spinSourceof_sales.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { + @Override + public void onItemSelected(AdapterView adapterView, View view, int pos, long l) { + if (pos != 0) { + try { + str_sourceof_sales = sourceofsaleslist.get(pos - 1).getSourcesOfSale(); + rl_complete_layout.setVisibility(View.VISIBLE); + img_visble.setVisibility(View.VISIBLE); + } catch (Exception e) { + throw new RuntimeException(e); + } + } else { + str_sourceof_sales = ""; + } + } + + @Override + public void onNothingSelected(AdapterView adapterView) { + } + }); + + ///for Age Adapter + AgeAdapter = new ArrayAdapter<>(context, R.layout.spinner_custom_item); + AgeAdapter.add("- Select Age Range -"); + + for (int i = 0; i < ageLimits.size(); i++) { + AgeAdapter.add(ageLimits.get(i).getAgeLimit()); + } + + spin_age.setAdapter(AgeAdapter); + AgeAdapter.setDropDownViewResource(R.layout.spinner_custom_item); + spin_age.setOnItemSelectedListener(this); + + SkinTypeAdapter = new ArrayAdapter<>(context, R.layout.spinner_custom_item); + SkinTypeAdapter.add("- Select Skin Type -"); + + for (int i = 0; i < skinTypes.size(); i++) { + SkinTypeAdapter.add(skinTypes.get(i).getSkinType()); + } + + spin_skin_type.setAdapter(SkinTypeAdapter); + SkinTypeAdapter.setDropDownViewResource(R.layout.spinner_custom_item); + spin_skin_type.setOnItemSelectedListener(this); + db.open(); + dialog_product_list = db.getproduct_masterlist("T_StockSummary", visit_date, CounterId, from); + } + + @Override + public void onItemSelected(AdapterView adapterView, View view, int pos, long l) { + + } + + @Override + public void onNothingSelected(AdapterView adapterView) { + + } + + private static class MultiPurposeDialog extends Dialog { + private MultiPurposeDialog(Context context) { + super(context); + // DIALOG USER_INTERFACE TEMPLATE + WindowManager.LayoutParams wmLayoutParams = Objects.requireNonNull(getWindow()).getAttributes(); + wmLayoutParams.gravity = Gravity.CENTER; + getWindow().setAttributes(wmLayoutParams); + setTitle(null); + setCancelable(false); + setOnCancelListener(null); + LinearLayout layout = new LinearLayout(context); + layout.setOrientation(LinearLayout.VERTICAL); + } + } + + @SuppressLint("UseCompatLoadingForDrawables") + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data); + if (result == null) { + switch (resultCode) { + case 0: + Log.i("MakeMachine", "User cancelled"); + break; + case -1: + if (_pathforcheck != null && !_pathforcheck.isEmpty()) { + if (new File(CommonString.getImagesFolder(context) + _pathforcheck).exists()) { + convertBitmap(CommonString.getImagesFolder(context) + _pathforcheck); + img_only_demo.setImageDrawable(getResources().getDrawable(R.mipmap.camera_bsd)); + str_img_demo_no_sale = _pathforcheck; + _pathforcheck = ""; + } + } + + break; + } + } else if (result != null) { + if (result.getContents() == null) { + //test("ScanActivity", "Cancelled scan"); + Toast.makeText(this, "Cancelled", Toast.LENGTH_SHORT).show(); + } else { + + db.open(); + ArrayList productList = db.getsku_fromproductusing_eancode(result.getContents(), true, visit_date, CounterId, from); + if (productList.isEmpty()) { + db.open(); + productList = db.getsku_fromproductusing_eancode(removeFirstChar(result.getContents()), true, visit_date, CounterId, from); + } + + if (!productList.isEmpty()) { + show_dialog_forsku(context, productList, rl_actual_qty, actual_qty_dialog); + sku_name.setText(productList.get(0).getProductName()); + sku_name.setVisibility(View.VISIBLE); + stock_text_value.setText("0"); + minteger = 0; + } else { + minteger = 0; + product_name = ""; + product_scan_code = ""; + qrcode_text.setText(""); + AlertandMessages.showToastMsg(context, "Unable To Scan Correct Data. Please Try Again."); + } + } + + } else + super.onActivityResult(requestCode, resultCode, data); + } + + + private class ValueAdapter extends RecyclerView.Adapter { + private final LayoutInflater inflator; + ArrayList data; + int added_value = 0; + + + public ValueAdapter(Context context, ArrayList data) { + inflator = LayoutInflater.from(context); + this.data = data; + } + + @NonNull + @Override + public ValueAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) { + View view = inflator.inflate(R.layout.row_adapter_proforma_sale, parent, false); + return new ValueAdapter.MyViewHolder(view); + } + + @SuppressLint("SetTextI18n") + @Override + public void onBindViewHolder(@NonNull final ValueAdapter.MyViewHolder holder, @SuppressLint("RecyclerView") final int position) { + final InvoiceGetterSetter current = data.get(position); + + if (current.isPromo_flag() && current.getPromo_type().equalsIgnoreCase("OffSameProduct")) { + holder.select_promo_productRl.setVisibility(View.VISIBLE); + holder.select_promo_productRl.setId(position); + + holder.select_productRl.setVisibility(View.GONE); + holder.select_productRl.setId(position); + + if (CommonFunctions.isTablet(context)) { + holder.txt_promo_str.setText("Applied Promo - " + current.getPromotion_name() + " - " + "Discounted Rs - " + current.getProduct()); + holder.txt_promo_str.setId(position); + } else { + holder.txt_promo_str.setText("Applied Promo - " + current.getPromotion_name() + "\n" + "Discounted Rs - " + current.getProduct()); + holder.txt_promo_str.setId(position); + } + } else if (current.isPromo_flag() && current.getPromo_type().equalsIgnoreCase("OffAdditionalProduct")) { + holder.select_promo_productRl.setVisibility(View.VISIBLE); + holder.select_promo_productRl.setId(position); + holder.select_productRl.setVisibility(View.GONE); + holder.select_productRl.setId(position); + + if (CommonFunctions.isTablet(context)) { + holder.txt_promo_str.setText("Applied Promo - " + current.getPromotion_name() + " - " + "Discounted Rs - " + current.getProduct()); + holder.txt_promo_str.setId(position); + } else { + holder.txt_promo_str.setText("Applied Promo - " + current.getPromotion_name() + "\n" + "Discounted Rs - " + current.getProduct()); + holder.txt_promo_str.setId(position); + } + } else if (current.isPromo_flag() && current.getPromo_type().equalsIgnoreCase("ValueOffAdditionalProduct")) { + holder.select_promo_productRl.setVisibility(View.VISIBLE); + holder.select_promo_productRl.setId(position); + holder.select_productRl.setVisibility(View.GONE); + holder.select_productRl.setId(position); + + if (CommonFunctions.isTablet(context)) { + holder.txt_promo_str.setText("Applied Promo - " + current.getPromotion_name() + " - " + "Discounted Rs - " + current.getProduct()); + holder.txt_promo_str.setId(position); + } else { + holder.txt_promo_str.setText("Applied Promo - " + current.getPromotion_name() + "\n" + "Discounted Rs - " + current.getProduct()); + holder.txt_promo_str.setId(position); + } + + } else if (current.isPromo_flag() && current.getPromo_type().equalsIgnoreCase("OffWorth") || current.isPromo_flag() && current.getPromo_type().equalsIgnoreCase("WorthWithProduct")) { + holder.select_promo_productRl.setVisibility(View.VISIBLE); + holder.select_promo_productRl.setId(position); + holder.select_productRl.setVisibility(View.GONE); + holder.select_productRl.setId(position); + + if (CommonFunctions.isTablet(context)) { + holder.txt_promo_str.setText("Applied Promo - " + current.getPromotion_name() + " - " + "Discounted Rs - " + current.getProduct()); + holder.txt_promo_str.setId(position); + } else { + holder.txt_promo_str.setText("Applied Promo - " + current.getPromotion_name() + "\n" + "Discounted Rs - " + current.getProduct()); + holder.txt_promo_str.setId(position); + } + + } else if (current.isPromo_flag() && current.getPromo_type().equalsIgnoreCase("OffProduct")) { + + holder.select_promo_productRl.setVisibility(View.GONE); + holder.select_promo_productRl.setId(position); + + holder.select_productRl.setVisibility(View.VISIBLE); + holder.select_productRl.setId(position); + + holder.text_item.setText("Applied Promo - " + current.getPromotion_name() + " - " + current.getProduct() + " - Discounted Rs - " + current.getSkuType()); + holder.text_item.setId(position); + + holder.text_qty.setText(current.getQuantity()); + holder.text_qty.setId(position); + + holder.txt_amount.setText(current.getProduct_rate()); + holder.txt_amount.setId(position); + + } else if (current.isPromo_flag() && current.getPromo_type().equalsIgnoreCase("Worth")) { + holder.select_promo_productRl.setVisibility(View.VISIBLE); + holder.select_promo_productRl.setId(position); + + holder.select_productRl.setVisibility(View.GONE); + holder.select_productRl.setId(position); + + if (CommonFunctions.isTablet(context)) { + holder.txt_promo_str.setText("Applied Promo - " + current.getPromotion_name() + " - " + "Discounted Rs - " + current.getProduct()); + holder.txt_promo_str.setId(position); + } else { + holder.txt_promo_str.setText("Applied Promo - " + current.getPromotion_name() + "\n" + "Discounted Rs - " + current.getProduct()); + holder.txt_promo_str.setId(position); + } + + + } else if (current.isPromo_flag() && current.getPromo_type().equalsIgnoreCase("Gift")) { + holder.select_promo_productRl.setVisibility(View.VISIBLE); + holder.select_promo_productRl.setId(position); + + holder.select_productRl.setVisibility(View.GONE); + holder.select_productRl.setId(position); + + if (CommonFunctions.isTablet(context)) { + holder.txt_promo_str.setText("Applied Promo - " + current.getPromotion_name() + " - " + "Gift - " + current.getProduct()); + holder.txt_promo_str.setId(position); + } else { + holder.txt_promo_str.setText("Applied Promo - " + current.getPromotion_name() + "\n" + "Gift - " + current.getProduct()); + holder.txt_promo_str.setId(position); + } + + } else if (current.isPromo_flag() && current.getPromo_type().equalsIgnoreCase("Product")) { + holder.select_promo_productRl.setVisibility(View.VISIBLE); + holder.select_promo_productRl.setId(position); + + holder.select_productRl.setVisibility(View.GONE); + holder.select_productRl.setId(position); + + if (CommonFunctions.isTablet(context)) { + holder.txt_promo_str.setText("Applied Promo - " + current.getPromotion_name() + " - (" + current.getProduct().toLowerCase() + ")"); + holder.txt_promo_str.setId(position); + } else { + holder.txt_promo_str.setText("Applied Promo - " + current.getPromotion_name() + "\n" + current.getProduct().toLowerCase()); + holder.txt_promo_str.setId(position); + } + } else { + holder.select_promo_productRl.setVisibility(View.GONE); + holder.select_promo_productRl.setId(position); + holder.select_productRl.setVisibility(View.VISIBLE); + holder.select_productRl.setId(position); + + int quantity = Integer.parseInt(current.getQuantity()); + double amount = Double.parseDouble(current.getProduct_rate()); + amount = amount * quantity; + double cCom = ((amount) * current.getDiscount()); + if (current.getDiscount() == 0.0 || current.getDiscount() == 0) { + if (!current.getStr_invoiceType().isEmpty() && current.getStr_invoiceType().equalsIgnoreCase("Sample") || + !current.getStr_invoiceType().isEmpty() && current.getStr_invoiceType().equalsIgnoreCase("GWP")) { + holder.text_item.setText(current.getProduct() + " - Type - " + current.getStr_invoiceType()); + holder.text_item.setId(position); + } else { + holder.text_item.setText(current.getProduct()); + holder.text_item.setId(position); + } + + } else { + String string = current.getDiscount().toString(); + holder.text_item.setText(current.getProduct() + " Discount : " + string.substring(string.length() - 1) + "0%"); + holder.text_item.setId(position); + } + + holder.text_qty.setText(current.getQuantity()); + holder.text_qty.setId(position); + + holder.txt_amount.setText(current.getProduct_rate()); + holder.txt_amount.setId(position); + + } + + + holder.update_img.setOnClickListener(view -> { + product_add_flag = true; + holder.delete_added_product.setVisibility(View.GONE); + holder.delete_added_product.setId(position); + holder.rl_increaseqty.setVisibility(View.VISIBLE); + holder.rl_increaseqty.setId(position); + holder.verify_icon.setVisibility(View.VISIBLE); + holder.verify_icon.setId(position); + + }); + + holder.verify_icon.setOnClickListener(view -> { + product_add_flag = true; + holder.delete_added_product.setVisibility(View.VISIBLE); + holder.delete_added_product.setId(position); + holder.rl_increaseqty.setVisibility(View.GONE); + holder.rl_increaseqty.setId(position); + holder.verify_icon.setVisibility(View.GONE); + holder.verify_icon.setId(position); + holder.update_img.setVisibility(View.VISIBLE); + holder.update_img.setId(position); + current_total_stock.setText("Total : " + calculate_total_consume(selected_list)); + + }); + + holder.stock_img_plus.setOnClickListener(v -> { + db.open(); + product_add_flag = true; + if (flag_for_consumer_Update != null && flag_for_consumer_Update.equals("1")) { + db.open(); + int actual_stock = db.getActualSaleableStock(current.getProduct_Id(), null, visit_date, CounterId, from).getStock(); + if (added_value == actual_stock && actual_stock == 0) { + AlertandMessages.showToastMsg(context, "Stock for this Product is Zero. Cannot allow to add this Product"); + } else { + int minteger = Integer.parseInt(current.getQuantity()); + minteger = minteger + 1; + added_value = added_value + 1; + db.open(); + if (actual_stock > 0 && added_value > actual_stock) { + minteger = minteger - 1; + added_value = added_value - 1; + holder.text_qty.setText("" + minteger); + holder.text_qty.setId(position); + current.setQuantity("" + minteger); + AlertandMessages.showToastMsg(context, "Stock Low. Please reduce sale quantity below or equal to the stock value"); + } else { + holder.text_qty.setText("" + minteger); + holder.text_qty.setId(position); + current.setQuantity("" + minteger); + } + } + } else { + db.open(); + int actual_stock = db.getActualSaleableStock(current.getProduct_Id(), null, visit_date, CounterId, from).getStock(); + if (actual_stock == 0) { + AlertandMessages.showToastMsg(context, "Stock for this Product is Zero. Cannot allow to add this Product"); + } else { + int minteger = Integer.parseInt(current.getQuantity()); + minteger = minteger + 1; + db.open(); + if (actual_stock > 0 && minteger > actual_stock) { + minteger = minteger - 1; + holder.text_qty.setText("" + minteger); + holder.text_qty.setId(position); + current.setQuantity("" + minteger); + AlertandMessages.showToastMsg(context, "Stock Low. Please reduce sale quantity below or equal to the stock value"); + } else { + holder.text_qty.setText("" + minteger); + holder.text_qty.setId(position); + current.setQuantity("" + minteger); + } + } + } + }); + + holder.stock_img_minus.setOnClickListener(v -> { + product_add_flag = true; + int minteger = Integer.parseInt(current.getQuantity()); + if (minteger == 1) { + AlertandMessages.showToastMsg(context, "Product quantity should not be less than One"); + } else { + minteger = minteger - 1; + holder.text_qty.setText("" + minteger); + holder.text_qty.setId(position); + current.setQuantity("" + minteger); + } + }); + + holder.delete_added_product.setOnClickListener(v -> { + product_add_flag = true; + if (tagmode != null && !tagmode.isEmpty() && tagmode.equals("1")) { + AlertDialog.Builder builder = new AlertDialog.Builder(context).setMessage("Are you sure you want to Delete ?").setTitle(getString(R.string.password_rules)).setCancelable(false).setPositiveButton("Yes", new DialogInterface.OnClickListener() { + @SuppressLint("NotifyDataSetChanged") + public void onClick(DialogInterface dialog, int id) { + if (current.getReccept_count() != 0) { + db.delete_sale(visit_date, current.getReccept_count(), username); + data.remove(position); + notifyDataSetChanged(); + if (!data.isEmpty()) { + current_total_stock.setText("Total : " + calculate_total_consume(data)); + ValueAdapter adapter = new ValueAdapter(context, data); + drawer_layout_recycle_store.setAdapter(adapter); + adapter.notifyDataSetChanged(); + } else { + current_total_stock.setText("Total : " + calculate_total_consume(data)); + } + notifyDataSetChanged(); + } else { + data.remove(position); + notifyDataSetChanged(); + if (!data.isEmpty()) { + current_total_stock.setText("Total : " + calculate_total_consume(data)); + ValueAdapter adapter = new ValueAdapter(context, data); + drawer_layout_recycle_store.setAdapter(adapter); + adapter.notifyDataSetChanged(); + } else { + current_total_stock.setText("Total : " + calculate_total_consume(data)); + } + notifyDataSetChanged(); + } + } + }).setNegativeButton("No", (dialog, id) -> dialog.cancel()); + AlertDialog alert = builder.create(); + alert.show(); + } else if (tagmode.isEmpty() && calculate(data) > 0 && calculate(data) > 1) { + AlertDialog.Builder builder = new AlertDialog.Builder(context).setMessage("Are you sure you want to Delete ?").setTitle(getString(R.string.password_rules)).setCancelable(false).setPositiveButton("Yes", new DialogInterface.OnClickListener() { + @SuppressLint("NotifyDataSetChanged") + public void onClick(DialogInterface dialog, int id) { + if (current.getReccept_count() != 0) { + db.open(); + db.delete_sale(visit_date, current.getReccept_count(), username); + data.remove(position); + notifyDataSetChanged(); + if (!data.isEmpty()) { + current_total_stock.setText("Total : " + calculate_total_consume(data)); + ValueAdapter adapter = new ValueAdapter(context, data); + drawer_layout_recycle_store.setAdapter(adapter); + adapter.notifyDataSetChanged(); + } + notifyDataSetChanged(); + + } else { + data.remove(position); + notifyDataSetChanged(); + if (!data.isEmpty()) { + current_total_stock.setText("Total : " + calculate_total_consume(data)); + ValueAdapter adapter = new ValueAdapter(context, data); + drawer_layout_recycle_store.setAdapter(adapter); + adapter.notifyDataSetChanged(); + } + + notifyDataSetChanged(); + } + } + }) + .setNegativeButton("No", + (dialog, id) -> dialog.cancel()); + AlertDialog alert = builder.create(); + alert.show(); + } else if (tagmode.isEmpty()) { + AlertandMessages.showToastMsg(context, "Atleast One Product Has To Be Present"); + } + + }); + } + + @Override + public int getItemCount() { + return data.size(); + } + + class MyViewHolder extends RecyclerView.ViewHolder { + TextView text_item, text_qty, txt_amount, txt_promo_str; + LinearLayout select_promo_productRl, select_productRl, rl_increaseqty, rl_edit; + Button stock_img_minus, stock_img_plus; + ImageView delete_added_product, verify_icon, update_img; + + public MyViewHolder(View itemView) { + super(itemView); + text_item = (TextView) itemView.findViewById(R.id.text_item); + text_qty = (TextView) itemView.findViewById(R.id.text_qty); + txt_amount = (TextView) itemView.findViewById(R.id.txt_amount); + txt_promo_str = (TextView) itemView.findViewById(R.id.txt_promo_str); + delete_added_product = (ImageView) itemView.findViewById(R.id.delete_added_product); + select_promo_productRl = (LinearLayout) itemView.findViewById(R.id.select_promo_productRl); + select_productRl = (LinearLayout) itemView.findViewById(R.id.select_productRl); + rl_increaseqty = (LinearLayout) itemView.findViewById(R.id.rl_increaseqty); + rl_edit = (LinearLayout) itemView.findViewById(R.id.rl_edit); + stock_img_minus = (Button) itemView.findViewById(R.id.stock_img_minus); + stock_img_plus = (Button) itemView.findViewById(R.id.stock_img_plus); + verify_icon = (ImageView) itemView.findViewById(R.id.verify_icon); + update_img = (ImageView) itemView.findViewById(R.id.update_img); + } + } + } + + private int calculate(ArrayList data) { + int size = 0; + try { + if (!data.isEmpty()) { + for (int k = 0; k < data.size(); k++) { + if (!data.get(k).isPromo_flag()) { + size = size + 1; + + } + } + } + } catch (Exception e) { + e.fillInStackTrace(); + } + return size; + } + + public void getotp_from_mobile_no(String jsondata, final MultiPurposeDialog multiDialog) { + try { + loading = ProgressDialog.show(context, "Processing", "Please wait...", false, true); + final OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, + TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build(); + RequestBody jsonData = RequestBody.create(Objects.requireNonNull(MediaType.parse("application/json")), jsondata); + Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build(); + PostApi api = adapter.create(PostApi.class); + retrofit2.Call call = api.getOTPMethod(jsonData); + call.enqueue(new retrofit2.Callback() { + @Override + public void onResponse(@NonNull retrofit2.Call call, @NonNull retrofit2.Response response) { + ResponseBody responseBody = response.body(); + String data = null; + loading.dismiss(); + + if (multiDialog != null && multiDialog.isShowing()) { + multiDialog.dismiss(); + } + + if (loading != null && loading.isShowing()) { + loading.dismiss(); + } + if (responseBody != null && response.isSuccessful()) { + try { + assert response.body() != null; + data = response.body().string(); + JSONObject jObject = new JSONObject(data); + otp_code = jObject.getString("SendOTPResult"); + + } catch (Exception e) { + e.fillInStackTrace(); + loading.dismiss(); + } + } else { + assert loading != null; + loading.dismiss(); + if (loading != null && loading.isShowing()) { + loading.dismiss(); + } + Toast.makeText(context, "Server Not Responding . Please Try Again.", Toast.LENGTH_SHORT).show(); + } + } + + @Override + public void onFailure(@NonNull retrofit2.Call call, @NonNull Throwable t) { + loading.dismiss(); + if (loading != null && loading.isShowing()) { + loading.dismiss(); + } + AlertandMessages.showAlertlogin((Activity) context, getString(R.string.nonetwork)); + } + }); + } catch (Exception e) { + e.fillInStackTrace(); + loading.dismiss(); + } + } + + + @SuppressLint("SetTextI18n") + private void show_dialog_forsku_categorywise(final Context context) { + minteger = 0; + final MultiPurposeDialog multiDialog = new MultiPurposeDialog(context); + multiDialog.requestWindowFeature(Window.FEATURE_NO_TITLE); + multiDialog.setContentView(R.layout.custom_sku_list_with_category); + final WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); + lp.copyFrom(Objects.requireNonNull(multiDialog.getWindow()).getAttributes()); + lp.width = WindowManager.LayoutParams.MATCH_PARENT; + lp.height = WindowManager.LayoutParams.WRAP_CONTENT; + lp.gravity = Gravity.CENTER; + multiDialog.getWindow().setAttributes(lp); + multiDialog.setCancelable(false); + multiDialog.show(); + + dialog_invoiceType = "Saleable"; + ///new changes 19 aug + final Button btn_invoice_type_saleable = (Button) multiDialog.findViewById(R.id.btn_invoice_type_saleable); + final Button btn_invoice_type_sample = (Button) multiDialog.findViewById(R.id.btn_invoice_type_sample); + final Button btn_invoice_type_gwp = (Button) multiDialog.findViewById(R.id.btn_invoice_type_gwp); + final LinearLayout rl_invoice_type = (LinearLayout) multiDialog.findViewById(R.id.rl_invoice_type); + rl_invoice_type.setVisibility(View.VISIBLE); + final Spinner dialog_brand_spin = (Spinner) multiDialog.findViewById(R.id.dialog_brand_spin); + final Spinner dialog_subbrand_spin = (Spinner) multiDialog.findViewById(R.id.dialog_subbrand_spin); + final Spinner dialog_reference_spin = (Spinner) multiDialog.findViewById(R.id.dialog_reference_spin); + final Spinner dialog_product_spin = (Spinner) multiDialog.findViewById(R.id.dialog_product_spin); + final EditText et_search = (EditText) multiDialog.findViewById(R.id.et_search); + final TextView stock_text_value = (TextView) multiDialog.findViewById(R.id.stock_text_value); + final Button stock_img_minus = (Button) multiDialog.findViewById(R.id.stock_img_minus); + Button stock_img_plus = (Button) multiDialog.findViewById(R.id.stock_img_plus); + ImageView cancet_btn = (ImageView) multiDialog.findViewById(R.id.cancet_btn); + final ImageView btn_add = (ImageView) multiDialog.findViewById(R.id.btn_add); + //for actual Quantity form Tstock_Summery + rl_actual_qty = (LinearLayout) multiDialog.findViewById(R.id.rl_actual_qty); + actual_qty_dialog = (TextView) multiDialog.findViewById(R.id.actual_qty_dialog); + TextView txt_current_invoice_type = (TextView) multiDialog.findViewById(R.id.txt_current_invoice_type); + et_search.addTextChangedListener(new TextWatcher() { + @Override + public void beforeTextChanged(CharSequence s, int start, int count, int after) { + } + + @Override + public void onTextChanged(CharSequence s, int start, int before, int count) { + String text = s.toString(); + if (dialog_invoiceType.equalsIgnoreCase("Sample") || dialog_invoiceType.equalsIgnoreCase("GWP")) { + setSearchFilter(db.getproduct_masterlist(dialog_invoiceType, visit_date, CounterId, from), text, dialog_product_spin); + } else { + setSearchFilter(dialog_product_list, text, dialog_product_spin); + } + } + + @Override + public void afterTextChanged(Editable s) { + } + }); + + db.open(); + validate_spin_ui_data(btn_invoice_type_saleable, btn_invoice_type_sample, btn_invoice_type_gwp, dialog_brand_spin, dialog_subbrand_spin, + dialog_reference_spin, dialog_product_spin, stock_text_value, rl_actual_qty, actual_qty_dialog, txt_current_invoice_type); + + + cancet_btn.setOnClickListener(v -> { + multiDialog.dismiss(); + + if (multiDialog.isShowing()) { + multiDialog.dismiss(); + } + }); + + + stock_img_minus.setOnClickListener(v -> { + if (minteger == 0) { + AlertandMessages.showToastMsg(context, "Product quantity should not be less than Zero"); + } else { + minteger = minteger - 1; + stock_text_value.setText("" + minteger); + } + }); + + stock_img_plus.setOnClickListener(v -> { + if (!product_Id.equals("0")) { + db.open(); + if (!product_Id.equals("0")) { + rl_actual_qty.setVisibility(View.VISIBLE); + db.open(); + if (dialog_invoiceType.equalsIgnoreCase("Saleable") && db.getActualSaleableStock(product_Id, "SaleableBalance", visit_date, CounterId, from).getStock() == 0) { + AlertandMessages.showToastMsg(context, "Stock for this Product is Zero. Cannot allow to add this Product"); + } else if (dialog_invoiceType.equalsIgnoreCase("Sample") && db.getActualSaleableStock(product_Id, "SampleBalance", visit_date, CounterId, from).getStock() == 0) { + AlertandMessages.showToastMsg(context, "Stock for this Product is Zero. Cannot allow to add this Product"); + } else if (dialog_invoiceType.equalsIgnoreCase("GWP") && db.getActualSaleableStock(product_Id, "GwpBalance", visit_date, CounterId, from).getStock() == 0) { + AlertandMessages.showToastMsg(context, "Stock for this Product is Zero. Cannot allow to add this Product"); + } else { + minteger = minteger + 1; + db.open(); + if (dialog_invoiceType.equalsIgnoreCase("Saleable") && db.getActualSaleableStock(product_Id, "SaleableBalance", visit_date, CounterId, from).getStock() > 0 && minteger > db.getActualSaleableStock(product_Id, "SaleableBalance", visit_date, CounterId, from).getStock()) { + minteger = minteger - 1; + AlertandMessages.showToastMsg(context, "Stock Low. Please reduce sale quantity below or equal to the stock value"); + } else if (dialog_invoiceType.equalsIgnoreCase("Sample") && db.getActualSaleableStock(product_Id, "SampleBalance", visit_date, CounterId, from).getStock() > 0 && minteger > db.getActualSaleableStock(product_Id, "SampleBalance", visit_date, CounterId, from).getStock()) { + minteger = minteger - 1; + AlertandMessages.showToastMsg(context, "Stock Low. Please reduce sale quantity below or equal to the stock value"); + } else if (dialog_invoiceType.equalsIgnoreCase("GWP") && db.getActualSaleableStock(product_Id, "GwpBalance", visit_date, CounterId, from).getStock() > 0 && minteger > db.getActualSaleableStock(product_Id, "GwpBalance", visit_date, CounterId, from).getStock()) { + minteger = minteger - 1; + AlertandMessages.showToastMsg(context, "Stock Low. Please reduce sale quantity below or equal to the stock value"); + } else { + stock_text_value.setText("" + minteger); + } + } + } + } + }); + + btn_add.setOnClickListener(v -> { + ((ConsumerUserDetailsActivity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); + // get selected radio button from radioGroup + int selectedId = radioSexGroup.getCheckedRadioButtonId(); + // find the radiobutton by returned id + radioSexButton = (RadioButton) findViewById(selectedId); + db.open(); + if (dialog_product_spin.getSelectedItemId() == 0) { + AlertandMessages.showToastMsg(context, "Please Select Product"); + } else if (stock_text_value.getText().toString().equals("0")) { + AlertandMessages.showToastMsg(context, "Please add Atleast One Product Quantity"); + } else if (dialog_invoiceType.equalsIgnoreCase("Saleable") && db.getActualSaleableStock(product_Id, "SaleableBalance", visit_date, CounterId, from).getStock() == 0) { + AlertandMessages.showToastMsg(context, "Stock for this Product is Zero. Cannot allow to add this Product"); + if (multiDialog.isShowing()) { + multiDialog.dismiss(); + } + minteger = 0; + stock_text_value.setText("0"); + product_scan_code = ""; + dialog_brand_Id = ""; + dialog_sub_brand_Id = ""; + dialog_reference_Id = ""; + product_name = ""; + product_Id = "0"; + productType = ""; + discount = 0.0; + } else if (dialog_invoiceType.equalsIgnoreCase("Sample") && db.getActualSaleableStock(product_Id, "SampleBalance", visit_date, CounterId, from).getStock() == 0) { + AlertandMessages.showToastMsg(context, "Stock for this Product is Zero. Cannot allow to add this Product"); + if (multiDialog.isShowing()) { + multiDialog.dismiss(); + } + minteger = 0; + stock_text_value.setText("0"); + product_scan_code = ""; + dialog_brand_Id = ""; + dialog_sub_brand_Id = ""; + dialog_reference_Id = ""; + product_name = ""; + product_Id = "0"; + productType = ""; + discount = 0.0; + db.open(); + } else if (dialog_invoiceType.equalsIgnoreCase("GWP") && db.getActualSaleableStock(product_Id, "GwpBalance", visit_date, CounterId, from).getStock() == 0) { + AlertandMessages.showToastMsg(context, "Stock for this Product is Zero. Cannot allow to add this Product"); + if (multiDialog.isShowing()) { + multiDialog.dismiss(); + } + minteger = 0; + stock_text_value.setText("0"); + product_scan_code = ""; + dialog_brand_Id = ""; + dialog_sub_brand_Id = ""; + dialog_reference_Id = ""; + product_name = ""; + product_Id = "0"; + productType = ""; + discount = 0.0; + } else { + if (checkduplicate_entry()) { + object = new InvoiceGetterSetter(); + object = returnobject(); + + object.setProduct_rate(product_mrp); + object.setProduct(product_name); + object.setProduct_Id(product_Id); + object.setDiscount(discount); + object.setQuantity(stock_text_value.getText().toString()); + object.setScan_ean_code_or_enterd_ean_code(product_scan_code); + object.setSkuType(productType); + object.setStr_invoiceType(dialog_invoiceType); + object.setPromo_flag(false); + object.setPromo_type(""); + object.setPromotion_name(""); + object.setPromotion_Id("0"); + selected_list.add(object); + + current_total_stock.setText("Total : " + calculate_total_consume(selected_list)); + minteger = 0; + stock_text_value.setText("0"); + product_scan_code = ""; + dialog_brand_Id = ""; + dialog_sub_brand_Id = ""; + dialog_reference_Id = ""; + product_name = ""; + product_Id = "0"; + productType = ""; + discount = 0.0; + dialog_invoiceType = "Saleable"; + drawer_layout_recycle_store.setAdapter(new ValueAdapter(context, selected_list)); + drawer_layout_recycle_store.setLayoutManager(new LinearLayoutManager(context)); + product_add_flag = true; + if (multiDialog.isShowing()) { + multiDialog.dismiss(); + } + + } + } + }); + + multiDialog.show(); + } + + ////sku scannnnnnnnnnnn + private void show_dialog_forsku(final Context context, ArrayList skuList_with_eancode, LinearLayout rl_actual_qty, TextView actual_qty_dialog) { + final MultiPurposeDialog multiPurposeDialog = new MultiPurposeDialog(context); + multiPurposeDialog.requestWindowFeature(Window.FEATURE_NO_TITLE); + multiPurposeDialog.setContentView(R.layout.custom_sku_adapter); + final WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); + lp.copyFrom(Objects.requireNonNull(multiPurposeDialog.getWindow()).getAttributes()); + lp.width = WindowManager.LayoutParams.MATCH_PARENT; + lp.height = WindowManager.LayoutParams.WRAP_CONTENT; + lp.gravity = Gravity.CENTER; + multiPurposeDialog.getWindow().setAttributes(lp); + multiPurposeDialog.setCancelable(false); + multiPurposeDialog.show(); + + TextView sale_trcking_name = (TextView) multiPurposeDialog.findViewById(R.id.sale_trcking_name); + sale_trcking_name.setText(skuList_with_eancode.get(0).getProductName()); + RecyclerView recycl_sku = (RecyclerView) multiPurposeDialog.findViewById(R.id.recycl_sku); + + recycl_sku.setAdapter(new AdapterforSku(context, skuList_with_eancode, multiPurposeDialog, "0", rl_actual_qty, actual_qty_dialog)); + recycl_sku.setLayoutManager(new LinearLayoutManager(context)); + ImageView dismiss_dialog = (ImageView) multiPurposeDialog.findViewById(R.id.dismiss_dialog); + dismiss_dialog.setOnClickListener(v -> { + if (multiPurposeDialog.isShowing()) { + multiPurposeDialog.dismiss(); + } + }); + + multiPurposeDialog.show(); + } + + + private class AdapterforSku extends RecyclerView.Adapter { + private final LayoutInflater inflator; + List data; + String show_dialog; + MultiPurposeDialog multiPurposeDialog; + LinearLayout rl_actual_qty; + TextView actual_qty_dialog; + + public AdapterforSku(Context context, List data, MultiPurposeDialog multiPurposeDialog, String show_dialog + , LinearLayout rl_actual_qty, TextView actual_qty_dialog) { + inflator = LayoutInflater.from(context); + this.data = data; + this.show_dialog = show_dialog; + this.multiPurposeDialog = multiPurposeDialog; + + this.actual_qty_dialog = actual_qty_dialog; + this.rl_actual_qty = rl_actual_qty; + } + + @NonNull + @Override + public AdapterforSku.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) { + View view = inflator.inflate(R.layout.adapter_custom, parent, false); + return new AdapterforSku.MyViewHolder(view); + } + + + @SuppressLint("SetTextI18n") + @Override + public void onBindViewHolder(@NonNull final MyViewHolder holder, final int position) { + final ProductMaster current = data.get(position); + if (show_dialog.equals("1")) { + holder.sale_card.setVisibility(View.VISIBLE); + holder.sale_card.setId(position); + holder.sale_trcking_name.setText("Date : " + current.getVisit_date()); + holder.sale_trcking_name.setId(position); + holder.consumer_recycle.setVisibility(View.VISIBLE); + holder.consumer_recycle.setId(position); + + } else { + holder.sale_card.setVisibility(View.VISIBLE); + holder.sale_card.setId(position); + holder.sale_trcking_name.setText("(MRP - " + current.getMrp().toString() + ")"); + holder.sale_trcking_name.setId(position); + + holder.consumer_recycle.setVisibility(View.GONE); + holder.consumer_recycle.setId(position); + + holder.sale_card.setOnClickListener(v -> { + qrcode_text.setVisibility(View.VISIBLE); + qrcode_text.setText(current.getEanCode()); + product_name = current.getProductName(); + product_Id = current.getProductId().toString(); + product_scan_code = current.getEanCode(); + product_mrp = current.getMrp().toString(); + productType = current.getProductType(); + sku_name.setText(product_name + " Mrp - " + product_mrp); + sku_name.setVisibility(View.VISIBLE); + multiPurposeDialog.dismiss(); + + if (multiPurposeDialog != null && multiPurposeDialog.isShowing()) { + multiPurposeDialog.dismiss(); + } + + if (!product_Id.equals("0")) { + db.open(); + actual_qty_dialog.setText("" + db.getActualSaleableStock(product_Id, null, visit_date, CounterId, from).getStock()); + rl_actual_qty.setVisibility(View.VISIBLE); + } + }); + } + } + + + @Override + public int getItemCount() { + return data.size(); + } + + class MyViewHolder extends RecyclerView.ViewHolder { + TextView sale_trcking_name; + CardView sale_card; + RecyclerView consumer_recycle; + + + public MyViewHolder(View itemView) { + super(itemView); + sale_card = (CardView) itemView.findViewById(R.id.sale_card); + sale_trcking_name = (TextView) itemView.findViewById(R.id.sale_trcking_name); + ////for consumer product + consumer_recycle = (RecyclerView) itemView.findViewById(R.id.consumer_recycle); + } + } + } + + private boolean checkduplicate_entry() { + boolean status = true; + try { + if (selected_list != null && !selected_list.isEmpty()) { + for (int k = 0; k < selected_list.size(); k++) { + if (selected_list.get(k).getProduct_Id().equals(product_Id) && selected_list.get(k).getProduct_rate().equals(product_mrp)) { + Toast.makeText(context, "This Product Already Added", Toast.LENGTH_SHORT).show(); + status = false; + break; + } + } + } + } catch (Exception e) { + e.fillInStackTrace(); + } + return status; + } + + private boolean checkindex() { + boolean status = false; + try { + String str = edt_mobile_no.getText().toString(); + String[] strArray = str.split(" "); + //print elements of String array + for (String parentMenuId : strArray) { + if (parentMenuId.contains("1") || parentMenuId.contains("2") || parentMenuId.contains("3") || parentMenuId.contains("4") || parentMenuId.contains("5") || parentMenuId.contains("6") || parentMenuId.contains("7") || parentMenuId.contains("9") || parentMenuId.contains("8")) { + status = true; + break; + } + } + } catch (Exception e) { + e.fillInStackTrace(); + } + + return status; + } + + @SuppressLint("SetTextI18n") + private void show_consumer_previous_histry(final Context context, List previusHistoryList) { + final MultiPurposeDialog multiPurposeDialog = new MultiPurposeDialog(context); + multiPurposeDialog.requestWindowFeature(Window.FEATURE_NO_TITLE); + multiPurposeDialog.setContentView(R.layout.custom_sku_adapter); + final WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); + lp.copyFrom(Objects.requireNonNull(multiPurposeDialog.getWindow()).getAttributes()); + lp.width = WindowManager.LayoutParams.MATCH_PARENT; + lp.height = WindowManager.LayoutParams.WRAP_CONTENT; + lp.gravity = Gravity.CENTER; + multiPurposeDialog.getWindow().setAttributes(lp); + multiPurposeDialog.setCancelable(false); + TextView txt_bar_code = multiPurposeDialog.findViewById(R.id.txt_bar_code); + txt_bar_code.setText("Consumer Purchase History"); + TextView sale_trcking_name = (TextView) multiPurposeDialog.findViewById(R.id.sale_trcking_name); + sale_trcking_name.setVisibility(View.GONE); + RecyclerView recycl_sku = (RecyclerView) multiPurposeDialog.findViewById(R.id.recycl_sku); + + if (previusHistoryList.get(0).getGender().equalsIgnoreCase("Male")) { + //radioSexButton + radioSexGroup.check(R.id.radioM); + } else if (previusHistoryList.get(0).getGender().equalsIgnoreCase("Female")) { + //radioSexButton + radioSexGroup.check(R.id.radioF); + } else { + radioSexGroup.check(R.id.radio_other); + } + + for (int k = 0; k < ageLimits.size(); k++) { + if (!previusHistoryList.get(0).getAgeGroup().isEmpty()) + db.open(); + if (ageLimits.get(k).getAgeLimit().equalsIgnoreCase(previusHistoryList.get(0).getAgeGroup())) { + spin_age.setSelection(k + 1); + break; + } + } + + for (int k = 0; k < skinTypes.size(); k++) { + if (!previusHistoryList.get(0).getSkinType().isEmpty()) + db.open(); + if (skinTypes.get(k).getSkinType().equals(previusHistoryList.get(0).getSkinType())) { + spin_skin_type.setSelection(k + 1); + break; + } + } + + recycl_sku.setAdapter(new AdapterforHistry(context, previusHistoryList, multiPurposeDialog)); + recycl_sku.setLayoutManager(new LinearLayoutManager(context)); + + ImageView dismiss_dialog = (ImageView) multiPurposeDialog.findViewById(R.id.dismiss_dialog); + dismiss_dialog.setOnClickListener(v -> { + multiPurposeDialog.dismiss(); + if (multiPurposeDialog != null && multiPurposeDialog.isShowing()) { + multiPurposeDialog.dismiss(); + } + }); + + multiPurposeDialog.show(); + } + + private class AdapterforHistry extends RecyclerView.Adapter { + private final LayoutInflater inflator; + List data; + MultiPurposeDialog multiPurposeDialog; + + AdapterforHistry(Context context, List data, MultiPurposeDialog multiPurposeDialog) { + inflator = LayoutInflater.from(context); + this.data = data; + this.multiPurposeDialog = multiPurposeDialog; + } + + @NonNull + @Override + public AdapterforHistry.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) { + View view = inflator.inflate(R.layout.adapter_custom_history_product, parent, false); + return new AdapterforHistry.MyViewHolder(view); + + } + + + @SuppressLint("SetTextI18n") + @Override + public void onBindViewHolder(final MyViewHolder holder, final int position) { + final ConsumerSalesHistory current = data.get(position); + + holder.text_visit_date.setText("Date : " + current.getVisitDate()); + holder.text_visit_date.setId(position); + + holder.consume_product.setText("Product Name : " + current.getProductName()); + holder.consume_product.setId(position); + + holder.consume_product_qty_with_date.setText("MRP : " + current.getMrp().toString()); + holder.consume_product_qty_with_date.setId(position); + + holder.qty_sold_txt.setText("QTY Sold : " + current.getQtySold().toString()); + holder.qty_sold_txt.setId(position); + + holder.total_amount_txt.setText("Total Amount : " + current.getTotalAmount().toString()); + holder.total_amount_txt.setId(position); + + + if (position != 0) { + if (data.get(position - 1).getVisitDate().equalsIgnoreCase(current.getVisitDate())) { + holder.rl_visit_date.setVisibility(View.GONE); + holder.rl_visit_date.setId(position); + } else { + holder.rl_visit_date.setVisibility(View.VISIBLE); + holder.rl_visit_date.setId(position); + } + } + } + + + @Override + public int getItemCount() { + return data.size(); + } + + class MyViewHolder extends RecyclerView.ViewHolder { + TextView consume_product, consume_product_qty_with_date, text_visit_date, qty_sold_txt, total_amount_txt; + LinearLayout rl_visit_date; + + public MyViewHolder(View itemView) { + super(itemView); + rl_visit_date = (LinearLayout) itemView.findViewById(R.id.rl_visit_date); + consume_product_qty_with_date = (TextView) itemView.findViewById(R.id.consume_product_qty_with_date); + consume_product = (TextView) itemView.findViewById(R.id.consume_product); + text_visit_date = (TextView) itemView.findViewById(R.id.text_visit_date); + qty_sold_txt = (TextView) itemView.findViewById(R.id.qty_sold_txt); + total_amount_txt = (TextView) itemView.findViewById(R.id.total_amount_txt); + } + } + } + + @SuppressLint("UseCompatLoadingForDrawables") + private void + validate_spin_ui_data(final Button btn_invoice_type_saleable, final Button btn_invoice_type_sample, final Button btn_invoice_type_gwp, final Spinner dialog_brand_spin, final Spinner dialog_sub_brand_spin, + final Spinner dialog_franchise_spin, final Spinner dialog_product_spin, + final TextView stock_text_value, final LinearLayout rl_actual_qty, final TextView actual_qty_dialog, + final TextView txt_current_invoice_type) { + db.open(); + brandList = db.getproductdata_dialog("BrandName", "BrandId", false, "", visit_date, CounterId, from); + subbrandList = db.getproductdata_dialog("SubBrandName", "SubBrandId", false, "", visit_date, CounterId, from); + referenceList = db.getproductdata_dialog("ReferenceName", "ReferenceId", false, "", visit_date, CounterId, from); + productList = db.getbrand_wise_sku_fromproduct(null, null, visit_date, CounterId, from); + ///for invoice type + setBrandSpinnerData(brandList, dialog_brand_spin); + setSubBrandSpinnerData(subbrandList, dialog_sub_brand_spin); + setReferenceSpinnerData(referenceList, dialog_franchise_spin); + setProductSpinnerData(productList, dialog_product_spin); + + btn_invoice_type_saleable.setOnClickListener(view -> { + flag_filter_by_edt = false; + dialog_invoiceType = "Saleable"; + brandList = db.getproductdata_dialog("BrandName", "BrandId", false, "", visit_date, CounterId, from); + subbrandList = db.getproductdata_dialog("SubBrandName", "SubBrandId", false, "", visit_date, CounterId, from); + referenceList = db.getproductdata_dialog("ReferenceName", "ReferenceId", false, "", visit_date, CounterId, from); + productList = db.getbrand_wise_sku_fromproduct(null, null, visit_date, CounterId, from); + setBrandSpinnerData(brandList, dialog_brand_spin); + setSubBrandSpinnerData(subbrandList, dialog_sub_brand_spin); + setReferenceSpinnerData(referenceList, dialog_franchise_spin); + setProductSpinnerData(productList, dialog_product_spin); + db.open(); + dialog_product_list = db.getproduct_masterlist("T_StockSummary", visit_date, CounterId, from); + btn_invoice_type_saleable.setBackground(getResources().getDrawable(R.drawable.rouded_corner)); + btn_invoice_type_saleable.setTextColor(getResources().getColor(R.color.white)); + btn_invoice_type_sample.setBackground(getResources().getDrawable(R.drawable.round_btn_color_primary)); + btn_invoice_type_sample.setTextColor(getResources().getColor(R.color.grayfor_login)); + btn_invoice_type_gwp.setBackground(getResources().getDrawable(R.drawable.round_btn_color_primary)); + btn_invoice_type_gwp.setTextColor(getResources().getColor(R.color.grayfor_login)); + }); + + btn_invoice_type_sample.setOnClickListener(view -> { + flag_filter_by_edt = false; + if (!dialog_invoiceType.equalsIgnoreCase("Sample")) { + rl_actual_qty.setVisibility(View.GONE); + } + dialog_invoiceType = "Sample"; + db.open(); + brandList = db.getproductdata_dialog("BrandName", "BrandId", true, "SampleBalance", visit_date, CounterId, from); + subbrandList = db.getproductdata_dialog("SubBrandName", "SubBrandId", true, "SampleBalance", visit_date, CounterId, from); + referenceList = db.getproductdata_dialog("ReferenceName", "ReferenceId", true, "SampleBalance", visit_date, CounterId, from); + productList = db.getbrand_wise_sku_fromproduct(null, "SampleBalance", visit_date, CounterId, from); + setBrandSpinnerData(brandList, dialog_brand_spin); + setSubBrandSpinnerData(subbrandList, dialog_sub_brand_spin); + setReferenceSpinnerData(referenceList, dialog_franchise_spin); + setProductSpinnerData(productList, dialog_product_spin); + btn_invoice_type_sample.setBackground(getResources().getDrawable(R.drawable.rouded_corner)); + btn_invoice_type_sample.setTextColor(getResources().getColor(R.color.white)); + btn_invoice_type_saleable.setBackground(getResources().getDrawable(R.drawable.round_btn_color_primary)); + btn_invoice_type_saleable.setTextColor(getResources().getColor(R.color.grayfor_login)); + btn_invoice_type_gwp.setBackground(getResources().getDrawable(R.drawable.round_btn_color_primary)); + btn_invoice_type_gwp.setTextColor(getResources().getColor(R.color.grayfor_login)); + db.open(); + dialog_product_list = db.getproduct_masterlist(dialog_invoiceType, visit_date, CounterId, from); + + }); + + btn_invoice_type_gwp.setOnClickListener(view -> { + flag_filter_by_edt = false; + if (!dialog_invoiceType.equalsIgnoreCase("GWP")) { + rl_actual_qty.setVisibility(View.GONE); + } + dialog_invoiceType = "GWP"; + db.open(); + brandList = db.getproductdata_dialog("BrandName", "BrandId", true, "GwpBalance", visit_date, CounterId, from); + subbrandList = db.getproductdata_dialog("SubBrandName", "SubBrandId", true, "GwpBalance", visit_date, CounterId, from); + referenceList = db.getproductdata_dialog("ReferenceName", "ReferenceId", true, "GwpBalance", visit_date, CounterId, from); + productList = db.getbrand_wise_sku_fromproduct(null, "GwpBalance", visit_date, CounterId, from); + setBrandSpinnerData(brandList, dialog_brand_spin); + setSubBrandSpinnerData(subbrandList, dialog_sub_brand_spin); + setReferenceSpinnerData(referenceList, dialog_franchise_spin); + setProductSpinnerData(productList, dialog_product_spin); + btn_invoice_type_gwp.setBackground(getResources().getDrawable(R.drawable.rouded_corner)); + btn_invoice_type_gwp.setTextColor(getResources().getColor(R.color.white)); + btn_invoice_type_saleable.setBackground(getResources().getDrawable(R.drawable.round_btn_color_primary)); + btn_invoice_type_saleable.setTextColor(getResources().getColor(R.color.grayfor_login)); + btn_invoice_type_sample.setBackground(getResources().getDrawable(R.drawable.round_btn_color_primary)); + btn_invoice_type_sample.setTextColor(getResources().getColor(R.color.grayfor_login)); + db.open(); + dialog_product_list = db.getproduct_masterlist(dialog_invoiceType, visit_date, CounterId, from); + }); + + dialog_brand_spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { + @Override + public void onItemSelected(AdapterView adapterView, View view, int pos, long l) { + if (pos != 0) { + try { + flag_for_filter = true; + flag_filter_by_edt = false; + dialog_brand_Id = adapterView.getSelectedItem().toString(); + if (dialog_invoiceType.equalsIgnoreCase("GWP") || dialog_invoiceType.equalsIgnoreCase("Sample")) { + setFilter(FILTER_FOR_BRAND, dialog_product_spin); + setSubBrandSpinnerData(db.getsub_brand_using_brand_Id(dialog_brand_Id, "SubBrandName", "SubBrandId", "BrandName", dialog_invoiceType, visit_date, CounterId, true, from), dialog_sub_brand_spin); + setReferenceSpinnerData(db.getsub_brand_using_brand_Id(dialog_brand_Id, "ReferenceName", "ReferenceId", "BrandName", dialog_invoiceType, visit_date, CounterId, true, from), dialog_franchise_spin); + } else { + setFilter(FILTER_FOR_BRAND, dialog_product_spin); + setSubBrandSpinnerData(db.getsub_brand_using_brand_Id(dialog_brand_Id, "SubBrandName", "SubBrandId", "BrandName", null, visit_date, CounterId, true, from), dialog_sub_brand_spin); + setReferenceSpinnerData(db.getsub_brand_using_brand_Id(dialog_brand_Id, "ReferenceName", "ReferenceId", "BrandName", null, visit_date, CounterId, true, from), dialog_franchise_spin); + } + } catch (Exception e) { + throw new RuntimeException(e); + } + } else { + dialog_brand_Id = ""; + if (!dialog_invoiceType.isEmpty() || dialog_brand_spin.getSelectedItemPosition() != 0 || dialog_sub_brand_spin.getSelectedItemPosition() != 0 || dialog_franchise_spin.getSelectedItemPosition() != 0) { + flag_for_filter = true; + } else { + setFilter(CLEAR_FILTER, dialog_product_spin); + flag_for_filter = false; + } + } + } + + + @Override + public void onNothingSelected(AdapterView adapterView) { + + } + }); + + dialog_sub_brand_spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { + @Override + public void onItemSelected(AdapterView adapterView, View view, int pos, long l) { + if (pos != 0) { + try { + flag_for_filter = true; + flag_filter_by_edt = false; + dialog_sub_brand_Id = adapterView.getSelectedItem().toString(); + if (dialog_invoiceType.equalsIgnoreCase("GWP") || dialog_invoiceType.equalsIgnoreCase("Sample")) { + setFilter(FILTER_FOR_SUB_BRAND, dialog_product_spin); + setReferenceSpinnerData(db.getsub_brand_using_brand_Id(dialog_sub_brand_Id, "ReferenceName", "ReferenceId", "SubBrandName", dialog_invoiceType, visit_date, CounterId, true, from), dialog_franchise_spin); + } else { + setFilter(FILTER_FOR_SUB_BRAND, dialog_product_spin); + setReferenceSpinnerData(db.getsub_brand_using_brand_Id(dialog_sub_brand_Id, "ReferenceName", "ReferenceId", "SubBrandName", null, visit_date, CounterId, true, from), dialog_franchise_spin); + } + } catch (Exception e) { + throw new RuntimeException(e); + } + } else { + dialog_sub_brand_Id = ""; + if (!dialog_invoiceType.isEmpty() || dialog_brand_spin.getSelectedItemPosition() != 0 || dialog_sub_brand_spin.getSelectedItemPosition() != 0 || dialog_franchise_spin.getSelectedItemPosition() != 0) { + flag_for_filter = true; + } else { + setFilter(CLEAR_FILTER, dialog_product_spin); + flag_for_filter = false; + } + } + } + + @Override + public void onNothingSelected(AdapterView adapterView) { + + } + }); + + dialog_franchise_spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { + @Override + public void onItemSelected(AdapterView adapterView, View view, int pos, long l) { + if (pos != 0) { + try { + flag_for_filter = true; + flag_filter_by_edt = false; + dialog_reference_Id = adapterView.getSelectedItem().toString(); + setFilter(FILTER_FOR_REFERENCE_NAME, dialog_product_spin); + } catch (Exception e) { + throw new RuntimeException(e); + } + } else { + dialog_reference_Id = ""; + if (!dialog_invoiceType.isEmpty() || dialog_brand_spin.getSelectedItemPosition() != 0 || dialog_sub_brand_spin.getSelectedItemPosition() != 0 || + dialog_franchise_spin.getSelectedItemPosition() != 0) { + flag_for_filter = true; + } else { + setFilter(CLEAR_FILTER, dialog_product_spin); + flag_for_filter = false; + } + } + } + + @Override + public void onNothingSelected(AdapterView adapterView) { + + } + }); + + dialog_product_spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { + @SuppressLint("SetTextI18n") + @Override + public void onItemSelected(AdapterView parent, View view, int position, long id) { + if (position != 0) { + try { + if (flag_filter_by_edt) { + product_name = dialog_product_using_searchlist.get(position - 1).getProductName(); + product_Id = dialog_product_using_searchlist.get(position - 1).getProductId().toString(); + product_mrp = dialog_product_using_searchlist.get(position - 1).getMrp().toString(); + product_scan_code = dialog_product_using_searchlist.get(position - 1).getEanCode(); + productType = dialog_product_using_searchlist.get(position - 1).getProductType(); + if (dialog_invoiceType.equalsIgnoreCase("Sample") || dialog_invoiceType.equalsIgnoreCase("GWP")) { + product_mrp = "0"; + } + + stock_text_value.setText("0"); + if (!product_Id.equals("0")) { + rl_actual_qty.setVisibility(View.VISIBLE); + if (dialog_invoiceType.equalsIgnoreCase("Saleable")) { + txt_current_invoice_type.setText(R.string.current_stock_saleable); + db.open(); + actual_qty_dialog.setText("" + db.getActualSaleableStock(product_Id, "SaleableBalance", visit_date, CounterId, from).getStock()); + } else if (dialog_invoiceType.equalsIgnoreCase("Sample")) { + txt_current_invoice_type.setText(R.string.current_stock_sample); + actual_qty_dialog.setText("" + db.getActualSaleableStock(product_Id, "SampleBalance", visit_date, CounterId, from).getStock()); + } else if (dialog_invoiceType.equalsIgnoreCase("GWP")) { + txt_current_invoice_type.setText(R.string.current_stock_gwp); + actual_qty_dialog.setText("" + db.getActualSaleableStock(product_Id, "GwpBalance", visit_date, CounterId, from).getStock()); + } + } + minteger = 0; + } else if (flag_for_filter && dialog_brand_spin.getSelectedItemPosition() != 0 || dialog_sub_brand_spin.getSelectedItemPosition() != 0 || dialog_franchise_spin.getSelectedItemPosition() != 0) { + product_name = filterListForReferencename(dialog_product_list, dialog_reference_Id, dialog_brand_Id, dialog_sub_brand_Id, dialog_invoiceType).get(position - 1).getProductName(); + product_Id = filterListForReferencename(dialog_product_list, dialog_reference_Id, dialog_brand_Id, dialog_sub_brand_Id, dialog_invoiceType).get(position - 1).getProductId().toString(); + product_mrp = filterListForReferencename(dialog_product_list, dialog_reference_Id, dialog_brand_Id, dialog_sub_brand_Id, dialog_invoiceType).get(position - 1).getMrp().toString(); + product_scan_code = filterListForReferencename(dialog_product_list, dialog_reference_Id, dialog_brand_Id, dialog_sub_brand_Id, dialog_invoiceType).get(position - 1).getEanCode(); + productType = filterListForReferencename(dialog_product_list, dialog_reference_Id, dialog_brand_Id, dialog_sub_brand_Id, dialog_invoiceType).get(position - 1).getProductType(); + if (dialog_invoiceType.equalsIgnoreCase("Sample") || dialog_invoiceType.equalsIgnoreCase("GWP")) { + product_mrp = "0"; + } + if (!product_Id.equals("0")) { + rl_actual_qty.setVisibility(View.VISIBLE); + if (dialog_invoiceType.equalsIgnoreCase("Saleable")) { + txt_current_invoice_type.setText(getString(R.string.current_stock_saleable)); + db.open(); + actual_qty_dialog.setText("" + db.getActualSaleableStock(product_Id, "SaleableBalance", visit_date, CounterId, from).getStock()); + } else if (dialog_invoiceType.equalsIgnoreCase("Sample")) { + txt_current_invoice_type.setText(getString(R.string.current_stock_sample)); + actual_qty_dialog.setText("" + db.getActualSaleableStock(product_Id, "SampleBalance", visit_date, CounterId, from).getStock()); + } else if (dialog_invoiceType.equalsIgnoreCase("GWP")) { + txt_current_invoice_type.setText(getString(R.string.current_stock_gwp)); + db.open(); + actual_qty_dialog.setText("" + db.getActualSaleableStock(product_Id, "GwpBalance", visit_date, CounterId, from).getStock()); + } + + } + stock_text_value.setText("0"); + minteger = 0; + } else { + product_name = productList.get(position - 1).getProductName(); + product_Id = productList.get(position - 1).getProductId().toString(); + product_mrp = productList.get(position - 1).getMrp().toString(); + product_scan_code = productList.get(position - 1).getEanCode(); + productType = productList.get(position - 1).getProductType(); + if (dialog_invoiceType.equalsIgnoreCase("Sample") || dialog_invoiceType.equalsIgnoreCase("GWP")) { + product_mrp = "0"; + } + if (!product_Id.equals("0")) { + rl_actual_qty.setVisibility(View.VISIBLE); + db.open(); + if (dialog_invoiceType.equalsIgnoreCase("Saleable")) { + txt_current_invoice_type.setText(getString(R.string.current_stock_saleable)); + actual_qty_dialog.setText("" + db.getActualSaleableStock(product_Id, "SaleableBalance", visit_date, CounterId, from).getStock()); + } else if (dialog_invoiceType.equalsIgnoreCase("Sample")) { + txt_current_invoice_type.setText(getString(R.string.current_stock_sample)); + actual_qty_dialog.setText("" + db.getActualSaleableStock(product_Id, "SampleBalance", visit_date, CounterId, from).getStock()); + } else if (dialog_invoiceType.equalsIgnoreCase("GWP")) { + txt_current_invoice_type.setText(getString(R.string.current_stock_gwp)); + actual_qty_dialog.setText("" + db.getActualSaleableStock(product_Id, "GwpBalance", visit_date, CounterId, from).getStock()); + } + } + stock_text_value.setText("0"); + minteger = 0; + } + } catch (Exception e) { + throw new RuntimeException(e); + } + } else { + stock_text_value.setText("0"); + product_scan_code = ""; + product_mrp = "0"; + product_name = ""; + product_Id = "0"; + productType = ""; + discount = 0.0; + minteger = 0; + } + } + + @Override + public void onNothingSelected(AdapterView parent) { + + } + }); + + } + + private void setBrandSpinnerData(ArrayList brandList, Spinner dialog_brand_spin) { + try { + dialog_brand_adapter = new ArrayAdapter<>(this, R.layout.spinner_custom_item); + dialog_brand_adapter.add("- Select Brand -"); + for (int i = 0; i < brandList.size(); i++) { + dialog_brand_adapter.add(brandList.get(i).getBrandName()); + } + dialog_brand_spin.setAdapter(dialog_brand_adapter); + dialog_brand_adapter.setDropDownViewResource(R.layout.spinner_custom_item); + } catch (Exception e) { + e.fillInStackTrace(); + } + + } + + private void setSubBrandSpinnerData(ArrayList axeList, Spinner dialog_sub_brand_spin) { + try { + dialog_sub_brand_adapter = new ArrayAdapter<>(context, R.layout.spinner_custom_item); + dialog_sub_brand_adapter.add("- Select Sub Brand -"); + for (int i = 0; i < axeList.size(); i++) { + dialog_sub_brand_adapter.add(axeList.get(i).getBrandName()); + } + dialog_sub_brand_spin.setAdapter(dialog_sub_brand_adapter); + dialog_sub_brand_adapter.setDropDownViewResource(R.layout.spinner_custom_item); + } catch (Exception ignored) { + } + } + + private void setReferenceSpinnerData(ArrayList referenceList, Spinner dialog_franchise_spin) { + dialog_frenchise_adapter = new ArrayAdapter<>(this, R.layout.spinner_custom_item); + dialog_frenchise_adapter.add("- Select Franchise -"); + for (int i = 0; i < referenceList.size(); i++) { + dialog_frenchise_adapter.add(referenceList.get(i).getBrandName()); + } + + dialog_franchise_spin.setAdapter(dialog_frenchise_adapter); + dialog_frenchise_adapter.setDropDownViewResource(R.layout.spinner_custom_item); + } + + private void setProductSpinnerData(ArrayList productList, Spinner dialog_product_spin) { + try { + dialog_sku_adapter = new ArrayAdapter<>(this, R.layout.spinner_custom_item); + dialog_sku_adapter.add("- Select Product -"); + if (dialog_invoiceType.equalsIgnoreCase("Sample") || dialog_invoiceType.equalsIgnoreCase("GWP")) { + for (int i = 0; i < productList.size(); i++) { + dialog_sku_adapter.add(productList.get(i).getProductName() + " - Type-" + dialog_invoiceType); + } + } else { + for (int i = 0; i < productList.size(); i++) { + dialog_sku_adapter.add(productList.get(i).getProductName() + " - (MRP-" + productList.get(i).getMrp().toString() + ")"); + } + } + + dialog_product_spin.setAdapter(dialog_sku_adapter); + dialog_sku_adapter.setDropDownViewResource(R.layout.spinner_custom_item); + } catch (Exception ignored) { + } + } + + public void setFilter(int filterType, Spinner dialog_spin) { + try { + if (filterType == FILTER_FOR_BRAND) { + dialog_sku_adapter = new ArrayAdapter<>(context, R.layout.spinner_custom_item); + dialog_sku_adapter.add("- Select Product -"); + if (dialog_invoiceType.equalsIgnoreCase("Sample") || dialog_invoiceType.equalsIgnoreCase("GWP")) { + for (int i = 0; i < filterListForBrand(dialog_product_list, dialog_brand_Id).size(); i++) { + dialog_sku_adapter.add(filterListForBrand(dialog_product_list, dialog_brand_Id).get(i).getProductName() + "- Type-" + dialog_invoiceType); + } + } else { + for (int i = 0; i < filterListForBrand(dialog_product_list, dialog_brand_Id).size(); i++) { + dialog_sku_adapter.add(filterListForBrand(dialog_product_list, dialog_brand_Id).get(i).getProductName() + " - (MRP-" + filterListForBrand(dialog_product_list, dialog_brand_Id).get(i).getMrp().toString() + ")"); + } + } + + dialog_spin.setAdapter(dialog_sku_adapter); + dialog_sku_adapter.setDropDownViewResource(R.layout.spinner_custom_item); + } else if (filterType == FILTER_FOR_SUB_BRAND) { + dialog_sku_adapter = new ArrayAdapter<>(context, R.layout.spinner_custom_item); + dialog_sku_adapter.add("- Select Product -"); + if (dialog_invoiceType.equalsIgnoreCase("Sample") || dialog_invoiceType.equalsIgnoreCase("GWP")) { + for (int i = 0; i < filterListForSubBrand(dialog_product_list, dialog_sub_brand_Id, dialog_brand_Id).size(); i++) { + dialog_sku_adapter.add(filterListForSubBrand(dialog_product_list, dialog_sub_brand_Id, dialog_brand_Id).get(i).getProductName() + " - Type-" + dialog_invoiceType); + } + } else { + for (int i = 0; i < filterListForSubBrand(dialog_product_list, dialog_sub_brand_Id, dialog_brand_Id).size(); i++) { + dialog_sku_adapter.add(filterListForSubBrand(dialog_product_list, dialog_sub_brand_Id, dialog_brand_Id).get(i).getProductName() + " - (MRP-" + + filterListForSubBrand(dialog_product_list, dialog_sub_brand_Id, dialog_brand_Id).get(i).getMrp().toString() + ")"); + } + } + dialog_spin.setAdapter(dialog_sku_adapter); + dialog_sku_adapter.setDropDownViewResource(R.layout.spinner_custom_item); + } else if (filterType == FILTER_FOR_REFERENCE_NAME) { + dialog_sku_adapter = new ArrayAdapter<>(context, R.layout.spinner_custom_item); + dialog_sku_adapter.add("- Select Product -"); + if (dialog_invoiceType.equalsIgnoreCase("Sample") || dialog_invoiceType.equalsIgnoreCase("GWP")) { + for (int i = 0; i < filterListForReferencename(dialog_product_list, dialog_reference_Id, dialog_brand_Id, dialog_sub_brand_Id, dialog_invoiceType).size(); i++) { + dialog_sku_adapter.add(filterListForReferencename(dialog_product_list, dialog_reference_Id, dialog_brand_Id, dialog_sub_brand_Id, dialog_invoiceType).get(i).getProductName() + " - Type-" + dialog_invoiceType); + } + } else { + for (int i = 0; i < filterListForReferencename(dialog_product_list, dialog_reference_Id, dialog_brand_Id, dialog_sub_brand_Id, dialog_invoiceType).size(); i++) { + dialog_sku_adapter.add(filterListForReferencename(dialog_product_list, dialog_reference_Id, dialog_brand_Id, dialog_sub_brand_Id, dialog_invoiceType).get(i).getProductName() + " - (MRP-" + filterListForReferencename(dialog_product_list, dialog_reference_Id, dialog_brand_Id, dialog_sub_brand_Id, dialog_invoiceType).get(i).getMrp().toString() + ")"); + } + } + dialog_spin.setAdapter(dialog_sku_adapter); + dialog_sku_adapter.setDropDownViewResource(R.layout.spinner_custom_item); + } else { + dialog_sku_adapter = new ArrayAdapter<>(context, R.layout.spinner_custom_item); + dialog_sku_adapter.add("- Select Product -"); + if (dialog_invoiceType.equalsIgnoreCase("Sample") || dialog_invoiceType.equalsIgnoreCase("GWP")) { + for (int i = 0; i < dialog_product_list.size(); i++) { + dialog_sku_adapter.add(dialog_product_list.get(i).getProductName() + " - Type-" + dialog_invoiceType); + } + } else { + for (int i = 0; i < dialog_product_list.size(); i++) { + dialog_sku_adapter.add(dialog_product_list.get(i).getProductName() + " - (MRP-" + dialog_product_list.get(i).getMrp().toString() + ")"); + } + } + dialog_spin.setAdapter(dialog_sku_adapter); + dialog_sku_adapter.setDropDownViewResource(R.layout.spinner_custom_item); + } + dialog_spin.invalidate(); + } catch (Exception e) { + e.fillInStackTrace(); + } + } + + final int CLEAR_FILTER = 0; + final int FILTER_FOR_BRAND = 1; + final int FILTER_FOR_SUB_BRAND = 2; + final int FILTER_FOR_REFERENCE_NAME = 3; + + public ArrayList filterListForBrand(List originalList, String text) { + ArrayList filterList = new ArrayList<>(); + for (ProductMaster object : originalList) { + if (object.getBrandName().equalsIgnoreCase(text)) { + filterList.add(object); + } + } + return filterList; + } + + public ArrayList filterListForSubBrand(List originalList, String sub_brand_name_id, String brand_Id) { + ArrayList filterList = new ArrayList<>(); + for (ProductMaster object : originalList) { + if (sub_brand_name_id.isEmpty() && object.getBrandName().equalsIgnoreCase(brand_Id)) { + filterList.add(object); + } else if (object.getSubBrandName().equalsIgnoreCase(sub_brand_name_id) && (brand_Id.isEmpty() || object.getBrandName().equalsIgnoreCase(brand_Id))) { + filterList.add(object); + } + } + + return filterList; + } + + + public ArrayList filterListForReferencename(List originalList, String franchise_Id, String brandName_Id, String sub_brand_name_Id, String invoiceTyp_str) { + ArrayList filterList = new ArrayList<>(); + for (ProductMaster object : originalList) { + if (!invoiceTyp_str.isEmpty() && object.getBrandName().equalsIgnoreCase(invoiceTyp_str) && sub_brand_name_Id.isEmpty() && franchise_Id.isEmpty() && brandName_Id.isEmpty()) { + filterList.add(object); + } else if (sub_brand_name_Id.isEmpty() && object.getBrandName().equalsIgnoreCase(brandName_Id)) { + filterList.add(object); + } else if (franchise_Id.isEmpty() && object.getSubBrandName().equalsIgnoreCase(sub_brand_name_Id)) { + filterList.add(object); + } else if (object.getReferenceName().equalsIgnoreCase(franchise_Id) && (brandName_Id.isEmpty() || object.getBrandName().equalsIgnoreCase(brandName_Id)) && (sub_brand_name_Id.isEmpty() || object.getSubBrandName().equalsIgnoreCase(sub_brand_name_Id))) { + filterList.add(object); + } + } + + return filterList; + } + + + public void setSearchFilter(ArrayList originalList, String text, Spinner dialog_product_spin) { + try { + flag_filter_by_edt = true; + dialog_sku_adapter = new ArrayAdapter<>(context, R.layout.spinner_custom_item); + dialog_sku_adapter.add("- Select Product -"); + dialog_product_using_searchlist = new ArrayList<>(); + dialog_product_using_searchlist = filterListForProduct_edt(originalList, text); + if (filterListForProduct_edt(originalList, text).isEmpty()) { + dialog_product_using_searchlist = originalList; + } + if (dialog_invoiceType.equalsIgnoreCase("Sample") || dialog_invoiceType.equalsIgnoreCase("GWP")) { + for (int i = 0; i < dialog_product_using_searchlist.size(); i++) { + dialog_sku_adapter.add(dialog_product_using_searchlist.get(i).getProductName() + " - Type-" + dialog_invoiceType); + } + } else { + for (int i = 0; i < dialog_product_using_searchlist.size(); i++) { + dialog_sku_adapter.add(dialog_product_using_searchlist.get(i).getProductName() + " - (MRP-" + dialog_product_using_searchlist.get(i).getMrp().toString() + ")"); + } + + } + dialog_product_spin.setAdapter(dialog_sku_adapter); + dialog_sku_adapter.setDropDownViewResource(R.layout.spinner_custom_item); + + dialog_product_spin.invalidate(); + } catch (Exception e) { + e.fillInStackTrace(); + } + } + + public ArrayList filterListForProduct_edt(List originalList, String text) { + ArrayList filterList = new ArrayList<>(); + for (ProductMaster object : originalList) { + if (object.getProductName().toLowerCase().contains(text.toLowerCase())) { + filterList.add(object); + } + } + + return filterList; + } + + public void getpreviousHistory_from_mobile_no(final Context context, final ProgressDialog loading, String jsondata) { + try { + final OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, + TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build(); + RequestBody jsonData = RequestBody.create(Objects.requireNonNull(MediaType.parse("application/json")), jsondata); + Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build(); + PostApi api = adapter.create(PostApi.class); + retrofit2.Call call = api.getDownloadAll(jsonData); + call.enqueue(new retrofit2.Callback() { + @Override + public void onResponse(@NonNull retrofit2.Call call, @NonNull retrofit2.Response response) { + String responseBody = response.body(); + String data_for = null; + loading.dismiss(); + if (responseBody != null && response.isSuccessful()) { + txt_history.setEnabled(true); + data_for = response.body(); + assert data_for != null; + if (data_for.isEmpty()) { + txt_history.setEnabled(true); + } else { + if (!data_for.contains("No Data")) { + MasterBAProfileGetterSetter masterPromoOfferObject = new Gson().fromJson(data_for, MasterBAProfileGetterSetter.class); + if (masterPromoOfferObject != null) { + List previusHistoryList = masterPromoOfferObject.getConsumerSalesHistory(); + if (!previusHistoryList.isEmpty()) { + show_consumer_previous_histry(context, previusHistoryList); + } + } else { + loading.dismiss(); + } + } else { + loading.dismiss(); + Toast.makeText(context, "No Previous History", Toast.LENGTH_SHORT).show(); + } + } + } else { + loading.dismiss(); + AlertandMessages.showAlertlogin((Activity) context, "Unable To Connect Server. History Data Not Updated"); + } + } + + @Override + public void onFailure(@NonNull retrofit2.Call call, @NonNull Throwable t) { + loading.dismiss(); + AlertandMessages.showAlertlogin((Activity) context, "Unable To Connect Server. History Data Not Updated"); + } + }); + } catch (Exception e) { + e.fillInStackTrace(); + loading.dismiss(); + } + } + + + private void getstatusof_termcondition() { + edt_mobile_no.addTextChangedListener(new TextWatcher() { + @Override + public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { + + } + + @Override + public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { + + } + + @Override + public void afterTextChanged(Editable editable) { + if (!editable.toString().isEmpty() && editable.toString().length() == 10) { + if (CommonFunctions.checkNetIsAvailable(context) && checkindex()) { + try { + JSONObject jsonObject1 = new JSONObject(); + jsonObject1.put("Downloadtype", "Consumer_TermsConditionAccept"); + jsonObject1.put("Username", username); + jsonObject1.put("Param2", CounterId); + jsonObject1.put("Param1", edt_mobile_no.getText().toString()); + getstatusoftermscondition_status(context, jsonObject1.toString()); + } catch (JSONException e) { + e.fillInStackTrace(); + } + } else { + response_term_condition = "0"; + } + } else { + rl_term_condition.setTextColor(getResources().getColor(R.color.blue)); + rl_term_condition.setEnabled(true); + } + } + }); + + } + + public void getstatusoftermscondition_status(final Context context, String jsondata) { + try { + final OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, + TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build(); + RequestBody jsonData = RequestBody.create(Objects.requireNonNull(MediaType.parse("application/json")), jsondata); + Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build(); + PostApi api = adapter.create(PostApi.class); + retrofit2.Call call = api.getDownloadAll(jsonData); + call.enqueue(new retrofit2.Callback() { + @Override + public void onResponse(@NonNull retrofit2.Call call, @NonNull retrofit2.Response response) { + String responseBody = response.body(); + String data_for = null; + if (responseBody != null && response.isSuccessful()) { + data_for = response.body(); + assert data_for != null; + if (!data_for.isEmpty()) { + if (!data_for.contains("No Data")) { + MasterBAProfileGetterSetter reportbaAvailabilityGetterSetter = new Gson().fromJson(data_for, MasterBAProfileGetterSetter.class); + if (reportbaAvailabilityGetterSetter != null) { + List dataresponce = reportbaAvailabilityGetterSetter.getConsumerTermsConditionAccept(); + if (dataresponce.get(0).getTermsConditionAccept()) { + response_term_condition = "1"; + rl_term_condition.setTextColor(getResources().getColor(R.color.gray)); + rl_term_condition.setEnabled(false); + + } else { + response_term_condition = "0"; + } + } else { + response_term_condition = "0"; + } + } else { + response_term_condition = "0"; + } + } + } else { + response_term_condition = "0"; + } + } + + @Override + public void onFailure(@NonNull retrofit2.Call call, @NonNull Throwable t) { + response_term_condition = "0"; + } + }); + } catch (Exception e) { + e.fillInStackTrace(); + response_term_condition = "0"; + } + } + + @SuppressLint("SetTextI18n") + @Override + protected void onResume() { + super.onResume(); + if (!response_term_condition.isEmpty() && !response_term_condition.equals("0")) { + rl_term_condition.setTextColor(getResources().getColor(R.color.gray)); + rl_term_condition.setEnabled(false); + } + + current_total_stock.setText("Total : " + calculate_total_consume(selected_list)); + } + + @SuppressLint("SetTextI18n") + private void show_promotion_dialog(final Context context, final MasterPromotion promoList, + final boolean flag_free_product, final String getentity_type) { + final MultiPurposeDialog dialog = new MultiPurposeDialog(context); + dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); + dialog.setContentView(R.layout.promotion_dialog_free_product); + dialog.setCancelable(false); + WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); + lp.copyFrom(Objects.requireNonNull(dialog.getWindow()).getAttributes()); + lp.width = WindowManager.LayoutParams.MATCH_PARENT; + lp.height = WindowManager.LayoutParams.WRAP_CONTENT; + lp.gravity = Gravity.CENTER; + dialog.getWindow().setAttributes(lp); + dialog.setCancelable(false); + RecyclerView recycl_promotion = (RecyclerView) dialog.findViewById(R.id.recycl_promotion); + final ImageView cancet_btn = (ImageView) dialog.findViewById(R.id.cancet_btn); + final ImageView btn_add = (ImageView) dialog.findViewById(R.id.btn_add); + TextView promo_name = (TextView) dialog.findViewById(R.id.promo_name); + TextView tvTitle = (TextView) dialog.findViewById(R.id.tvTitle); + if (flag_free_product) tvTitle.setText("Free Products"); + else tvTitle.setText("Additional Products"); + promo_name.setText("Promotion : " + promoList.getPromotionName()); + db.open(); + final ArrayList prodictlist_promo = db.getPromotiongetProduct(promoList.getPromoId(), getentity_type, visit_date, CounterId, from); + recycl_promotion.setAdapter(new PromotionSkuWiseAdapter(context, dialog, prodictlist_promo, promoList, getentity_type)); + recycl_promotion.setLayoutManager(new LinearLayoutManager(context)); + cancet_btn.setOnClickListener(view -> dialog.dismiss()); + + btn_add.setOnClickListener(view -> { + dialog.dismiss(); + try { + if (!prodictlist_promo.isEmpty()) { + for (int k = 0; k < prodictlist_promo.size(); k++) { + if (prodictlist_promo.get(k).getSelected_item_qty() > 0) { + selected_promoList.add(prodictlist_promo.get(k)); + } + } + /////////////add product with setentityType-------------- + if (getentity_type.equalsIgnoreCase("OffProduct")) { + for (int k = 0; k < selected_promoList.size(); k++) { + InvoiceGetterSetter invoiceGetterSetter; + invoiceGetterSetter = returnobject(); + invoiceGetterSetter.setQuantity("1"); + invoiceGetterSetter.setScan_ean_code_or_enterd_ean_code(selected_promoList.get(k).getEan_code()); + invoiceGetterSetter.setStr_invoiceType(""); + invoiceGetterSetter.setPromo_flag(true); + invoiceGetterSetter.setPromo_type("OffProduct"); + invoiceGetterSetter.setPromotion_name(promoList.getPromotionName()); + invoiceGetterSetter.setPromotion_Id(promoList.getPromoId().toString()); + int amount = Integer.parseInt(selected_promoList.get(k).getMrp_product()); + int tip_per = Integer.parseInt(promoList.getPromotionGetEntityValue()); + int tip_cal = (amount * tip_per) / 100; + + invoiceGetterSetter.setSkuType(String.valueOf(tip_cal)); + invoiceGetterSetter.setDiscount(0.0); + invoiceGetterSetter.setProduct_rate(selected_promoList.get(k).getMrp_product()); + invoiceGetterSetter.setProduct(selected_promoList.get(k).getProductname()); + invoiceGetterSetter.setProduct_Id(selected_promoList.get(k).getProductId().toString()); + added_prmo_products.add(invoiceGetterSetter); + } + selected_promoList = new ArrayList<>(); + } else if (getentity_type.equalsIgnoreCase("Gift")) { + ///////////for gift promo + if (!selected_promoList.isEmpty()) { + for (int k = 0; k < selected_promoList.size(); k++) { + InvoiceGetterSetter invoiceGetterSetter; + invoiceGetterSetter = returnobject(); + + invoiceGetterSetter.setQuantity(String.valueOf(selected_promoList.get(k).getSelected_item_qty())); + invoiceGetterSetter.setProduct_rate("0"); + invoiceGetterSetter.setDiscount(0.0); + invoiceGetterSetter.setScan_ean_code_or_enterd_ean_code(selected_promoList.get(k).getEan_code()); + invoiceGetterSetter.setSkuType(""); + invoiceGetterSetter.setStr_invoiceType(""); + invoiceGetterSetter.setPromo_flag(true); + invoiceGetterSetter.setPromo_type("Gift"); + invoiceGetterSetter.setPromotion_name(promoList.getPromotionName()); + invoiceGetterSetter.setPromotion_Id(promoList.getPromoId().toString()); + invoiceGetterSetter.setProduct(selected_promoList.get(k).getProductname() + " - QTY - " + selected_promoList.get(k).getSelected_item_qty()); + invoiceGetterSetter.setProduct_Id(selected_promoList.get(k).getProductId().toString()); + added_prmo_products.add(invoiceGetterSetter); + } + + selected_promoList = new ArrayList<>(); + } + + } else { + ///applyed promo for Product + if (!selected_promoList.isEmpty()) { + for (int k = 0; k < selected_promoList.size(); k++) { + InvoiceGetterSetter invoiceGetterSetter; + invoiceGetterSetter = returnobject(); + invoiceGetterSetter.setQuantity(String.valueOf(selected_promoList.get(k).getSelected_item_qty())); + invoiceGetterSetter.setProduct_rate("0"); + invoiceGetterSetter.setDiscount(0.0); + invoiceGetterSetter.setScan_ean_code_or_enterd_ean_code(selected_promoList.get(k).getEan_code()); + invoiceGetterSetter.setSkuType(""); + invoiceGetterSetter.setStr_invoiceType(""); + invoiceGetterSetter.setPromo_flag(true); + invoiceGetterSetter.setPromo_type("Product"); + invoiceGetterSetter.setPromotion_name(promoList.getPromotionName()); + invoiceGetterSetter.setPromotion_Id(promoList.getPromoId().toString()); + invoiceGetterSetter.setProduct(selected_promoList.get(k).getProductname() + " - QTY - " + selected_promoList.get(k).getSelected_item_qty()); + invoiceGetterSetter.setProduct_Id(selected_promoList.get(k).getProductId().toString()); + added_prmo_products.add(invoiceGetterSetter); + } + + selected_promoList = new ArrayList<>(); + } + } + } + } catch (NumberFormatException e) { + e.fillInStackTrace(); + } + }); + + dialog.show(); + } + + @SuppressLint("SetTextI18n") + private void show_promotion_skuwise_dialog(final Context context, ArrayList selected_productList, + final ArrayList promoList, final boolean flag_worth) { + final MultiPurposeDialog purposeDialog = new MultiPurposeDialog(context); + purposeDialog.requestWindowFeature(Window.FEATURE_NO_TITLE); + purposeDialog.setContentView(R.layout.promotion_dialog); + purposeDialog.setCancelable(false); + WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); + lp.copyFrom(Objects.requireNonNull(purposeDialog.getWindow()).getAttributes()); + lp.width = WindowManager.LayoutParams.MATCH_PARENT; + lp.height = WindowManager.LayoutParams.WRAP_CONTENT; + lp.gravity = Gravity.CENTER; + purposeDialog.getWindow().setAttributes(lp); + purposeDialog.show(); + + RecyclerView recycl_promotion = (RecyclerView) purposeDialog.findViewById(R.id.recycl_promotion); + final ImageView cancet_btn = (ImageView) purposeDialog.findViewById(R.id.cancet_btn); + final ImageView btn_add = (ImageView) purposeDialog.findViewById(R.id.btn_add); + final TextView header_txt = (TextView) purposeDialog.findViewById(R.id.header_txt); + final LinearLayout rl_changes_color = (LinearLayout) purposeDialog.findViewById(R.id.rl_changes_color); + + if (flag_worth) { + header_txt.setText("Applicable Worth Promotions"); + rl_changes_color.setBackgroundColor(getResources().getColor(R.color.dashboard_less_ach)); + } else { + header_txt.setText("Applicable Product Promotions"); + rl_changes_color.setBackgroundColor(getResources().getColor(R.color.colorPrimary)); + } + + ////show product selected + recycl_promotion.setAdapter(new PromotionSpinnerAdapter(context, purposeDialog, promoList, flag_worth)); + recycl_promotion.setLayoutManager(new LinearLayoutManager(context)); + + cancet_btn.setOnClickListener(view -> { + purposeDialog.dismiss(); + added_prmo_products.clear(); + if (purposeDialog != null && purposeDialog.isShowing()) { + purposeDialog.dismiss(); + } + }); + + btn_add.setOnClickListener(view -> { + try { + purposeDialog.dismiss(); + if (purposeDialog != null && purposeDialog.isShowing()) { + purposeDialog.dismiss(); + } + + if (flag_worth) { + if (!added_prmo_products.isEmpty()) { + selected_list.addAll(added_prmo_products); + } + drawer_layout_recycle_store.setAdapter(new ValueAdapter(context, selected_list)); + drawer_layout_recycle_store.setLayoutManager(new LinearLayoutManager(context)); + startActivity(new Intent(context, InvoiceReportProformaActivity.class). + putExtra(CommonString.TAG_OBJECT, selected_list) + .putExtra(CommonString.Key_For_Consumer_Update, flag_for_consumer_Update) + .putExtra(CommonString.Key_For_Reciept_Count, String.valueOf(reciept_count)). + putExtra(CommonString.FLAG_FOR_TERMCONDITION, str_termCondition) + .putExtra(CommonString.KEY_IMAGE, str_img_demo_no_sale).putExtra("from", from)); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + added_prmo_products = new ArrayList<>(); + } else { + ////change for worrh promotin,,,,,,,, + try { + AlertandMessages.showToastMsg(context, "Checking Promotion"); + db.open(); + db.insert_temp_sales_data(visit_date, CounterId, selected_list); + new LoadTask().execute(false); + } catch (Exception e) { + new LoadTask().execute(false); + } + } + } catch (Exception e) { + e.fillInStackTrace(); + } + }); + purposeDialog.show(); + } + + + private class PromotionSkuWiseAdapter extends RecyclerView.Adapter { + ArrayList promo_product_list; + Context context; + MultiPurposeDialog dialog; + private final LayoutInflater inflator; + MasterPromotion promo_object; + String getentity_type; + int total_getentity_value = 0, select_product_count = 0, getentity_for_off_product = 1; + + public PromotionSkuWiseAdapter(Context context, final MultiPurposeDialog dialog, ArrayList promo_product_list, + MasterPromotion promo_object, String getentity_type) { + this.dialog = dialog; + this.context = context; + this.promo_object = promo_object; + this.promo_product_list = promo_product_list; + inflator = LayoutInflater.from(context); + this.getentity_type = getentity_type; + } + + @NonNull + @Override + public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) { + View view = inflator.inflate(R.layout.row_promotion, parent, false); + return new ViewHolder(view); + } + + @SuppressLint("SetTextI18n") + @Override + public void onBindViewHolder(@NonNull final ViewHolder viewHolder, final int pos) { + ////show product selected + final MasterPromotionSetProductGroup current = promo_product_list.get(pos); + total_getentity_value = Integer.parseInt(promo_object.getPromotionGetEntityValue()); + + if (CommonFunctions.isTablet(context)) { + viewHolder.tvstorename.setText("Product : " + current.getProductname().trim() + " - Stock : " + current.getSallable_stock_qty()); + viewHolder.tvstorename.setId(pos); + } else { + viewHolder.tvstorename.setText("Product : " + current.getProductname().trim() + "\n" + "Stock : " + current.getSallable_stock_qty()); + viewHolder.tvstorename.setId(pos); + } + + viewHolder.stock_img_plus.setOnClickListener(v -> { + try { + int minteger = current.getSelected_item_qty(); + select_product_count = select_product_count + 1; + minteger = minteger + 1; + if (getentity_type.equalsIgnoreCase("OffAdditionalProduct")) { + + } else if (getentity_type.equalsIgnoreCase("OffProduct")) { + if (select_product_count > getentity_for_off_product) { + minteger = minteger - 1; + select_product_count = select_product_count - 1; + AlertandMessages.showToastMsg(context, "You can not add more than allowed free product"); + } else { + viewHolder.stock_text_value.setText("" + minteger); + current.setSelected_item_qty(minteger); + } + } else { + if (select_product_count > total_getentity_value) { + minteger = minteger - 1; + select_product_count = select_product_count - 1; + AlertandMessages.showToastMsg(context, "You can not add more than allowed free product"); + } else { + viewHolder.stock_text_value.setText("" + minteger); + current.setSelected_item_qty(minteger); + } + } + } catch (Exception e) { + e.fillInStackTrace(); + } + }); + + viewHolder.stock_img_minus.setOnClickListener(v -> { + try { + int minteger = current.getSelected_item_qty(); + if (minteger == 0) { + AlertandMessages.showToastMsg(context, "Product quantity should not be less than Zero"); + } else { + minteger = minteger - 1; + select_product_count = select_product_count - 1; + viewHolder.stock_text_value.setText("" + minteger); + current.setSelected_item_qty(minteger); + } + } catch (Exception e) { + e.fillInStackTrace(); + } + }); + + } + + @Override + public int getItemCount() { + return promo_product_list.size(); + } + + public class ViewHolder extends RecyclerView.ViewHolder { + Button stock_img_minus, stock_img_plus; + TextView stock_text_value; + CardView card_view; + TextView tvstorename; + + public ViewHolder(@NonNull View itemView) { + super(itemView); + card_view = (CardView) itemView.findViewById(R.id.card_view); + tvstorename = (TextView) itemView.findViewById(R.id.tvstorename); + stock_img_minus = (Button) itemView.findViewById(R.id.stock_img_minus); + stock_img_plus = (Button) itemView.findViewById(R.id.stock_img_plus); + stock_text_value = (TextView) itemView.findViewById(R.id.stock_text_value); + + } + } + } + + private class PromotionSpinnerAdapter extends RecyclerView.Adapter { + ArrayList promotionList; + Context context; + MultiPurposeDialog dialog; + private final LayoutInflater inflator; + boolean flag_worth; + + public PromotionSpinnerAdapter(Context context, final MultiPurposeDialog dialog, ArrayList list, boolean flag_worth) { + this.dialog = dialog; + this.context = context; + this.promotionList = list; + inflator = LayoutInflater.from(context); + this.flag_worth = flag_worth; + } + + @NonNull + @Override + public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) { + View view = inflator.inflate(R.layout.row_promotion_spin_list, parent, false); + return new ViewHolder(view); + } + + @SuppressLint("NotifyDataSetChanged") + @Override + public void onBindViewHolder(@NonNull final ViewHolder viewHolder, @SuppressLint("RecyclerView") final int pos) { + final MasterPromotion current = promotionList.get(pos); + StringBuilder aplyied_products = new StringBuilder(); + db.open(); + ArrayList qualified_products = db.getqualified_Product_List(CounterId, username, visit_date, current.getPromoId()); + if (!qualified_products.isEmpty()) { + for (int k = 0; k < qualified_products.size(); k++) { + if (k == 0) { + aplyied_products = new StringBuilder(qualified_products.get(k).getProduct()); + } else { + aplyied_products.append(" , ").append(qualified_products.get(k).getProduct()); + } + } + } + + viewHolder.category.setText(current.getPromotionName().trim()); + viewHolder.category.setId(pos); + + if (!qualified_products.isEmpty() && !aplyied_products.toString().isEmpty()) { + viewHolder.aplyed_products.setVisibility(View.VISIBLE); + viewHolder.aplyed_products.setText(aplyied_products.toString()); + viewHolder.aplyed_products.setId(pos); + } else { + viewHolder.aplyed_products.setVisibility(View.GONE); + viewHolder.aplyed_products.setId(pos); + } + + viewHolder.check_promo.setOnClickListener(view -> { + try { + if (viewHolder.check_promo.isChecked()) { + boolean valid_flag = true; + assert promotionList != null; + for (int l = 0; l < promotionList.size(); l++) { + if ((promotionList.get(l).getPromoId().intValue() != current.getPromoId().intValue()) && promotionList.get(l).isPromotionactive()) { + db.open(); + if (db.checked_applyied_promo(promotionList.get(l).getPromoId().toString(), username, visit_date, CounterId, + current.getPromoId().toString()) > 0) { + AlertandMessages.showToastMsg(context, "Promotion already applied on this product"); + current.setPromotionactive(false); + viewHolder.check_promo.setChecked(false); + viewHolder.check_promo.setId(pos); + notifyDataSetChanged(); + valid_flag = false; + break; + } + } + } + + if (valid_flag) { + current.setPromotionactive(true); + viewHolder.check_promo.setChecked(true); + viewHolder.check_promo.setId(pos); + //New Promotion Addede + if (current.getPromotionGetEntityType().equalsIgnoreCase("OffSameProduct")) { + applyeid_products = new ArrayList<>(); + db.open(); + ArrayList OffSameProduct = db.getqualifiedOffSameProduct(CounterId, username, visit_date, current.getPromoId()); + int total_off = 0, total_qty = 0, calculatetedper_values = 0, total_maxvalue = 0, previous_qty = 0; + int addOff = 0; + if (!OffSameProduct.isEmpty()) { + for (int l = 0; l < OffSameProduct.size(); l++) { + int rate = Integer.parseInt(OffSameProduct.get(l).getProduct_rate()); + int qty = Integer.parseInt(OffSameProduct.get(l).getQuantity()); + total_qty = total_qty + qty; + total_off = total_off + rate * qty; + //Updated logic for new promo------ + InvoiceGetterSetter invoiceGetterSetter; + invoiceGetterSetter = returnobject(); + invoiceGetterSetter.setPromo_flag(true); + invoiceGetterSetter.setPromo_type("OffSameProduct"); + invoiceGetterSetter.setPromotion_name(current.getPromotionName()); + invoiceGetterSetter.setPromotion_Id(current.getPromoId().toString()); + invoiceGetterSetter.setProduct(OffSameProduct.get(l).getProduct()); + invoiceGetterSetter.setQuantity(OffSameProduct.get(l).getQuantity()); + invoiceGetterSetter.setProduct_Id(OffSameProduct.get(l).getProduct_Id()); + invoiceGetterSetter.setProduct_rate(OffSameProduct.get(l).getProduct_rate()); + ///calculate percentage + double calculate_per_productwise = 0.0, getentityValue = 0.0, total_valueper_productwise = 0.0; + try { + total_valueper_productwise = rate * qty; + getentityValue = Double.parseDouble(current.getPromotionGetEntityValue()); + if (current.getMaxValue() != null && !current.getMaxValue().isEmpty()) { + if (total_qty > Integer.parseInt(current.getMaxValue()) && previous_qty <= Integer.parseInt(current.getMaxValue())) { + if (previous_qty == 0) { + addOff = rate * Integer.parseInt(current.getMaxValue()); + calculate_per_productwise = (addOff * getentityValue) / 100; + } else if (previous_qty <= Integer.parseInt(current.getMaxValue())) { + addOff = (Integer.parseInt(current.getMaxValue()) - previous_qty) * rate; + calculate_per_productwise = (addOff * getentityValue) / 100; + } else { + calculate_per_productwise = 0; + } + previous_qty = total_qty; + } else { + previous_qty = total_qty; + if (total_qty <= Integer.parseInt(current.getMaxValue())) { + calculate_per_productwise = (total_valueper_productwise * getentityValue) / 100; + } + } + } else { + calculate_per_productwise = (total_valueper_productwise * getentityValue) / 100; + } + } catch (NumberFormatException e) { + e.fillInStackTrace(); + } + invoiceGetterSetter.setDiscounted_value_productwise(new DecimalFormat("##.##").format(calculate_per_productwise)); + invoiceGetterSetter.setScan_ean_code_or_enterd_ean_code(OffSameProduct.get(l).getScan_ean_code_or_enterd_ean_code()); + applyeid_products.add(invoiceGetterSetter); + } + if (CommonFunctions.mod(total_qty, Integer.parseInt(current.getPromotionSetEntityValue())) == 0) { + int totqty = 0; + int prevqty = 0; + int totoff = 0; + int tip_per = Integer.parseInt(current.getPromotionGetEntityValue()); + if (current.getMaxValue() != null && !current.getMaxValue().isEmpty()) { + if (total_qty > Integer.parseInt(current.getMaxValue())) { + for (int l = 0; l < OffSameProduct.size(); l++) { + int rate = Integer.parseInt(OffSameProduct.get(l).getProduct_rate()); + int qty = Integer.parseInt(OffSameProduct.get(l).getQuantity()); + totqty = totqty + qty; + totoff = totoff + rate * qty; + if (totqty > Integer.parseInt(current.getMaxValue())) { + int totaldata = 0; + int remainqty = 0; + if (prevqty == 0) { + remainqty = Integer.parseInt(current.getMaxValue()); + } else { + remainqty = Integer.parseInt(current.getMaxValue()) - prevqty; + } + totaldata = totoff - (rate * qty); + total_maxvalue = totaldata + rate * remainqty; + AlertandMessages.showToastMsg(context, "Exceeds Limit, Promo will apply on" + " " + current.getMaxValue() + " " + "Quantity only"); + break; + } else { + prevqty = prevqty + qty; + } + } + calculatetedper_values = (total_maxvalue * tip_per) / 100; + } else { + calculatetedper_values = (total_off * tip_per) / 100; + } + } else { + calculatetedper_values = (total_off * tip_per) / 100; + } + } else { + int tip_per = Integer.parseInt(current.getPromotionGetEntityValue()); + int totqty = 0; + int prevqty = 0; + int totoff = 0; + if (current.getMaxValue() != null && !current.getMaxValue().isEmpty()) { + if (total_qty > Integer.parseInt(current.getMaxValue())) { + for (int l = 0; l < OffSameProduct.size(); l++) { + int rate = Integer.parseInt(OffSameProduct.get(l).getProduct_rate()); + int qty = Integer.parseInt(OffSameProduct.get(l).getQuantity()); + totqty = totqty + qty; + totoff = totoff + rate * qty; + if (totqty > Integer.parseInt(current.getMaxValue())) { + int totaldata = 0; + int remainqty = 0; + if (prevqty == 0) { + remainqty = Integer.parseInt(current.getMaxValue()); + } else { + remainqty = Integer.parseInt(current.getMaxValue()) - prevqty; + } + totaldata = totoff - (rate * qty); + total_maxvalue = totaldata + rate * remainqty; + AlertandMessages.showToastMsg(context, "Exceeds Limit, Promo will apply on" + " " + current.getMaxValue() + " " + "Quantity only"); + break; + } else { + prevqty = prevqty + qty; + } + } + calculatetedper_values = (total_maxvalue * tip_per) / 100; + } else { + calculatetedper_values = (total_off * tip_per) / 100; + } + } else { + calculatetedper_values = (total_off * tip_per) / 100; + } + } + } + + MasterPromotionSetProductGroup ob = new MasterPromotionSetProductGroup(); + ob.setPromotion_name(current.getPromotionName()); + ob.setPromotionId(current.getPromoId().toString()); + ob.setPromotion_deducted_price(current.getPromotionGetEntityValue()); + InvoiceGetterSetter invoiceGetterSetter; + invoiceGetterSetter = returnobject(); + + invoiceGetterSetter.setQuantity("0"); + invoiceGetterSetter.setProduct_rate("0"); + invoiceGetterSetter.setDiscount(0.0); + invoiceGetterSetter.setScan_ean_code_or_enterd_ean_code(""); + invoiceGetterSetter.setSkuType(""); + invoiceGetterSetter.setStr_invoiceType(""); + invoiceGetterSetter.setPromo_flag(true); + invoiceGetterSetter.setPromo_type("OffSameProduct"); + invoiceGetterSetter.setPromotion_name(current.getPromotionName()); + invoiceGetterSetter.setPromotion_Id(current.getPromoId().toString()); + + invoiceGetterSetter.setProduct(String.valueOf(calculatetedper_values)); + invoiceGetterSetter.setProduct_Id("0"); + //////added applyied products in list + invoiceGetterSetter.setApplyiedproductList(applyeid_products); + added_prmo_products.add(invoiceGetterSetter); + } else if (current.getPromotionGetEntityType().equalsIgnoreCase("OffWorth")) { + db.open(); + ArrayList qualified_products1 = db.getqualified_Product_List(CounterId, username, visit_date, current.getPromoId()); + int total_offworth = 0; + applyeid_products = new ArrayList<>(); + if (!qualified_products1.isEmpty()) { + for (int l = 0; l < qualified_products1.size(); l++) { + int rate = Integer.parseInt(qualified_products1.get(l).getProduct_rate()); + int qty = Integer.parseInt(qualified_products1.get(l).getQuantity()); + total_offworth = total_offworth + rate * qty; + //Updated logic for new promo------ + InvoiceGetterSetter invoiceGetterSetter; + invoiceGetterSetter = returnobject(); + invoiceGetterSetter.setPromo_flag(true); + invoiceGetterSetter.setPromo_type("OffWorth"); + invoiceGetterSetter.setPromotion_name(current.getPromotionName()); + invoiceGetterSetter.setPromotion_Id(current.getPromoId().toString()); + invoiceGetterSetter.setProduct(qualified_products1.get(l).getProduct()); + invoiceGetterSetter.setQuantity(qualified_products1.get(l).getQuantity()); + invoiceGetterSetter.setProduct_Id(qualified_products1.get(l).getProduct_Id()); + invoiceGetterSetter.setProduct_rate(qualified_products1.get(l).getProduct_rate()); + ///calculate percentage + double calculate_per_productwise = 0.0, getentityValue = 0.0, total_valueper_productwise = 0.0; + try { + total_valueper_productwise = rate * qty; + getentityValue = Double.parseDouble(current.getPromotionGetEntityValue()); + calculate_per_productwise = (total_valueper_productwise * getentityValue) / 100; + } catch (NumberFormatException e) { + e.fillInStackTrace(); + } + invoiceGetterSetter.setDiscounted_value_productwise(new DecimalFormat("##.##").format(calculate_per_productwise)); + invoiceGetterSetter.setScan_ean_code_or_enterd_ean_code(qualified_products1.get(l).getScan_ean_code_or_enterd_ean_code()); + + applyeid_products.add(invoiceGetterSetter); + } + } + + MasterPromotionSetProductGroup ob = new MasterPromotionSetProductGroup(); + ob.setPromotion_name(current.getPromotionName()); + ob.setPromotionId(current.getPromoId().toString()); + ob.setPromotion_deducted_price(current.getPromotionGetEntityValue()); + InvoiceGetterSetter invoiceGetterSetter; + invoiceGetterSetter = returnobject(); + + invoiceGetterSetter.setQuantity("0"); + invoiceGetterSetter.setProduct_rate("0"); + invoiceGetterSetter.setDiscount(0.0); + invoiceGetterSetter.setScan_ean_code_or_enterd_ean_code(""); + invoiceGetterSetter.setSkuType(""); + invoiceGetterSetter.setStr_invoiceType(""); + invoiceGetterSetter.setPromo_flag(true); + invoiceGetterSetter.setPromo_type("OffWorth"); + invoiceGetterSetter.setPromotion_name(current.getPromotionName()); + invoiceGetterSetter.setPromotion_Id(current.getPromoId().toString()); + int tip_per = Integer.parseInt(current.getPromotionGetEntityValue()); + int tip_cal = (total_offworth * tip_per) / 100; + /////////calculate max value + if (current.getMaxValue() != null && !current.getMaxValue().isEmpty()) { + int max_value = Integer.parseInt(current.getMaxValue()); + if (max_value != 0) { + if (tip_cal > max_value) { + tip_cal = max_value; + } + } + } + invoiceGetterSetter.setProduct("" + tip_cal); + invoiceGetterSetter.setProduct_Id("0"); + //////added applyied products in list + invoiceGetterSetter.setApplyiedproductList(applyeid_products); + added_prmo_products.add(invoiceGetterSetter); + } else if (current.getPromotionGetEntityType().equalsIgnoreCase("OffAdditionalProduct")) { + db.open(); + ArrayList qualified_products1 = db.getqualified_Product_List(CounterId, username, visit_date, current.getPromoId()); + int total_offworth = 0; + int total_qty = 0; + int previous_qty = 0; + applyeid_products = new ArrayList<>(); + ArrayList prodictlist_promo = db.getPromotiongetProduct(current.getPromoId(), current.getPromotionGetEntityType(), visit_date, CounterId, from); + if (!qualified_products1.isEmpty() && !prodictlist_promo.isEmpty() && !selected_list.isEmpty()) { + Collections.sort(prodictlist_promo, new Comparator() { + @Override + public int compare(Object o1, Object o2) { + MasterPromotionSetProductGroup p1 = (MasterPromotionSetProductGroup) o1; + MasterPromotionSetProductGroup p2 = (MasterPromotionSetProductGroup) o2; + return p1.getMrp_product().compareToIgnoreCase(p2.getMrp_product()); + } + }); + + for (int k = 0; k < prodictlist_promo.size(); k++) { + for (int l = 0; l < selected_list.size(); l++) { + if (selected_list.get(l).getProduct_Id().equals(String.valueOf(prodictlist_promo.get(k).getProductId()))) { + int rate = Integer.parseInt(selected_list.get(l).getProduct_rate()); + int qty = Integer.parseInt(selected_list.get(l).getQuantity()); + total_qty = total_qty + qty; + total_offworth = total_offworth + rate * qty; + //Updated logic for new promo------ + InvoiceGetterSetter invoiceGetterSetter; + invoiceGetterSetter = returnobject(); + invoiceGetterSetter.setPromo_flag(true); + invoiceGetterSetter.setPromo_type("OffAdditionalProduct"); + invoiceGetterSetter.setPromotion_name(current.getPromotionName()); + invoiceGetterSetter.setPromotion_Id(current.getPromoId().toString()); + invoiceGetterSetter.setProduct(selected_list.get(l).getProduct()); + invoiceGetterSetter.setQuantity(selected_list.get(l).getQuantity()); + invoiceGetterSetter.setProduct_Id(selected_list.get(l).getProduct_Id()); + invoiceGetterSetter.setProduct_rate(selected_list.get(l).getProduct_rate()); + ///calculate percentage + double calculate_per_productwise = 0.0, getentityValue = 0.0, total_valueper_productwise = 0.0, addOff = 0; + try { + total_valueper_productwise = rate * qty; + getentityValue = Double.parseDouble(current.getPromotionGetEntityValue()); + if (current.getMaxValue() != null && !current.getMaxValue().isEmpty()) { + if (total_qty > Integer.parseInt(current.getMaxValue()) && previous_qty <= Integer.parseInt(current.getMaxValue())) { + if (previous_qty == 0) { + addOff = rate * Integer.parseInt(current.getMaxValue()); + calculate_per_productwise = (addOff * getentityValue) / 100; + } else if (previous_qty <= Integer.parseInt(current.getMaxValue())) { + addOff = (Integer.parseInt(current.getMaxValue()) - previous_qty) * rate; + calculate_per_productwise = (addOff * getentityValue) / 100; + } else { + calculate_per_productwise = 0; + } + previous_qty = total_qty; + } else { + previous_qty = total_qty; + if (total_qty <= Integer.parseInt(current.getMaxValue())) { + calculate_per_productwise = (total_valueper_productwise * getentityValue) / 100; + } + } + } else { + calculate_per_productwise = (total_valueper_productwise * getentityValue) / 100; + } + //test("promodata", String.valueOf(calculate_per_productwise)); + } catch (NumberFormatException e) { + e.fillInStackTrace(); + } + invoiceGetterSetter.setDiscounted_value_productwise(new DecimalFormat("##.##").format(calculate_per_productwise)); + invoiceGetterSetter.setScan_ean_code_or_enterd_ean_code(selected_list.get(l).getScan_ean_code_or_enterd_ean_code()); + applyeid_products.add(invoiceGetterSetter); + } + } + } + } + + MasterPromotionSetProductGroup ob = new MasterPromotionSetProductGroup(); + ob.setPromotion_name(current.getPromotionName()); + ob.setPromotionId(current.getPromoId().toString()); + ob.setPromotion_deducted_price(current.getPromotionGetEntityValue()); + + InvoiceGetterSetter invoiceGetterSetter; + invoiceGetterSetter = returnobject(); + + invoiceGetterSetter.setQuantity("0"); + invoiceGetterSetter.setProduct_rate("0"); + invoiceGetterSetter.setDiscount(0.0); + invoiceGetterSetter.setScan_ean_code_or_enterd_ean_code(""); + invoiceGetterSetter.setSkuType(""); + invoiceGetterSetter.setStr_invoiceType(""); + invoiceGetterSetter.setPromo_flag(true); + invoiceGetterSetter.setPromo_type("OffAdditionalProduct"); + invoiceGetterSetter.setPromotion_name(current.getPromotionName()); + invoiceGetterSetter.setPromotion_Id(current.getPromoId().toString()); + int tip_per = Integer.parseInt(current.getPromotionGetEntityValue()); + int addOffProduct = 0; + int tip_cal = 0; + int prevqty = 0; + int remainqty = 0; + int totqty = 0; + int totoff = 0; + + if (current.getMaxValue() != null && !current.getMaxValue().isEmpty()) { + for (int k = 0; k < prodictlist_promo.size(); k++) { + for (int l = 0; l < selected_list.size(); l++) { + if (selected_list.get(l).getProduct_Id().equals(String.valueOf(prodictlist_promo.get(k).getProductId()))) { + int rate = Integer.parseInt(selected_list.get(l).getProduct_rate()); + int qty = Integer.parseInt(selected_list.get(l).getQuantity()); + totqty = totqty + qty; + totoff = totoff + rate * qty; + addOffProduct = 0; + //test("qtydata", totqty + "," + prevqty); + if (totqty > Integer.parseInt(current.getMaxValue()) && prevqty <= Integer.parseInt(current.getMaxValue())) { + if (prevqty == 0) { + prevqty = prevqty + qty; + remainqty = Integer.parseInt(current.getMaxValue()); + } else { + remainqty = Integer.parseInt(current.getMaxValue()) - prevqty; + } + addOffProduct = totoff - (rate * qty); + int tip = addOffProduct + rate * remainqty; + tip_cal = (tip * tip_per) / 100; + //test("discountdata", tip_cal + "," + addOffProduct + "," + total_offworth + "," + totoff + "," + tip + "," + rate * qty); + AlertandMessages.showToastMsg(context, "Exceeds Limit, Promo will apply on" + " " + current.getMaxValue() + " " + "Quantity only"); + } else { + prevqty = prevqty + qty; + if (totqty > Integer.parseInt(current.getMaxValue())) { + break; + } else if (totqty < Integer.parseInt(current.getMaxValue())) { + tip_cal = (total_offworth * tip_per) / 100; + } + } + break; + } + } + } + } else { + tip_cal = (total_offworth * tip_per) / 100; + } + + invoiceGetterSetter.setProduct(String.valueOf(tip_cal)); + invoiceGetterSetter.setProduct_Id("0"); + //////added applyied products in list + invoiceGetterSetter.setApplyiedproductList(applyeid_products); + added_prmo_products.add(invoiceGetterSetter); + } else if (current.getPromotionGetEntityType().equalsIgnoreCase("ValueOffAdditionalProduct")) { + db.open(); + ArrayList qualified_products1 = db.getqualified_Product_List(CounterId, username, visit_date, current.getPromoId()); + int total_offworth = 0; + int total_qty = 0; + int previous_qty = 0; + applyeid_products = new ArrayList<>(); + ArrayList prodictlist_promo = db.getPromotiongetProduct(current.getPromoId(), current.getPromotionGetEntityType(), visit_date, CounterId, from); + if (!qualified_products1.isEmpty() && !prodictlist_promo.isEmpty() && !selected_list.isEmpty()) { + for (int k = 0; k < prodictlist_promo.size(); k++) { + for (int l = 0; l < selected_list.size(); l++) { + if (selected_list.get(l).getProduct_Id().equals(String.valueOf(prodictlist_promo.get(k).getProductId()))) { + int rate = Integer.parseInt(selected_list.get(l).getProduct_rate()); + int qty = Integer.parseInt(selected_list.get(l).getQuantity()); + total_offworth = total_offworth + rate * qty; + total_qty = total_qty + qty; + //Updated logic for new promo------ + InvoiceGetterSetter invoiceGetterSetter; + invoiceGetterSetter = returnobject(); + invoiceGetterSetter.setPromo_flag(true); + invoiceGetterSetter.setPromo_type("ValueOffAdditionalProduct"); + invoiceGetterSetter.setPromotion_name(current.getPromotionName()); + invoiceGetterSetter.setPromotion_Id(current.getPromoId().toString()); + invoiceGetterSetter.setProduct(selected_list.get(l).getProduct()); + invoiceGetterSetter.setQuantity(selected_list.get(l).getQuantity()); + invoiceGetterSetter.setProduct_Id(selected_list.get(l).getProduct_Id()); + invoiceGetterSetter.setProduct_rate(selected_list.get(l).getProduct_rate()); + ///calculate percentage + double calculate_per_productwise = 0.0, getentityValue = 0.0, total_valueper_productwise = 0.0; + try { + getentityValue = Double.parseDouble(current.getPromotionGetEntityValue()); + if (current.getMaxValue() != null && !current.getMaxValue().isEmpty()) { + if (total_qty > Integer.parseInt(current.getMaxValue()) && previous_qty <= Integer.parseInt(current.getMaxValue())) { + if (previous_qty == 0) { + // previous_qty = total_qty; + calculate_per_productwise = getentityValue * Integer.parseInt(current.getMaxValue()); + } else if (previous_qty <= Integer.parseInt(current.getMaxValue())) { + calculate_per_productwise = (Integer.parseInt(current.getMaxValue()) - previous_qty) * getentityValue; + } else { + calculate_per_productwise = 0; + } + previous_qty = total_qty; + } else { + previous_qty = total_qty; + if (total_qty <= Integer.parseInt(current.getMaxValue())) { + calculate_per_productwise = getentityValue * qty; + } + } + } else { + calculate_per_productwise = getentityValue * qty; + } + //test("promodata", String.valueOf(calculate_per_productwise)); + } catch (NumberFormatException e) { + e.fillInStackTrace(); + } + invoiceGetterSetter.setDiscounted_value_productwise(new DecimalFormat("##.##").format(calculate_per_productwise)); + invoiceGetterSetter.setScan_ean_code_or_enterd_ean_code(selected_list.get(l).getScan_ean_code_or_enterd_ean_code()); + applyeid_products.add(invoiceGetterSetter); + } + } + } + } + + MasterPromotionSetProductGroup ob = new MasterPromotionSetProductGroup(); + ob.setPromotion_name(current.getPromotionName()); + ob.setPromotionId(current.getPromoId().toString()); + ob.setPromotion_deducted_price(current.getPromotionGetEntityValue()); + + InvoiceGetterSetter invoiceGetterSetter; + invoiceGetterSetter = returnobject(); + + invoiceGetterSetter.setQuantity("0"); + invoiceGetterSetter.setProduct_rate("0"); + invoiceGetterSetter.setDiscount(0.0); + invoiceGetterSetter.setScan_ean_code_or_enterd_ean_code(""); + invoiceGetterSetter.setSkuType(""); + invoiceGetterSetter.setStr_invoiceType(""); + invoiceGetterSetter.setPromo_flag(true); + invoiceGetterSetter.setPromo_type("ValueOffAdditionalProduct"); + invoiceGetterSetter.setPromotion_name(current.getPromotionName()); + invoiceGetterSetter.setPromotion_Id(current.getPromoId().toString()); + int tip_per = Integer.parseInt(current.getPromotionGetEntityValue()); + + int addOffProduct = 0; + int tip_cal = 0; + int totqty = 0; + int prevqty = 0; + int remainqty = 0; + for (int k = 0; k < prodictlist_promo.size(); k++) { + for (int l = 0; l < selected_list.size(); l++) { + if (selected_list.get(l).getProduct_Id().equals(String.valueOf(prodictlist_promo.get(k).getProductId()))) { + int rate = Integer.parseInt(selected_list.get(l).getProduct_rate()); + int qty = Integer.parseInt(selected_list.get(l).getQuantity()); + totqty = totqty + qty; + if (current.getMaxValue() != null && !current.getMaxValue().isEmpty()) { + if (totqty > Integer.parseInt(current.getMaxValue())) { + if (prevqty == 0) { + tip_cal = 0; + addOffProduct = tip_cal + tip_per * Integer.parseInt(current.getMaxValue()); + } else { + remainqty = Integer.parseInt(current.getMaxValue()) - prevqty; + addOffProduct = tip_cal + (tip_per * remainqty); + } + tip_cal = addOffProduct; + AlertandMessages.showToastMsg(context, "Exceeds Limit, Promo will apply on" + " " + current.getMaxValue() + " " + "Quantity only"); + break; + } else { + prevqty = totqty; + if (totqty > Integer.parseInt(current.getMaxValue())) { + break; + } else { + tip_cal = tip_cal + (tip_per * qty); + } + } + } else { + tip_cal = tip_per * qty; + } + break; + } + } + } + + invoiceGetterSetter.setProduct(String.valueOf(tip_cal)); + invoiceGetterSetter.setProduct_Id("0"); + //////added applyied products in list + invoiceGetterSetter.setApplyiedproductList(applyeid_products); + added_prmo_products.add(invoiceGetterSetter); + } else if (current.getPromotionGetEntityType().equalsIgnoreCase("OffProduct")) { + db.open(); + if (!db.getPromotiongetProduct(current.getPromoId(), current.getPromotionGetEntityType(), visit_date, CounterId, from).isEmpty()) { + show_promotion_dialog(context, current, true, current.getPromotionGetEntityType()); + } else { + AlertandMessages.showToastMsg(context, "OffProduct not in stock"); + } + } else if (current.getPromotionGetEntityType().equalsIgnoreCase("Product")) { + db.open(); + if (!db.getPromotiongetProduct(current.getPromoId(), current.getPromotionGetEntityType(), visit_date, CounterId, from).isEmpty()) { + show_promotion_dialog(context, current, true, current.getPromotionGetEntityType()); + } else { + AlertandMessages.showToastMsg(context, "Free Product not in stock"); + } + } else if (current.getPromotionGetEntityType().equalsIgnoreCase("Gift")) { + db.open(); + if (!db.getPromotiongetProduct(current.getPromoId(), current.getPromotionGetEntityType(), visit_date, CounterId, from).isEmpty()) { + show_promotion_dialog(context, current, true, current.getPromotionGetEntityType()); + } else { + AlertandMessages.showToastMsg(context, "Free Product not in stock"); + } + } else if (current.getPromotionGetEntityType().equalsIgnoreCase("Worth")) { + MasterPromotionSetProductGroup ob = new MasterPromotionSetProductGroup(); + ob.setPromotion_name(current.getPromotionName()); + ob.setPromotionId(current.getPromoId().toString()); + ob.setPromotion_deducted_price(current.getPromotionGetEntityValue()); + InvoiceGetterSetter invoiceGetterSetter; + invoiceGetterSetter = returnobject(); + invoiceGetterSetter.setQuantity("0"); + invoiceGetterSetter.setProduct_rate("0"); + invoiceGetterSetter.setDiscount(0.0); + invoiceGetterSetter.setScan_ean_code_or_enterd_ean_code(""); + invoiceGetterSetter.setSkuType(""); + invoiceGetterSetter.setStr_invoiceType(""); + invoiceGetterSetter.setPromo_flag(true); + invoiceGetterSetter.setPromo_type("Worth"); + invoiceGetterSetter.setPromotion_name(current.getPromotionName()); + invoiceGetterSetter.setPromotion_Id(current.getPromoId().toString()); + invoiceGetterSetter.setProduct(current.getPromotionGetEntityValue()); + invoiceGetterSetter.setProduct_Id("0"); + added_prmo_products.add(invoiceGetterSetter); + } else if (current.getPromotionGetEntityType().equalsIgnoreCase("WorthWithProduct")) { + db.open(); + ArrayList applyiedPromoProducts = db.getqualified_Product_List(CounterId, username, visit_date, current.getPromoId()); + int totalQty = 0, total_discount = 0; + applyeid_products = new ArrayList<>(); + if (!applyiedPromoProducts.isEmpty()) { + for (int l = 0; l < applyiedPromoProducts.size(); l++) { + int qty = Integer.parseInt(applyiedPromoProducts.get(l).getQuantity()); + totalQty += qty; + //Updated logic for new promo------ + InvoiceGetterSetter invoiceGetterSetter; + invoiceGetterSetter = returnobject(); + invoiceGetterSetter.setPromo_flag(true); + invoiceGetterSetter.setPromo_type("WorthWithProduct"); + invoiceGetterSetter.setPromotion_name(current.getPromotionName()); + invoiceGetterSetter.setPromotion_Id(current.getPromoId().toString()); + invoiceGetterSetter.setProduct(applyiedPromoProducts.get(l).getProduct()); + invoiceGetterSetter.setQuantity(applyiedPromoProducts.get(l).getQuantity()); + invoiceGetterSetter.setProduct_Id(applyiedPromoProducts.get(l).getProduct_Id()); + invoiceGetterSetter.setProduct_rate(applyiedPromoProducts.get(l).getProduct_rate()); + invoiceGetterSetter.setScan_ean_code_or_enterd_ean_code(applyiedPromoProducts.get(l).getScan_ean_code_or_enterd_ean_code()); + + invoiceGetterSetter.setDiscounted_value_productwise("0"); + applyeid_products.add(invoiceGetterSetter); + } + } + + MasterPromotionSetProductGroup ob = new MasterPromotionSetProductGroup(); + ob.setPromotion_name(current.getPromotionName()); + ob.setPromotionId(current.getPromoId().toString()); + ob.setPromotion_deducted_price(current.getPromotionGetEntityValue()); + InvoiceGetterSetter invoiceGetterSetter; + invoiceGetterSetter = returnobject(); + + invoiceGetterSetter.setQuantity("0"); + invoiceGetterSetter.setProduct_rate("0"); + invoiceGetterSetter.setDiscount(0.0); + invoiceGetterSetter.setScan_ean_code_or_enterd_ean_code(""); + invoiceGetterSetter.setSkuType(""); + invoiceGetterSetter.setStr_invoiceType(""); + invoiceGetterSetter.setPromo_flag(true); + invoiceGetterSetter.setPromo_type("WorthWithProduct"); + invoiceGetterSetter.setPromotion_name(current.getPromotionName()); + invoiceGetterSetter.setPromotion_Id(current.getPromoId().toString()); + int setEntityValue = Integer.parseInt(current.getPromotionSetEntityValue()); + /////////calculate max value + if (current.getMaxValue() != null && !current.getMaxValue().isEmpty()) { + int max_value = Integer.parseInt(current.getMaxValue()); + if (max_value != 0) { + if (totalQty > max_value) { + totalQty = max_value; + } + } + } + + if (totalQty >= setEntityValue) { + total_discount = ((int) (totalQty / setEntityValue)) * Integer.parseInt(current.getPromotionGetEntityValue()); + } + + invoiceGetterSetter.setProduct(String.valueOf(total_discount)); + invoiceGetterSetter.setProduct_Id("0"); + //added applyied products in list + invoiceGetterSetter.setApplyiedproductList(applyeid_products); + added_prmo_products.add(invoiceGetterSetter); + } + } + } else { + current.setPromotionactive(false); + viewHolder.check_promo.setChecked(false); + remove_added_promo_fromtemp(current.getPromoId().toString()); + } + } catch (NumberFormatException e) { + e.fillInStackTrace(); + } + }); + + + if (current.isPromotionactive()) { + viewHolder.check_promo.setChecked(true); + viewHolder.check_promo.setId(pos); + } else { + viewHolder.check_promo.setChecked(false); + viewHolder.check_promo.setId(pos); + } + + viewHolder.img_product.setOnClickListener(view -> { + ArrayList qualified_products12 = db.getqualified_Product_List(CounterId, username, visit_date, current.getPromoId()); + if (!qualified_products12.isEmpty()) { + show_qualified_products_dialog(context, qualified_products12, false, current); + } + }); + + viewHolder.img_promo.setOnClickListener(view -> show_qualified_products_dialog(context, null, true, current)); + } + + @Override + public int getItemCount() { + return promotionList.size(); + } + + public class ViewHolder extends RecyclerView.ViewHolder { + ImageView img_product, img_promo; + CheckBox check_promo; + CardView card_view; + TextView category, aplyed_products; + + public ViewHolder(@NonNull View itemView) { + super(itemView); + card_view = (CardView) itemView.findViewById(R.id.card_view); + category = (TextView) itemView.findViewById(R.id.tvstorename); + aplyed_products = (TextView) itemView.findViewById(R.id.aplyed_products); + check_promo = (CheckBox) itemView.findViewById(R.id.check_promo); + img_product = (ImageView) itemView.findViewById(R.id.img_product); + img_promo = (ImageView) itemView.findViewById(R.id.img_promo); + } + } + } + + protected boolean check_isPromo() { + boolean status = false; + try { + if (!selected_list.isEmpty()) { + for (int k = 0; k < selected_list.size(); k++) { + if (selected_list.get(k).isPromo_flag()) { + status = true; + break; + } + } + } + } catch (Exception e) { + e.fillInStackTrace(); + } + + return status; + } + + protected void remove_added_promo_index() { + try { + if (!selected_list.isEmpty()) { + Iterator it = selected_list.iterator(); + while (it.hasNext()) { + InvoiceGetterSetter name = it.next(); + if (name.isPromo_flag()) { + it.remove(); + } + // Do something + } + } + } catch (Exception e) { + e.fillInStackTrace(); + } + } + + protected void remove_added_promo_fromtemp(String promoId) { + try { + if (!added_prmo_products.isEmpty()) { + Iterator it = added_prmo_products.iterator(); + while (it.hasNext()) { + InvoiceGetterSetter name = it.next(); + if (promoId.equals(name.getPromotion_Id())) { + it.remove(); + } + // Do something + } + } + } catch (Exception e) { + e.fillInStackTrace(); + } + } + + + @SuppressLint("SetJavaScriptEnabled") + private void show_qualified_products_dialog(final Context context, final ArrayList qualifiedProducts, boolean + pic_promo_flag, final MasterPromotion current) { + final MultiPurposeDialog purposeDialog = new MultiPurposeDialog(context); + purposeDialog.requestWindowFeature(Window.FEATURE_NO_TITLE); + purposeDialog.setContentView(R.layout.qualified_product); + purposeDialog.setCancelable(false); + WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); + lp.copyFrom(Objects.requireNonNull(purposeDialog.getWindow()).getAttributes()); + lp.width = WindowManager.LayoutParams.MATCH_PARENT; + lp.height = WindowManager.LayoutParams.WRAP_CONTENT; + lp.gravity = Gravity.CENTER; + purposeDialog.getWindow().setAttributes(lp); + purposeDialog.show(); + + RecyclerView recycl_promotion = (RecyclerView) purposeDialog.findViewById(R.id.recycl_promotion); + final ImageView close_white = (ImageView) purposeDialog.findViewById(R.id.img_close); + final WebView web_view = (WebView) purposeDialog.findViewById(R.id.web_view); + + if (pic_promo_flag) { + web_view.setVisibility(View.VISIBLE); + recycl_promotion.setVisibility(View.GONE); + if (CommonFunctions.checkNetIsAvailable(context)) { + //load notice board url + web_view.setWebViewClient(new MyWebViewClient()); + web_view.getSettings().setJavaScriptEnabled(true); + web_view.getSettings().setBuiltInZoomControls(true); + String url = ""; + if (CommonFunctions.isTablet(context)) { + url = current.getPromoPath() + current.getPromoOfferTab(); + } else { + url = current.getPromoPath() + current.getPromoOfferMobile(); + } + if (url != null && !url.isEmpty()) { + web_view.loadUrl(url); + } + } + } else { + web_view.setVisibility(View.GONE); + recycl_promotion.setVisibility(View.VISIBLE); + if (qualifiedProducts != null) { + recycl_promotion.setAdapter(new QualifiedProductsAdapter(context, purposeDialog, qualifiedProducts)); + recycl_promotion.setLayoutManager(new LinearLayoutManager(context)); + } + } + + close_white.setOnClickListener(view -> { + purposeDialog.dismiss(); + if (purposeDialog != null && purposeDialog.isShowing()) { + purposeDialog.dismiss(); + } + }); + + purposeDialog.show(); + } + + private class QualifiedProductsAdapter extends RecyclerView.Adapter { + ArrayList products; + Context context; + MultiPurposeDialog dialog; + private final LayoutInflater inflator; + + public QualifiedProductsAdapter(Context context, final MultiPurposeDialog dialog, ArrayList products) { + this.dialog = dialog; + this.context = context; + this.products = products; + inflator = LayoutInflater.from(context); + } + + @NonNull + @Override + public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) { + View view = inflator.inflate(R.layout.row_qualified_products, parent, false); + return new ViewHolder(view); + } + + @SuppressLint("SetTextI18n") + @Override + public void onBindViewHolder(@NonNull final ViewHolder viewHolder, final int pos) { + ////show product selected + final InvoiceGetterSetter current = products.get(pos); + + viewHolder.tvstorename.setText("Product : " + current.getProduct().trim()); + viewHolder.tvstorename.setId(pos); + + viewHolder.qty_qualified.setText("QTY : " + current.getQuantity()); + viewHolder.qty_qualified.setId(pos); + + viewHolder.rate_qualified.setText("Rate : " + current.getProduct_rate()); + viewHolder.rate_qualified.setId(pos); + } + + @Override + public int getItemCount() { + return products.size(); + } + + public class ViewHolder extends RecyclerView.ViewHolder { + CardView card_view; + TextView tvstorename, qty_qualified, rate_qualified; + + public ViewHolder(@NonNull View itemView) { + super(itemView); + card_view = (CardView) itemView.findViewById(R.id.card_view); + tvstorename = (TextView) itemView.findViewById(R.id.tvstorename); + qty_qualified = (TextView) itemView.findViewById(R.id.qty_qualified); + rate_qualified = (TextView) itemView.findViewById(R.id.rate_qualified); + } + } + } + + private class MyWebViewClient extends WebViewClient { + @Override + public boolean shouldOverrideUrlLoading(WebView view, String url) { + view.loadUrl(url); + return true; + } + + @Override + public void onPageFinished(WebView view, String url) { + super.onPageFinished(view, url); + view.clearCache(true); + } + + @Override + public void onPageStarted(WebView view, String url, Bitmap favicon) { + super.onPageStarted(view, url, favicon); + } + } + + @Override + protected void onDestroy() { + super.onDestroy(); + if (loading != null && loading.isShowing()) { + loading.dismiss(); + } + } + + private Dialog dialog; + ProgressBar pb; + + class LoadTask extends AsyncTask { + boolean flag = false; + + @Override + protected void onPreExecute() { + super.onPreExecute(); + dialog = new Dialog(context); + dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); + Objects.requireNonNull(dialog.getWindow()).setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT)); + dialog.setContentView(R.layout.circular_progress_bar); + pb = (ProgressBar) dialog.findViewById(R.id.progressBar1); + dialog.setCancelable(false); + dialog.show(); + } + + @Override + protected Void doInBackground(Boolean... bool) { + flag = bool[0]; + if (flag) { + added_check_promotion(); + } else { + check_promotion_for_worth(); + } + return null; + } + + @Override + protected void onPostExecute(Void aVoid) { + super.onPostExecute(aVoid); + dialog.dismiss(); + + if (dialog != null && dialog.isShowing()) { + dialog.dismiss(); + } + } + } + + private void deletesome_temptable_data() { + try { + db.open(); + db.insert_consumer_tempsales_data(username, visit_date, CounterId, selected_list); + db.delete_table_temp(); + db.delete_table_tempforsameproduct(); + db.delete_table_tempfor_andpromo(); + } catch (Exception e) { + e.fillInStackTrace(); + } + } + + private void added_check_promotion() { + try { + db.open(); + deletesome_temptable_data(); + ///insert temp sale for checked Setentity Value promotion + ////get promotion by jeevan + ////for product promotion + db.open(); + ArrayList promoMaster = db.getPromotionMaster(true); + // //test("promosize", String.valueOf(promoMaster.size())); + + if (!promoMaster.isEmpty()) { + final ArrayList validPromoList = new ArrayList<>(); + for (int x = 0; x < promoMaster.size(); x++) { + //if promotion set entity type is - Product + ///--------for AND promotion ------ + if (promoMaster.get(x).getPromoType().equalsIgnoreCase("AND")) { + db.open(); + ArrayList promoAndList = db.getsetintitiytemId(promoMaster.get(x).getPromoId()); + if (!promoAndList.isEmpty()) { + boolean flag_for_and = true; + for (int q = 0; q < promoAndList.size(); q++) { + db.open(); + int product_countfor_and = db.getPromotiongetProductforAndPromo(promoAndList.get(q).getId(), + promoAndList.get(q).getPromoId().toString(), true, username, visit_date, CounterId); + ////checking AND promo itemcount + if (product_countfor_and >= promoAndList.get(q).getItemCount()) { + db.open(); + db.update_temp_promo_apply_definitionfor_andpromo(promoAndList.get(q).getId(), CounterId, username, + promoAndList.get(q).getPromoId(), visit_date); + } else { + db.open(); + flag_for_and = false; + db.delete_table_tempfor_andpromo(); + break; + } + } + + if (flag_for_and) { + //////--------insert all AND Promo data to Apply Definition.Table...----------- + db.open(); + db.inserttemp_promo_data(CounterId, visit_date, username, promoMaster.get(x)); + validPromoList.add(promoMaster.get(x)); + } + } + } else { + db.open(); + int product_count = db.getPromotiongetProductall(promoMaster.get(x), true, username, visit_date, CounterId); + //test("product_count", String.valueOf(product_count)); + if (product_count > 0) { + if (product_count >= Integer.parseInt(promoMaster.get(x).getPromotionSetEntityValue())) { + db.open(); + db.update_temp_promo_apply_definition(CounterId, username, promoMaster.get(x).getPromoId().toString(), visit_date); + validPromoList.add(promoMaster.get(x)); + } + } + } + } + + if (!validPromoList.isEmpty()) { + runOnUiThread(() -> { + if (dialog != null && dialog.isShowing()) { + dialog.dismiss(); + } + show_promotion_skuwise_dialog(context, selected_list, validPromoList, false); + }); + + } else { + ///finish + checkPromoWorth(promoMaster); + } + } else { + ////get promotion by jeevan + ////for worth promotion + db.open(); + promoMaster = db.getPromotionMaster(false); + //test("promosizeworth", String.valueOf(promoMaster.size())); + if (!promoMaster.isEmpty()) { + final ArrayList validPromoList = new ArrayList<>(); + for (int x = 0; x < promoMaster.size(); x++) { + //if promotion set entity type is - Product + ///--------for AND promotion ------ + if (promoMaster.get(x).getPromoType().equalsIgnoreCase("AND")) { + db.open(); + ArrayList promoAndList = db.getsetintitiytemId(promoMaster.get(x).getPromoId()); + if (!promoAndList.isEmpty()) { + boolean flag_for_and = true; + for (int q = 0; q < promoAndList.size(); q++) { + db.open(); + int product_countfor_and = db.getPromotiongetProductforAndPromo(promoAndList.get(q).getId(), promoAndList.get(q).getPromoId().toString(), false, username, visit_date, CounterId); + ////checking AND promo itemcount + if (product_countfor_and >= promoAndList.get(q).getItemCount()) { + db.open(); + db.update_temp_promo_apply_definitionfor_andpromo(promoAndList.get(q).getId(), CounterId, username, promoAndList.get(q).getPromoId(), visit_date); + } else { + db.open(); + flag_for_and = false; + db.delete_table_tempfor_andpromo(); + break; + } + } + + if (flag_for_and) { + //////--------insert all AND Promo data to Apply Definition.Table...----------- + db.open(); + db.inserttemp_promo_data(CounterId, visit_date, username, promoMaster.get(x)); + validPromoList.add(promoMaster.get(x)); + } + } + } else { + db.open(); + int product_count = db.getPromotiongetProductall(promoMaster.get(x), false, username, visit_date, CounterId); + //test("product_count", String.valueOf(product_count)); + if (product_count > 0) { + if (product_count >= Integer.parseInt(promoMaster.get(x).getPromotionSetEntityValue())) { + db.open(); + db.update_temp_promo_apply_definition(CounterId, username, promoMaster.get(x).getPromoId().toString(), visit_date); + validPromoList.add(promoMaster.get(x)); + } + } + } + } + + if (!validPromoList.isEmpty()) { + runOnUiThread(() -> { + if (dialog != null && dialog.isShowing()) { + dialog.dismiss(); + } + show_promotion_skuwise_dialog(context, selected_list, validPromoList, true); + }); + } else { + ///finish + runOnUiThread(() -> { + if (dialog != null && dialog.isShowing()) { + dialog.dismiss(); + } + drawer_layout_recycle_store.setAdapter(new ValueAdapter(context, selected_list)); + drawer_layout_recycle_store.setLayoutManager(new LinearLayoutManager(context)); + startActivity(new Intent(context, InvoiceReportProformaActivity.class). + putExtra(CommonString.TAG_OBJECT, selected_list) + .putExtra(CommonString.Key_For_Consumer_Update, flag_for_consumer_Update) + .putExtra(CommonString.Key_For_Reciept_Count, String.valueOf(reciept_count)). + putExtra(CommonString.FLAG_FOR_TERMCONDITION, str_termCondition) + .putExtra(CommonString.KEY_IMAGE, str_img_demo_no_sale).putExtra("from", from)); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + added_prmo_products = new ArrayList<>(); + }); + } + + } else { + + runOnUiThread(() -> { + if (dialog != null && dialog.isShowing()) { + dialog.dismiss(); + } + drawer_layout_recycle_store.setAdapter(new ValueAdapter(context, selected_list)); + drawer_layout_recycle_store.setLayoutManager(new LinearLayoutManager(context)); + startActivity(new Intent(context, InvoiceReportProformaActivity.class). + putExtra(CommonString.TAG_OBJECT, selected_list) + .putExtra(CommonString.Key_For_Consumer_Update, flag_for_consumer_Update) + .putExtra(CommonString.Key_For_Reciept_Count, String.valueOf(reciept_count)). + putExtra(CommonString.FLAG_FOR_TERMCONDITION, str_termCondition) + .putExtra(CommonString.KEY_IMAGE, str_img_demo_no_sale).putExtra("from", from)); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + added_prmo_products = new ArrayList<>(); + }); + } + + } + } catch (NumberFormatException e) { + e.fillInStackTrace(); + } + } + + private void checkPromoWorth(ArrayList promoMaster) { + db.open(); + promoMaster = db.getPromotionMaster(false); + if (!promoMaster.isEmpty()) { + final ArrayList validPromoList = new ArrayList<>(); + for (int x = 0; x < promoMaster.size(); x++) { + //if promotion set entity type is - Product + ///--------for AND promotion ------ + if (promoMaster.get(x).getPromoType().equalsIgnoreCase("AND")) { + db.open(); + ArrayList promoAndList = db.getsetintitiytemId(promoMaster.get(x).getPromoId()); + if (!promoAndList.isEmpty()) { + boolean flag_for_and = true; + for (int q = 0; q < promoAndList.size(); q++) { + db.open(); + int product_countfor_and = db.getPromotiongetProductforAndPromo(promoAndList.get(q).getId(), promoAndList.get(q).getPromoId().toString(), false, username, visit_date, CounterId); + ////checking AND promo itemcount + if (product_countfor_and >= promoAndList.get(q).getItemCount()) { + db.open(); + db.update_temp_promo_apply_definitionfor_andpromo(promoAndList.get(q).getId(), CounterId, username, promoAndList.get(q).getPromoId(), visit_date); + } else { + db.open(); + flag_for_and = false; + db.delete_table_tempfor_andpromo(); + break; + } + } + + if (flag_for_and) { + //////--------insert all AND Promo data to Apply Definition.Table...----------- + db.open(); + db.inserttemp_promo_data(CounterId, visit_date, username, promoMaster.get(x)); + validPromoList.add(promoMaster.get(x)); + } + } + } else { + db.open(); + int product_count = db.getPromotiongetProductall(promoMaster.get(x), false, username, visit_date, CounterId); + if (product_count > 0) { + if (product_count >= Integer.parseInt(promoMaster.get(x).getPromotionSetEntityValue())) { + db.open(); + db.update_temp_promo_apply_definition(CounterId, username, promoMaster.get(x).getPromoId().toString(), visit_date); + validPromoList.add(promoMaster.get(x)); + } + } + } + } + + if (!validPromoList.isEmpty()) { + runOnUiThread(() -> { + if (dialog != null && dialog.isShowing()) { + dialog.dismiss(); + } + show_promotion_skuwise_dialog(context, selected_list, validPromoList, true); + }); + } else { + ///finish + runOnUiThread(() -> { + if (dialog != null && dialog.isShowing()) { + dialog.dismiss(); + } + drawer_layout_recycle_store.setAdapter(new ValueAdapter(context, selected_list)); + drawer_layout_recycle_store.setLayoutManager(new LinearLayoutManager(context)); + startActivity(new Intent(context, InvoiceReportProformaActivity.class). + putExtra(CommonString.TAG_OBJECT, selected_list) + .putExtra(CommonString.Key_For_Consumer_Update, flag_for_consumer_Update) + .putExtra(CommonString.Key_For_Reciept_Count, String.valueOf(reciept_count)). + putExtra(CommonString.FLAG_FOR_TERMCONDITION, str_termCondition) + .putExtra(CommonString.KEY_IMAGE, str_img_demo_no_sale).putExtra("from", from)); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + added_prmo_products = new ArrayList(); + }); + } + + } else { + + runOnUiThread(() -> { + if (dialog != null && dialog.isShowing()) { + dialog.dismiss(); + } + drawer_layout_recycle_store.setAdapter(new ValueAdapter(context, selected_list)); + drawer_layout_recycle_store.setLayoutManager(new LinearLayoutManager(context)); + startActivity(new Intent(context, InvoiceReportProformaActivity.class). + putExtra(CommonString.TAG_OBJECT, selected_list) + .putExtra(CommonString.Key_For_Consumer_Update, flag_for_consumer_Update) + .putExtra(CommonString.Key_For_Reciept_Count, String.valueOf(reciept_count)). + putExtra(CommonString.FLAG_FOR_TERMCONDITION, str_termCondition) + .putExtra(CommonString.KEY_IMAGE, str_img_demo_no_sale).putExtra("from", from)); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + added_prmo_products = new ArrayList<>(); + }); + } + } + + private void check_promotion_for_worth() { + try { + db.open(); + deletesome_temptable_data(); + db.open(); + ArrayList promoMaster = db.getPromotionMaster(false); + if (!promoMaster.isEmpty()) { + final ArrayList validPromoList = new ArrayList<>(); + for (int x = 0; x < promoMaster.size(); x++) { + //if promotion set entity type is - Product + ///--------for AND promotion ------ + if (promoMaster.get(x).getPromoType().equalsIgnoreCase("AND")) { + db.open(); + ArrayList promoAndList = db.getsetintitiytemId(promoMaster.get(x).getPromoId()); + if (!promoAndList.isEmpty()) { + boolean flag_for_and = true; + for (int q = 0; q < promoAndList.size(); q++) { + db.open(); + int product_countfor_and = db.getPromotiongetProductforAndPromo(promoAndList.get(q).getId(), promoAndList.get(q).getPromoId().toString(), false, username, visit_date, CounterId); + ////checking AND promo itemcount + if (product_countfor_and >= promoAndList.get(q).getItemCount()) { + db.open(); + db.update_temp_promo_apply_definitionfor_andpromo(promoAndList.get(q).getId(), CounterId, username, promoAndList.get(q).getPromoId(), visit_date); + } else { + db.open(); + flag_for_and = false; + db.delete_table_tempfor_andpromo(); + break; + } + } + if (flag_for_and) { + //////--------insert all AND Promo data to Apply Definition.Table...----------- + db.open(); + db.inserttemp_promo_data(CounterId, visit_date, username, promoMaster.get(x)); + validPromoList.add(promoMaster.get(x)); + } + } + } else { + db.open(); + int product_count = db.getPromotiongetProductall(promoMaster.get(x), false, username, visit_date, CounterId); + //test("Productcount", String.valueOf(product_count)); + if (product_count > 0) { + if (product_count >= Integer.parseInt(promoMaster.get(x).getPromotionSetEntityValue())) { + db.open(); + db.update_temp_promo_apply_definition(CounterId, username, promoMaster.get(x).getPromoId().toString(), visit_date); + validPromoList.add(promoMaster.get(x)); + } + } + } + } + if (!validPromoList.isEmpty()) { + runOnUiThread(() -> show_promotion_skuwise_dialog(context, selected_list, validPromoList, true)); + + } else { + runOnUiThread(() -> { + if (!added_prmo_products.isEmpty()) { + selected_list.addAll(added_prmo_products); + } + added_prmo_products = new ArrayList<>(); + ///finish + drawer_layout_recycle_store.setAdapter(new ValueAdapter(context, selected_list)); + drawer_layout_recycle_store.setLayoutManager(new LinearLayoutManager(context)); + startActivity(new Intent(context, InvoiceReportProformaActivity.class). + putExtra(CommonString.TAG_OBJECT, selected_list) + .putExtra(CommonString.Key_For_Consumer_Update, flag_for_consumer_Update) + .putExtra(CommonString.Key_For_Reciept_Count, String.valueOf(reciept_count)). + putExtra(CommonString.FLAG_FOR_TERMCONDITION, str_termCondition) + .putExtra(CommonString.KEY_IMAGE, str_img_demo_no_sale).putExtra("from", from)); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + added_prmo_products = new ArrayList<>(); + }); + } + } else { + + runOnUiThread(() -> { + if (!added_prmo_products.isEmpty()) { + selected_list.addAll(added_prmo_products); + } + added_prmo_products = new ArrayList<>(); + drawer_layout_recycle_store.setAdapter(new ValueAdapter(context, selected_list)); + drawer_layout_recycle_store.setLayoutManager(new LinearLayoutManager(context)); + startActivity(new Intent(context, InvoiceReportProformaActivity.class). + putExtra(CommonString.TAG_OBJECT, selected_list) + .putExtra(CommonString.Key_For_Consumer_Update, flag_for_consumer_Update) + .putExtra(CommonString.Key_For_Reciept_Count, String.valueOf(reciept_count)). + putExtra(CommonString.FLAG_FOR_TERMCONDITION, str_termCondition) + .putExtra(CommonString.KEY_IMAGE, str_img_demo_no_sale).putExtra("from", from)); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + added_prmo_products = new ArrayList<>(); + }); + } + } catch (NumberFormatException e) { + e.fillInStackTrace(); + } + } + + private InvoiceGetterSetter returnobject() { + InvoiceGetterSetter object = new InvoiceGetterSetter(); + try { + object = new InvoiceGetterSetter(); + // get selected radio button from radioGroup + int selectedId = radioSexGroup.getCheckedRadioButtonId(); + // find the radiobutton by returned id + radioSexButton = (RadioButton) findViewById(selectedId); + object.setUserName(username); + object.setStore_name(storeDataObject.getCounterName()); + object.setStore_address(storeDataObject.getAddress() + "," + storeDataObject.getCityName()); + object.setCustomer_name(CommonFunctions.removed_special_char(edt_customer)); + object.setMobile_no(edt_mobile_no.getText().toString()); + object.setConsumer_email_Id(edt_email_address.getText().toString()); + if (spin_age.getSelectedItemId() == 0) { + object.setConsumer_age(""); + } else { + object.setConsumer_age(spin_age.getSelectedItem().toString()); + } + if (spin_skin_type.getSelectedItemId() == 0) { + object.setConsumer_skinType(""); + } else { + object.setConsumer_skinType(spin_skin_type.getSelectedItem().toString()); + } + object.setCustomer_gender(radioSexButton.getText().toString()); + object.setDemo_given_str(demo_given_str); + object.setSkin_genius_str(skin_genius_str); + object.setMaybelline_vto_str(maybelline_vto); + object.setProduct_sold_str(product_sold_str); + object.setPercheasing_tym(perchasing_tym); + object.setSourceofSales(str_sourceof_sales); + object.setConsumer_no_saleImg(str_img_demo_no_sale); + } catch (Exception e) { + e.fillInStackTrace(); + } + + return object; + } +} + diff --git a/app/src/main/java/com/cpm/lorealbaautomation/consumeractivity/InvoiceReportProformaActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/consumeractivity/InvoiceReportProformaActivity.java new file mode 100644 index 0000000..3053bf2 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/consumeractivity/InvoiceReportProformaActivity.java @@ -0,0 +1,567 @@ +package com.cpm.lorealbaautomation.consumeractivity; + +import android.annotation.SuppressLint; +import android.app.AlertDialog; + +import android.app.Dialog; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.graphics.drawable.ColorDrawable; +import android.os.AsyncTask; +import android.os.Bundle; + +import com.google.android.material.floatingactionbutton.FloatingActionButton; + +import androidx.annotation.NonNull; +import androidx.appcompat.app.AppCompatActivity; +import androidx.appcompat.widget.SwitchCompat; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; +import androidx.appcompat.widget.Toolbar; + +import android.util.Log; +import android.view.LayoutInflater; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; +import android.view.Window; +import android.widget.CompoundButton; +import android.widget.ImageView; +import android.widget.LinearLayout; +import android.widget.ProgressBar; +import android.widget.TextView; + +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.constant.AlertandMessages; +import com.cpm.lorealbaautomation.constant.CommonFunctions; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.gsonGetterSetter.InvoiceGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.JourneyPlan; +import com.cpm.lorealbaautomation.printer.PrinterActivity; + + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Objects; + +public class InvoiceReportProformaActivity extends AppCompatActivity implements View.OnClickListener, CompoundButton.OnCheckedChangeListener { + String CounterId, counterCode, visit_date, username, flag_for_consumer_Update = "", reciept_count = "", TransId = "", disable_pos = "", str_termCondition = "0", str_img_demo_no_sale = ""; + ArrayList invoice_List = new ArrayList<>(); + TextView text_cus_name, text_mobile_number, text_inr_value, invoice_storename, invoice_storename_address, invoice_gst_no; + RecyclerView drawer_layout_recycle_store; + LinearLayout rl_pos; + double total = 0.0; + double off_worth_total = 0.0, worth_total = 0.0, OffSameProduct = 0.0, off_worth_additional = 0.0, value_off_worth_additional = 0.0; + boolean pos_sale_flag = false; + // Array of choices + SwitchCompat switch_pos_sale; + FloatingActionButton fab; + ImageView img_printer; + Lorealba_Database db; + Context context; + ArrayList consumerSalesHeaderList; + HashMap> listDataChild; + JourneyPlan storeDataObject = new JourneyPlan(); + String from = ""; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_invoice_report_proforma); + from = getIntent().getStringExtra("from"); + context = this; + db = new Lorealba_Database(context); + db.open(); + validateui_design(); + setTitle("Pink Slip -" + username); + prepareListData(); + } + + @SuppressLint({"RestrictedApi", "SetTextI18n", "CommitPrefEdits"}) + void validateui_design() { + Toolbar toolbar = findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + Objects.requireNonNull(getSupportActionBar()).setHomeButtonEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + if (!CommonFunctions.isTablet(context)) { + toolbar.setTitleTextAppearance(context, R.style.changestext_sizefor_mobile); + } + SharedPreferences preferences = PrefHelper.getPrefs(context); + CounterId = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + counterCode = preferences.getString(CommonString.KEY_COUNTER_CODE, ""); + username = preferences.getString(CommonString.KEY_USERNAME, ""); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + drawer_layout_recycle_store = findViewById(R.id.drawer_layout_recycle_store); + text_cus_name = (TextView) findViewById(R.id.text_cus_name); + text_mobile_number = (TextView) findViewById(R.id.text_mobile_number); + text_inr_value = (TextView) findViewById(R.id.text_inr_value); + fab = (FloatingActionButton) findViewById(R.id.fab); + img_printer = (ImageView) findViewById(R.id.img_printer); + rl_pos = (LinearLayout) findViewById(R.id.rl_pos); + + invoice_storename = (TextView) findViewById(R.id.invoice_storename); + invoice_storename_address = (TextView) findViewById(R.id.invoice_storename_address); + invoice_gst_no = (TextView) findViewById(R.id.invoice_gst_no); + switch_pos_sale = (SwitchCompat) findViewById(R.id.switch_pos_sale); + + switch_pos_sale.setSwitchPadding(40); + switch_pos_sale.setOnCheckedChangeListener(this); + db.open(); + storeDataObject = db.getspecific_storenamewith_counter_name(visit_date, CounterId, username); + if (storeDataObject != null && storeDataObject.getStoreName() != null) { + invoice_storename.setText("Counter Code : " + counterCode + " , Counter Name - " + storeDataObject.getCounterName()); + invoice_storename_address.setText(storeDataObject.getAddress() + " , " + storeDataObject.getCityName()); + } + + invoice_gst_no.setText("Date : " + visit_date); + invoice_List = (ArrayList) getIntent().getSerializableExtra(CommonString.TAG_OBJECT); + flag_for_consumer_Update = getIntent().getStringExtra(CommonString.Key_For_Consumer_Update); + reciept_count = getIntent().getStringExtra(CommonString.Key_For_Reciept_Count); + disable_pos = getIntent().getStringExtra(CommonString.Key_For_Disable_POS_And_Save); + str_termCondition = getIntent().getStringExtra(CommonString.FLAG_FOR_TERMCONDITION); + str_img_demo_no_sale = getIntent().getStringExtra(CommonString.KEY_IMAGE); + TransId = CommonFunctions.getUUID(context); + + if (invoice_List != null && !invoice_List.isEmpty()) { + username = invoice_List.get(0).getUserName(); + text_cus_name.setText("Customer Name : " + invoice_List.get(0).getCustomer_name()); + text_mobile_number.setText("Mobile Number : " + invoice_List.get(0).getMobile_no()); + + calculate_invoice_added_data(invoice_List); + drawer_layout_recycle_store.setAdapter(new ValueAdapter(context, invoice_List)); + drawer_layout_recycle_store.setLayoutManager(new LinearLayoutManager(context)); + text_inr_value.setText("" + total); + } + + img_printer.setOnClickListener(this); + fab.setOnClickListener(this); + setreciept_count(); + if (disable_pos != null && disable_pos.equals("1")) { + fab.setVisibility(View.GONE); + rl_pos.setVisibility(View.GONE); + } + } + + private void setreciept_count() { + try { + for (int k = 0; k < invoice_List.size(); k++) { + invoice_List.get(k).setUnique_code(TransId); + } + } catch (Exception e) { + e.fillInStackTrace(); + } + } + + + @SuppressLint("NonConstantResourceId") + @Override + public void onClick(View view) { + + if (view.getId() == R.id.fab) { + AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle(R.string.parinaam).setMessage(R.string.alertsaveData); + builder.setPositiveButton(android.R.string.yes, (dialogInterface, i) -> new InsertAsync().execute()).setNegativeButton(android.R.string.cancel, (dialogInterface, i) -> dialogInterface.cancel()); + builder.show(); + } else if (view.getId() == R.id.img_printer) { + startActivity(new Intent(context, PrinterActivity.class).putExtra(CommonString.TAG_OBJECT, invoice_List)); + } + } + + private long calculate_data_insert_data() { + long l = 0; + try { + if (flag_for_consumer_Update != null && flag_for_consumer_Update.equals("1")) { + db.open(); + db.deleteconsumersale(visit_date, Integer.parseInt(reciept_count), username); + db.open(); + l = db.insert_consumer_sales_data(username, visit_date, CounterId, String.valueOf(total), pos_sale_flag, TransId, str_termCondition, listDataChild, consumerSalesHeaderList, str_img_demo_no_sale, from); + } else { + db.open(); + l = db.insert_consumer_sales_data(username, visit_date, CounterId, String.valueOf(total), pos_sale_flag, TransId, str_termCondition, listDataChild, consumerSalesHeaderList, str_img_demo_no_sale, from); + } + } catch (NumberFormatException e) { + e.fillInStackTrace(); + } + + return l; + } + + @Override + public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) { + if (compoundButton.getId() == R.id.switch_pos_sale) { + pos_sale_flag = isChecked; + Log.i("switch_compat", String.valueOf(isChecked)); + } + + } + + private class ValueAdapter extends RecyclerView.Adapter { + private final LayoutInflater inflator; + List data; + + public ValueAdapter(Context context, List data) { + inflator = LayoutInflater.from(context); + this.data = data; + } + + @NonNull + @Override + public ValueAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) { + View view = inflator.inflate(R.layout.row_adapter_proforma_invoice, parent, false); + return new ValueAdapter.MyViewHolder(view); + } + + @SuppressLint("SetTextI18n") + @Override + public void onBindViewHolder(@NonNull final ValueAdapter.MyViewHolder holder, final int position) { + final InvoiceGetterSetter current = data.get(position); + + if (current.isPromo_flag() && current.getPromo_type().equalsIgnoreCase("OffSameProduct")) { + holder.select_promo_productRl.setVisibility(View.VISIBLE); + holder.select_promo_productRl.setId(position); + + holder.select_productRl.setVisibility(View.GONE); + holder.select_productRl.setId(position); + + if (CommonFunctions.isTablet(context)) { + holder.txt_promo_str.setText("Applied Promo - " + current.getPromotion_name() + " - " + "Discounted Rs - " + current.getProduct()); + holder.txt_promo_str.setId(position); + } else { + holder.txt_promo_str.setText("Applied Promo - " + current.getPromotion_name() + "\n" + "Discounted Rs - " + current.getProduct()); + holder.txt_promo_str.setId(position); + } + } else if (current.isPromo_flag() && current.getPromo_type().equalsIgnoreCase("OffAdditionalProduct")) { + holder.select_promo_productRl.setVisibility(View.VISIBLE); + holder.select_promo_productRl.setId(position); + holder.select_productRl.setVisibility(View.GONE); + holder.select_productRl.setId(position); + + if (CommonFunctions.isTablet(context)) { + holder.txt_promo_str.setText("Applied Promo - " + current.getPromotion_name() + " - " + "Discounted Rs - " + current.getProduct()); + holder.txt_promo_str.setId(position); + } else { + holder.txt_promo_str.setText("Applied Promo - " + current.getPromotion_name() + "\n" + "Discounted Rs - " + current.getProduct()); + holder.txt_promo_str.setId(position); + } + } else if (current.isPromo_flag() && current.getPromo_type().equalsIgnoreCase("ValueOffAdditionalProduct")) { + holder.select_promo_productRl.setVisibility(View.VISIBLE); + holder.select_promo_productRl.setId(position); + + holder.select_productRl.setVisibility(View.GONE); + holder.select_productRl.setId(position); + + if (CommonFunctions.isTablet(context)) { + holder.txt_promo_str.setText("Applied Promo - " + current.getPromotion_name() + " - " + "Discounted Rs - " + current.getProduct()); + holder.txt_promo_str.setId(position); + } else { + holder.txt_promo_str.setText("Applied Promo - " + current.getPromotion_name() + "\n" + "Discounted Rs - " + current.getProduct()); + holder.txt_promo_str.setId(position); + } + } else if (current.isPromo_flag() && current.getPromo_type().equalsIgnoreCase("OffWorth") || current.isPromo_flag() && current.getPromo_type().equalsIgnoreCase("WorthWithProduct")) { + holder.select_promo_productRl.setVisibility(View.VISIBLE); + holder.select_promo_productRl.setId(position); + + holder.select_productRl.setVisibility(View.GONE); + holder.select_productRl.setId(position); + + if (CommonFunctions.isTablet(context)) { + holder.txt_promo_str.setText("Applied Promo - " + current.getPromotion_name() + " - " + "Discounted Rs - " + current.getProduct()); + holder.txt_promo_str.setId(position); + } else { + holder.txt_promo_str.setText("Applied Promo - " + current.getPromotion_name() + "\n" + "Discounted Rs - " + current.getProduct()); + holder.txt_promo_str.setId(position); + } + } else if (current.isPromo_flag() && current.getPromo_type().equalsIgnoreCase("OffProduct")) { + holder.select_promo_productRl.setVisibility(View.GONE); + holder.select_promo_productRl.setId(position); + + holder.select_productRl.setVisibility(View.VISIBLE); + holder.select_productRl.setId(position); + + holder.product.setText("Applied Promo - " + current.getPromotion_name() + " - " + current.getProduct() + " - Discounted Rs - " + current.getSkuType()); + holder.product.setId(position); + + holder.qty.setText(current.getQuantity()); + holder.qty.setId(position); + + holder.rate.setText(current.getProduct_rate()); + holder.rate.setId(position); + + holder.total_amount.setText(current.getTotal_amount()); + holder.total_amount.setId(position); + + + } else if (current.isPromo_flag() && current.getPromo_type().equalsIgnoreCase("Worth")) { + holder.select_promo_productRl.setVisibility(View.VISIBLE); + holder.select_promo_productRl.setId(position); + + holder.select_productRl.setVisibility(View.GONE); + holder.select_productRl.setId(position); + + if (CommonFunctions.isTablet(context)) { + holder.txt_promo_str.setText("Applied Promo - " + current.getPromotion_name() + " - " + "Discounted Rs - " + current.getProduct()); + holder.txt_promo_str.setId(position); + } else { + holder.txt_promo_str.setText("Applied Promo - " + current.getPromotion_name() + "\n" + "Discounted Rs - " + current.getProduct()); + holder.txt_promo_str.setId(position); + } + + } else if (current.isPromo_flag() && current.getPromo_type().equalsIgnoreCase("Gift")) { + holder.select_promo_productRl.setVisibility(View.VISIBLE); + holder.select_promo_productRl.setId(position); + + holder.select_productRl.setVisibility(View.GONE); + holder.select_productRl.setId(position); + + if (CommonFunctions.isTablet(context)) { + holder.txt_promo_str.setText("Applied Promo - " + current.getPromotion_name() + " - " + "Gift - " + current.getProduct()); + holder.txt_promo_str.setId(position); + } else { + holder.txt_promo_str.setText("Applied Promo - " + current.getPromotion_name() + "\n" + "Gift - " + current.getProduct()); + holder.txt_promo_str.setId(position); + } + + + } else if (current.isPromo_flag() && current.getPromo_type().equalsIgnoreCase("Product")) { + holder.select_promo_productRl.setVisibility(View.VISIBLE); + holder.select_promo_productRl.setId(position); + + holder.select_productRl.setVisibility(View.GONE); + holder.select_productRl.setId(position); + + if (CommonFunctions.isTablet(context)) { + holder.txt_promo_str.setText("Applied Promo - " + current.getPromotion_name() + " - (" + current.getProduct().toLowerCase() + ")"); + holder.txt_promo_str.setId(position); + } else { + holder.txt_promo_str.setText("Applied Promo - " + current.getPromotion_name() + "\n" + current.getProduct().toLowerCase()); + holder.txt_promo_str.setId(position); + } + } else { + holder.select_promo_productRl.setVisibility(View.GONE); + holder.select_promo_productRl.setId(position); + holder.select_productRl.setVisibility(View.VISIBLE); + holder.select_productRl.setId(position); + if (current.getDiscount() != 0.0) { + String string = current.getDiscount().toString(); + holder.product.setText(current.getProduct() + "\n" + string.substring(string.length() - 1) + "0% Discount - " + current.getDiscounted_value()); + + holder.product.setId(position); + + holder.rate.setText(current.getProduct_rate()); + holder.rate.setId(position); + + holder.total_amount.setText(String.valueOf(current.getActual_price_per_product())); + holder.total_amount.setId(position); + + holder.qty.setText(current.getQuantity()); + holder.qty.setId(position); + } else { + holder.rate.setText(current.getProduct_rate()); + holder.rate.setId(position); + holder.total_amount.setText(current.getTotal_amount()); + holder.total_amount.setId(position); + holder.qty.setText(current.getQuantity()); + holder.qty.setId(position); + + if (!current.getStr_invoiceType().isEmpty() && current.getStr_invoiceType().equalsIgnoreCase("Sample") || !current.getStr_invoiceType().isEmpty() && current.getStr_invoiceType().equalsIgnoreCase("GWP")) { + holder.product.setText(current.getProduct() + " - Type - " + current.getStr_invoiceType()); + holder.product.setId(position); + } else { + holder.product.setText(current.getProduct()); + holder.product.setId(position); + } + } + } + } + + @Override + public int getItemCount() { + return data.size(); + } + + class MyViewHolder extends RecyclerView.ViewHolder { + TextView product, qty, rate, total_amount, txt_promo_str; + LinearLayout select_promo_productRl, select_productRl; + + public MyViewHolder(View itemView) { + super(itemView); + product = (TextView) itemView.findViewById(R.id.product); + qty = (TextView) itemView.findViewById(R.id.qty); + rate = (TextView) itemView.findViewById(R.id.rate); + total_amount = (TextView) itemView.findViewById(R.id.total_amount); + txt_promo_str = (TextView) itemView.findViewById(R.id.txt_promo_str); + select_promo_productRl = (LinearLayout) itemView.findViewById(R.id.select_promo_productRl); + select_productRl = (LinearLayout) itemView.findViewById(R.id.select_productRl); + } + } + } + + @Override + public void onBackPressed() { + super.onBackPressed(); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + InvoiceReportProformaActivity.this.finish(); + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + if (id == android.R.id.home) { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + InvoiceReportProformaActivity.this.finish(); + } + + return super.onOptionsItemSelected(item); + } + + private void calculate_invoice_added_data(ArrayList invoice_List) { + double cCom = 0.0, total_INR_value = 0.0; + try { + for (int k = 0; k < invoice_List.size(); k++) { + if (!invoice_List.get(k).isPromo_flag()) { + if (invoice_List.get(k).getDiscount() != 0.0) { + int quantity = Integer.parseInt(invoice_List.get(k).getQuantity()); + double amount = Double.parseDouble(invoice_List.get(k).getProduct_rate()); + amount = amount * quantity; + invoice_List.get(k).setTotal_amount(String.valueOf(amount)); + cCom = cCom + ((Double.parseDouble(invoice_List.get(k).getTotal_amount())) * invoice_List.get(k).getDiscount()); + } else { + int quantity = Integer.parseInt(invoice_List.get(k).getQuantity()); + double amount = Double.parseDouble(invoice_List.get(k).getProduct_rate()); + amount = amount * quantity; + invoice_List.get(k).setTotal_amount(String.valueOf(amount)); + } + + invoice_List.get(k).setStore_name(storeDataObject.getStoreName()); + invoice_List.get(k).setStore_address(storeDataObject.getAddress() + "," + storeDataObject.getCityName()); + + double amount_ofproduct = ((Double.parseDouble(invoice_List.get(k).getTotal_amount())) * invoice_List.get(k).getDiscount()); + amount_ofproduct = (Double.parseDouble(invoice_List.get(k).getTotal_amount())) - amount_ofproduct; + + total_INR_value = total_INR_value + Double.parseDouble(invoice_List.get(k).getTotal_amount()); + + if (invoice_List.get(k).getDiscount() == 0.0 || invoice_List.get(k).getDiscount() == 0) { + invoice_List.get(k).setActual_price_per_product((Double.parseDouble(invoice_List.get(k).getTotal_amount()))); + invoice_List.get(k).setDiscounted_value(0.0); + } else { + invoice_List.get(k).setDiscounted_value(((Double.parseDouble(invoice_List.get(k).getTotal_amount())) * invoice_List.get(k).getDiscount())); + invoice_List.get(k).setActual_price_per_product((Double.parseDouble(invoice_List.get(k).getTotal_amount()) - ((Double.parseDouble(invoice_List.get(k).getTotal_amount())) * invoice_List.get(k).getDiscount()))); + } + } else { + if (invoice_List.get(k).getPromo_type().equalsIgnoreCase("OffProduct")) { + if (invoice_List.get(k).getDiscount() != 0.0) { + int quantity = Integer.parseInt(invoice_List.get(k).getQuantity()); + double amount = Double.parseDouble(invoice_List.get(k).getProduct_rate()); + amount = amount * quantity; + amount = amount - Integer.parseInt(invoice_List.get(k).getSkuType()); + invoice_List.get(k).setTotal_amount(String.valueOf(amount)); + cCom = cCom + ((Double.parseDouble(invoice_List.get(k).getTotal_amount())) * invoice_List.get(k).getDiscount()); + } else { + int quantity = Integer.parseInt(invoice_List.get(k).getQuantity()); + double amount = Double.parseDouble(invoice_List.get(k).getProduct_rate()); + amount = amount * quantity; + amount = amount - Integer.parseInt(invoice_List.get(k).getSkuType()); + invoice_List.get(k).setTotal_amount(String.valueOf(amount)); + } + + invoice_List.get(k).setStore_name(storeDataObject.getStoreName()); + invoice_List.get(k).setStore_address(storeDataObject.getAddress() + "," + storeDataObject.getCityName()); + double amount_ofproduct = ((Double.parseDouble(invoice_List.get(k).getTotal_amount())) * invoice_List.get(k).getDiscount()); + amount_ofproduct = (Double.parseDouble(invoice_List.get(k).getTotal_amount())) - amount_ofproduct; + if (invoice_List.get(k).getDiscount() == 0.0 || invoice_List.get(k).getDiscount() == 0) { + invoice_List.get(k).setActual_price_per_product((Double.parseDouble(invoice_List.get(k).getTotal_amount()))); + invoice_List.get(k).setDiscounted_value(0.0); + } else { + invoice_List.get(k).setDiscounted_value(((Double.parseDouble(invoice_List.get(k).getTotal_amount())) * invoice_List.get(k).getDiscount())); + invoice_List.get(k).setActual_price_per_product((Double.parseDouble(invoice_List.get(k).getTotal_amount()) - ((Double.parseDouble(invoice_List.get(k).getTotal_amount())) * invoice_List.get(k).getDiscount()))); + } + + total_INR_value = total_INR_value + Double.parseDouble(invoice_List.get(k).getTotal_amount()); + } else if (invoice_List.get(k).getPromo_type().equalsIgnoreCase("OffWorth") || invoice_List.get(k).getPromo_type().equalsIgnoreCase("WorthWithProduct")) { + off_worth_total = off_worth_total + Double.parseDouble(invoice_List.get(k).getProduct()); + } else if (invoice_List.get(k).getPromo_type().equalsIgnoreCase("OffAdditionalProduct")) { + off_worth_additional = off_worth_additional + Double.parseDouble(invoice_List.get(k).getProduct()); + } else if (invoice_List.get(k).getPromo_type().equalsIgnoreCase("ValueOffAdditionalProduct")) { + value_off_worth_additional = value_off_worth_additional + Double.parseDouble(invoice_List.get(k).getProduct()); + } else if (invoice_List.get(k).getPromo_type().equalsIgnoreCase("Worth")) { + worth_total = worth_total + Double.parseDouble(invoice_List.get(k).getProduct()); + } else if (invoice_List.get(k).getPromo_type().equalsIgnoreCase("OffSameProduct")) { + OffSameProduct = OffSameProduct + Double.parseDouble(invoice_List.get(k).getProduct()); + } + } + } + + + total = total_INR_value - cCom; + total = total - off_worth_total; + total = total - value_off_worth_additional; + total = total - worth_total; + total = total - OffSameProduct; + total = total - off_worth_additional; + } catch (NumberFormatException e) { + e.fillInStackTrace(); + } + } + + private void prepareListData() { + consumerSalesHeaderList = new ArrayList<>(); + listDataChild = new HashMap<>(); + consumerSalesHeaderList.add(invoice_List.get(0)); + consumerSalesHeaderList.size();// Adding child data + for (int i = 0; i < consumerSalesHeaderList.size(); i++) { + listDataChild.put(consumerSalesHeaderList.get(i), invoice_List); // Header, Child data + } + } + + @SuppressLint("StaticFieldLeak") + private class InsertAsync extends AsyncTask { + boolean flag = false; + Dialog dialog = null; + long l = 0; + ProgressBar pb; + + @Override + protected void onPreExecute() { + dialog = new Dialog(context); + dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); + Objects.requireNonNull(dialog.getWindow()).setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT)); + dialog.setContentView(R.layout.circular_progress_bar); + pb = (ProgressBar) dialog.findViewById(R.id.progressBar1); + dialog.setCancelable(false); + dialog.show(); + super.onPreExecute(); + } + + @Override + protected Void doInBackground(Boolean... bool) { + l = calculate_data_insert_data(); + if (l > 0) { + if (pos_sale_flag) { + if (CommonFunctions.checkNetIsAvailable(context)) { + CommonFunctions.call_upload(context); + } + } + } + return null; + } + + @Override + protected void onPostExecute(Void aVoid) { + super.onPostExecute(aVoid); + dialog.cancel(); + if (l > 0) { + startActivity(new Intent(context, ConsumerIntractionDetailActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP).putExtra("from", from)); + AlertandMessages.showToastMsg(context, "Data Saved Successfully"); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + InvoiceReportProformaActivity.this.finish(); + } else { + AlertandMessages.showToastMsg(context, "Data not Saved.Please try again."); + } + } + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/BAProfileActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/BAProfileActivity.java new file mode 100644 index 0000000..bc84337 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/BAProfileActivity.java @@ -0,0 +1,1079 @@ +package com.cpm.lorealbaautomation.dailyactivity; + +import android.annotation.SuppressLint; +import android.app.Activity; +import android.app.AlertDialog; +import android.app.DatePickerDialog; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.graphics.Bitmap; +import android.graphics.BitmapFactory; +import android.os.Bundle; + +import com.google.android.material.floatingactionbutton.FloatingActionButton; + +import androidx.annotation.NonNull; +import androidx.core.content.ContextCompat; +import androidx.appcompat.app.AppCompatActivity; +import androidx.cardview.widget.CardView; +import androidx.recyclerview.widget.RecyclerView; +import androidx.appcompat.widget.Toolbar; + +import android.text.InputFilter; +import android.text.InputType; +import android.text.Spanned; +import android.util.Log; +import android.view.LayoutInflater; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; +import android.view.WindowManager; +import android.view.inputmethod.InputMethodManager; +import android.widget.AbsListView; +import android.widget.AdapterView; +import android.widget.ArrayAdapter; +import android.widget.BaseExpandableListAdapter; +import android.widget.EditText; +import android.widget.ExpandableListView; +import android.widget.ImageView; +import android.widget.RadioGroup; +import android.widget.RelativeLayout; +import android.widget.Spinner; +import android.widget.TextView; + +import com.androidbuts.multispinnerfilter.KeyPairBoolData; +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.constant.AlertandMessages; +import com.cpm.lorealbaautomation.constant.CommonFunctions; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.constant.RoundedImageView; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.download.Downloader; +import com.cpm.lorealbaautomation.gettersetter.AuditDataGetterSetter; +import com.cpm.lorealbaautomation.gettersetter.BaProfileGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.JourneyPlan; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterProfile; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterProfileQuestion; +import com.cpm.lorealbaautomation.makeupexpert.BaProfileMultiSelection; +import com.squareup.picasso.NetworkPolicy; +import com.squareup.picasso.Picasso; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.HashMap; +import java.util.List; +import java.util.Objects; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import static com.cpm.lorealbaautomation.constant.CommonFunctions.getCurrentTime; +import static com.cpm.lorealbaautomation.dailyactivity.StoreImageActivity.convertBitmap; + +public class BAProfileActivity extends AppCompatActivity implements View.OnClickListener { + EditText edt_employee_code, edt_full_name, supervisor_name, edt_address, edt_brand, edt_counter, edt_store_name, edt_location, edt_mobile_no, edt_email, edt_enstagram_address, edt_city, edt_current_bp; + EditText edt_landmark; + ImageView img_dob; + Toolbar toolbar; + TextView storeProfile_dob; + private RoundedImageView round_img_pic; + ArrayList baProfileListData = new ArrayList<>(); + Lorealba_Database db; + SharedPreferences preferences; + SharedPreferences.Editor editor = null; + Context context; + String counterId, visitdate, user_type; + boolean update_flag = false; + String user_name; + int mYear, mMonth, mDay; + DatePickerDialog dpd; + Calendar c; + List checkHeaderArray = new ArrayList<>(); + List checkGroupArray = new ArrayList<>(); + boolean checkflag = true; + String pathforcheck = "", _path = "", str, img_str = ""; + ArrayList question_list, childListData; + HashMap> hashMapAnsListChildData; + int child_position = -1; + String error_msg = ""; + ExpandableListView expandableListView; + ExpandableListAdapter adapter; + ArrayList listDataHeader = new ArrayList<>(); + HashMap> listDataChild; + FloatingActionButton fab; + ArrayList storelist = new ArrayList<>(); + String merCd; + MasterProfile baProfileGetterSetter = new MasterProfile(); + boolean multitouch = false; + Bitmap bitmp; + private RadioGroup radioSexGroup; + TextView profile_user, profile_user_type; + boolean backpress_flag = false; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_baprofile); + getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); + getViewId(); + validate(); + getQuizProfileData(); + } + + @Override + protected void onResume() { + super.onResume(); + context = this; + db.open(); + } + + + void getViewId() { + context = this; + db = new Lorealba_Database(context); + db.open(); + preferences = PrefHelper.getPrefs(context); + editor = preferences.edit(); + str = CommonString.getImagesFolder(context); + counterId = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + visitdate = preferences.getString(CommonString.KEY_DATE, ""); + user_name = preferences.getString(CommonString.KEY_USERNAME, ""); + user_type = preferences.getString(CommonString.KEY_USER_TYPE, ""); + radioSexGroup = (RadioGroup) findViewById(R.id.radioGrp); + edt_employee_code = (EditText) findViewById(R.id.edt_employee_code); + edt_full_name = (EditText) findViewById(R.id.edt_full_name); + supervisor_name = (EditText) findViewById(R.id.supervisor_name); + + edt_address = (EditText) findViewById(R.id.edt_address); + storeProfile_dob = (TextView) findViewById(R.id.storeProfile_dob); + profile_user = (TextView) findViewById(R.id.profile_user); + profile_user_type = (TextView) findViewById(R.id.profile_user_type); + edt_brand = (EditText) findViewById(R.id.edt_brand); + edt_counter = (EditText) findViewById(R.id.edt_counter); + edt_store_name = (EditText) findViewById(R.id.edt_store_name); + edt_location = (EditText) findViewById(R.id.edt_location); + edt_city = (EditText) findViewById(R.id.edt_city); + edt_mobile_no = (EditText) findViewById(R.id.edt_mobile_no); + edt_email = (EditText) findViewById(R.id.edt_email); + edt_enstagram_address = (EditText) findViewById(R.id.edt_enstagram_address); + edt_current_bp = (EditText) findViewById(R.id.edt_current_bp); + edt_landmark = (EditText) findViewById(R.id.edt_landmark); + img_dob = (ImageView) findViewById(R.id.img_dob); + round_img_pic = (RoundedImageView) findViewById(R.id.round_img_pic); + toolbar = findViewById(R.id.toolbar); + fab = (FloatingActionButton) findViewById(R.id.fab); + setSupportActionBar(toolbar); + Objects.requireNonNull(getSupportActionBar()).setHomeButtonEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + if (!CommonFunctions.isTablet(context)) { + toolbar.setTitleTextAppearance(context, R.style.changestext_sizefor_mobile); + } + + if (!user_type.isEmpty() && user_type.equalsIgnoreCase(CommonString.TAG_FROM_BA)) { + setTitle(getString(R.string.ba_profile_data) + " - " + user_name); + } else if (!user_type.isEmpty() && user_type.equalsIgnoreCase(CommonString.TAG_FROM_TBA)) { + setTitle("TBA Profile - " + user_name); + } else if (!user_type.isEmpty() && user_type.equalsIgnoreCase(CommonString.TAG_FROM_ME)) { + setTitle("ME Profile - " + user_name); + } + img_dob.setOnClickListener(this); + round_img_pic.setOnClickListener(this); + db.open(); + } + + @SuppressLint("NonConstantResourceId") + @Override + public void onClick(View view) { + + if (view.getId() == R.id.img_dob) { + c = Calendar.getInstance(); + mYear = c.get(Calendar.YEAR); + mMonth = c.get(Calendar.MONTH); + mDay = c.get(Calendar.DAY_OF_MONTH); + // Launch Date Picker Dialog + dpd = new DatePickerDialog(this, (view1, year, monthOfYear, dayOfMonth) -> { + String dob = (monthOfYear + 1) + "/" + dayOfMonth + "/" + year; + storeProfile_dob.setText(dob); + }, mYear, mMonth, mDay); + dpd.getDatePicker().setMaxDate(System.currentTimeMillis()); + dpd.show(); + } else if (view.getId() == R.id.round_img_pic) { + pathforcheck = counterId + "_ba_profile_img_" + user_name + "_" + visitdate.replace("/", "") + "_" + getCurrentTime().replace(":", "") + ".jpg"; + _path = CommonString.getImagesFolder(context) + pathforcheck; + CommonFunctions.startAnncaCameraActivity(context, _path, null, false, CommonString.CAMERA_FACE_REAR); + backpress_flag = true; + } + } + + public ArrayList getFileNames(File[] file) { + ArrayList arrayFiles = new ArrayList(); + if (file != null) { + for (File value : file) arrayFiles.add(value.getName()); + } + return arrayFiles; + } + + private void deleteexistingfile() { + File dir = new File(CommonString.getProfileFolder(context)); + ArrayList list1; + list1 = getFileNames(dir.listFiles()); + try { + if (list1 != null && !list1.isEmpty()) { + for (int k = 0; k < list1.size(); k++) { + if (list1.get(k).contains("_ba_profile_img_" + user_name)) { + File originalFile = new File(CommonString.getProfileFolder(context) + list1.get(k)); + originalFile.delete(); + break; + } + } + } + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + + void getQuizProfileData() { + hashMapAnsListChildData = new HashMap<>(); + childListData = new ArrayList<>(); + expandableListView = (ExpandableListView) findViewById(R.id.list); + db.open(); + listDataHeader = db.getAuditQuestionCategoryData(user_type); + question_list = new ArrayList<>(); + listDataChild = new HashMap<>(); + if (!listDataHeader.isEmpty()) { + for (int i = 0; i < listDataHeader.size(); i++) { + question_list = new ArrayList<>(); + db.open(); + question_list = db.getAfterSaveAuditQuestionAnswerData(user_name, listDataHeader.get(i).getCategoryId().toString()); + if (question_list.isEmpty()) { + db.open(); + question_list = db.getSaveServerData(listDataHeader.get(i).getCategoryId().toString(), user_name); + if (question_list.isEmpty()) { + db.open(); + question_list = db.getAuditCategoryWise(listDataHeader.get(i).getCategoryId()); + } + } + + if (!question_list.isEmpty()) { + String select = getString(R.string.title_activity_select_dropdown); + // Adding child data + for (int j = 0; j < question_list.size(); j++) { + db.open(); + childListData = db.getAuditAnswerData(question_list.get(j), select); + if (question_list.get(j).getANSWER_TYPE().equalsIgnoreCase("Multi selection")) { + if (question_list.get(j).getANSWER() != null) { + final ArrayList finalSelectedSamplingData = getKeyPairBoolData(j); + question_list.get(j).setSelectedSamplingData(finalSelectedSamplingData); + } + } + ArrayList answerList = new ArrayList<>(childListData); + hashMapAnsListChildData.put(question_list.get(j), answerList); // Header, Child data + } + } + + listDataChild.put(listDataHeader.get(i), question_list); + } + + adapter = new ExpandableListAdapter(context, listDataHeader, listDataChild); + expandableListView.setAdapter(adapter); + expandableListView.setAdapter(adapter); + for (int i = 0; i < adapter.getGroupCount(); i++) { + expandableListView.expandGroup(i); + } + } else { + expandableListView.setVisibility(View.GONE); + } + + expandableListView.setOnScrollListener(new AbsListView.OnScrollListener() { + @Override + public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { + expandableListView.invalidate(); + int lastItem = firstVisibleItem + visibleItemCount; + if (firstVisibleItem == 0) { + fab.show();//.setVisibility(View.VISIBLE); + } else if (lastItem == totalItemCount) { + fab.hide();//setVisibility(View.INVISIBLE); + } else { + fab.show();//setVisibility(View.VISIBLE); + } + } + + @Override + public void onScrollStateChanged(AbsListView arg0, int arg1) { + InputMethodManager inputManager = (InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE); + if (getCurrentFocus() != null) { + inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0); + getCurrentFocus().clearFocus(); + } + + expandableListView.invalidateViews(); + } + }); + + + fab.setOnClickListener(view -> { + expandableListView.clearFocus(); + expandableListView.invalidateViews(); + baProfileGetterSetter.setLandmark(edt_landmark.getText().toString().trim().replaceAll("[(!@#$%^&*?)\"]", "")); + baProfileGetterSetter.setLocation(edt_location.getText().toString().trim().replaceAll("[(!@#$%^&*?)\"]", "")); + baProfileGetterSetter.setAddress(edt_address.getText().toString().trim().replaceAll("[(!@#$%^&*?)\"]", "")); + baProfileGetterSetter.setDob(storeProfile_dob.getText().toString()); + baProfileGetterSetter.setMobile(edt_mobile_no.getText().toString().trim()); + baProfileGetterSetter.setEmail(edt_email.getText().toString().trim()); + baProfileGetterSetter.setInstragramAddress(edt_enstagram_address.getText().toString()); + if (validateimg_str()) { + if (validateData(listDataHeader, listDataChild)) { + AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle(R.string.parinaam); + builder.setMessage(R.string.title_activity_Want_save).setCancelable(false).setPositiveButton(R.string.yes, (dialog, id) -> { + db.open(); + db.insertBaProfiledata(counterId, user_name, user_type, visitdate, baProfileGetterSetter); + if (!listDataHeader.isEmpty()) { + db.open(); + db.saveAuditQuestionAnswerData(listDataChild, listDataHeader, user_name, visitdate); + } + //upload service + Intent intent = new Intent(BAProfileActivity.this, Downloader.class); + BaProfileGetterSetter baProfileList = new BaProfileGetterSetter(); + ArrayList data = new ArrayList<>(); + for (int i = 0; i < listDataHeader.size(); i++) { + List list = listDataChild.get(listDataHeader.get(i)); + if (list != null && !list.isEmpty()) data.addAll(list); + } + if (!data.isEmpty()) { + baProfileList.setBaProfileList(data); + intent.putExtra(CommonString.KEY_BaProfile, baProfileGetterSetter); + intent.putExtra(CommonString.KEY_BaProfile_list, baProfileList); + Downloader.enqueueWork(BAProfileActivity.this, intent); + } + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + BAProfileActivity.this.finish(); + }).setNegativeButton(R.string.no, (dialog, id) -> dialog.cancel()); + AlertDialog alert = builder.create(); + alert.show(); + } else { + AlertandMessages.showToastMsg(context, error_msg); + } + } + }); + + expandableListView.clearFocus(); + } + + private @NonNull ArrayList getKeyPairBoolData(int j) { + final ArrayList finalSelectedSamplingData = new ArrayList<>(); + for (int k = 0; k < childListData.size(); k++) { + KeyPairBoolData h1 = new KeyPairBoolData(); + h1.setAnswerCd(childListData.get(k).getANSWER_ID()); + h1.setName(childListData.get(k).getANSWER()); + h1.setSelected(question_list.get(j).getANSWER().contains(childListData.get(k).getANSWER())); + finalSelectedSamplingData.add(h1); + } + return finalSelectedSamplingData; + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // Handle action bar item clicks here. The action bar will + // automatically handle clicks on the Home/Up button, so long + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + if (id == android.R.id.home) { + if (backpress_flag) { + alert(); + } else { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + finish(); + } + } + + return super.onOptionsItemSelected(item); + } + + @Override + public void onBackPressed() { + if (backpress_flag) { + alert(); + } else { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + finish(); + } + } + + private void alert() { + AlertDialog.Builder builder = new AlertDialog.Builder(context); + builder.setTitle(R.string.dialog_title); + builder.setMessage(getResources().getString(R.string.data_will_be_lost)).setCancelable(false).setPositiveButton(getString(R.string.ok), (dialog, id) -> { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + finish(); + }).setNegativeButton(getString(R.string.cancel), (dialog, which) -> dialog.dismiss()); + AlertDialog alert = builder.create(); + alert.show(); + } + + public class ExpandableListAdapter extends BaseExpandableListAdapter { + Context _context; + ArrayList listDataHeader; // header titles + HashMap> listDataChild; + + public ExpandableListAdapter(Context context, ArrayList listDataHeader, HashMap> listDataChild) { + this._context = context; + this.listDataHeader = listDataHeader; + this.listDataChild = listDataChild; + } + + @Override + public Object getChild(int groupPosition, int childPosititon) { + return this.listDataChild.get(this.listDataHeader.get(groupPosition)).get(childPosititon); + } + + @Override + public long getChildId(int groupPosition, int childPosition) { + return childPosition; + } + + @SuppressLint({"NewApi", "ClickableViewAccessibility", "InflateParams"}) + @Override + public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { + ArrayList selectedSamplingData = new ArrayList<>(); + + + final AuditDataGetterSetter checkList = (AuditDataGetterSetter) getChild(groupPosition, childPosition); + ViewHolder holder = null; + if (convertView == null) { + LayoutInflater infalInflater = (LayoutInflater) this._context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); + convertView = infalInflater.inflate(R.layout.audit_question_list_item, null); + holder = new ViewHolder(convertView); + convertView.setTag(holder); + } else { + holder = (ViewHolder) convertView.getTag(); + } + + holder.data = checkList; + holder.txt_question.setText(holder.data.getQUESTION()); + holder.txt_question.setId(childPosition); + + final ArrayList ans_list = hashMapAnsListChildData.get(holder.data); + + if (holder.data.getANSWER_TYPE().equalsIgnoreCase("Single selection")) { + holder.sp_auditAnswer.setVisibility(View.VISIBLE); + holder.edt_answer.setVisibility(View.GONE); + holder.relay_multisppener.setVisibility(View.GONE); + } else if (holder.data.getANSWER_TYPE().equalsIgnoreCase("Multi selection")) { + holder.edt_answer.setVisibility(View.GONE); + holder.sp_auditAnswer.setVisibility(View.GONE); + holder.relay_multisppener.setVisibility(View.VISIBLE); + } else if (holder.data.getANSWER_TYPE().equalsIgnoreCase("Text")) { + holder.edt_answer.setVisibility(View.VISIBLE); + holder.sp_auditAnswer.setVisibility(View.GONE); + holder.relay_multisppener.setVisibility(View.GONE); + holder.edt_answer.setInputType(InputType.TYPE_CLASS_TEXT); + holder.edt_answer.setFilters(new InputFilter[]{new InputFilter.LengthFilter(50)}); + } else if (holder.data.getANSWER_TYPE().equalsIgnoreCase("Number")) { + holder.edt_answer.setVisibility(View.VISIBLE); + holder.sp_auditAnswer.setVisibility(View.GONE); + holder.relay_multisppener.setVisibility(View.GONE); + holder.edt_answer.setInputType(InputType.TYPE_CLASS_NUMBER); + holder.edt_answer.setFilters(new InputFilter[]{new InputFilter.LengthFilter(6)}); + } else if (holder.data.getANSWER_TYPE().equalsIgnoreCase("Decimal")) { + holder.edt_answer.setVisibility(View.VISIBLE); + holder.sp_auditAnswer.setVisibility(View.GONE); + holder.relay_multisppener.setVisibility(View.GONE); + holder.edt_answer.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL); + holder.edt_answer.setFilters(new InputFilter[]{new DecimalDigitsInputFilter(6, 1)}); + + } + + assert ans_list != null; + if (!ans_list.isEmpty()) { + holder.sp_auditAnswer.setAdapter(new AnswerSpinnerAdapter(context, R.layout.custom_spinner_audit_item, ans_list)); + holder.sp_auditAnswer.setId(childPosition); + } + + final ViewHolder finalHolder = holder; + holder.sp_auditAnswer.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { + @Override + public void onItemSelected(AdapterView parent, View view, int position, long id) { + if (position != 0) { + AuditDataGetterSetter ans = ans_list.get(position); + finalHolder.data.setANSWER_ID(ans.getANSWER_ID()); + finalHolder.data.setANSWER(ans.getANSWER()); + finalHolder.data.setCAMERA_ALLOW(ans.getCAMERA_ALLOW()); + if (finalHolder.data.getCAMERA_ALLOW().equals("1")) { + finalHolder.parent_cam_layout.setVisibility(View.VISIBLE); + finalHolder.parent_cam_layout.setId(childPosition); + } else { + finalHolder.parent_cam_layout.setVisibility(View.GONE); + finalHolder.parent_cam_layout.setId(childPosition); + + if (finalHolder.data.getCAM_IMAGE() != null && finalHolder.data.getCAM_IMAGE().isEmpty()) { + if (new File(str + finalHolder.data.getCAM_IMAGE()).exists()) { + new File(str + finalHolder.data.getCAM_IMAGE()).delete(); + } + } + finalHolder.data.setCAM_IMAGE(""); + finalHolder.img_cam.setBackgroundResource(R.mipmap.camera); + finalHolder.img_cam.setId(childPosition); + } + + if (ans.getANSWER().equalsIgnoreCase("Others")) { + finalHolder.edt_for_others.setVisibility(View.VISIBLE); + finalHolder.edt_for_others.setId(childPosition); + } else { + finalHolder.data.setSpin_others_for_edt(""); + finalHolder.edt_for_others.setText(""); + finalHolder.edt_for_others.setVisibility(View.GONE); + finalHolder.edt_for_others.setId(childPosition); + + } + } else { + finalHolder.data.setANSWER_ID("0"); + finalHolder.data.setANSWER(""); + finalHolder.data.setSpin_others_for_edt(""); + finalHolder.edt_for_others.setText(""); + finalHolder.edt_for_others.setId(childPosition); + finalHolder.img_cam.setBackgroundResource(R.mipmap.camera); + finalHolder.img_cam.setId(childPosition); + finalHolder.parent_cam_layout.setVisibility(View.GONE); + finalHolder.parent_cam_layout.setId(childPosition); + finalHolder.edt_for_others.setVisibility(View.GONE); + finalHolder.edt_for_others.setId(childPosition); + } + } + + @Override + public void onNothingSelected(AdapterView parent) { + + } + }); + + + List listArray0 = new ArrayList<>(); + if (!checkList.getSelectedSamplingData().isEmpty()) { + selectedSamplingData.clear(); + listArray0.addAll(checkList.getSelectedSamplingData()); + holder.tv_mer.setVisibility(View.GONE); + } else { + for (int i = 0; i < ans_list.size(); i++) { + KeyPairBoolData h = new KeyPairBoolData(); + h.setId(i + 1); + merCd = getEmp_idFromName(ans_list, ans_list.get(i).getANSWER()); + h.setName(ans_list.get(i).getANSWER()); + h.setMerCd(merCd); + h.setSelected(false); + listArray0.add(h); + holder.tv_mer.setVisibility(View.GONE); + + } + } + + + holder.searchSpinner.setOnTouchListener((view, motionEvent) -> { + multitouch = true; + return false; + }); + + final ArrayList finalSelectedSamplingData = selectedSamplingData; + final ViewHolder finalHolder2 = holder; + + holder.searchSpinner.setItemsProduct(listArray0, -1, items -> { + if (multitouch) { + multitouch = false; + finalSelectedSamplingData.clear(); + for (int i = 0; i < items.size(); i++) { + KeyPairBoolData h1 = new KeyPairBoolData(); + h1.setAnswerCd(items.get(i).getAnswerCd()); + h1.setName(items.get(i).getName()); + h1.setSelected(items.get(i).isSelected()); + finalSelectedSamplingData.add(h1); + Log.i("MultiSpinner", i + " : " + items.get(i).getAnswer() + " : " + items.get(i).isSelected()); + } + + if (!finalSelectedSamplingData.isEmpty()) { + boolean selectedData = false; + for (int i = 0; i < finalSelectedSamplingData.size(); i++) { + if (finalSelectedSamplingData.get(i).isSelected()) { + selectedData = true; + break; + } + } + finalHolder2.tv_mer.setVisibility(View.GONE); + finalHolder2.tv_mer.setId(childPosition); + } else { + finalHolder2.tv_mer.setVisibility(View.GONE); + finalHolder2.tv_mer.setId(childPosition); + } + checkList.setSelectedSamplingData(finalSelectedSamplingData); + adapter.notifyDataSetChanged(); + } + }); + + + holder.img_cam.setOnClickListener(v -> { + pathforcheck = counterId + "_ba_AuditPic_" + visitdate.replace("/", "") + CommonFunctions.getCurrentTimeHHMMSS().replace(":", "") + ".jpg"; + _path = CommonString.getImagesFolder(context) + pathforcheck; + CommonFunctions.startAnncaCameraActivity(context, _path, null, false, CommonString.CAMERA_FACE_REAR); + child_position = childPosition; + }); + + final ViewHolder finalHolder1 = holder; + holder.edt_answer.setOnFocusChangeListener((v, hasFocus) -> { + if (!hasFocus) { + finalHolder1.data.setANSWER_ID("0"); + finalHolder1.data.setANSWER(((EditText) v).getText().toString().trim().replaceAll("[(!@#$%^&*?)\"]", "")); + + } + }); + + + holder.edt_for_others.setOnFocusChangeListener((v, hasFocus) -> { + if (!hasFocus) { + finalHolder1.data.setSpin_others_for_edt(CommonFunctions.removed_special_char((EditText) v)); + } + }); + + if ((holder.data.getANSWER_TYPE().equalsIgnoreCase("Single selection"))) { + if (!ans_list.isEmpty()) { + for (int i = 0; i < ans_list.size(); i++) { + if (ans_list.get(i).getANSWER_ID().equals(holder.data.getANSWER_ID())) { + holder.sp_auditAnswer.setSelection(i); + break; + } + } + } + + + holder.edt_for_others.setText(holder.data.getSpin_others_for_edt()); + holder.edt_for_others.setId(childPosition); + + + } else if (holder.data.getANSWER_TYPE().equalsIgnoreCase("Number") || holder.data.getANSWER_TYPE().equalsIgnoreCase("Decimal") || holder.data.getANSWER_TYPE().equalsIgnoreCase("Text")) { + + holder.edt_answer.setText(holder.data.getANSWER()); + holder.edt_answer.setId(childPosition); + } + + if (!img_str.isEmpty()) { + if (child_position == childPosition) { + holder.data.setCAM_IMAGE(img_str); + img_str = ""; + child_position = -1; + } + } + + if (holder.data.getCAM_IMAGE().isEmpty()) { + holder.img_cam.setBackgroundResource(R.mipmap.camera); + holder.img_cam.setId(childPosition); + } else { + holder.img_cam.setBackgroundResource(R.mipmap.camera_tick); + holder.img_cam.setId(childPosition); + } + + if (!checkflag) { + if (checkGroupArray.contains(groupPosition) && checkHeaderArray.contains(childPosition)) { + holder.card_view.setBackgroundColor(ContextCompat.getColor(_context, R.color.red)); + holder.card_view.setId(childPosition); + } else { + holder.card_view.setBackgroundColor(ContextCompat.getColor(_context, R.color.white)); + holder.card_view.setId(childPosition); + } + } + + + return convertView; + } + + @Override + public int getChildrenCount(int groupPosition) { + return this.listDataChild.get(this.listDataHeader.get(groupPosition)).size(); + } + + @Override + public Object getGroup(int groupPosition) { + return this.listDataHeader.get(groupPosition); + } + + @Override + public int getGroupCount() { + return this.listDataHeader.size(); + } + + @Override + public long getGroupId(int groupPosition) { + return groupPosition; + } + + @Override + public View getGroupView(final int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { + if (convertView == null) { + LayoutInflater infalInflater = (LayoutInflater) this._context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); + convertView = infalInflater.inflate(R.layout.item_header_expandable_window, parent, false); + } + + final MasterProfileQuestion headerTitle = (MasterProfileQuestion) getGroup(groupPosition); + TextView lblListHeader = (TextView) convertView.findViewById(R.id.txt_header); + CardView cardView = (CardView) convertView.findViewById(R.id.cardview_exists); + lblListHeader.setText(headerTitle.getCategory()); + + cardView.setOnClickListener(v -> { + if (expandableListView.isGroupExpanded(groupPosition)) { + expandableListView.collapseGroup(groupPosition); + } else { + expandableListView.expandGroup(groupPosition); + } + }); + + if (!checkflag) { + if (checkGroupArray.contains(groupPosition)) { + cardView.setBackgroundColor(ContextCompat.getColor(_context, R.color.red)); + } else { + cardView.setBackgroundColor(ContextCompat.getColor(_context, R.color.colorPrimaryDark)); + } + } + + return convertView; + } + + @Override + public boolean hasStableIds() { + return false; + } + + @Override + public boolean isChildSelectable(int groupPosition, int childPosition) { + return true; + } + + public class ViewHolder extends RecyclerView.ViewHolder { + public final View mView; + public final TextView txt_question; + public final Spinner sp_auditAnswer; + public final EditText edt_answer, edt_for_others; + public final ImageView img_cam; + public final RelativeLayout parent_cam_layout; + CardView card_view; + public final RelativeLayout relay_multisppener; + BaProfileMultiSelection searchSpinner; + public final TextView tv_mer; + AuditDataGetterSetter data; + + public ViewHolder(View view) { + super(view); + mView = view; + tv_mer = (TextView) view.findViewById(R.id.tv_mer); + txt_question = (TextView) view.findViewById(R.id.txt_question); + sp_auditAnswer = (Spinner) view.findViewById(R.id.sp_auditAnswer); + card_view = (CardView) view.findViewById(R.id.card_view); + edt_answer = (EditText) view.findViewById(R.id.edt_answer); + edt_for_others = (EditText) view.findViewById(R.id.edt_for_others); + img_cam = (ImageView) view.findViewById(R.id.img_cam); + parent_cam_layout = (RelativeLayout) view.findViewById(R.id.parent_cam_layout); + relay_multisppener = (RelativeLayout) view.findViewById(R.id.relay_multisppener); + searchSpinner = (BaProfileMultiSelection) view.findViewById(R.id.searchSpinner); + } + } + + } + + + public static class AnswerSpinnerAdapter extends ArrayAdapter { + List list; + Context context; + int resourceId; + + public AnswerSpinnerAdapter(Context context, int resourceId, ArrayList list) { + super(context, resourceId, list); + this.context = context; + this.list = list; + this.resourceId = resourceId; + } + + @NonNull + @SuppressLint("ViewHolder") + @Override + public View getView(int position, View convertView, @NonNull ViewGroup parent) { + View view = convertView; + LayoutInflater inflater = ((Activity) context).getLayoutInflater(); + view = inflater.inflate(resourceId, parent, false); + AuditDataGetterSetter cm = list.get(position); + TextView txt_spinner = (TextView) view.findViewById(R.id.tv_text); + txt_spinner.setText(list.get(position).getANSWER()); + + return view; + } + + @Override + public View getDropDownView(int position, View convertView, @NonNull ViewGroup parent) { + View view = convertView; + LayoutInflater inflater = ((Activity) context).getLayoutInflater(); + view = inflater.inflate(resourceId, parent, false); + AuditDataGetterSetter cm = list.get(position); + TextView txt_spinner = (TextView) view.findViewById(R.id.tv_text); + txt_spinner.setText(cm.getANSWER()); + return view; + } + } + + boolean validateData(ArrayList listDataHeader, HashMap> listDataChild) { + checkHeaderArray.clear(); + checkGroupArray.clear(); + loop: + for (int j = 0; j < listDataHeader.size(); j++) { + ArrayList data = listDataChild.get(listDataHeader.get(j)); + for (int i = 0; i < data.size(); i++) { + if (data.get(i).getANSWER_TYPE().equalsIgnoreCase("Text") || data.get(i).getANSWER_TYPE().equalsIgnoreCase("Number") || data.get(i).getANSWER_TYPE().equalsIgnoreCase("Decimal")) { + if (data.get(i).getANSWER() == null || data.get(i).getANSWER().equalsIgnoreCase("")) { + error_msg = getString(R.string.pls_answer_all_qns); + checkflag = false; + } else { + checkflag = true; + } + } else if (data.get(i).getANSWER_TYPE().equalsIgnoreCase("Single selection")) { + if (data.get(i).getANSWER_ID().equalsIgnoreCase("0")) { + error_msg = getString(R.string.pls_answer_all_qns); + checkflag = false; + } else if (data.get(i).getCAMERA_ALLOW().equals("1") && data.get(i).getCAM_IMAGE().isEmpty()) { + error_msg = getString(R.string.click_image); + checkflag = false; + } else { + checkflag = true; + } + } else if (data.get(i).getANSWER_TYPE().equalsIgnoreCase("Multi selection")) { + if (!data.get(i).getSelectedSamplingData().isEmpty()) { + checkflag = false; + for (int k = 0; k < data.get(i).getSelectedSamplingData().size(); k++) { + if (data.get(i).getSelectedSamplingData().get(k).isSelected()) { + checkflag = true; + } + } + if (!checkflag) { + error_msg = ("Please select atleast one checklist answer"); + } + } else { + checkflag = false; + error_msg = ("Please select atleast one checklist answer"); + } + } + + if (!checkflag) { + if (!checkHeaderArray.contains(i)) { + checkHeaderArray.add(i); + checkGroupArray.add(j); + } + break loop; + } + } + } + + + return checkflag; + } + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + super.onActivityResult(requestCode, resultCode, data); + Log.i("MakeMachine", "resultCode: " + resultCode); + switch (resultCode) { + case 0: + Log.i("MakeMachine", "User cancelled"); + break; + case -1: + if (pathforcheck != null && !pathforcheck.isEmpty()) { + if (new File(CommonString.getImagesFolder(context) + pathforcheck).exists()) { + deleteexistingfile(); + try { + Bitmap bmp = convertBitmap(CommonString.getImagesFolder(context) + pathforcheck); + round_img_pic.setImageBitmap(bmp); + } catch (OutOfMemoryError ex) { + CommonFunctions.setScaledImage(round_img_pic, CommonString.getImagesFolder(context) + pathforcheck); + } + + round_img_pic.setVisibility(View.VISIBLE); + img_str = pathforcheck; + baProfileGetterSetter.setProfilePic(img_str); + copyFile(pathforcheck); + pathforcheck = ""; + } + } + break; + } + super.onActivityResult(requestCode, resultCode, data); + } + + private void copyFile(String file_name) { + try { + // the file to be moved or copied + File sourceLocation = new File(CommonString.getImagesFolder(context) + file_name); + // make sure your target location folder exists! + File targetLocation = new File(CommonString.getProfileFolder(context), file_name); + // make sure the target file exists + if (sourceLocation.exists()) { + InputStream in = new FileInputStream(sourceLocation); + OutputStream out = new FileOutputStream(targetLocation); + // Copy the bits from instream to outstream + byte[] buf = new byte[1024]; + int len; + while ((len = in.read(buf)) > 0) { + out.write(buf, 0, len); + } + in.close(); + out.close(); + Log.v("", "Copy file successful."); + } else { + Log.v("", "Copy file failed. Source file missing."); + } + } catch (Exception e) { + e.fillInStackTrace(); + } + } + + private class DecimalDigitsInputFilter implements InputFilter { + Pattern mPattern; + + private DecimalDigitsInputFilter(int digitsBeforeZero, int digitsAfterZero) { + mPattern = Pattern.compile("[0-9]{0," + (digitsBeforeZero - 1) + "}+((\\.[0-9]{0," + (digitsAfterZero - 1) + "})?)||(\\.)?"); + } + + @Override + public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { + Matcher matcher = mPattern.matcher(dest); + if (!matcher.matches()) return ""; + return null; + } + + } + + String getEmp_idFromName(ArrayList finalAns_list, String name) { + String emp_cd = "0"; + for (int i = 0; i < finalAns_list.size(); i++) { + if (finalAns_list.get(i).getANSWER().equalsIgnoreCase(name)) { + emp_cd = String.valueOf(finalAns_list.get(i).getANSWER_ID()); + break; + } + } + + return emp_cd; + } + + + private boolean validateimg_str() { + boolean status = true; + if (baProfileGetterSetter.getProfilePic() == null && !baProfileListData.isEmpty() && baProfileListData.get(0).getProfilePic().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Click Profile Imge"); + status = false; + } else if (edt_mobile_no.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter Mobile Number"); + status = false; + } else if (edt_mobile_no.getText().toString().length() < 10) { + AlertandMessages.showToastMsg(context, "Please Enter Atleast 10 Digit Contact Number "); + status = false; + } else if (storeProfile_dob.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Tab To Select DOB"); + status = false; + } else if (edt_address.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter Address"); + status = false; + } else if (edt_landmark.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter Landmark"); + status = false; + } else if (edt_location.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter Location"); + status = false; + } else if (edt_email.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter Email Address"); + status = false; + } else if (!edt_email.getText().toString().isEmpty() && !CommonFunctions.isValidEmail(edt_email.getText().toString())) { + AlertandMessages.showToastMsg(context, "Please Enter Valid Email Id "); + status = false; + } + + return status; + } + + @SuppressLint("SetTextI18n") + private void validate() { + update_flag = false; + db.open(); + storelist = db.getStoreData(visitdate, user_name, counterId); + baProfileGetterSetter = db.getBaProfileData(user_name, visitdate, false); + baProfileListData = db.getBAProfileListAllData(user_name, visitdate); + + if (!storelist.isEmpty()) { + edt_brand.setText(storelist.get(0).getStoreTypeName()); + edt_counter.setText(storelist.get(0).getClassId().toString()); + edt_store_name.setText(storelist.get(0).getStoreName()); + edt_location.setText(storelist.get(0).getLocation()); + edt_city.setText(storelist.get(0).getCityName()); + edt_landmark.setText(storelist.get(0).getLandmark()); + } + + + if (!baProfileListData.isEmpty()) { + profile_user.setText(baProfileListData.get(0).getFullName()); + if (user_type != null && !user_type.isEmpty() && user_type.equalsIgnoreCase(CommonString.TAG_FROM_BA)) { + profile_user_type.setText("Beauty Advisor"); + } else if (user_type != null && !user_type.isEmpty() && user_type.equalsIgnoreCase(CommonString.TAG_FROM_TBA)) { + profile_user_type.setText("Temp Beauty Advisor"); + } else if (user_type != null && !user_type.isEmpty() && user_type.equalsIgnoreCase(CommonString.TAG_FROM_ME)) { + profile_user_type.setText("Makeup Expert"); + } + + edt_enstagram_address.setText(baProfileListData.get(0).getInstragramAddress()); + edt_email.setText(baProfileListData.get(0).getEmail()); + edt_mobile_no.setText(baProfileListData.get(0).getMobile()); + storeProfile_dob.setText(baProfileListData.get(0).getDob()); + edt_address.setText(baProfileListData.get(0).getAddress()); + edt_employee_code.setText(baProfileListData.get(0).getEmpCode()); + edt_full_name.setText(baProfileListData.get(0).getFullName()); + supervisor_name.setText(baProfileListData.get(0).getSupervisor()); + edt_current_bp.setText(baProfileListData.get(0).getCurrentBPgrade()); + /////for radio group + if (baProfileListData.get(0).getGender().equalsIgnoreCase("Male")) { + //radioSexButton + radioSexGroup.check(R.id.radioM); + } else if (baProfileListData.get(0).getGender().equalsIgnoreCase("Female")) { + //radioSexButton + radioSexGroup.check(R.id.radioF); + } else { + radioSexGroup.check(R.id.radio_other); + } + } + + + if (baProfileGetterSetter != null && baProfileGetterSetter.getUserId() != null && !baProfileGetterSetter.getUserId().isEmpty()) { + fab.setImageDrawable(ContextCompat.getDrawable(this, R.mipmap.edit)); + edt_address.setText(baProfileGetterSetter.getAddress() != null ? baProfileGetterSetter.getAddress() : ""); + edt_location.setText(baProfileGetterSetter.getLocation() != null ? baProfileGetterSetter.getLocation() : ""); + edt_landmark.setText(baProfileGetterSetter.getLandmark() != null ? baProfileGetterSetter.getLandmark() : ""); + storeProfile_dob.setText(baProfileGetterSetter.getDob() != null ? baProfileGetterSetter.getDob() : ""); + edt_mobile_no.setEnabled(baProfileGetterSetter.getMobile() != null); + edt_mobile_no.setText(baProfileGetterSetter.getMobile() != null ? baProfileGetterSetter.getMobile() : ""); + edt_email.setText(baProfileGetterSetter.getEmail() != null ? baProfileGetterSetter.getEmail() : ""); + edt_enstagram_address.setText(baProfileGetterSetter.getInstragramAddress() != null ? baProfileGetterSetter.getInstragramAddress() : ""); + pathforcheck = baProfileGetterSetter.getProfilePic() != null ? baProfileGetterSetter.getProfilePic() : ""; + } + + assert baProfileGetterSetter != null; + if (baProfileGetterSetter.getProfilePic() != null && !baProfileGetterSetter.getProfilePic().isEmpty()) { + if (new File(CommonString.getProfileFolder(context) + pathforcheck).exists()) { + Bitmap bitmp = convertBitmap(CommonString.getProfileFolder(context) + baProfileGetterSetter.getProfilePic()); + assert bitmp != null; + round_img_pic.setImageBitmap(bitmp); + } else { + bitmp = BitmapFactory.decodeResource(getResources(), R.mipmap.profile_image); + round_img_pic.setImageBitmap(bitmp); + } + } else if (!baProfileListData.isEmpty() && baProfileListData.get(0).getProfilePic() != null && !baProfileListData.get(0).getProfilePic().isEmpty()) { + Picasso.with(context).load(baProfileListData.get(0).getProfilePic()).networkPolicy(NetworkPolicy.NO_CACHE).into(round_img_pic); + } else { + bitmp = BitmapFactory.decodeResource(getResources(), R.mipmap.profile_image); + round_img_pic.setImageBitmap(bitmp); + } + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/BASurveyActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/BASurveyActivity.java new file mode 100644 index 0000000..856d489 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/BASurveyActivity.java @@ -0,0 +1,776 @@ +package com.cpm.lorealbaautomation.dailyactivity; + +import android.annotation.SuppressLint; +import android.app.Activity; +import android.app.AlertDialog; +import android.app.Dialog; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.graphics.drawable.ColorDrawable; +import android.os.AsyncTask; +import android.os.Bundle; + +import com.google.android.material.floatingactionbutton.FloatingActionButton; + +import androidx.annotation.NonNull; +import androidx.appcompat.app.AppCompatActivity; +import androidx.cardview.widget.CardView; +import androidx.recyclerview.widget.RecyclerView; +import androidx.appcompat.widget.Toolbar; + +import android.text.InputType; +import android.util.Log; +import android.view.LayoutInflater; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; +import android.view.Window; +import android.view.inputmethod.InputMethodManager; +import android.widget.AbsListView; +import android.widget.AdapterView; +import android.widget.ArrayAdapter; +import android.widget.BaseExpandableListAdapter; +import android.widget.EditText; +import android.widget.ExpandableListView; +import android.widget.ImageView; +import android.widget.ProgressBar; +import android.widget.RelativeLayout; +import android.widget.Spinner; +import android.widget.TextView; + +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.constant.AlertandMessages; +import com.cpm.lorealbaautomation.constant.CommonFunctions; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.gsonGetterSetter.BASurveyGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.JourneyPlan; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterSurvey; +import com.cpm.lorealbaautomation.retrofit.PostApi; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.File; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.TimeUnit; + +import okhttp3.MediaType; +import okhttp3.OkHttpClient; +import okhttp3.RequestBody; +import okhttp3.ResponseBody; +import retrofit2.Call; +import retrofit2.Callback; +import retrofit2.Response; +import retrofit2.Retrofit; +import retrofit2.converter.gson.GsonConverterFactory; + +import static com.cpm.lorealbaautomation.dailyactivity.StoreImageActivity.convertBitmap; + + +public class BASurveyActivity extends AppCompatActivity { + List checkHeaderArray = new ArrayList<>(); + List checkGroupArray = new ArrayList<>(); + boolean checkflag = true; + SharedPreferences preferences; + String pathforcheck = "", _path = "", str, img_str = "", counter_id = "", surveyId = "", surveyType = ""; //img_str2 = ""; + String visit_date, username; + Lorealba_Database db; + ArrayList question_list, childListData; + HashMap> hashMapAnsListChildData; + int child_position = -1; + String error_msg = ""; + Toolbar toolbar; + Context context; + FloatingActionButton fab; + ExpandableListView expandableListView; + ExpandableListAdapter adapter; + ArrayList listDataHeader; + ArrayList listChildData; + HashMap> listDataChild; + JourneyPlan jcp_Object = new JourneyPlan(); + ArrayList list = new ArrayList<>(); + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_ba_survey); + context = this; + //Intent data + if (getIntent().getStringExtra("SurveyId") != null && getIntent().getStringExtra("SurveyType") != null) { + surveyId = getIntent().getStringExtra("SurveyId"); + surveyType = getIntent().getStringExtra("SurveyType"); + } + + preferences = PrefHelper.getPrefs(this); + counter_id = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + username = preferences.getString(CommonString.KEY_USERNAME, ""); + + toolbar = (Toolbar) findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + + if (!CommonFunctions.isTablet(context)) { + toolbar.setTitleTextAppearance(context, R.style.changestext_sizefor_mobile); + } + + Objects.requireNonNull(getSupportActionBar()).setHomeButtonEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + + if (surveyType.equalsIgnoreCase("BA")) { + setTitle("BA Survey - " + username); + } else { + setTitle("Counter Survey - " + visit_date); + } + + str = CommonString.getImagesFolder(context); + expandableListView = (ExpandableListView) findViewById(R.id.list); + fab = (FloatingActionButton) findViewById(R.id.fab); + expandableListView.setOnScrollListener(new AbsListView.OnScrollListener() { + @Override + public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { + int lastItem = firstVisibleItem + visibleItemCount; + if (firstVisibleItem == 0) { + fab.show();//.setVisibility(View.VISIBLE); + } else if (lastItem == totalItemCount) { + fab.hide();//setVisibility(View.INVISIBLE); + } else { + fab.show();//setVisibility(View.VISIBLE); + } + } + + @Override + public void onScrollStateChanged(AbsListView arg0, int arg1) { + InputMethodManager inputManager = (InputMethodManager) getApplicationContext() + .getSystemService(Context.INPUT_METHOD_SERVICE); + if (getCurrentFocus() != null) { + inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0); + getCurrentFocus().clearFocus(); + } + } + }); + + db = new Lorealba_Database(context); + db.open(); + jcp_Object = db.getBIDfromJCP(username, counter_id); + //Header + question_list = new ArrayList<>(); + listDataChild = new HashMap<>(); + if (surveyType.equalsIgnoreCase("BA")) { + db.open(); + listDataHeader = db.getSurveyData("BA", surveyId); + } else { + db.open(); + listDataHeader = db.getSurveyData("Counter", surveyId); + } + + for (int i = 0; i < listDataHeader.size(); i++) { + // Adding child data + db.open(); + question_list = db.getSurveyWiseData(listDataHeader.get(i).getSurveyId()); + if (!question_list.isEmpty()) { + String select = getString(R.string.title_activity_select_dropdown); + for (int j = 0; j < question_list.size(); j++) { + // Adding answer list data + db.open(); + childListData = db.getSurveyAnswerData(question_list.get(j), select); + question_list.get(j).setAnswerList(childListData); + } + } + + listDataChild.put(listDataHeader.get(i), question_list); + } + + adapter = new ExpandableListAdapter(context, listDataHeader, listDataChild); + expandableListView.setAdapter(adapter); + for (int i = 0; i < adapter.getGroupCount(); i++) { + expandableListView.expandGroup(i); + } + + fab.setOnClickListener(view -> { + expandableListView.clearFocus(); + if (validateData(listDataHeader, listDataChild)) { + if (CommonFunctions.checkNetIsAvailable(context)) { + AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle(R.string.parinaam).setMessage(R.string.ba_survey_save_data_msg) + .setCancelable(false) + .setPositiveButton(R.string.yes, (dialog, id) -> { + db.open(); + if (db.saveBASurveyAnswerData(listDataHeader, listDataChild, counter_id, visit_date, jcp_Object, surveyType) > 0) { + if (CommonFunctions.checkNetIsAvailable(context)) { + new InsertAsync().execute(false); + } + } else { + AlertandMessages.showToastMsg(context, "Error in data saving"); + } + }).setNegativeButton(R.string.no, (dialog, id) -> dialog.cancel()); + + AlertDialog alert = builder.create(); + alert.show(); + } else { + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE); + } + } else { + AlertandMessages.showToastMsg(context, error_msg); + } + }); + } + + private Dialog dialog; + ProgressBar pb; + + @SuppressLint("StaticFieldLeak") + class InsertAsync extends AsyncTask { + boolean flag = false; + + @Override + protected void onPreExecute() { + dialog = new Dialog(context); + dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); + Objects.requireNonNull(dialog.getWindow()).setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT)); + dialog.setContentView(R.layout.circular_progress_bar); + pb = (ProgressBar) dialog.findViewById(R.id.progressBar1); + dialog.setCancelable(false); + dialog.show(); + super.onPreExecute(); + } + + + @Override + protected Void doInBackground(Boolean... bool) { + UploadStockRecursive(jcp_Object); + return null; + } + + + @Override + protected void onPostExecute(Void aVoid) { + super.onPostExecute(aVoid); + } + } + + + private void UploadStockRecursive(JourneyPlan jcp) { + try { + JSONArray topUpArray = new JSONArray(); + String key = ""; + db.open(); + if (surveyType.equalsIgnoreCase("BA")) { + key = "BASurveyData"; + listDataHeader = db.getBASurveySavedData("BA", jcp, visit_date); + } else { + key = "CounterSurveyData"; + listDataHeader = db.getBASurveySavedData("Counter", jcp, visit_date); + } + + for (int j = 0; j < listDataHeader.size(); j++) { + JSONObject obj = new JSONObject(); + obj.put("BID", jcp.getBID()); + obj.put("UserId", username); + obj.put("CounterId", counter_id); + obj.put("SurveyType", listDataHeader.get(j).getSurveyType()); + obj.put("SurveyId", listDataHeader.get(j).getSurveyId()); + db.open(); + listChildData = db.getChildData(surveyType, jcp, visit_date, listDataHeader.get(j).getCommon_id()); + + for (int i = 0; i < listChildData.size(); i++) { + JSONObject obj1 = getJsonObject(jcp, i); + topUpArray.put(obj1); + } + } + JSONObject jsonObject = new JSONObject(); + jsonObject.put("MID", jcp.getMID()); + jsonObject.put("Keys", key); + jsonObject.put("JsonData", topUpArray.toString()); + jsonObject.put("UserId", username); + + String jsonString = jsonObject.toString(); + + OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, + TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build(); + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsonString); + Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build(); + PostApi api = adapter.create(PostApi.class); + Call call = null; + call = api.getUploadJsonDetail(jsonData); + + call.enqueue(new Callback() { + @Override + public void onResponse(@NonNull Call call, @NonNull Response response) { + ResponseBody responseBody = response.body(); + String data = null; + if (responseBody != null && response.isSuccessful()) { + try { + assert response.body() != null; + data = response.body().string(); + if (data.equalsIgnoreCase("")) { + } else { + data = data.substring(1, data.length() - 1).replace("\\", ""); + if (data.contains("Success")) { + db.open(); + db.updateBASurveyData(surveyType, "1"); + dialog.cancel(); + finish(); + } + } + + } catch (Exception e) { + dialog.cancel(); + e.fillInStackTrace(); + + } + } else { + dialog.cancel(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_NO_RESPONSE_SERVER); + } + } + + @Override + public void onFailure(@NonNull Call call, @NonNull Throwable t) { + dialog.cancel(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE); + } + }); + + + } catch (JSONException e) { + dialog.cancel(); + e.fillInStackTrace(); + } + } + + private @NonNull JSONObject getJsonObject(JourneyPlan jcp, int i) throws JSONException { + JSONObject obj1 = new JSONObject(); + if (surveyType.equalsIgnoreCase("BA")) { + obj1.put("BID", jcp.getBID()); + } else { + obj1.put("MID", jcp.getMID()); + } + obj1.put("UserId", username); + obj1.put("CounterId", counter_id); + obj1.put("Visit_date", visit_date); + obj1.put("SurveyId", listChildData.get(i).getSurveyId()); + obj1.put("SurveyQuestionId", listChildData.get(i).getSurveyQuestionId()); + if (listChildData.get(i).getCorrect_answer_id().equalsIgnoreCase("0")) { + obj1.put("Survey_Correct_Answer_Id", "0"); + } else { + obj1.put("Survey_Correct_Answer_Id", listChildData.get(i).getCorrect_answer_id()); + } + + obj1.put("Survey_Correct_Answer", listChildData.get(i).getSurveyAnswer()); + obj1.put("Survey_Image", listChildData.get(i).getCam_image()); + return obj1; + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // Handle action bar item clicks here. The action bar will + // automatically handle clicks on the Home/Up button, so long + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + if (id == android.R.id.home) { + AlertDialog.Builder builder = new AlertDialog.Builder(context); + builder.setTitle("Parinaam"); + builder.setMessage(getResources().getString(R.string.data_will_be_lost)).setCancelable(false) + .setPositiveButton(getString(R.string.ok), (dialog, id1) -> { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + finish(); + }) + .setNegativeButton(getString(R.string.cancel), (dialog, which) -> { + dialog.dismiss(); + }); + AlertDialog alert = builder.create(); + alert.show(); + } + + return super.onOptionsItemSelected(item); + } + + @Override + public void onBackPressed() { + AlertDialog.Builder builder = new AlertDialog.Builder(context); + builder.setTitle("Parinaam"); + builder.setMessage(getResources().getString(R.string.data_will_be_lost)).setCancelable(false) + .setPositiveButton(getString(R.string.ok), (dialog, id) -> finish()) + .setNegativeButton(getString(R.string.cancel), (dialog, which) -> { + + }); + AlertDialog alert = builder.create(); + alert.show(); + } + + private class ExpandableListAdapter extends BaseExpandableListAdapter { + Context _context; + ArrayList listDataHeader; // header titles + HashMap> listDataChild; + + public ExpandableListAdapter(Context context, ArrayList listDataHeader, HashMap> listDataChild) { + this._context = context; + this.listDataHeader = listDataHeader; + this.listDataChild = listDataChild; + } + + @Override + public Object getChild(int groupPosition, int childPosititon) { + return this.listDataChild.get(this.listDataHeader.get(groupPosition)).get(childPosititon); + } + + @Override + public long getChildId(int groupPosition, int childPosition) { + return childPosition; + } + + @SuppressLint({"NewApi", "InflateParams"}) + @Override + public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { + + BASurveyGetterSetter checkList = (BASurveyGetterSetter) getChild(groupPosition, childPosition); + ViewHolder holder = null; + if (convertView == null) { + LayoutInflater infalInflater = (LayoutInflater) this._context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); + convertView = infalInflater.inflate(R.layout.audit_question_list_item, null); + holder = new ViewHolder(convertView); + convertView.setTag(holder); + } else { + holder = (ViewHolder) convertView.getTag(); + } + + holder.data = checkList; + holder.txt_question.setText(holder.data.getSurveyQuestion()); + + final ArrayList ans_list = (holder.data).getAnswerList(); + + if (holder.data.getSurveyQuestionType().equalsIgnoreCase("List Single Choice") || + holder.data.getSurveyQuestionType().equalsIgnoreCase("List Multiple Choice")) { + holder.sp_auditAnswer.setVisibility(View.VISIBLE); + holder.edt_answer.setVisibility(View.GONE); + } else { + holder.edt_answer.setVisibility(View.VISIBLE); + holder.sp_auditAnswer.setVisibility(View.GONE); + } + + + if (!ans_list.isEmpty()) { + holder.sp_auditAnswer.setAdapter(new AnswerSpinnerAdapter(context, R.layout.custom_spinner_item, ans_list)); + } + + final ViewHolder finalHolder = holder; + holder.sp_auditAnswer.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { + @Override + public void onItemSelected(AdapterView parent, View view, int position, long id) { + if (position != 0) { + BASurveyGetterSetter ans = ans_list.get(position); + finalHolder.data.setCorrect_answer_id(ans.getSurveyAnswerId()); + finalHolder.data.setSurveyAnswer(ans.getSurveyAnswer()); + //finalHolder.data.setImageAllow(ans.getImageAllow()); + if (finalHolder.data.getImageAllow().equals("1")) { + finalHolder.parent_cam_layout.setVisibility(View.VISIBLE); + } else { + finalHolder.parent_cam_layout.setVisibility(View.GONE); + if (finalHolder.data.getCam_image() != null && !finalHolder.data.getCam_image().isEmpty()) { + if (new File(str + finalHolder.data.getCam_image()).exists()) { + new File(str + finalHolder.data.getCam_image()).delete(); + } + } + finalHolder.data.setCam_image(""); + finalHolder.img_cam.setBackgroundResource(R.mipmap.camera_bsd); + } + } else { + if ((finalHolder.data.getSurveyQuestionType().equalsIgnoreCase("List Single Choice") || + finalHolder.data.getSurveyQuestionType().equalsIgnoreCase("List Multiple Choice"))) { + finalHolder.data.setCorrect_answer_id("0"); + finalHolder.data.setSurveyAnswer(""); + } + } + } + + @Override + public void onNothingSelected(AdapterView parent) { + + } + }); + + holder.img_cam.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + if (surveyType.equalsIgnoreCase("BA")) { + pathforcheck = jcp_Object.getBID() + "_" + counter_id + "_BASurveyPic-" + visit_date.replace("/", "") + CommonFunctions.getCurrentTimeHHMMSS().replace(":", "") + ".jpg"; + } else { + pathforcheck = jcp_Object.getMID() + "_" + counter_id + "_CounterSurveyPic-" + visit_date.replace("/", "") + CommonFunctions.getCurrentTimeHHMMSS().replace(":", "") + ".jpg"; + } + _path = CommonString.getImagesFolder(context) + pathforcheck; + CommonFunctions.startAnncaCameraActivity(context, _path, null, false, CommonString.CAMERA_FACE_REAR); + child_position = childPosition; + //startCameraActivity(0); + } + }); + + + if (holder.data.getSurveyQuestionType().equalsIgnoreCase("Number")) { + holder.edt_answer.setInputType(InputType.TYPE_CLASS_NUMBER); + } else if (holder.data.getSurveyQuestionType().equalsIgnoreCase("Decimal")) { + holder.edt_answer.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL); + } else { + holder.edt_answer.setInputType(InputType.TYPE_CLASS_TEXT); + } + + holder.edt_answer.setOnFocusChangeListener((v, hasFocus) -> { + if (!hasFocus) { + finalHolder.data.setSurveyAnswerId("0"); + finalHolder.data.setSurveyAnswer(((EditText) v).getText().toString()); + } + }); + + if (ans_list.size() > 0) { + for (int i = 0; i < ans_list.size(); i++) { + if ((holder.data.getSurveyQuestionType().equalsIgnoreCase("List Single Choice") || + holder.data.getSurveyQuestionType().equalsIgnoreCase("List Multiple Choice")) && + ans_list.get(i).getSurveyAnswerId().equals(holder.data.getCorrect_answer_id())) { + holder.sp_auditAnswer.setSelection(i); + break; + } + } + } + + if (holder.data.getSurveyQuestionType().equalsIgnoreCase("Text") || + holder.data.getSurveyQuestionType().equalsIgnoreCase("Decimal") || + holder.data.getSurveyQuestionType().equalsIgnoreCase("Number")) { + holder.edt_answer.setText(holder.data.getSurveyAnswer()); + holder.edt_answer.setId(childPosition); + } + + if (holder.data.getImageAllow().equalsIgnoreCase("1")) { + finalHolder.parent_cam_layout.setVisibility(View.VISIBLE); + holder.img_cam.setVisibility(View.VISIBLE); + } else { + finalHolder.parent_cam_layout.setVisibility(View.GONE); + holder.img_cam.setVisibility(View.GONE); + } + + if (!img_str.equals("")) { + if (child_position == childPosition) { + holder.data.setCam_image(img_str); + img_str = ""; + child_position = -1; + } + } + + if (holder.data.getCam_image().equals("")) { + holder.img_cam.setBackgroundResource(R.mipmap.camera_star); + holder.img_cam.setId(childPosition); + } else { + holder.img_cam.setBackgroundResource(R.mipmap.camera_bsd); + holder.img_cam.setId(childPosition); + } + + if (!checkflag) { + if (checkGroupArray.contains(groupPosition) && checkHeaderArray.contains(childPosition)) { + holder.card_view.setBackgroundColor(getResources().getColor(R.color.red)); + holder.card_view.setId(childPosition); + } else { + holder.card_view.setBackgroundColor(getResources().getColor(R.color.white)); + holder.card_view.setId(childPosition); + } + } else { + holder.card_view.setBackgroundColor(getResources().getColor(R.color.white)); + holder.card_view.setId(childPosition); + } + + return convertView; + } + + @Override + public int getChildrenCount(int groupPosition) { + return this.listDataChild.get(this.listDataHeader.get(groupPosition)).size(); + } + + @Override + public Object getGroup(int groupPosition) { + return this.listDataHeader.get(groupPosition); + } + + @Override + public int getGroupCount() { + return this.listDataHeader.size(); + } + + @Override + public long getGroupId(int groupPosition) { + return groupPosition; + } + + @Override + public View getGroupView(final int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { + if (convertView == null) { + LayoutInflater infalInflater = (LayoutInflater) this._context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); + convertView = infalInflater.inflate(R.layout.item_header_expandable_window, parent, false); + } + final MasterSurvey headerTitle = (MasterSurvey) getGroup(groupPosition); + + TextView lblListHeader = (TextView) convertView.findViewById(R.id.txt_header); + CardView cardView = (CardView) convertView.findViewById(R.id.cardview_exists); + lblListHeader.setText(headerTitle.getSurveyName()); + + cardView.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + if (expandableListView.isGroupExpanded(groupPosition)) { + expandableListView.collapseGroup(groupPosition); + } else { + expandableListView.expandGroup(groupPosition); + } + } + }); + + if (!checkflag) { + if (checkGroupArray.contains(groupPosition)) { + cardView.setBackgroundColor(getResources().getColor(R.color.red)); + } else { + cardView.setBackgroundColor(getResources().getColor(R.color.colorPrimaryDark)); + } + } + return convertView; + } + + @Override + public boolean hasStableIds() { + return false; + } + + @Override + public boolean isChildSelectable(int groupPosition, int childPosition) { + return true; + } + + public class ViewHolder extends RecyclerView.ViewHolder { + public final View mView; + public final TextView txt_question; + public final Spinner sp_auditAnswer; + public final EditText edt_answer; + public final ImageView img_cam; + public final RelativeLayout parent_cam_layout; + CardView card_view; + BASurveyGetterSetter data; + + public ViewHolder(View view) { + super(view); + mView = view; + + txt_question = (TextView) view.findViewById(R.id.txt_question); + sp_auditAnswer = (Spinner) view.findViewById(R.id.sp_auditAnswer); + card_view = (CardView) view.findViewById(R.id.card_view); + edt_answer = (EditText) view.findViewById(R.id.edt_answer); + img_cam = (ImageView) view.findViewById(R.id.img_cam); + parent_cam_layout = (RelativeLayout) view.findViewById(R.id.parent_cam_layout); + } + } + + } + + + private static class AnswerSpinnerAdapter extends ArrayAdapter { + List list; + Context context; + int resourceId; + + public AnswerSpinnerAdapter(Context context, int resourceId, ArrayList list) { + super(context, resourceId, list); + this.context = context; + this.list = list; + this.resourceId = resourceId; + } + + @NonNull + @SuppressLint("ViewHolder") + @Override + public View getView(int position, View convertView, @NonNull ViewGroup parent) { + + View view = convertView; + LayoutInflater inflater = ((Activity) context).getLayoutInflater(); + view = inflater.inflate(resourceId, parent, false); + BASurveyGetterSetter cm = list.get(position); + TextView txt_spinner = (TextView) view.findViewById(R.id.tv_ans); + txt_spinner.setText(list.get(position).getSurveyAnswer()); + + return view; + } + + @Override + public View getDropDownView(int position, View _convertView, @NonNull ViewGroup parent) { + View view = _convertView; + LayoutInflater inflater = ((Activity) context).getLayoutInflater(); + view = inflater.inflate(resourceId, parent, false); + + BASurveyGetterSetter cm = list.get(position); + + TextView txt_spinner = (TextView) view.findViewById(R.id.tv_ans); + txt_spinner.setText(cm.getSurveyAnswer()); + + return view; + } + } + + boolean validateData(ArrayList listDataHeader, HashMap> listDataChild) { + checkHeaderArray.clear(); + checkGroupArray.clear(); + loop: + for (int j = 0; j < listDataHeader.size(); j++) { + ArrayList data = listDataChild.get(listDataHeader.get(j)); + for (int i = 0; i < Objects.requireNonNull(data).size(); i++) { + if (data.get(i).getSurveyQuestionType().equalsIgnoreCase("Text") || data.get(i).getSurveyQuestionType().equalsIgnoreCase("Decimal") || data.get(i).getSurveyQuestionType().equalsIgnoreCase("Number")) { + if (data.get(i).getSurveyAnswer() == null || data.get(i).getSurveyAnswer().equalsIgnoreCase("")) { + error_msg = getString(R.string.pls_answer); + checkflag = false; + } else { + checkflag = true; + } + } else { + if (data.get(i).getCorrect_answer_id().equalsIgnoreCase("0")) { + error_msg = getString(R.string.pls_answer_all_qns); + checkflag = false; + } else if (data.get(i).getImageAllow().equals("1") && data.get(i).getCam_image().equals("")) { + error_msg = getString(R.string.click_image); + checkflag = false; + } else { + checkflag = true; + } + } + if (!checkflag) { + if (!checkHeaderArray.contains(i)) { + checkHeaderArray.add(i); + checkGroupArray.add(j); + } + break loop; + } + } + } + adapter.notifyDataSetChanged(); + return checkflag; + } + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + super.onActivityResult(requestCode, resultCode, data); + Log.i("MakeMachine", "resultCode: " + resultCode); + switch (resultCode) { + case 0: + Log.i("MakeMachine", "User cancelled"); + break; + case -1: + if (pathforcheck != null && !pathforcheck.isEmpty()) { + if (new File(CommonString.getImagesFolder(context) + pathforcheck).exists()) { + convertBitmap(CommonString.getImagesFolder(context) + pathforcheck); + img_str = pathforcheck; + pathforcheck = ""; + adapter.notifyDataSetChanged(); + } + } + + } + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/BASurveyListActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/BASurveyListActivity.java new file mode 100644 index 0000000..438818e --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/BASurveyListActivity.java @@ -0,0 +1,205 @@ +package com.cpm.lorealbaautomation.dailyactivity; + +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.os.Bundle; + +import androidx.annotation.NonNull; +import androidx.appcompat.app.AppCompatActivity; +import androidx.cardview.widget.CardView; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; +import androidx.appcompat.widget.Toolbar; +import android.view.LayoutInflater; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; +import android.widget.ImageView; +import android.widget.TextView; + +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.constant.AlertandMessages; +import com.cpm.lorealbaautomation.constant.CommonFunctions; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.gsonGetterSetter.JourneyPlan; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterSurvey; + +import java.util.ArrayList; +import java.util.List; + + +public class BASurveyListActivity extends AppCompatActivity { + List checkHeaderArray = new ArrayList<>(); + boolean checkflag = true; + private SharedPreferences preferences; + String username, date, counter_id = "", SurveyType; + Lorealba_Database db; + Toolbar toolbar; + RecyclerView BAListView; + ArrayList listDataHeader; + Context _context; + BASurveyListAdapter adapter; + JourneyPlan jcp_Object = new JourneyPlan(); + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_ba_survey_list); + _context = this; + preferences = PrefHelper.getPrefs(this); + date = preferences.getString(CommonString.KEY_DATE, null); + username = preferences.getString(CommonString.KEY_USERNAME, null); + counter_id = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + toolbar = (Toolbar) findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + if (!CommonFunctions.isTablet(_context)) { + toolbar.setTitleTextAppearance(_context, R.style.changestext_sizefor_mobile); + } + + getSupportActionBar().setHomeButtonEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + + + BAListView = (RecyclerView) findViewById(R.id.ba_survey_list); + + db = new Lorealba_Database(_context); + db.open(); + jcp_Object = db.getBIDfromJCP(username, counter_id); + //Intent data + if (getIntent().getStringExtra("SurveyType") != null) { + SurveyType = getIntent().getStringExtra("SurveyType"); + } + + if (SurveyType.equalsIgnoreCase("BA")) { + db.open(); + listDataHeader = db.getBASurveySavedData("BA", jcp_Object, date); + } else { + db.open(); + listDataHeader = db.getBASurveySavedData("Counter", jcp_Object, date); + } + + if (listDataHeader.isEmpty()) { + if (SurveyType.equalsIgnoreCase("BA")) { + db.open(); + listDataHeader = db.getSurveyData("BA"); + } else { + db.open(); + listDataHeader = db.getSurveyData("Counter"); + } + } + + adapter = new BASurveyListAdapter(_context, listDataHeader); + BAListView.setLayoutManager(new LinearLayoutManager(_context)); + BAListView.setAdapter(adapter); + + if (SurveyType.equalsIgnoreCase("BA")) { + setTitle("BA Survey List - " + username); + } else { + setTitle("Counter Survey List - " + date); + } + } + + @Override + protected void onResume() { + super.onResume(); + if (getIntent().getStringExtra("SurveyType") != null) { + SurveyType = getIntent().getStringExtra("SurveyType"); + } + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // Handle action bar item clicks here. The action bar will + // automatically handle clicks on the Home/Up button, so long + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + if (id == android.R.id.home) { + finish(); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + } + + return super.onOptionsItemSelected(item); + } + + @Override + public void onBackPressed() { + super.onBackPressed(); + finish(); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + + } + + private class BASurveyListAdapter extends RecyclerView.Adapter { + Context context; + ArrayList listDataHeader; + + public BASurveyListAdapter(Context context, ArrayList listDataHeader) { + this.context = context; + this.listDataHeader = listDataHeader; + } + + @NonNull + @Override + public BASurveyListAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) { + View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.content_ba_survey_list_view, parent, false); + return new ViewHolder(view); + } + + @Override + public void onBindViewHolder(@NonNull BASurveyListAdapter.ViewHolder holder, final int pos) { + final MasterSurvey object = listDataHeader.get(pos); + holder.surveyName.setText(object.getSurveyName().trim()); + holder.surveyName.setId(pos); + db.open(); + if (object.getUploadStatus() == 1) { + holder.complete_icon.setVisibility(View.VISIBLE); + holder.complete_icon.setId(pos); + db.open(); + } else if (db.getSurveyUploadStatus(SurveyType, object.getSurveyId().toString(), username, counter_id)) { + holder.complete_icon.setVisibility(View.VISIBLE); + holder.complete_icon.setId(pos); + } else { + holder.complete_icon.setVisibility(View.GONE); + holder.complete_icon.setId(pos); + } + + holder.cardView.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + db.open(); + if (object.getUploadStatus() == 1) { + AlertandMessages.showToastMsg(context, "Survey Already Done"); + } else if (db.getSurveyUploadStatus(SurveyType, object.getSurveyId().toString(), username, counter_id)) { + AlertandMessages.showToastMsg(context, "Survey Already Done"); + } else { + startActivity(new Intent(context, BASurveyActivity.class).putExtra("SurveyId", listDataHeader.get(pos).getSurveyId().toString()).putExtra("SurveyType", SurveyType)); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + BASurveyListActivity.this.finish(); + } + } + }); + + } + + @Override + public int getItemCount() { + return listDataHeader.size(); + } + + public class ViewHolder extends RecyclerView.ViewHolder { + TextView surveyName; + CardView cardView; + ImageView complete_icon; + + public ViewHolder(@NonNull View itemView) { + super(itemView); + surveyName = (TextView) itemView.findViewById(R.id.survey_name); + cardView = (CardView) itemView.findViewById(R.id.survey_view); + complete_icon = (ImageView) itemView.findViewById(R.id.complete_img); + } + } + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/ConsumerReturnActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/ConsumerReturnActivity.java new file mode 100644 index 0000000..e04a386 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/ConsumerReturnActivity.java @@ -0,0 +1,2354 @@ +package com.cpm.lorealbaautomation.dailyactivity; + +import android.annotation.SuppressLint; +import android.app.Activity; +import android.app.AlertDialog; +import android.app.Dialog; +import android.app.ProgressDialog; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.SharedPreferences; +import android.content.res.Resources; + +import com.google.android.material.floatingactionbutton.FloatingActionButton; + +import androidx.annotation.NonNull; +import androidx.appcompat.app.AppCompatActivity; + +import android.os.Bundle; + +import androidx.cardview.widget.CardView; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; +import androidx.appcompat.widget.Toolbar; + +import android.text.Editable; +import android.text.TextWatcher; +import android.util.Log; +import android.view.Gravity; +import android.view.LayoutInflater; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; +import android.view.Window; +import android.view.WindowManager; +import android.widget.AdapterView; +import android.widget.ArrayAdapter; +import android.widget.Button; +import android.widget.EditText; +import android.widget.ImageView; +import android.widget.LinearLayout; +import android.widget.RadioButton; +import android.widget.RadioGroup; +import android.widget.Spinner; +import android.widget.TextView; +import android.widget.Toast; + +import com.google.firebase.crashlytics.FirebaseCrashlytics; +import com.google.gson.Gson; +import com.google.zxing.integration.android.IntentIntegrator; +import com.google.zxing.integration.android.IntentResult; +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.constant.AlertandMessages; +import com.cpm.lorealbaautomation.constant.CommonFunctions; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.consumeractivity.ConsumerReturnReplaceProductActivity; +import com.cpm.lorealbaautomation.consumeractivity.ConsumerReturnsHistoryActivity; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.gsonGetterSetter.ConsumerSalesHistory; +import com.cpm.lorealbaautomation.gsonGetterSetter.InvoiceGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.JourneyPlan; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterBAProfileGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterReturnReason; +import com.cpm.lorealbaautomation.gsonGetterSetter.ProductMaster; +import com.cpm.lorealbaautomation.retrofit.PostApi; + +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.File; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.TimeUnit; + +import okhttp3.MediaType; +import okhttp3.OkHttpClient; +import okhttp3.RequestBody; +import okhttp3.ResponseBody; +import retrofit2.Retrofit; +import retrofit2.converter.gson.GsonConverterFactory; + +import static com.cpm.lorealbaautomation.constant.CommonFunctions.getCurrentTime; +import static com.cpm.lorealbaautomation.constant.CommonFunctions.removeFirstChar; +import static com.cpm.lorealbaautomation.dailyactivity.StoreImageActivity.convertBitmap; + +public class ConsumerReturnActivity extends AppCompatActivity implements View.OnClickListener { + ArrayAdapter dialog_brand_adapter, dialog_sub_brand_adapter, dialog_frenchise_adapter, dialog_sku_adapter, return_reason_adapter; + public ArrayList selected_list = new ArrayList<>(); + public static ArrayList replace_productList = new ArrayList<>(); + public ArrayList dialog_product_list = new ArrayList<>(); + public ArrayList returnReasonList = new ArrayList<>(); + public ArrayList dialog_product_using_searchlist = new ArrayList<>(); + String counterID, username, visit_date, dialog_brand_Id = "", dialog_sub_brand_Id = "", dialog_reference_Id = "", product_name = "", product_Id = "0", product_mrp = "0", product_scan_code = "", otp_code = "", return_reason_Id = "0", return_reason_name = "", TransId = "", str_return_bill_img = "", _pathforcheck = "", _path = ""; + private SharedPreferences preferences; + Button btn_scan, btn_enter_code, btn_sku_list, btn_send_otp; + EditText edt_customer, edt_bill_no, edt_mobile_no, edt_scan_code, edt_otp; + RecyclerView drawer_layout_recycle_store; + TextView qrcode_text, sku_name, stock_text_value, txt_history; + FloatingActionButton save_fab, add_product_fab; + boolean clicked_flag = false, flag_for_filter = false, flag_filter_by_edt = false, flag_click_history = false; + Lorealba_Database db; + Context context; + MultiPurposeDialog multiPurposeDialog; + InvoiceGetterSetter object; + int minteger = 0; + ProgressDialog loading; + private RadioGroup radioSexGroup; + private RadioButton radioSexButton; + ArrayList returnheaderList; + HashMap> listDataChild; + JourneyPlan storeDataObject = new JourneyPlan(); + List previusHistoryList = new ArrayList<>(); + InvoiceGetterSetter calculateReplace_product = new InvoiceGetterSetter(); + LinearLayout rl_bill_return_img, rl_send_otp; + ImageView img_bill; + EditText edt_email_address; + + @SuppressLint("SetTextI18n") + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_consumer_return); + context = this; + ((ConsumerReturnActivity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); + Toolbar toolbar = findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + if (!CommonFunctions.isTablet(context)) { + toolbar.setTitleTextAppearance(context, R.style.changestext_sizefor_mobile); + } + + + Objects.requireNonNull(getSupportActionBar()).setHomeButtonEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + iduserinterface(); + TransId = CommonFunctions.getUUID(context); + setTitle("Consumer Returns -" + username); + getstatusof_termcondition(); + + String couter_code = preferences.getString(CommonString.KEY_COUNTER_CODE, ""); + TextView txt_counter_code = (TextView) findViewById(R.id.txt_counter_code); + txt_counter_code.setText("Counter Code - " + couter_code + " / Id - " + counterID); + } + + + @SuppressLint("RestrictedApi") + private void iduserinterface() { + db = new Lorealba_Database(context); + db.open(); + preferences = PrefHelper.getPrefs(context); + @SuppressLint("CommitPrefEdits") SharedPreferences.Editor editor = preferences.edit(); + counterID = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + username = preferences.getString(CommonString.KEY_USERNAME, ""); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + txt_history = (TextView) findViewById(R.id.txt_history); + btn_send_otp = (Button) findViewById(R.id.btn_send_otp); + btn_scan = (Button) findViewById(R.id.btn_scan); + btn_enter_code = (Button) findViewById(R.id.btn_enter_code); + btn_sku_list = (Button) findViewById(R.id.btn_sku_list); + save_fab = (FloatingActionButton) findViewById(R.id.save_fab); + edt_customer = (EditText) findViewById(R.id.edt_customer); + edt_bill_no = (EditText) findViewById(R.id.edt_bill_no); + edt_mobile_no = (EditText) findViewById(R.id.edt_mobile_no); + edt_otp = (EditText) findViewById(R.id.edt_otp); + radioSexGroup = (RadioGroup) findViewById(R.id.radioGrp); + add_product_fab = (FloatingActionButton) findViewById(R.id.btn_select_sku); + + drawer_layout_recycle_store = (RecyclerView) findViewById(R.id.drawer_layout_recycle_store); + ///////new changes + rl_bill_return_img = (LinearLayout) findViewById(R.id.rl_bill_return_img); + rl_send_otp = (LinearLayout) findViewById(R.id.rl_send_otp); + img_bill = (ImageView) findViewById(R.id.img_bill); + edt_email_address = (EditText) findViewById(R.id.edt_email_address); + + db.open(); + storeDataObject = db.getspecific_storenamewith_counter_name(visit_date, counterID, username); + btn_scan.setOnClickListener(this); + btn_enter_code.setOnClickListener(this); + btn_sku_list.setOnClickListener(this); + save_fab.setOnClickListener(this); + btn_send_otp.setOnClickListener(this); + txt_history.setOnClickListener(this); + img_bill.setOnClickListener(this); + add_product_fab.setOnClickListener(this); + + db.open(); + dialog_product_list = db.getproduct_masterlist(null, visit_date, counterID, null); + returnReasonList = db.getreturn_reasonList(); + setDataToListView(); + add_product_fab.hide(); + save_fab.show(); + } + + + public void setDataToListView() { + try { + db.open(); + selected_list = db.getconsumerReturndataformDb(counterID, visit_date, username); + if (!selected_list.isEmpty()) { + Collections.reverse(selected_list); + drawer_layout_recycle_store.setAdapter(new ValueAdapter(context, selected_list)); + drawer_layout_recycle_store.setLayoutManager(new LinearLayoutManager(context)); + } + + } catch (Exception e) { + FirebaseCrashlytics.getInstance().recordException(e); + //test("Exception when fetching", e.toString()); + } + } + + + @Override + public void onBackPressed() { + if (clicked_flag) { + AlertDialog.Builder builder = new AlertDialog.Builder(context).setMessage(CommonString.ONBACK_ALERT_MESSAGE).setCancelable(false).setPositiveButton("Ok", new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + ConsumerReturnActivity.this.finish(); + } + }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { + dialog.cancel(); + } + }); + AlertDialog alert = builder.create(); + alert.show(); + } else { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + ConsumerReturnActivity.this.finish(); + } + } + + @Override + public void onClick(View v) { + int id = v.getId(); + if (id == R.id.img_bill) { + _pathforcheck = counterID + "_invoiceimg_" + username + "_" + visit_date.replace("/", "") + "_" + getCurrentTime().replace(":", "") + ".jpg"; + _path = CommonString.getImagesFolder(context) + _pathforcheck; + CommonFunctions.startAnncaCameraActivity(context, _path, null, false, CommonString.CAMERA_FACE_REAR); + } else if (id == R.id.txt_history) { + if (edt_customer.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter Customer Name "); + } else if (edt_bill_no.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter Bill Number "); + } else if (edt_mobile_no.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter Mobile Number"); + } else if (edt_mobile_no.getText().toString().length() < 10) { + AlertandMessages.showToastMsg(context, "Please Enter Atleast 10 Digit Contact Number"); + } else if (!edt_email_address.getText().toString().isEmpty() && !CommonFunctions.isValidEmail(edt_email_address.getText().toString())) { + AlertandMessages.showToastMsg(context, "Please Enter Valid Email Id "); + } else if (checkindex()) { + if (CommonFunctions.checkNetIsAvailable(context)) { + try { + JSONObject jsonObject1 = new JSONObject(); + jsonObject1.put("Downloadtype", "Consumer_SalesHistory"); + jsonObject1.put("Username", username); + jsonObject1.put("Param2", edt_email_address.getText().toString()); + jsonObject1.put("Param1", edt_mobile_no.getText().toString()); + loading = ProgressDialog.show(context, "Processing", "Please wait...", false, false); + getpreviousHistory_from_mobile_no(context, loading, jsonObject1.toString()); + flag_click_history = true; + } catch (JSONException e) { + e.fillInStackTrace(); + } + } else { + AlertandMessages.showAlertlogin((Activity) context, "Unable To Connect Server. History Data Not Updated"); + } + } + + } else if (id == R.id.btn_send_otp) { + try { + ((ConsumerReturnActivity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); + if (edt_mobile_no.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter Mobile Number"); + } else if (edt_mobile_no.getText().toString().length() < 10) { + AlertandMessages.showToastMsg(context, "Please Enter Atleast 10 Digit Contact Number"); + } else { + if (checkindex()) { + JSONObject jsonObject = new JSONObject(); + jsonObject.put("MobileNumber", edt_mobile_no.getText().toString()); + getotp_from_mobile_no(jsonObject.toString()); + } else { + AlertandMessages.showToastMsg(context, "Invalid Mobile Number. Please Enter Correct Mobile Number"); + } + } + } catch (JSONException e) { + e.fillInStackTrace(); + } + + } else if (id == R.id.btn_scan) { + clicked_flag = true; + ((ConsumerReturnActivity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); + if (edt_customer.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter Customer Name"); + } else if (edt_bill_no.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter Bill Number"); + } else if (edt_mobile_no.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter Mobile Number"); + } else if (edt_mobile_no.getText().toString().length() < 10) { + AlertandMessages.showToastMsg(context, "Please Enter Atleast 10 Digit Contact Number"); + } else if (!edt_email_address.getText().toString().isEmpty() && !CommonFunctions.isValidEmail(edt_email_address.getText().toString())) { + AlertandMessages.showToastMsg(context, "Please Enter Valid Email Id "); + } else if (!flag_click_history) { + AlertandMessages.showToastMsg(context, "Please Click Show History"); + } else { + show_proforma_dialog(context, true); + } + + } else if (id == R.id.btn_enter_code) { + clicked_flag = true; + ((ConsumerReturnActivity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); + if (edt_customer.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter Customer Name "); + } else if (edt_bill_no.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter Bill Number "); + } else if (edt_mobile_no.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter Mobile Number"); + } else if (edt_mobile_no.getText().toString().length() < 10) { + AlertandMessages.showToastMsg(context, "Please Enter Atleast 10 Digit Contact Number"); + } else if (!edt_email_address.getText().toString().isEmpty() && !CommonFunctions.isValidEmail(edt_email_address.getText().toString())) { + AlertandMessages.showToastMsg(context, "Please Enter Valid Email Id "); + } else if (!flag_click_history) { + AlertandMessages.showToastMsg(context, "Please Click Show History"); + } else { + show_proforma_dialog(context, false); + } + + } else if (id == R.id.btn_select_sku) { + prepareListData(); + if (calculateReplace_product != null && calculateReplace_product.getTotal_replace_product_value() != 0) { + startActivity(new Intent(context, ConsumerReturnReplaceProductActivity.class).putExtra(CommonString.TAG_OBJECT, calculateReplace_product)); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + } + + } else if (id == R.id.save_fab) { + if (selected_list.size() > 0) { + if (previusHistoryList.size() == 0 && edt_otp.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter OTP"); + } else if (previusHistoryList.size() == 0 && !otp_code.equals(edt_otp.getText().toString().trim())) { + AlertandMessages.showToastMsg(context, "Please Enter Correct OTP"); + } else if (str_return_bill_img.equals("")) { + AlertandMessages.showToastMsg(context, "Please Capture Bill Image"); + } else { + prepareListData(); + if (calculateReplace_product != null && calculateReplace_product.getTotal_replace_product_value() != 0 && replace_productList.size() == 0) { + startActivity(new Intent(context, ConsumerReturnReplaceProductActivity.class).putExtra(CommonString.TAG_OBJECT, calculateReplace_product)); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + } else { + show_selected_invoice(context); + } + } + } else { + AlertandMessages.showToastMsg(context, "Please Add first "); + } + + } else if (id == R.id.btn_sku_list) { + clicked_flag = true; + ((ConsumerReturnActivity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); + if (edt_customer.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter Customer Name "); + } else if (edt_bill_no.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter Bill Number "); + } else if (edt_mobile_no.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter Mobile Number"); + } else if (edt_mobile_no.getText().toString().length() < 10) { + AlertandMessages.showToastMsg(context, "Please Enter Atleast 10 Digit Contact Number"); + } else if (!edt_email_address.getText().toString().isEmpty() && !CommonFunctions.isValidEmail(edt_email_address.getText().toString())) { + AlertandMessages.showToastMsg(context, "Please Enter Valid Email Id "); + } else if (!flag_click_history) { + AlertandMessages.showToastMsg(context, "Please Click Show History"); + } else { + show_dialog_forsku_categorywise(context); + } + } + } + + + public class MultiPurposeDialog extends Dialog { + public MultiPurposeDialog(Context context) { + super(context); + // DIALOG USER_INTERFACE TEMPLATE + WindowManager.LayoutParams wmLayoutParams = getWindow().getAttributes(); + wmLayoutParams.gravity = Gravity.CENTER; + getWindow().setAttributes(wmLayoutParams); + setTitle(null); + setCancelable(false); + setOnCancelListener(null); + LinearLayout layout = new LinearLayout(context); + layout.setOrientation(LinearLayout.VERTICAL); + } + } + + private void show_dialog_forsku_categorywise(final Context context) { + minteger = 0; + multiPurposeDialog = new MultiPurposeDialog(context); + multiPurposeDialog.requestWindowFeature(Window.FEATURE_NO_TITLE); + multiPurposeDialog.setContentView(R.layout.custom_sku_list_with_category); + final WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); + lp.copyFrom(multiPurposeDialog.getWindow().getAttributes()); + lp.width = WindowManager.LayoutParams.MATCH_PARENT; + lp.height = WindowManager.LayoutParams.WRAP_CONTENT; + lp.gravity = Gravity.CENTER; + multiPurposeDialog.getWindow().setAttributes(lp); + multiPurposeDialog.setCancelable(false); + ///new changes 19 aug + + LinearLayout rl_actualreaturn_qty = (LinearLayout) multiPurposeDialog.findViewById(R.id.rl_actualreaturn_qty); + final EditText edt_actual_qty_reaturn = (EditText) multiPurposeDialog.findViewById(R.id.edt_actual_qty_reaturn); + final Spinner dialog_brand_spin = (Spinner) multiPurposeDialog.findViewById(R.id.dialog_brand_spin); + final Spinner dialog_subbrand_spin = (Spinner) multiPurposeDialog.findViewById(R.id.dialog_subbrand_spin); + final Spinner dialog_reference_spin = (Spinner) multiPurposeDialog.findViewById(R.id.dialog_reference_spin); + final Spinner dialog_product_spin = (Spinner) multiPurposeDialog.findViewById(R.id.dialog_product_spin); + final EditText et_search = (EditText) multiPurposeDialog.findViewById(R.id.et_search); + final TextView stock_text_value = (TextView) multiPurposeDialog.findViewById(R.id.stock_text_value); + + final Button stock_img_minus = (Button) multiPurposeDialog.findViewById(R.id.stock_img_minus); + Button stock_img_plus = (Button) multiPurposeDialog.findViewById(R.id.stock_img_plus); + + ImageView cancet_btn = (ImageView) multiPurposeDialog.findViewById(R.id.cancet_btn); + final ImageView btn_add = (ImageView) multiPurposeDialog.findViewById(R.id.btn_add); + + final LinearLayout rl_return_reason = (LinearLayout) multiPurposeDialog.findViewById(R.id.rl_return_reason); + final Spinner return_reason_spin = (Spinner) multiPurposeDialog.findViewById(R.id.return_reason_spin); + + rl_return_reason.setVisibility(View.VISIBLE); + rl_actualreaturn_qty.setVisibility(View.GONE); + + setReturnReasonSpinnerData(returnReasonList, return_reason_spin); + + return_reason_spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { + @Override + public void onItemSelected(AdapterView adapterView, View view, int pos, long l) { + if (pos != 0) { + return_reason_name = returnReasonList.get(pos - 1).getReason(); + return_reason_Id = returnReasonList.get(pos - 1).getReasonId().toString(); + } else { + return_reason_name = ""; + return_reason_Id = "0"; + } + } + + @Override + public void onNothingSelected(AdapterView adapterView) { + + } + }); + + et_search.addTextChangedListener(new TextWatcher() { + @Override + public void beforeTextChanged(CharSequence s, int start, int count, int after) { + + } + + @Override + public void onTextChanged(CharSequence s, int start, int before, int count) { + String text = s.toString(); + setSearchFilter(dialog_product_list, text, dialog_product_spin); + } + + @Override + public void afterTextChanged(Editable s) { + String text = s.toString(); + } + }); + + + db.open(); + validate_spin_ui_data(dialog_brand_spin, dialog_subbrand_spin, dialog_reference_spin, dialog_product_spin, db.getproductdata_dialogfor_return("BrandName", "BrandId", false, ""), db.getproductdata_dialogfor_return("SubBrandName", "SubBrandId", false, ""), db.getproductdata_dialogfor_return("ReferenceName", "ReferenceId", false, ""), db.getbrand_wise_sku_fromproductfor_return(), stock_text_value); + + + cancet_btn.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + multiPurposeDialog.dismiss(); + } + }); + + stock_img_plus.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + // if (!edt_actual_qty_reaturn.getText().toString().isEmpty()) { + if (!product_Id.equals("0")) { + try { + minteger = minteger + 1; + stock_text_value.setText("" + minteger); + /* if (minteger > Integer.parseInt(edt_actual_qty_reaturn.getText().toString())) { + minteger = minteger - 1; + stock_text_value.setText("" + minteger); + AlertandMessages.showToastMsg(context, "Product quantity should not be Greater than Invoice Actual Quantity "); + } else { + stock_text_value.setText("" + minteger); + }*/ + } catch (NumberFormatException e) { + e.fillInStackTrace(); + } + } else { + AlertandMessages.showToastMsg(context, "First Select Product"); + } + // } else { + // AlertandMessages.showToastMsg(context, "First Enter Invoice Actual Quantity"); + // } + } + }); + + stock_img_minus.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + //if (!edt_actual_qty_reaturn.getText().toString().isEmpty()) { + if (minteger == 0) { + AlertandMessages.showToastMsg(context, "Product quantity should not be less than Zero "); + } else { + minteger = minteger - 1; + stock_text_value.setText("" + minteger); + } + // } else { + // AlertandMessages.showToastMsg(context, "First Enter Invoice Actual Quantity"); + // } + } + }); + + + btn_add.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + ((ConsumerReturnActivity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); + if (dialog_product_spin.getSelectedItemId() == 0) { + AlertandMessages.showToastMsg(context, "Please Select Product"); + }/* else if (edt_actual_qty_reaturn.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "First Enter Invoice Actual Quantity"); + } else if (edt_actual_qty_reaturn.getText().toString().equals("0")) { + AlertandMessages.showToastMsg(context, "Please Enter atleast One Invoice Actual Quantity"); + }*/ else if (stock_text_value.getText().toString().equals("0")) { + AlertandMessages.showToastMsg(context, "Please add atleast One Product Quantity "); + } else if (return_reason_spin.getSelectedItemId() == 0) { + AlertandMessages.showToastMsg(context, "Please Select Return Reason "); + }/* else if (Integer.parseInt(stock_text_value.getText().toString()) > Integer.parseInt(edt_actual_qty_reaturn.getText().toString())) { + AlertandMessages.showToastMsg(context, "Product Quantity Should be Less Than OR equal to Invoice Actual Quantity"); + }*/ else { + // get selected radio button from radioGroup + int selectedId = radioSexGroup.getCheckedRadioButtonId(); + // find the radiobutton by returned id + radioSexButton = (RadioButton) findViewById(selectedId); + object = new InvoiceGetterSetter(); + object.setStore_name(storeDataObject.getCounterName()); + object.setStore_address(storeDataObject.getAddress() + "," + storeDataObject.getCityName()); + object.setCustomer_name(edt_customer.getText().toString().trim().replaceAll("[(!@#$%^&*?)\"]", "")); + object.setMobile_no(edt_mobile_no.getText().toString()); + object.setConsumer_email_Id(edt_email_address.getText().toString()); + + object.setConsumer_return_bill_no(edt_bill_no.getText().toString()); + object.setProduct_rate(product_mrp); + object.setProduct(product_name); + object.setProduct_Id(product_Id); + object.setCustomer_gender(radioSexButton.getText().toString()); + object.setScan_ean_code_or_enterd_ean_code(product_scan_code); + object.setQuantity(stock_text_value.getText().toString()); + // object.setActualQty(edt_actual_qty_reaturn.getText().toString()); + object.setActualQty("0"); + object.setCon_return_reason(return_reason_name); + object.setCon_return_reason_Id(return_reason_Id); + object.setReturn_bill_img(str_return_bill_img); + selected_list.add(object); + + /////for return to product + if (calcualtereturntoprodcutList(selected_list)) { + save_fab.hide(); + add_product_fab.show(); + } else { + save_fab.show(); + add_product_fab.hide(); + } + + minteger = 0; + //edt_actual_qty_reaturn.setText("0"); + stock_text_value.setText("0"); + product_scan_code = ""; + dialog_brand_Id = ""; + dialog_sub_brand_Id = ""; + dialog_reference_Id = ""; + product_name = ""; + product_Id = "0"; + drawer_layout_recycle_store.setAdapter(new ValueAdapter(context, selected_list)); + drawer_layout_recycle_store.setLayoutManager(new LinearLayoutManager(context)); + multiPurposeDialog.dismiss(); + + } + } + }); + + multiPurposeDialog.show(); + } + + + private void validate_spin_ui_data(final Spinner dialog_brand_spin, final Spinner dialog_sub_brand_spin, final Spinner dialog_franchise_spin, final Spinner dialog_product_spin, final ArrayList brandList, final ArrayList subbrandList, final ArrayList referenceList, final ArrayList productList, final TextView stock_text_value) { + + dialog_brand_adapter = new ArrayAdapter<>(this, R.layout.spinner_custom_item); + dialog_brand_adapter.add("- Select Brand -"); + + for (int i = 0; i < brandList.size(); i++) { + dialog_brand_adapter.add(brandList.get(i).getBrandName()); + } + + dialog_brand_spin.setAdapter(dialog_brand_adapter); + + dialog_brand_adapter.setDropDownViewResource(R.layout.spinner_custom_item); + + setSubBrandSpinnerData(subbrandList, dialog_sub_brand_spin); + + setReferenceSpinnerData(referenceList, dialog_franchise_spin); + + setProductSpinnerData(productList, dialog_product_spin); + + dialog_brand_spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { + @Override + public void onItemSelected(AdapterView adapterView, View view, int pos, long l) { + if (pos != 0) { + db.open(); + flag_for_filter = true; + flag_filter_by_edt = false; + dialog_brand_Id = adapterView.getSelectedItem().toString(); + setFilter(FILTER_FOR_BRAND, dialog_product_spin); + + setSubBrandSpinnerData(db.getsub_brand_using_brand_Id(dialog_brand_Id, "SubBrandName", "SubBrandId", "BrandName", null, visit_date, counterID, false, null), dialog_sub_brand_spin); + setReferenceSpinnerData(db.getsub_brand_using_brand_Id(dialog_brand_Id, "ReferenceName", "ReferenceId", "BrandName", null, visit_date, counterID, false, null), dialog_franchise_spin); + } else { + dialog_brand_Id = ""; + if (dialog_brand_spin.getSelectedItemPosition() != 0 || dialog_sub_brand_spin.getSelectedItemPosition() != 0 || dialog_franchise_spin.getSelectedItemPosition() != 0) { + flag_for_filter = true; + } else { + setFilter(CLEAR_FILTER, dialog_product_spin); + flag_for_filter = false; + } + } + } + + + @Override + public void onNothingSelected(AdapterView adapterView) { + + } + }); + + dialog_sub_brand_spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { + @Override + public void onItemSelected(AdapterView adapterView, View view, int pos, long l) { + if (pos != 0) { + db.open(); + flag_for_filter = true; + flag_filter_by_edt = false; + dialog_sub_brand_Id = adapterView.getSelectedItem().toString(); + setFilter(FILTER_FOR_SUB_BRAND, dialog_product_spin); + setReferenceSpinnerData(db.getsub_brand_using_brand_Id(dialog_sub_brand_Id, "ReferenceName", "ReferenceId", "SubBrandName", null, visit_date, counterID, false, null), dialog_franchise_spin); + } else { + dialog_sub_brand_Id = ""; + if (dialog_brand_spin.getSelectedItemPosition() != 0 || dialog_sub_brand_spin.getSelectedItemPosition() != 0 || dialog_franchise_spin.getSelectedItemPosition() != 0) { + flag_for_filter = true; + } else { + setFilter(CLEAR_FILTER, dialog_product_spin); + flag_for_filter = false; + } + } + } + + @Override + public void onNothingSelected(AdapterView adapterView) { + + } + }); + + dialog_franchise_spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { + @Override + public void onItemSelected(AdapterView adapterView, View view, int pos, long l) { + if (pos != 0) { + flag_for_filter = true; + flag_filter_by_edt = false; + dialog_reference_Id = adapterView.getSelectedItem().toString(); + setFilter(FILTER_FOR_REFERENCE_NAME, dialog_product_spin); + + } else { + dialog_reference_Id = ""; + if (dialog_brand_spin.getSelectedItemPosition() != 0 || dialog_sub_brand_spin.getSelectedItemPosition() != 0 || dialog_franchise_spin.getSelectedItemPosition() != 0) { + flag_for_filter = true; + } else { + setFilter(CLEAR_FILTER, dialog_product_spin); + flag_for_filter = false; + } + } + } + + @Override + public void onNothingSelected(AdapterView adapterView) { + + } + }); + + + dialog_product_spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { + @Override + public void onItemSelected(AdapterView parent, View view, int position, long id) { + if (position != 0) { + if (flag_filter_by_edt) { + product_name = dialog_product_using_searchlist.get(position - 1).getProductName(); + product_Id = dialog_product_using_searchlist.get(position - 1).getProductId().toString(); + product_mrp = dialog_product_using_searchlist.get(position - 1).getMrp().toString(); + product_scan_code = dialog_product_using_searchlist.get(position - 1).getEanCode(); + stock_text_value.setText("0"); + minteger = 0; + } else if (flag_for_filter) { + product_name = filterListForReferencename(dialog_product_list, dialog_reference_Id, dialog_brand_Id, dialog_sub_brand_Id).get(position - 1).getProductName(); + product_Id = filterListForReferencename(dialog_product_list, dialog_reference_Id, dialog_brand_Id, dialog_sub_brand_Id).get(position - 1).getProductId().toString(); + product_mrp = filterListForReferencename(dialog_product_list, dialog_reference_Id, dialog_brand_Id, dialog_sub_brand_Id).get(position - 1).getMrp().toString(); + product_scan_code = filterListForReferencename(dialog_product_list, dialog_reference_Id, dialog_brand_Id, dialog_sub_brand_Id).get(position - 1).getEanCode(); + stock_text_value.setText("0"); + minteger = 0; + } else { + product_name = productList.get(position - 1).getProductName(); + product_Id = productList.get(position - 1).getProductId().toString(); + product_mrp = productList.get(position - 1).getMrp().toString(); + product_scan_code = productList.get(position - 1).getEanCode(); + stock_text_value.setText("0"); + minteger = 0; + } + + } else { + stock_text_value.setText("0"); + product_scan_code = ""; + product_mrp = "0"; + product_name = ""; + product_Id = "0"; + minteger = 0; + } + } + + @Override + public void onNothingSelected(AdapterView parent) { + + } + }); + + } + + + private void setSubBrandSpinnerData(ArrayList axeList, Spinner dialog_sub_brand_spin) { + dialog_sub_brand_adapter = new ArrayAdapter<>(this, R.layout.spinner_custom_item); + dialog_sub_brand_adapter.add("- Select Sub Brand -"); + + for (int i = 0; i < axeList.size(); i++) { + dialog_sub_brand_adapter.add(axeList.get(i).getBrandName()); + } + + dialog_sub_brand_spin.setAdapter(dialog_sub_brand_adapter); + dialog_sub_brand_adapter.setDropDownViewResource(R.layout.spinner_custom_item); + + } + + + private void setReferenceSpinnerData(ArrayList referenceList, Spinner dialog_franchise_spin) { + dialog_frenchise_adapter = new ArrayAdapter<>(this, R.layout.spinner_custom_item); + dialog_frenchise_adapter.add("- Select Franchise -"); + + for (int i = 0; i < referenceList.size(); i++) { + dialog_frenchise_adapter.add(referenceList.get(i).getBrandName()); + } + + dialog_franchise_spin.setAdapter(dialog_frenchise_adapter); + dialog_frenchise_adapter.setDropDownViewResource(R.layout.spinner_custom_item); + } + + private void setProductSpinnerData(ArrayList productList, Spinner dialog_product_spin) { + dialog_sku_adapter = new ArrayAdapter<>(this, R.layout.spinner_custom_item); + dialog_sku_adapter.add("- Select Product -"); + + for (int i = 0; i < productList.size(); i++) { + dialog_sku_adapter.add(productList.get(i).getProductName() + " - (MRP-" + productList.get(i).getMrp().toString() + ")"); + } + + dialog_product_spin.setAdapter(dialog_sku_adapter); + dialog_sku_adapter.setDropDownViewResource(R.layout.spinner_custom_item); + } + + + public void setFilter(int filterType, Spinner dialog_spin) { + if (filterType == FILTER_FOR_BRAND) { + dialog_sku_adapter = new ArrayAdapter<>(context, R.layout.spinner_custom_item); + dialog_sku_adapter.add("- Select Product -"); + + for (int i = 0; i < filterListForBrand(dialog_product_list, dialog_brand_Id).size(); i++) { + dialog_sku_adapter.add(filterListForBrand(dialog_product_list, dialog_brand_Id).get(i).getProductName() + " - (MRP-" + filterListForBrand(dialog_product_list, dialog_brand_Id).get(i).getMrp().toString() + ")"); + } + + dialog_spin.setAdapter(dialog_sku_adapter); + dialog_sku_adapter.setDropDownViewResource(R.layout.spinner_custom_item); + + } else if (filterType == FILTER_FOR_SUB_BRAND) { + dialog_sku_adapter = new ArrayAdapter<>(context, R.layout.spinner_custom_item); + dialog_sku_adapter.add("- Select Product -"); + + for (int i = 0; i < filterListForSubBrand(dialog_product_list, dialog_sub_brand_Id, dialog_brand_Id).size(); i++) { + dialog_sku_adapter.add(filterListForSubBrand(dialog_product_list, dialog_sub_brand_Id, dialog_brand_Id).get(i).getProductName() + " - (MRP-" + filterListForSubBrand(dialog_product_list, dialog_sub_brand_Id, dialog_brand_Id).get(i).getMrp().toString() + ")"); + } + dialog_spin.setAdapter(dialog_sku_adapter); + dialog_sku_adapter.setDropDownViewResource(R.layout.spinner_custom_item); + } else if (filterType == FILTER_FOR_REFERENCE_NAME) { + + dialog_sku_adapter = new ArrayAdapter<>(context, R.layout.spinner_custom_item); + dialog_sku_adapter.add("- Select Product -"); + + for (int i = 0; i < filterListForReferencename(dialog_product_list, dialog_reference_Id, dialog_brand_Id, dialog_sub_brand_Id).size(); i++) { + dialog_sku_adapter.add(filterListForReferencename(dialog_product_list, dialog_reference_Id, dialog_brand_Id, dialog_sub_brand_Id).get(i).getProductName() + " - (MRP-" + filterListForReferencename(dialog_product_list, dialog_reference_Id, dialog_brand_Id, dialog_sub_brand_Id).get(i).getMrp().toString() + ")"); + } + + dialog_spin.setAdapter(dialog_sku_adapter); + dialog_sku_adapter.setDropDownViewResource(R.layout.spinner_custom_item); + + } else { + dialog_sku_adapter = new ArrayAdapter<>(context, R.layout.spinner_custom_item); + dialog_sku_adapter.add("- Select Product -"); + + for (int i = 0; i < dialog_product_list.size(); i++) { + dialog_sku_adapter.add(dialog_product_list.get(i).getProductName() + " - (MRP-" + dialog_product_list.get(i).getMrp().toString() + ")"); + } + + dialog_spin.setAdapter(dialog_sku_adapter); + dialog_sku_adapter.setDropDownViewResource(R.layout.spinner_custom_item); + } + + dialog_spin.invalidate(); + } + + final int CLEAR_FILTER = 0; + final int FILTER_FOR_BRAND = 1; + final int FILTER_FOR_SUB_BRAND = 2; + final int FILTER_FOR_REFERENCE_NAME = 3; + + public ArrayList filterListForBrand(List originalList, String text) { + ArrayList filterList = new ArrayList<>(); + for (ProductMaster object : originalList) { + if (object.getBrandName().equalsIgnoreCase(text)) { + filterList.add(object); + } else { + continue; + } + } + return filterList; + } + + public ArrayList filterListForSubBrand(List originalList, String sub_brand_name_id, String brand_Id) { + ArrayList filterList = new ArrayList<>(); + for (ProductMaster object : originalList) { + if (sub_brand_name_id.equals("") && object.getBrandName().equalsIgnoreCase(brand_Id)) { + filterList.add(object); + } else if (object.getSubBrandName().equalsIgnoreCase(sub_brand_name_id) && (brand_Id.equals("") || object.getBrandName().equalsIgnoreCase(brand_Id))) { + filterList.add(object); + } else { + continue; + } + } + + return filterList; + } + + + public ArrayList filterListForReferencename(List originalList, String franchise_Id, String brandName_Id, String sub_brand_name_Id) { + ArrayList filterList = new ArrayList<>(); + for (ProductMaster object : originalList) { + if (sub_brand_name_Id.equals("") && object.getBrandName().equalsIgnoreCase(brandName_Id)) { + filterList.add(object); + } else if (franchise_Id.equals("") && object.getSubBrandName().equalsIgnoreCase(sub_brand_name_Id)) { + filterList.add(object); + } else if (object.getReferenceName().equalsIgnoreCase(franchise_Id) && (brandName_Id.equals("") || object.getBrandName().equalsIgnoreCase(brandName_Id)) && (sub_brand_name_Id.equals("") || object.getSubBrandName().equalsIgnoreCase(sub_brand_name_Id))) { + filterList.add(object); + } else { + continue; + } + } + + return filterList; + } + + + private class ValueAdapter extends RecyclerView.Adapter { + LayoutInflater inflator; + List data; + + + public ValueAdapter(Context context, List data) { + inflator = LayoutInflater.from(context); + this.data = data; + } + + @NonNull + @Override + public ValueAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) { + View view = inflator.inflate(R.layout.row_adapter_return_consumer, parent, false); + return new ValueAdapter.MyViewHolder(view); + } + + @Override + public void onBindViewHolder(final ValueAdapter.MyViewHolder holder, @SuppressLint("RecyclerView") final int position) { + final InvoiceGetterSetter current = data.get(position); + + holder.select_promo_productRl.setVisibility(View.GONE); + holder.select_promo_productRl.setId(position); + + holder.select_productRl.setVisibility(View.VISIBLE); + holder.select_productRl.setId(position); + + + int quantity = Integer.parseInt(current.getQuantity()); + double amount = Double.parseDouble(current.getProduct_rate()); + amount = amount * quantity; + double cCom = ((amount) * current.getDiscount()); + + if (current.getDiscount() == 0.0 || current.getDiscount() == 00) { + holder.text_item.setText(current.getProduct()); + holder.text_item.setId(position); + } else { + String string = current.getDiscount().toString(); + //test("last character: " + string.substring(string.length() - 1)); + holder.text_item.setText(current.getProduct() + " Discount : " + string.substring(string.length() - 1) + "0%"); + holder.text_item.setId(position); + } + + holder.text_qty.setText(current.getQuantity()); + holder.text_qty.setId(position); + + holder.text_actualqty.setText(current.getActualQty()); + holder.text_actualqty.setId(position); + + holder.txt_amount.setText(current.getProduct_rate()); + holder.txt_amount.setId(position); + + holder.delete_added_product.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + AlertDialog.Builder builder = new AlertDialog.Builder(context).setMessage("Are you sure you want to Delete ?").setTitle(getString(R.string.password_rules)).setCancelable(false).setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { + data.remove(position); + notifyDataSetChanged(); + if (data.size() > 0) { + ValueAdapter adapter = new ValueAdapter(context, data); + drawer_layout_recycle_store.setAdapter(adapter); + adapter.notifyDataSetChanged(); + } + + /////for return to product + if (calcualtereturntoprodcutList((ArrayList) data)) { + save_fab.hide(); + add_product_fab.show(); + } else { + save_fab.show(); + add_product_fab.hide(); + } + + notifyDataSetChanged(); + } + }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { + dialog.cancel(); + } + }); + AlertDialog alert = builder.create(); + alert.show(); + } + }); + + } + + @Override + public int getItemCount() { + return data.size(); + } + + class MyViewHolder extends RecyclerView.ViewHolder { + LinearLayout select_productRl, select_promo_productRl; + TextView text_item, text_qty, txt_amount, text_actualqty; + ImageView delete_added_product; + + public MyViewHolder(View itemView) { + super(itemView); + text_item = (TextView) itemView.findViewById(R.id.text_item); + text_qty = (TextView) itemView.findViewById(R.id.text_qty); + txt_amount = (TextView) itemView.findViewById(R.id.txt_amount); + text_actualqty = (TextView) itemView.findViewById(R.id.text_actualqty); + delete_added_product = (ImageView) itemView.findViewById(R.id.delete_added_product); + select_promo_productRl = (LinearLayout) itemView.findViewById(R.id.select_promo_productRl); + select_productRl = (LinearLayout) itemView.findViewById(R.id.select_productRl); + } + } + } + + + private void show_proforma_dialog(final Context context, final boolean flag_for_rl) { + minteger = 0; + final MultiPurposeDialog multiPurposeDialog = new MultiPurposeDialog(context); + multiPurposeDialog.requestWindowFeature(Window.FEATURE_NO_TITLE); + multiPurposeDialog.setContentView(R.layout.custom_bar_code_dialog); + multiPurposeDialog.setCancelable(false); + WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); + lp.copyFrom(multiPurposeDialog.getWindow().getAttributes()); + lp.width = WindowManager.LayoutParams.MATCH_PARENT; + lp.height = WindowManager.LayoutParams.WRAP_CONTENT; + lp.gravity = Gravity.CENTER; + multiPurposeDialog.getWindow().setAttributes(lp); + multiPurposeDialog.setCancelable(false); +//jp + + + LinearLayout rl_actualreaturn_qty = (LinearLayout) multiPurposeDialog.findViewById(R.id.rl_actualreaturn_qty); + final EditText edt_actual_qty_reaturn = (EditText) multiPurposeDialog.findViewById(R.id.edt_actual_qty_reaturn); + + LinearLayout rl_bar_code = (LinearLayout) multiPurposeDialog.findViewById(R.id.rl_bar_code); + LinearLayout RL_scan_code = (LinearLayout) multiPurposeDialog.findViewById(R.id.RL_scan_code); + Button check_exist_sku = (Button) multiPurposeDialog.findViewById(R.id.check_exist_sku); + TextView txt_bar_code = multiPurposeDialog.findViewById(R.id.txt_bar_code); + TextView txt_enterbar_code = multiPurposeDialog.findViewById(R.id.txt_enterbar_code); + LinearLayout rl_quantity = (LinearLayout) multiPurposeDialog.findViewById(R.id.rl_quantity); + RecyclerView recycl_mutliennter_qty = (RecyclerView) multiPurposeDialog.findViewById(R.id.recycl_mutliennter_qty); + recycl_mutliennter_qty.setVisibility(View.GONE); + rl_quantity.setVisibility(View.VISIBLE); + sku_name = multiPurposeDialog.findViewById(R.id.sku_name); + rl_actualreaturn_qty.setVisibility(View.GONE); + + if (flag_for_rl) { + RL_scan_code.setVisibility(View.GONE); + rl_bar_code.setVisibility(View.VISIBLE); + txt_bar_code.setVisibility(View.VISIBLE); + txt_enterbar_code.setVisibility(View.GONE); + } else { + rl_bar_code.setVisibility(View.GONE); + txt_bar_code.setVisibility(View.GONE); + RL_scan_code.setVisibility(View.VISIBLE); + txt_enterbar_code.setVisibility(View.VISIBLE); + } + + + qrcode_text = (TextView) multiPurposeDialog.findViewById(R.id.qrcode_text); + edt_scan_code = (EditText) multiPurposeDialog.findViewById(R.id.edt_scan_code); + final Button stock_img_minus = (Button) multiPurposeDialog.findViewById(R.id.stock_img_minus); + Button stock_img_plus = (Button) multiPurposeDialog.findViewById(R.id.stock_img_plus); + stock_text_value = (TextView) multiPurposeDialog.findViewById(R.id.stock_text_value); + + ImageView img_bar_code = (ImageView) multiPurposeDialog.findViewById(R.id.img_bar_code); + ImageView cancet_btn = (ImageView) multiPurposeDialog.findViewById(R.id.cancet_btn); + final ImageView btn_add = (ImageView) multiPurposeDialog.findViewById(R.id.btn_add); + + final LinearLayout rl_return_reason = (LinearLayout) multiPurposeDialog.findViewById(R.id.rl_return_reason); + final Spinner return_reason_spin = (Spinner) multiPurposeDialog.findViewById(R.id.return_reason_spin); + btn_add.setVisibility(View.VISIBLE); + rl_return_reason.setVisibility(View.VISIBLE); + + setReturnReasonSpinnerData(returnReasonList, return_reason_spin); + + return_reason_spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { + @Override + public void onItemSelected(AdapterView adapterView, View view, int pos, long l) { + if (pos != 0) { + return_reason_name = returnReasonList.get(pos - 1).getReason(); + return_reason_Id = returnReasonList.get(pos - 1).getReasonId().toString(); + } else { + return_reason_name = ""; + return_reason_Id = "0"; + } + + } + + @Override + public void onNothingSelected(AdapterView adapterView) { + + } + }); + + stock_img_plus.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + // if (!edt_actual_qty_reaturn.getText().toString().isEmpty()) { + if (!product_Id.equals("0")) { + minteger = minteger + 1; + stock_text_value.setText("" + minteger); + +// if (minteger > Integer.parseInt(edt_actual_qty_reaturn.getText().toString())) { +// minteger = minteger - 1; +// stock_text_value.setText("" + minteger); +// AlertandMessages.showToastMsg(context, "Product quantity should not be Greater than Invoice Actual Quantity "); +// } +// else { +// stock_text_value.setText("" + minteger); +// } + } else { + AlertandMessages.showToastMsg(context, "First Select Product"); + } + // } else { + // AlertandMessages.showToastMsg(context, "First Enter Invoice Actual Quantity"); + // } + } + }); + + stock_img_minus.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + // if (!edt_actual_qty_reaturn.getText().toString().isEmpty()) { + if (minteger == 0) { + AlertandMessages.showToastMsg(context, "Product quantity should not be less than Zero "); + } else { + minteger = minteger - 1; + stock_text_value.setText("" + minteger); + } + // } else { + // AlertandMessages.showToastMsg(context, "First Enter Invoice Actual Quantity"); + // } + } + }); + + cancet_btn.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + multiPurposeDialog.dismiss(); + sku_name.setText(""); + stock_text_value.setText(""); + qrcode_text.setText(""); + product_scan_code = ""; + product_name = ""; + product_mrp = ""; + product_Id = "0"; + sku_name.setVisibility(View.GONE); + } + }); + + check_exist_sku.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + if (!flag_for_rl && edt_scan_code.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter Bar Code "); + } else { + + db.open(); + ArrayList productList = db.getsku_fromproductusing_eancodefor_return(edt_scan_code.getText().toString()); + if (productList.size() == 0) { + db.open(); + productList = db.getsku_fromproductusing_eancodefor_return(removeFirstChar(edt_scan_code.getText().toString())); + } + + if (productList.size() == 0) { + edt_scan_code.setText(""); + AlertandMessages.showToastMsg(context, "Invalid Bar Code.Please try again "); + } else { + show_dialog_forsku(context, productList); + } + } + } + }); + + + btn_add.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + if (flag_for_rl && qrcode_text.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Scan Bar Code "); + } else if (!flag_for_rl && edt_scan_code.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter Bar Code "); + } + + /* else if (edt_actual_qty_reaturn.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "First Enter Invoice Actual Quantity"); + } else if (edt_actual_qty_reaturn.getText().toString().equals("0")) { + AlertandMessages.showToastMsg(context, "Please Enter atleast One Invoice Actual Quantity"); + } */ + + else if (stock_text_value.getText().toString().equals("0")) { + AlertandMessages.showToastMsg(context, "Please add atleast One Product Quantity "); + } else if (return_reason_spin.getSelectedItemId() == 0) { + AlertandMessages.showToastMsg(context, "Please Select Return Reason "); + } else if (product_Id.equals("0")) { + AlertandMessages.showToastMsg(context, "Please Click On Get Buttton "); + }/* else if (Integer.parseInt(stock_text_value.getText().toString()) > Integer.parseInt(edt_actual_qty_reaturn.getText().toString())) { + AlertandMessages.showToastMsg(context, "Product Quantity Should be Less Than OR equal to Invoice Actual Quantity"); + }*/ else { + object = new InvoiceGetterSetter(); + if (checkduplicate_entry()) { + if (!flag_for_rl) { + db.open(); + product_scan_code = edt_scan_code.getText().toString(); + if (db.getsku_fromproductusing_eancodefor_return(product_scan_code).size() == 0) { + AlertandMessages.showToastMsg(context, "Product not found "); + } else { + minteger = 0; + multiPurposeDialog.cancel(); + // get selected radio button from radioGroup + int selectedId = radioSexGroup.getCheckedRadioButtonId(); + // find the radiobutton by returned id + radioSexButton = (RadioButton) findViewById(selectedId); + + object = new InvoiceGetterSetter(); + object.setStore_name(storeDataObject.getCounterName()); + object.setStore_address(storeDataObject.getAddress() + "," + storeDataObject.getCityName()); + object.setCustomer_name(edt_customer.getText().toString().trim().replaceAll("[(!@#$%^&*?)\"]", "")); + object.setConsumer_return_bill_no(edt_bill_no.getText().toString()); + object.setMobile_no(edt_mobile_no.getText().toString()); + object.setConsumer_email_Id(edt_email_address.getText().toString()); + + object.setProduct_rate(product_mrp); + object.setProduct(product_name); + object.setProduct_Id(product_Id); + + object.setCustomer_gender(radioSexButton.getText().toString()); + object.setScan_ean_code_or_enterd_ean_code(product_scan_code); + object.setQuantity(stock_text_value.getText().toString()); + // object.setActualQty(edt_actual_qty_reaturn.getText().toString()); + object.setActualQty("0"); + object.setCon_return_reason(return_reason_name); + object.setCon_return_reason_Id(return_reason_Id); + object.setReturn_bill_img(str_return_bill_img); + selected_list.add(object); + + /////for return to product + if (calcualtereturntoprodcutList(selected_list)) { + save_fab.hide(); + add_product_fab.show(); + } else { + save_fab.show(); + add_product_fab.hide(); + } + + //edt_actual_qty_reaturn.setText(""); + stock_text_value.setText(""); + qrcode_text.setText(""); + edt_scan_code.setText(""); + product_scan_code = ""; + product_name = ""; + product_mrp = ""; + product_Id = "0"; + sku_name.setText(""); + sku_name.setVisibility(View.GONE); + drawer_layout_recycle_store.setAdapter(new ValueAdapter(context, selected_list)); + drawer_layout_recycle_store.setLayoutManager(new LinearLayoutManager(context)); + } + } else { + multiPurposeDialog.cancel(); + minteger = 0; + // get selected radio button from radioGroup + int selectedId = radioSexGroup.getCheckedRadioButtonId(); + // find the radiobutton by returned id + radioSexButton = (RadioButton) findViewById(selectedId); + object = new InvoiceGetterSetter(); + object.setStore_name(storeDataObject.getCounterName()); + object.setStore_address(storeDataObject.getAddress() + "," + storeDataObject.getCityName()); + object.setCustomer_name(edt_customer.getText().toString().trim().replaceAll("[(!@#$%^&*?)\"]", "")); + object.setConsumer_email_Id(edt_email_address.getText().toString()); + object.setConsumer_return_bill_no(edt_bill_no.getText().toString()); + object.setMobile_no(edt_mobile_no.getText().toString()); + object.setProduct_rate(product_mrp); + object.setProduct(product_name); + object.setProduct_Id(product_Id); + object.setCustomer_gender(radioSexButton.getText().toString()); + object.setScan_ean_code_or_enterd_ean_code(product_scan_code); + object.setQuantity(stock_text_value.getText().toString()); + // object.setActualQty(edt_actual_qty_reaturn.getText().toString()); + object.setActualQty("0"); + + object.setCon_return_reason(return_reason_name); + object.setCon_return_reason_Id(return_reason_Id); + object.setReturn_bill_img(str_return_bill_img); + selected_list.add(object); + + /////for return to product + if (calcualtereturntoprodcutList(selected_list)) { + save_fab.hide(); + add_product_fab.show(); + } else { + save_fab.show(); + add_product_fab.hide(); + } + + + stock_text_value.setText(""); + // edt_actual_qty_reaturn.setText(""); + qrcode_text.setText(""); + edt_scan_code.setText(""); + product_scan_code = ""; + product_name = ""; + product_mrp = ""; + product_Id = "0"; + sku_name.setText(""); + sku_name.setVisibility(View.GONE); + drawer_layout_recycle_store.setAdapter(new ValueAdapter(context, selected_list)); + drawer_layout_recycle_store.setLayoutManager(new LinearLayoutManager(context)); + + } + } + } + } + }); + + img_bar_code.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + openScanner(); + } + }); + multiPurposeDialog.show(); + } + + private void show_dialog_forsku(final Context context, ArrayList skuList_with_eancode) { + multiPurposeDialog = new MultiPurposeDialog(context); + multiPurposeDialog.requestWindowFeature(Window.FEATURE_NO_TITLE); + multiPurposeDialog.setContentView(R.layout.custom_sku_adapter); + final WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); + lp.copyFrom(multiPurposeDialog.getWindow().getAttributes()); + lp.width = WindowManager.LayoutParams.MATCH_PARENT; + lp.height = WindowManager.LayoutParams.WRAP_CONTENT; + lp.gravity = Gravity.CENTER; + multiPurposeDialog.getWindow().setAttributes(lp); + multiPurposeDialog.setCancelable(false); + + TextView sale_trcking_name = (TextView) multiPurposeDialog.findViewById(R.id.sale_trcking_name); + sale_trcking_name.setText(skuList_with_eancode.get(0).getProductName()); + RecyclerView recycl_sku = (RecyclerView) multiPurposeDialog.findViewById(R.id.recycl_sku); + recycl_sku.setAdapter(new AdapterforSku(context, skuList_with_eancode, multiPurposeDialog, "0")); + recycl_sku.setLayoutManager(new LinearLayoutManager(context)); + ImageView dismiss_dialog = (ImageView) multiPurposeDialog.findViewById(R.id.dismiss_dialog); + dismiss_dialog.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + multiPurposeDialog.dismiss(); + } + }); + + multiPurposeDialog.show(); + } + + public class AdapterforSku extends RecyclerView.Adapter { + private LayoutInflater inflator; + List data; + String show_dialog; + MultiPurposeDialog multiPurposeDialog; + + public AdapterforSku(Context context, List data, MultiPurposeDialog multiPurposeDialog, String show_dialog) { + inflator = LayoutInflater.from(context); + this.data = data; + this.show_dialog = show_dialog; + this.multiPurposeDialog = multiPurposeDialog; + } + + @Override + public AdapterforSku.MyViewHolder onCreateViewHolder(ViewGroup parent, int i) { + View view = inflator.inflate(R.layout.adapter_custom, parent, false); + return new AdapterforSku.MyViewHolder(view); + } + + + @Override + public void onBindViewHolder(final AdapterforSku.MyViewHolder holder, final int position) { + final ProductMaster current = data.get(position); + if (show_dialog.equals("1")) { + holder.sale_card.setVisibility(View.VISIBLE); + holder.sale_card.setId(position); + holder.sale_trcking_name.setText("Date : " + current.getVisit_date()); + holder.sale_trcking_name.setId(position); + holder.consumer_recycle.setVisibility(View.VISIBLE); + holder.consumer_recycle.setId(position); + + } else { + holder.sale_card.setVisibility(View.VISIBLE); + holder.sale_card.setId(position); + holder.sale_trcking_name.setText("(MRP - " + current.getMrp().toString() + ")"); + holder.sale_trcking_name.setId(position); + + holder.consumer_recycle.setVisibility(View.GONE); + holder.consumer_recycle.setId(position); + + holder.sale_card.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + qrcode_text.setText(current.getEanCode()); + product_name = current.getProductName(); + product_Id = current.getProductId().toString(); + product_scan_code = current.getEanCode(); + product_mrp = current.getMrp().toString(); + sku_name.setText(product_name + " Mrp - " + product_mrp); + sku_name.setVisibility(View.VISIBLE); + multiPurposeDialog.dismiss(); + } + }); + } + } + + + @Override + public int getItemCount() { + return data.size(); + } + + class MyViewHolder extends RecyclerView.ViewHolder { + TextView sale_trcking_name; + CardView sale_card; + RecyclerView consumer_recycle; + + + public MyViewHolder(View itemView) { + super(itemView); + sale_card = (CardView) itemView.findViewById(R.id.sale_card); + sale_trcking_name = (TextView) itemView.findViewById(R.id.sale_trcking_name); + ////for counter_image product + consumer_recycle = (RecyclerView) itemView.findViewById(R.id.consumer_recycle); + } + } + } + + private boolean checkduplicate_entry() { + boolean status = true; + if (selected_list != null && selected_list.size() > 0) { + for (int k = 0; k < selected_list.size(); k++) { + if (selected_list.get(k).getProduct_Id().equals(product_Id) && selected_list.get(k).getProduct_rate().equals(product_mrp)) { + AlertandMessages.showToastMsg(context, "This product already added "); + status = false; + break; + } + } + } + return status; + } + + private boolean checkduplicate_entrymultiple(String product_Id, String product_mrp) { + boolean status = true; + if (selected_list != null && selected_list.size() > 0) { + for (int k = 0; k < selected_list.size(); k++) { + if (selected_list.get(k).getProduct_Id().equals(product_Id) && selected_list.get(k).getProduct_rate().equals(product_mrp)) { + status = false; + } + } + } + return status; + } + + private boolean checkindex() { + boolean status = false; + String str = edt_mobile_no.getText().toString(); + String strArray[] = str.split(" "); + //print elements of String array + for (int i = 0; i < strArray.length; i++) { + if (strArray[i].contains("1") || strArray[i].contains("2") || strArray[i].contains("3") || strArray[i].contains("4") || strArray[i].contains("5") || strArray[i].contains("6") || strArray[i].contains("7") || strArray[i].contains("9") || strArray[i].contains("8")) { + status = true; + break; + } + } + return status; + } + + private void openScanner() { + IntentIntegrator intentIntegrator = new IntentIntegrator((Activity) context); + intentIntegrator.setBeepEnabled(true); + intentIntegrator.setOrientationLocked(false); + intentIntegrator.setPrompt("Scan the barcode or QR code to get the data"); + intentIntegrator.initiateScan(); + } + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data); + if (result == null) { + switch (resultCode) { + case 0: + Log.i("MakeMachine", "User cancelled"); + break; + case -1: + if (_pathforcheck != null && !_pathforcheck.isEmpty()) { + try { + if (new File(CommonString.getImagesFolder(context) + _pathforcheck).exists()) { + convertBitmap(CommonString.getImagesFolder(context) + _pathforcheck); + img_bill.setImageDrawable(getResources().getDrawable(R.mipmap.camera_bsd)); + str_return_bill_img = _pathforcheck; + _pathforcheck = ""; + + } + } catch (Resources.NotFoundException e) { + e.fillInStackTrace(); + } + } + + break; + } + + } else if (result != null) { + if (result.getContents() == null) { + //test("ScanActivity", "Cancelled scan"); + AlertandMessages.showToastMsg(context, "Cancelled "); + } else { + db.open(); + + db.open(); + ArrayList productList = db.getsku_fromproductusing_eancodefor_return(result.getContents()); + + if (productList.isEmpty()) { + db.open(); + productList = db.getsku_fromproductusing_eancodefor_return(removeFirstChar(result.getContents())); + } + + if (!productList.isEmpty()) { + show_dialog_forsku(context, productList); + stock_text_value.setText("0"); + minteger = 0; + } else { + product_name = ""; + product_scan_code = ""; + qrcode_text.setText(""); + minteger = 0; + AlertandMessages.showToastMsg(context, "Unable to Scan Correct data. Please try again "); + } + } + } else super.onActivityResult(requestCode, resultCode, data); + } + + public void getotp_from_mobile_no(String jsondata) { + try { + loading = ProgressDialog.show(context, "Processing", "Please wait...", false, true); + final OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build(); + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsondata.toString()); + Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build(); + PostApi api = adapter.create(PostApi.class); + retrofit2.Call call = api.getOTPMethod(jsonData); + call.enqueue(new retrofit2.Callback() { + @Override + public void onResponse(retrofit2.Call call, retrofit2.Response response) { + ResponseBody responseBody = response.body(); + String data = null; + if (responseBody != null && response.isSuccessful()) { + try { + + loading.dismiss(); + data = response.body().string(); + JSONObject jObject = new JSONObject(data); + otp_code = jObject.getString("SendOTPResult"); + + } catch (Exception e) { + e.fillInStackTrace(); + loading.dismiss(); + } + + } else { + loading.dismiss(); + AlertandMessages.showToastMsg(context, "Server Not Responding . Please Try Again "); + } + } + + @Override + public void onFailure(retrofit2.Call call, Throwable t) { + loading.dismiss(); + AlertandMessages.showAlertlogin((Activity) context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE); + } + }); + + } catch (Exception e) { + e.fillInStackTrace(); + loading.dismiss(); + } + } + + + private ArrayList calculate_invoice_added_data(ArrayList invoice_List) { + try { + for (int k = 0; k < invoice_List.size(); k++) { + + int quantity = Integer.parseInt(invoice_List.get(k).getQuantity()); + double amount = Double.parseDouble(invoice_List.get(k).getProduct_rate()); + amount = amount * quantity; + invoice_List.get(k).setTotal_amount("" + amount); + } + + } catch (NumberFormatException e) { + e.fillInStackTrace(); + } + + return invoice_List; + } + + public void setSearchFilter(ArrayList originalList, String text, Spinner dialog_product_spin) { + flag_filter_by_edt = true; + dialog_sku_adapter = new ArrayAdapter<>(context, R.layout.spinner_custom_item); + dialog_sku_adapter.add("- Select Product -"); + dialog_product_using_searchlist = new ArrayList<>(); + dialog_product_using_searchlist = filterListForProduct_edt(originalList, text); + + if (filterListForProduct_edt(originalList, text).size() == 0) { + dialog_product_using_searchlist = originalList; + } + + for (int i = 0; i < dialog_product_using_searchlist.size(); i++) { + dialog_sku_adapter.add(dialog_product_using_searchlist.get(i).getProductName() + " - (MRP-" + dialog_product_using_searchlist.get(i).getMrp().toString() + ")"); + } + dialog_product_spin.setAdapter(dialog_sku_adapter); + dialog_sku_adapter.setDropDownViewResource(R.layout.spinner_custom_item); + + dialog_product_spin.invalidate(); + } + + + private void setReturnReasonSpinnerData(ArrayList productList, Spinner return_reason_spin) { + return_reason_adapter = new ArrayAdapter<>(this, R.layout.spinner_custom_item); + return_reason_adapter.add("- Select Reason -"); + + for (int i = 0; i < productList.size(); i++) { + return_reason_adapter.add(productList.get(i).getReason()); + } + return_reason_spin.setAdapter(return_reason_adapter); + return_reason_adapter.setDropDownViewResource(R.layout.spinner_custom_item); + } + + public ArrayList filterListForProduct_edt(List originalList, String text) { + ArrayList filterList = new ArrayList<>(); + for (ProductMaster object : originalList) { + if (object.getProductName().toLowerCase().contains(text.toLowerCase())) { + filterList.add(object); + } else { + continue; + } + } + + return filterList; + } + + private void prepareListData() { + returnheaderList = new ArrayList<>(); + listDataChild = new HashMap<>(); + returnheaderList.add(selected_list.get(0)); + if (returnheaderList.size() > 0) { + // Adding child data + for (int i = 0; i < returnheaderList.size(); i++) { + listDataChild.put(returnheaderList.get(i), selected_list); // Header, Child data + } + } + + int total_replace_product_mrp = 0, total_replace_product_qty = 0; + if (selected_list.size() > 0) { + try { + for (int k = 0; k < selected_list.size(); k++) { + if (selected_list.get(k).getCon_return_reason_Id().equals("3")) { + total_replace_product_mrp = total_replace_product_mrp + (Integer.parseInt(selected_list.get(k).getQuantity()) * Integer.parseInt(selected_list.get(k).getProduct_rate())); + total_replace_product_qty = total_replace_product_qty + (Integer.parseInt(selected_list.get(k).getQuantity())); + } + } + + calculateReplace_product = new InvoiceGetterSetter(); + calculateReplace_product.setCustomer_name(edt_customer.getText().toString().trim().replaceAll("[(!@#$%^&*?)\"]", "")); + calculateReplace_product.setMobile_no(edt_mobile_no.getText().toString()); + calculateReplace_product.setConsumer_email_Id(edt_email_address.getText().toString()); + calculateReplace_product.setConsumer_return_bill_no(edt_bill_no.getText().toString()); + calculateReplace_product.setTotal_replace_product_value(total_replace_product_mrp); + calculateReplace_product.setTotal_replace_product_qty(total_replace_product_qty); + } catch (NumberFormatException e) { + e.fillInStackTrace(); + } + } + + } + + private boolean calcualtereturntoprodcutList(ArrayList selected_list) { + boolean status = false; + if (selected_list.size() > 0) { + for (int k = 0; k < selected_list.size(); k++) { + if (selected_list.get(k).getCon_return_reason_Id().equals("3")) { + status = true; + break; + } + } + } + return status; + } + + + public void getpreviousHistory_from_mobile_no(final Context context, final ProgressDialog loading, String jsondata) { + try { + final OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build(); + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsondata); + Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build(); + PostApi api = adapter.create(PostApi.class); + retrofit2.Call call = api.getDownloadAll(jsonData); + + call.enqueue(new retrofit2.Callback() { + @Override + public void onResponse(retrofit2.Call call, retrofit2.Response response) { + String responseBody = response.body(); + String data_for = null; + loading.dismiss(); + if (responseBody != null && response.isSuccessful()) { + data_for = response.body(); + if (data_for.equals("")) { + loading.dismiss(); + Toast.makeText(context, "No Previous History", Toast.LENGTH_SHORT).show(); + txt_history.setEnabled(false); + txt_history.setTextColor(getResources().getColor(R.color.gray)); + } else { + loading.dismiss(); + if (!data_for.contains("No Data")) { + loading.dismiss(); + edt_mobile_no.setEnabled(false); + MasterBAProfileGetterSetter masterPromoOfferObject = new Gson().fromJson(data_for, MasterBAProfileGetterSetter.class); + if (masterPromoOfferObject != null) { + previusHistoryList = masterPromoOfferObject.getConsumerSalesHistory(); + if (previusHistoryList.size() > 0) { + rl_send_otp.setVisibility(View.GONE); + show_consumer_previous_histry(context, previusHistoryList); + } + } else { + rl_send_otp.setVisibility(View.VISIBLE); + edt_mobile_no.setEnabled(true); + loading.dismiss(); + previusHistoryList.clear(); + } + } else { + txt_history.setEnabled(false); + edt_mobile_no.setEnabled(true); + rl_send_otp.setVisibility(View.VISIBLE); + txt_history.setTextColor(getResources().getColor(R.color.gray)); + previusHistoryList.clear(); + loading.dismiss(); + Toast.makeText(context, "No Previous History", Toast.LENGTH_SHORT).show(); + } + } + } else { + loading.dismiss(); + previusHistoryList.clear(); + txt_history.setEnabled(false); + edt_mobile_no.setEnabled(true); + rl_send_otp.setVisibility(View.VISIBLE); + txt_history.setTextColor(getResources().getColor(R.color.gray)); + AlertandMessages.showAlertlogin((Activity) context, "Unable To Connect Server. History Data Not Updated"); + } + } + + @Override + public void onFailure(retrofit2.Call call, Throwable t) { + loading.dismiss(); + previusHistoryList.clear(); + txt_history.setEnabled(false); + edt_mobile_no.setEnabled(true); + rl_send_otp.setVisibility(View.VISIBLE); + txt_history.setTextColor(getResources().getColor(R.color.gray)); + AlertandMessages.showAlertlogin((Activity) context, "Unable To Connect Server. History Data Not Updated"); + } + }); + } catch (Exception e) { + txt_history.setTextColor(getResources().getColor(R.color.gray)); + rl_send_otp.setVisibility(View.VISIBLE); + edt_mobile_no.setEnabled(true); + txt_history.setEnabled(false); + e.fillInStackTrace(); + loading.dismiss(); + } + } + + private void show_consumer_previous_histry(final Context context, final List previusHistoryList) { + multiPurposeDialog = new MultiPurposeDialog(context); + multiPurposeDialog.requestWindowFeature(Window.FEATURE_NO_TITLE); + multiPurposeDialog.setContentView(R.layout.custom_sku_adapter); + final WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); + lp.copyFrom(multiPurposeDialog.getWindow().getAttributes()); + lp.width = WindowManager.LayoutParams.MATCH_PARENT; + lp.height = WindowManager.LayoutParams.WRAP_CONTENT; + lp.gravity = Gravity.CENTER; + multiPurposeDialog.getWindow().setAttributes(lp); + multiPurposeDialog.setCancelable(false); + TextView txt_bar_code = multiPurposeDialog.findViewById(R.id.txt_bar_code); + txt_bar_code.setText("Consumer Previous History"); + TextView sale_trcking_name = (TextView) multiPurposeDialog.findViewById(R.id.sale_trcking_name); + sale_trcking_name.setVisibility(View.GONE); + + RecyclerView recycl_sku = (RecyclerView) multiPurposeDialog.findViewById(R.id.recycl_sku); + if (previusHistoryList.get(0).getGender().equalsIgnoreCase("Male")) { + //radioSexButton + radioSexGroup.check(R.id.radioM); + } else if (previusHistoryList.get(0).getGender().equalsIgnoreCase("Female")) { + //radioSexButton + radioSexGroup.check(R.id.radioF); + } else { + radioSexGroup.check(R.id.radio_other); + } + + + recycl_sku.setAdapter(new AdapterforHistry(context, previusHistoryList, multiPurposeDialog)); + recycl_sku.setLayoutManager(new LinearLayoutManager(context)); + ImageView dismiss_dialog = (ImageView) multiPurposeDialog.findViewById(R.id.dismiss_dialog); + dismiss_dialog.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + multiPurposeDialog.dismiss(); + +/* + if (previusHistoryList.size() > 0) { + if (checked_returnproduct(previusHistoryList)) { + for (int k = 0; k < previusHistoryList.size(); k++) { + if (previusHistoryList.get(k).isChecked_flag() + && checkduplicate_entrymultiple(previusHistoryList.get(k).getProductId().toString(), previusHistoryList.get(k).getMrp().toString())) { + // get selected radio button from radioGroup + int selectedId = radioSexGroup.getCheckedRadioButtonId(); + // find the radiobutton by returned id + radioSexButton = (RadioButton) findViewById(selectedId); + object = new InvoiceGetterSetter(); + object.setStore_name(storeDataObject.getCounterName()); + object.setStore_address(storeDataObject.getAddress() + "," + storeDataObject.getCityName()); + object.setCustomer_name(edt_customer.getText().toString().trim().replaceAll("[(!@#$%^&*?)\"]", "")); + object.setConsumer_return_bill_no(edt_bill_no.getText().toString()); + object.setMobile_no(edt_mobile_no.getText().toString()); + object.setConsumer_email_Id(edt_email_address.getText().toString()); + + object.setProduct_rate(previusHistoryList.get(k).getMrp().toString()); + object.setProduct(previusHistoryList.get(k).getProductName()); + object.setProduct_Id(previusHistoryList.get(k).getProductId().toString()); + object.setCustomer_gender(radioSexButton.getText().toString()); + object.setScan_ean_code_or_enterd_ean_code(previusHistoryList.get(k).getEanCode()); + object.setQuantity("" + previusHistoryList.get(k).getSelected_product_qty()); + object.setActualQty("" + previusHistoryList.get(k).getQtySold()); + object.setCon_return_reason(previusHistoryList.get(k).getSelected_reason()); + object.setCon_return_reason_Id(previusHistoryList.get(k).getSelected_reason_Id()); + object.setReturn_bill_img(str_return_bill_img); + selected_list.add(object); + } + } + + drawer_layout_recycle_store.setAdapter(new ValueAdapter(context, selected_list)); + drawer_layout_recycle_store.setLayoutManager(new LinearLayoutManager(context)); + + } + } +*/ + } + }); + + multiPurposeDialog.show(); + } + +/* + protected boolean checked_returnproduct(final List previusHistoryList) { + boolean status = true; + if (previusHistoryList.size() > 0) { + for (int k = 0; k < previusHistoryList.size(); k++) { + if (previusHistoryList.get(k).isChecked_flag()) { + if (previusHistoryList.get(k).getSelected_product_qty() == 0) { + AlertandMessages.showToastMsg(context, "Please add atleast One Product Quantity "); + status = false; + break; + } else if (previusHistoryList.get(k).getSelected_reason_Id().equals("0")) { + AlertandMessages.showToastMsg(context, "Please Select Selected Product Return Reason"); + status = false; + break; + } + } + } + } + + return status; + } +*/ + +/* + public class AdapterforHistry extends RecyclerView.Adapter { + private LayoutInflater inflator; + List data; + MultiPurposeDialog multiPurposeDialog; + + public AdapterforHistry(Context context, List data, MultiPurposeDialog multiPurposeDialog) { + inflator = LayoutInflater.from(context); + this.data = data; + this.multiPurposeDialog = multiPurposeDialog; + } + + @Override + public AdapterforHistry.MyViewHolder onCreateViewHolder(ViewGroup parent, int i) { + View view = inflator.inflate(R.layout.adapter_custom_history_product_return, parent, false); + return new AdapterforHistry.MyViewHolder(view); + } + + + @Override + public void onBindViewHolder(final AdapterforHistry.MyViewHolder holder, final int position) { + final ConsumerSalesHistory current = data.get(position); + + holder.txt_product_name.setText("Date : " + current.getVisitDate()); + holder.txt_product_name.setId(position); + + holder.txt_product_mrp.setText("Product Name : " + current.getProductName()); + holder.txt_product_mrp.setId(position); + + holder.txt_product_qty.setText("MRP : " + current.getMrp().toString()); + holder.txt_product_qty.setId(position); + + holder.qty_sold_txt.setText("QTY Sold : " + current.getQtySold().toString()); + holder.qty_sold_txt.setId(position); + + holder.total_amount_txt.setText("Total Amount : " + current.getTotalAmount().toString()); + holder.total_amount_txt.setId(position); + + if (position != 0) { + if (data.get(position - 1).getVisitDate().equalsIgnoreCase(current.getVisitDate())) { + holder.rl_visit_date.setVisibility(View.GONE); + holder.rl_visit_date.setId(position); + } else { + holder.rl_visit_date.setVisibility(View.VISIBLE); + holder.rl_visit_date.setId(position); + } + } + + holder.check_return_product.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + if (holder.check_return_product.isChecked()) { + current.setChecked_flag(true); + } else { + current.setChecked_flag(false); + } + } + }); + + holder.stock_img_minus.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + if (current.isChecked_flag()) { + try { + int minteger = current.getSelected_product_qty(); + if (minteger == 0) { + AlertandMessages.showToastMsg(context, "Product quantity should not be less than Zero"); + } else { + minteger = minteger - 1; + holder.stock_text_value.setText("" + minteger); + current.setSelected_product_qty(minteger); + } + } catch (Exception e) { + e.fillInStackTrace(); + } + } else { + AlertandMessages.showToastMsg(context, "First Tick check"); + } + + } + }); + + holder.stock_img_plus.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + if (current.isChecked_flag()) { + try { + int minteger = current.getSelected_product_qty(); + minteger = minteger + 1; + if (minteger > current.getQtySold()) { + minteger = minteger - 1; + AlertandMessages.showToastMsg(context, "Product Quantity should not be Greater Than Actual Product Quantity"); + } + + holder.stock_text_value.setText("" + minteger); + current.setSelected_product_qty(minteger); + } catch (Exception e) { + e.fillInStackTrace(); + } + } else { + AlertandMessages.showToastMsg(context, "First Tick check"); + } + } + }); + + setReturnReasonSpinnerData(returnReasonList, holder.return_reason_spin); + + holder.return_reason_spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { + @Override + public void onItemSelected(AdapterView adapterView, View view, int pos, long l) { + if (pos != 0) { + current.setSelected_reason(returnReasonList.get(pos - 1).getReason()); + current.setSelected_reason_Id(returnReasonList.get(pos - 1).getReasonId().toString()); + } else { + current.setSelected_reason(""); + current.setSelected_reason_Id("0"); + } + } + + @Override + public void onNothingSelected(AdapterView adapterView) { + + } + }); + + + if (returnReasonList.size() > 0) { + for (int k = 0; k < returnReasonList.size(); k++) { + if (current.getSelected_reason_Id().equals(returnReasonList.get(k).getReasonId().toString())) { + holder.return_reason_spin.setSelection(k + 1); + break; + } + } + } + + if (current.isChecked_flag()) { + holder.check_return_product.setChecked(true); + holder.check_return_product.setId(position); + + holder.stock_text_value.setText("" + current.getSelected_product_qty()); + holder.stock_text_value.setId(position); + } else { + holder.check_return_product.setChecked(false); + holder.check_return_product.setId(position); + + holder.stock_text_value.setText("" + 0); + holder.stock_text_value.setId(position); + + holder.return_reason_spin.setSelection(0); + holder.return_reason_spin.setId(position); + + current.setSelected_reason(""); + current.setSelected_reason_Id("0"); + } + } + + + @Override + public int getItemCount() { + return data.size(); + } + + class MyViewHolder extends RecyclerView.ViewHolder { + TextView txt_product_mrp, txt_product_qty, txt_product_name, qty_sold_txt, total_amount_txt, stock_text_value; + Button stock_img_minus, stock_img_plus; + + LinearLayout rl_visit_date; + CheckBox check_return_product; + Spinner return_reason_spin; + + public MyViewHolder(View itemView) { + super(itemView); + rl_visit_date = (LinearLayout) itemView.findViewById(R.id.rl_visit_date); + txt_product_qty = (TextView) itemView.findViewById(R.id.txt_product_qty); + txt_product_mrp = (TextView) itemView.findViewById(R.id.txt_product_mrp); + txt_product_name = (TextView) itemView.findViewById(R.id.txt_product_name); + qty_sold_txt = (TextView) itemView.findViewById(R.id.qty_sold_txt); + total_amount_txt = (TextView) itemView.findViewById(R.id.total_amount_txt); + stock_text_value = (TextView) itemView.findViewById(R.id.stock_text_value); + check_return_product = (CheckBox) itemView.findViewById(R.id.check_return_product); + return_reason_spin = (Spinner) itemView.findViewById(R.id.return_reason_spin); + stock_img_minus = (Button) itemView.findViewById(R.id.stock_img_minus); + stock_img_plus = (Button) itemView.findViewById(R.id.stock_img_plus); + } + } + } +*/ + + public class AdapterforHistry extends RecyclerView.Adapter { + private LayoutInflater inflator; + List data; + MultiPurposeDialog multiPurposeDialog; + + public AdapterforHistry(Context context, List data, MultiPurposeDialog multiPurposeDialog) { + inflator = LayoutInflater.from(context); + this.data = data; + this.multiPurposeDialog = multiPurposeDialog; + } + + @Override + public AdapterforHistry.MyViewHolder onCreateViewHolder(ViewGroup parent, int i) { + View view = inflator.inflate(R.layout.adapter_custom_history_product, parent, false); + return new AdapterforHistry.MyViewHolder(view); + + } + + + @Override + public void onBindViewHolder(final AdapterforHistry.MyViewHolder holder, final int position) { + final ConsumerSalesHistory current = data.get(position); + + holder.text_visit_date.setText("Date : " + current.getVisitDate()); + holder.text_visit_date.setId(position); + + holder.consume_product.setText("Product Name : " + current.getProductName()); + holder.consume_product.setId(position); + + holder.consume_product_qty_with_date.setText("MRP : " + current.getMrp().toString()); + holder.consume_product_qty_with_date.setId(position); + + holder.qty_sold_txt.setText("QTY Sold : " + current.getQtySold().toString()); + holder.qty_sold_txt.setId(position); + + holder.total_amount_txt.setText("Total Amount : " + current.getTotalAmount().toString()); + holder.total_amount_txt.setId(position); + + + if (position != 0) { + if (data.get(position - 1).getVisitDate().equalsIgnoreCase(current.getVisitDate())) { + holder.rl_visit_date.setVisibility(View.GONE); + holder.rl_visit_date.setId(position); + } else { + holder.rl_visit_date.setVisibility(View.VISIBLE); + holder.rl_visit_date.setId(position); + } + } + } + + + @Override + public int getItemCount() { + return data.size(); + } + + class MyViewHolder extends RecyclerView.ViewHolder { + TextView consume_product, consume_product_qty_with_date, text_visit_date, qty_sold_txt, total_amount_txt; + LinearLayout rl_visit_date; + + public MyViewHolder(View itemView) { + super(itemView); + rl_visit_date = (LinearLayout) itemView.findViewById(R.id.rl_visit_date); + consume_product_qty_with_date = (TextView) itemView.findViewById(R.id.consume_product_qty_with_date); + consume_product = (TextView) itemView.findViewById(R.id.consume_product); + text_visit_date = (TextView) itemView.findViewById(R.id.text_visit_date); + qty_sold_txt = (TextView) itemView.findViewById(R.id.qty_sold_txt); + total_amount_txt = (TextView) itemView.findViewById(R.id.total_amount_txt); + } + } + } + + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + getMenuInflater().inflate(R.menu.menu_return_product, menu); + return super.onCreateOptionsMenu(menu); + } + + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + int id = item.getItemId(); + + if (id == R.id.nav_return_history) { + //for Return history list with replace product.............. + db.open(); + if (db.getsaleReturnHeaderData(visit_date, counterID, username, false, false, null).size() > 0) { + startActivity(new Intent(context, ConsumerReturnsHistoryActivity.class)); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + } else { + AlertandMessages.showToastMsg(context, "Records Not Found"); + } + + } else if (id == android.R.id.home) { + if (clicked_flag) { + AlertDialog.Builder builder = new AlertDialog.Builder(context).setMessage(CommonString.ONBACK_ALERT_MESSAGE).setCancelable(false).setPositiveButton("Ok", (dialog, id1) -> { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + ConsumerReturnActivity.this.finish(); + }).setNegativeButton("Cancel", (dialog, id2) -> dialog.cancel()); + AlertDialog alert = builder.create(); + alert.show(); + } else { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + ConsumerReturnActivity.this.finish(); + } + } + + return super.onOptionsItemSelected(item); + } + + @Override + protected void onResume() { + super.onResume(); + /////for return to product + if (calcualtereturntoprodcutList(selected_list) && replace_productList.size() >= 0) { + save_fab.show(); + add_product_fab.show(); + } else { + save_fab.show(); + add_product_fab.hide(); + } + } + + private void getstatusof_termcondition() { + edt_mobile_no.addTextChangedListener(new TextWatcher() { + @Override + public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { + + } + + @Override + public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { + + } + + @Override + public void afterTextChanged(Editable editable) { + if (!editable.toString().equals("") && editable.toString().length() == 10) { + + } else { + edt_mobile_no.setEnabled(true); + txt_history.setEnabled(true); + previusHistoryList.clear(); + txt_history.setTextColor(getResources().getColor(R.color.blue)); + rl_send_otp.setVisibility(View.GONE); + } + } + }); + } + + + private void show_selected_invoice(final Context context) { + final MultiPurposeDialog multiPurposeDialog = new MultiPurposeDialog(context); + multiPurposeDialog.requestWindowFeature(Window.FEATURE_NO_TITLE); + multiPurposeDialog.setContentView(R.layout.custom_selected_invoice); + multiPurposeDialog.setCancelable(false); + WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); + lp.copyFrom(multiPurposeDialog.getWindow().getAttributes()); + lp.width = WindowManager.LayoutParams.MATCH_PARENT; + lp.height = WindowManager.LayoutParams.WRAP_CONTENT; + lp.gravity = Gravity.CENTER; + multiPurposeDialog.getWindow().setAttributes(lp); + multiPurposeDialog.setCancelable(false); + + RecyclerView recycl_return_product = (RecyclerView) multiPurposeDialog.findViewById(R.id.recycl_return_product); + RecyclerView recycl_replace_product = (RecyclerView) multiPurposeDialog.findViewById(R.id.recycl_replace_product); + ImageView cancet_btn = (ImageView) multiPurposeDialog.findViewById(R.id.cancet_btn); + final ImageView btn_submit = (ImageView) multiPurposeDialog.findViewById(R.id.btn_submit); + + TextView total_qty_returnProduct = (TextView) multiPurposeDialog.findViewById(R.id.total_qty_returnProduct); + TextView total_amount_return_product = (TextView) multiPurposeDialog.findViewById(R.id.total_amount_return_product); + + TextView total_qty_replace_Product = (TextView) multiPurposeDialog.findViewById(R.id.total_qty_replace_Product); + TextView total_amount_replace_product = (TextView) multiPurposeDialog.findViewById(R.id.total_amount_replace_product); + + LinearLayout rl_replaceProduct = (LinearLayout) multiPurposeDialog.findViewById(R.id.rl_replaceProduct); + + ////////set adapter of return products + if (selected_list.size() > 0) { + recycl_return_product.setAdapter(new CustomAdapter(context, selected_list)); + recycl_return_product.setLayoutManager(new LinearLayoutManager(context)); + + int return_total_qty = 0, return_total_amount = 0; + + for (int k = 0; k < selected_list.size(); k++) { + return_total_qty = return_total_qty + Integer.parseInt(selected_list.get(k).getQuantity()); + return_total_amount = return_total_amount + (Integer.parseInt(selected_list.get(k).getQuantity()) * Integer.parseInt(selected_list.get(k).getProduct_rate())); + } + + total_qty_returnProduct.setText("Total QTY : " + return_total_qty); + total_amount_return_product.setText("Total Amount : " + return_total_amount); + } + + ////////set adapter of replace products + if (replace_productList.size() > 0) { + rl_replaceProduct.setVisibility(View.VISIBLE); + + recycl_replace_product.setAdapter(new CustomAdapter(context, replace_productList)); + recycl_replace_product.setLayoutManager(new LinearLayoutManager(context)); + + int replace_product_total_qty = 0, replacep_total_amount = 0; + + for (int k = 0; k < replace_productList.size(); k++) { + replace_product_total_qty = replace_product_total_qty + Integer.parseInt(replace_productList.get(k).getQuantity()); + replacep_total_amount = replacep_total_amount + (Integer.parseInt(replace_productList.get(k).getQuantity()) * Integer.parseInt(replace_productList.get(k).getProduct_rate())); + } + + total_qty_replace_Product.setText("Total QTY : " + replace_product_total_qty); + total_amount_replace_product.setText("Total Amount : " + replacep_total_amount); + } + + cancet_btn.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + multiPurposeDialog.dismiss(); + } + }); + + btn_submit.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle(R.string.parinaam).setMessage(R.string.alertsaveData); + builder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialogInterface, int i) { + db.open(); + db.insert_consumer_return_headerchild_data(username, visit_date, counterID, TransId, listDataChild, returnheaderList, str_return_bill_img, replace_productList); + // Intent intent = new Intent(context, Downloader.class); + if (calculate_invoice_added_data(selected_list).size() > 0) { + // intent.putExtra(CommonString.KEY_Consumer_Return, returnheaderList); + // Downloader.enqueueWork(context, intent); + } + + replace_productList.clear(); + multiPurposeDialog.cancel(); + dialogInterface.cancel(); + CommonFunctions.call_upload(context); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + ConsumerReturnActivity.this.finish(); + } + }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialogInterface, int i) { + dialogInterface.cancel(); + } + }); + + builder.show(); + } + }); + + multiPurposeDialog.show(); + } + + public class CustomAdapter extends RecyclerView.Adapter { + private LayoutInflater inflator; + List data; + + + public CustomAdapter(Context context, List data) { + inflator = LayoutInflater.from(context); + this.data = data; + + } + + @Override + public CustomAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int i) { + View view = inflator.inflate(R.layout.adapter_custom_view, parent, false); + return new CustomAdapter.MyViewHolder(view); + + } + + + @Override + public void onBindViewHolder(final CustomAdapter.MyViewHolder holder, final int position) { + final InvoiceGetterSetter current = data.get(position); + + holder.txt_product_name.setText("Product : " + current.getProduct()); + holder.txt_product_name.setId(position); + + holder.txt_product_mrp.setText("QTY : " + current.getQuantity()); + holder.txt_product_mrp.setId(position); + + holder.txt_product_qty.setText("MRP : " + current.getProduct_rate()); + holder.txt_product_qty.setId(position); + + } + + + @Override + public int getItemCount() { + return data.size(); + } + + class MyViewHolder extends RecyclerView.ViewHolder { + TextView txt_product_mrp, txt_product_qty, txt_product_name; + + public MyViewHolder(View itemView) { + super(itemView); + txt_product_name = (TextView) itemView.findViewById(R.id.txt_product_name); + txt_product_qty = (TextView) itemView.findViewById(R.id.txt_product_qty); + txt_product_mrp = (TextView) itemView.findViewById(R.id.txt_product_mrp); + } + } + } + + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/CounterImageActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/CounterImageActivity.java new file mode 100644 index 0000000..9692a19 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/CounterImageActivity.java @@ -0,0 +1,500 @@ +package com.cpm.lorealbaautomation.dailyactivity; + +import android.Manifest; +import android.annotation.SuppressLint; +import android.app.Activity; +import android.app.AlertDialog; +import android.content.Context; +import android.content.Intent; +import android.content.IntentSender; +import android.content.SharedPreferences; +import android.content.pm.PackageManager; +import android.location.LocationManager; + +import com.google.android.gms.common.api.ResolvableApiException; +import com.google.android.gms.location.FusedLocationProviderClient; +import com.google.android.gms.location.LocationRequest; +import com.google.android.gms.location.LocationSettingsRequest; +import com.google.android.gms.location.SettingsClient; +import com.google.android.material.floatingactionbutton.FloatingActionButton; + +import androidx.core.app.ActivityCompat; +import androidx.appcompat.app.AppCompatActivity; + +import android.os.Bundle; + +import androidx.appcompat.widget.Toolbar; + +import android.util.Log; +import android.view.MenuItem; +import android.view.View; +import android.widget.ImageView; +import android.widget.LinearLayout; +import android.widget.Toast; + +import com.google.android.gms.location.LocationServices; +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.constant.AlertandMessages; +import com.cpm.lorealbaautomation.constant.CommonFunctions; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.download.Downloader; +import com.cpm.lorealbaautomation.gsonGetterSetter.JourneyPlan; + +import java.io.File; +import java.util.List; +import java.util.Objects; + +import static com.cpm.lorealbaautomation.constant.CommonFunctions.getCurrentTime_only; +import static com.cpm.lorealbaautomation.constant.CommonFunctions.show_image_preview; +import static com.cpm.lorealbaautomation.dailyactivity.StoreImageActivity.convertBitmap; + +public class CounterImageActivity extends AppCompatActivity implements + View.OnClickListener { + ImageView presetup_img_one, presetup_img_two, post_setup_img_one, post_setup_img_two,/*.......*/ + counter_img_one, counter_img_two; + String _pathforcheck, _path, counter_id, visit_date, username, user_type; + FloatingActionButton btn_save_selfie; + private static final int REQUEST_LOCATION = 1; + JourneyPlan counterimg_object = new JourneyPlan(); + LinearLayout layout_for_me_counterimg, layout_for_ba_counterimg; + SharedPreferences preferences; + private Lorealba_Database db; + double lat = 0.0, lon = 0.0; + boolean update_flag = false, click_flag = true; + AlertDialog alert; + Context context; + private FusedLocationProviderClient fusedLocationClient; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_counter_image); + context = this; + fusedLocationClient = LocationServices.getFusedLocationProviderClient(this); + Toolbar toolbar = findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + Objects.requireNonNull(getSupportActionBar()).setHomeButtonEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + if (!CommonFunctions.isTablet(context)) { + toolbar.setTitleTextAppearance(context, R.style.changestext_sizefor_mobile); + } + getLastLocation(); + db = new Lorealba_Database(context); + db.open(); + validateuidata(); + } + + private void getLastLocation() { + if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && + ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { + // Request location permissions + return; + } + try { + fusedLocationClient.getLastLocation() + .addOnSuccessListener(this, location -> { + if (location != null) { + lat = location.getLatitude(); + lon = location.getLongitude(); + //test("Location", "Lat: " + lat + ", Lng: " + lon); + } + }); + } catch (Exception e) { + e.fillInStackTrace(); //test("Location", "Lat: " + lat + ", Lng: " + lon);} + } + } + + @SuppressLint("RestrictedApi") + private void validateuidata() { + preferences = PrefHelper.getPrefs(context); + counter_id = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + username = preferences.getString(CommonString.KEY_USERNAME, ""); + user_type = preferences.getString(CommonString.KEY_USER_TYPE, ""); + presetup_img_one = (ImageView) findViewById(R.id.presetup_img_one); + presetup_img_two = (ImageView) findViewById(R.id.presetup_img_two); + post_setup_img_one = (ImageView) findViewById(R.id.post_setup_img_one); + post_setup_img_two = (ImageView) findViewById(R.id.post_setup_img_two); + btn_save_selfie = (FloatingActionButton) findViewById(R.id.btn_save_selfie); + ////new changes + layout_for_me_counterimg = (LinearLayout) findViewById(R.id.layout_for_me_counterimg); + layout_for_ba_counterimg = (LinearLayout) findViewById(R.id.layout_for_ba_counterimg); + counter_img_one = (ImageView) findViewById(R.id.counter_img_one); + counter_img_two = (ImageView) findViewById(R.id.counter_img_two); + + presetup_img_one.setOnClickListener(this); + presetup_img_two.setOnClickListener(this); + post_setup_img_one.setOnClickListener(this); + post_setup_img_two.setOnClickListener(this); + btn_save_selfie.setOnClickListener(this); + counter_img_one.setOnClickListener(this); + counter_img_two.setOnClickListener(this); + setTitle("Counter Image - " + visit_date); + db.open(); + counterimg_object = db.getinserted_counter_images(counter_id, visit_date); + if (!user_type.isEmpty() && user_type.equalsIgnoreCase("BA") || !user_type.isEmpty() && user_type.equalsIgnoreCase("TBA")) { + if (counterimg_object != null && !counterimg_object.getCounter_img_onefor_ba().isEmpty() || !counterimg_object.getCounter_img_two_for_ba().isEmpty()) { + btn_save_selfie.setVisibility(View.GONE); + update_flag = true; + validate_ui(); + } + layout_for_ba_counterimg.setVisibility(View.VISIBLE); + layout_for_me_counterimg.setVisibility(View.GONE); + } else { + layout_for_ba_counterimg.setVisibility(View.GONE); + layout_for_me_counterimg.setVisibility(View.VISIBLE); + if (counterimg_object != null && !counterimg_object.getPresetup_img_one_str().isEmpty()) { + update_flag = true; + validate_ui(); + } + } + } + + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + if (id == android.R.id.home) { + if (click_flag) { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + CounterImageActivity.this.finish(); + } else { + AlertDialog.Builder builder = new AlertDialog.Builder(context).setMessage(CommonString.ONBACK_ALERT_MESSAGE).setCancelable(false).setPositiveButton("Ok", + (dialog, id12) -> { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + CounterImageActivity.this.finish(); + }).setNegativeButton("Cancel", (dialog, id1) -> dialog.cancel()); + AlertDialog alert = builder.create(); + alert.show(); + } + } + return super.onOptionsItemSelected(item); + } + + @Override + public void onBackPressed() { + if (click_flag) { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + CounterImageActivity.this.finish(); + } else { + AlertDialog.Builder builder = new AlertDialog.Builder(context).setMessage(CommonString.ONBACK_ALERT_MESSAGE).setCancelable(false).setPositiveButton("Ok", + (dialog, id) -> { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + CounterImageActivity.this.finish(); + }).setNegativeButton("Cancel", (dialog, id) -> dialog.cancel()); + AlertDialog alert = builder.create(); + alert.show(); + } + } + + @SuppressLint("NonConstantResourceId") + @Override + public void onClick(View view) { + + if (view.getId() == R.id.counter_img_one) { + if (!update_flag) { + click_flag = false; + _pathforcheck = counter_id + "_counter_img_one_" + visit_date.replace("/", "") + "_" + getCurrentTime_only().replace(":", "") + ".jpg"; + _path = CommonString.getImagesFolder(context) + _pathforcheck; + CommonFunctions.startAnncaCameraActivity(this, _path, null, + false, CommonString.CAMERA_FACE_REAR); + } else { + show_image_preview(context, counterimg_object.getCounter_img_onefor_ba()); + } + } else if (view.getId() == R.id.counter_img_two) { + if (!update_flag) { + click_flag = false; + _pathforcheck = counter_id + "_counter_img_two_" + visit_date.replace("/", "") + "_" + getCurrentTime_only().replace(":", "") + ".jpg"; + _path = CommonString.getImagesFolder(context) + _pathforcheck; + CommonFunctions.startAnncaCameraActivity(this, _path, null, false, CommonString.CAMERA_FACE_REAR); + } else { + if (!counterimg_object.getCounter_img_two_for_ba().isEmpty()) { + show_image_preview(context, counterimg_object.getCounter_img_two_for_ba()); + } + } + + } else if (view.getId() == R.id.presetup_img_one) { + if (update_flag) { + if (counterimg_object != null && !counterimg_object.getPresetup_img_one_str().isEmpty()) { + show_image_preview(context, counterimg_object.getPresetup_img_one_str()); + } + } else { + if (counterimg_object != null && !counterimg_object.getPresetup_img_one_str().isEmpty()) { + show_image_preview(context, counterimg_object.getPresetup_img_one_str()); + } else { + click_flag = false; + _pathforcheck = counter_id + "_presetup_counter_img_one_" + visit_date.replace("/", "") + "_" + getCurrentTime_only().replace(":", "") + ".jpg"; + _path = CommonString.getImagesFolder(context) + _pathforcheck; + CommonFunctions.startAnncaCameraActivity(this, _path, null, false, CommonString.CAMERA_FACE_REAR); + } + } + + } else if (view.getId() == R.id.presetup_img_two) { + if (update_flag) { + if (counterimg_object != null && !counterimg_object.getPresetup_img_two_str().isEmpty()) { + show_image_preview(context, counterimg_object.getPresetup_img_two_str()); + } + } else { + if (counterimg_object != null && !counterimg_object.getPresetup_img_two_str().isEmpty()) { + show_image_preview(context, counterimg_object.getPresetup_img_two_str()); + } else { + click_flag = false; + _pathforcheck = counter_id + "_presetup_counter_img_two_" + visit_date.replace("/", "") + "_" + getCurrentTime_only().replace(":", "") + ".jpg"; + _path = CommonString.getImagesFolder(context) + _pathforcheck; + CommonFunctions.startAnncaCameraActivity(this, _path, null, false, CommonString.CAMERA_FACE_REAR); + } + } + + } else if (view.getId() == R.id.post_setup_img_one) { + if (update_flag) { + if (counterimg_object != null && !counterimg_object.getPostsetup_img_one_str().isEmpty()) { + show_image_preview(context, counterimg_object.getPostsetup_img_one_str()); + } else { + click_flag = false; + _pathforcheck = counter_id + "_postsetup_counter_img_one_" + visit_date.replace("/", "") + "_" + getCurrentTime_only().replace(":", "") + ".jpg"; + _path = CommonString.getImagesFolder(context) + _pathforcheck; + CommonFunctions.startAnncaCameraActivity(this, _path, null, false, CommonString.CAMERA_FACE_REAR); + } + + } else if (counterimg_object != null && !counterimg_object.getPresetup_img_one_str().isEmpty()) { + click_flag = false; + _pathforcheck = counter_id + "_postsetup_counter_img_one_" + visit_date.replace("/", "") + "_" + getCurrentTime_only().replace(":", "") + ".jpg"; + _path = CommonString.getImagesFolder(context) + _pathforcheck; + CommonFunctions.startAnncaCameraActivity(this, _path, null, false, CommonString.CAMERA_FACE_REAR); + } + + } else if (view.getId() == R.id.post_setup_img_two) { + if (update_flag) { + if (counterimg_object != null && !counterimg_object.getPostsetup_img_two_str().isEmpty()) { + show_image_preview(context, counterimg_object.getPostsetup_img_two_str()); + } else { + click_flag = false; + _pathforcheck = counter_id + "_possetup_counter_img_two_" + visit_date.replace("/", "") + "_" + getCurrentTime_only().replace(":", "") + ".jpg"; + _path = CommonString.getImagesFolder(context) + _pathforcheck; + CommonFunctions.startAnncaCameraActivity(this, _path, null, false, CommonString.CAMERA_FACE_REAR); + } + } else if (counterimg_object != null && !counterimg_object.getPresetup_img_one_str().isEmpty()) { + click_flag = false; + _pathforcheck = counter_id + "_possetup_counter_img_two_" + visit_date.replace("/", "") + "_" + getCurrentTime_only().replace(":", "") + ".jpg"; + _path = CommonString.getImagesFolder(context) + _pathforcheck; + CommonFunctions.startAnncaCameraActivity(this, _path, null, false, CommonString.CAMERA_FACE_REAR); + } + + } else if (view.getId() == R.id.btn_save_selfie) { + if (validateimg_str()) { + AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle(R.string.dialog_title).setMessage(R.string.title_activity_save_data).setCancelable(false) + .setPositiveButton(android.R.string.yes, (dialog, id1) -> { + alert.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false); + db.open(); + if (!user_type.isEmpty() && user_type.equalsIgnoreCase(CommonString.TAG_FROM_BA) + || !user_type.isEmpty() && user_type.equalsIgnoreCase(CommonString.TAG_FROM_TBA)) { + counterimg_object.setTransId(CommonFunctions.getUUID(context)); + db.insertcounteruserdata(counter_id, username, visit_date, counterimg_object, user_type); + //download service + Intent intent = new Intent(context, Downloader.class); + intent.putExtra(CommonString.KEY_BA_Counter_Image, counterimg_object); + Downloader.enqueueWork(context, intent); + } else { + db.open(); + if (update_flag) { + counterimg_object.setTransId(CommonFunctions.getUUID(context)); + db.update_CounterImage(counter_id, username, visit_date, counterimg_object); + } else { + counterimg_object.setTransId(CommonFunctions.getUUID(context)); + db.insertcounteruserdata(counter_id, username, visit_date, counterimg_object, user_type); + } + Intent intent = new Intent(context, Downloader.class); + intent.putExtra(CommonString.KEY_Me_Counter_Image, counterimg_object); + Downloader.enqueueWork(context, intent); + } + + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + AlertandMessages.showToastMsg(context, "Data saved successfully."); + CounterImageActivity.this.finish(); + }).setNegativeButton(android.R.string.cancel, (dialog, id12) -> dialog.cancel()); + + alert = builder.create(); + alert.show(); + } + + } + } + + @SuppressLint("UseCompatLoadingForDrawables") + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + Log.i("MakeMachine", "resultCode: " + resultCode); + switch (resultCode) { + + case 0: + Log.i("MakeMachine", "User cancelled"); + break; + + case -1: + if (_pathforcheck != null && !_pathforcheck.isEmpty()) { + if (new File(CommonString.getImagesFolder(context) + _pathforcheck).exists()) { + convertBitmap(CommonString.getImagesFolder(context) + _pathforcheck); + try { + if (_pathforcheck.contains("_presetup_counter_img_one_")) { + presetup_img_one.setImageDrawable(getResources().getDrawable(R.mipmap.camera_bsd)); + counterimg_object.setPresetup_img_one_str(_pathforcheck); + + } else if (_pathforcheck.contains("_presetup_counter_img_two_")) { + presetup_img_two.setImageDrawable(getResources().getDrawable(R.mipmap.camera_bsd)); + counterimg_object.setPresetup_img_two_str(_pathforcheck); + + } else if (_pathforcheck.contains("_postsetup_counter_img_one_")) { + post_setup_img_one.setImageDrawable(getResources().getDrawable(R.mipmap.camera_bsd)); + counterimg_object.setPostsetup_img_one_str(_pathforcheck); + + } else if (_pathforcheck.contains("_possetup_counter_img_two_")) { + post_setup_img_two.setImageDrawable(getResources().getDrawable(R.mipmap.camera_bsd)); + counterimg_object.setPostsetup_img_two_str(_pathforcheck); + } else if (_pathforcheck.contains("_counter_img_one_")) { + counter_img_one.setImageDrawable(getResources().getDrawable(R.mipmap.camera_bsd)); + counterimg_object.setCounter_img_onefor_ba(_pathforcheck); + } else if (_pathforcheck.contains("_counter_img_two_")) { + counter_img_two.setImageDrawable(getResources().getDrawable(R.mipmap.camera_bsd)); + counterimg_object.setCounter_img_two_for_ba(_pathforcheck); + } + + } catch (OutOfMemoryError ex) { + ex.fillInStackTrace(); + } + + _pathforcheck = ""; + } + } + break; + } + super.onActivityResult(requestCode, resultCode, data); + } + + @SuppressLint("UseCompatLoadingForDrawables") + private void validate_ui() { + if (!counterimg_object.getPresetup_img_one_str().isEmpty()) { + presetup_img_one.setImageDrawable(getResources().getDrawable(R.mipmap.camera_bsd)); + } + if (!counterimg_object.getPresetup_img_two_str().isEmpty()) { + presetup_img_two.setImageDrawable(getResources().getDrawable(R.mipmap.camera_bsd)); + } + if (!counterimg_object.getPostsetup_img_one_str().isEmpty()) { + post_setup_img_one.setImageDrawable(getResources().getDrawable(R.mipmap.camera_bsd)); + } + if (!counterimg_object.getPostsetup_img_two_str().isEmpty()) { + post_setup_img_two.setImageDrawable(getResources().getDrawable(R.mipmap.camera_bsd)); + } + + if (!counterimg_object.getCounter_img_onefor_ba().isEmpty()) { + counter_img_one.setImageDrawable(getResources().getDrawable(R.mipmap.camera_bsd)); + } + + if (!counterimg_object.getCounter_img_two_for_ba().isEmpty()) { + counter_img_two.setImageDrawable(getResources().getDrawable(R.mipmap.camera_bsd)); + } + + } + + private boolean validateimg_str() { + boolean status = true; + if (user_type != null && user_type.equalsIgnoreCase("BA") || user_type != null && user_type.equalsIgnoreCase("TBA")) { + if (!counterimg_object.getCounter_img_onefor_ba().isEmpty()) { + status = true; + } else { + AlertandMessages.showToastMsg(context, "Please click Counter Images"); + status = false; + } + } else { + if (!update_flag) { + if (counterimg_object.getPresetup_img_one_str().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please click Pre Set-Up Counter Images"); + status = false; + } + } else if (counterimg_object.getPostsetup_img_one_str().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please click Post Set-Up Counter Images"); + status = false; + } + } + + return status; + + } + + @Override + protected void onResume() { + super.onResume(); + checkgpsEnableDevice(); + createLocationRequest(); + } + + @SuppressLint("VisibleForTests") + protected void createLocationRequest() { + LocationRequest mLocationRequest = new LocationRequest(); + // Location updates intervals in sec + // 5 sec + int UPDATE_INTERVAL = 5000; + mLocationRequest.setInterval(UPDATE_INTERVAL); + // 1 sec + int FATEST_INTERVAL = 1000; + mLocationRequest.setFastestInterval(FATEST_INTERVAL); + mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); + // 10 meters + int DISPLACEMENT = 5; + mLocationRequest.setSmallestDisplacement(DISPLACEMENT); + } + + private void checkgpsEnableDevice() { + if (!hasGPSDevice(context)) { + Toast.makeText(context, "Gps not Supported", Toast.LENGTH_SHORT).show(); + } + + final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); + if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER) && hasGPSDevice(context)) { + enableLocationSettings(); + } else { + if (manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { + hasGPSDevice(context); + } + } + } + + private void enableLocationSettings() { + @SuppressLint("VisibleForTests") LocationRequest locationRequest = LocationRequest.create() + .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY) // new Priority constant + .setInterval(30 * 1000) + .setFastestInterval(5 * 1000); + LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder() + .addLocationRequest(locationRequest) + .setAlwaysShow(true); // show dialog if GPS is off + + SettingsClient settingsClient = LocationServices.getSettingsClient(this); + + settingsClient.checkLocationSettings(builder.build()) + .addOnSuccessListener(locationSettingsResponse -> { + // All location settings are satisfied. You can request location updates here. + }).addOnFailureListener(e -> { + if (e instanceof ResolvableApiException) { + try { + ResolvableApiException resolvable = (ResolvableApiException) e; + resolvable.startResolutionForResult((Activity) context, REQUEST_LOCATION); + } catch (IntentSender.SendIntentException sendEx) { + // Ignore the error. + sendEx.fillInStackTrace(); + } + } + }); + } + + private boolean hasGPSDevice(Context context) { + final LocationManager mgr = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); + if (mgr == null) + return false; + final List providers = mgr.getAllProviders(); + if (providers == null) + return false; + return providers.contains(LocationManager.GPS_PROVIDER); + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/CounterProfileActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/CounterProfileActivity.java new file mode 100644 index 0000000..f588240 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/CounterProfileActivity.java @@ -0,0 +1,440 @@ +package com.cpm.lorealbaautomation.dailyactivity; + +import android.annotation.SuppressLint; +import android.app.AlertDialog; +import android.app.DatePickerDialog; +import android.app.Dialog; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.graphics.Bitmap; +import android.os.Bundle; + +import com.google.android.material.floatingactionbutton.FloatingActionButton; + +import androidx.core.content.ContextCompat; +import androidx.appcompat.app.AppCompatActivity; +import androidx.appcompat.widget.Toolbar; + +import android.util.Log; +import android.view.MenuItem; +import android.view.View; +import android.view.Window; +import android.view.WindowManager; +import android.webkit.WebView; +import android.webkit.WebViewClient; +import android.widget.EditText; +import android.widget.ImageView; +import android.widget.LinearLayout; +import android.widget.TextView; + +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.constant.AlertandMessages; +import com.cpm.lorealbaautomation.constant.CommonFunctions; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.download.Downloader; +import com.cpm.lorealbaautomation.gsonGetterSetter.JourneyPlan; + +import java.io.File; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Date; +import java.util.Objects; +import java.util.concurrent.TimeUnit; + +import static com.cpm.lorealbaautomation.constant.CommonFunctions.getCurrentTime; +import static com.cpm.lorealbaautomation.dailyactivity.StoreImageActivity.convertBitmap; + +public class CounterProfileActivity extends AppCompatActivity implements View.OnClickListener { + private LinearLayout lay_counter_ageing; + private TextView edt_ageing, counter_type, countersetup_date; + private EditText edt_width, edt_hight; + private ImageView image1, image2, date, img_main; + Toolbar toolbar; + FloatingActionButton fab; + String _pathforcheck, _path, counter_id, visit_date, username, user_type, dob, newvalueDate = ""; + ArrayList storelist = new ArrayList<>(); + SharedPreferences preferences; + SharedPreferences.Editor editor = null; + private Lorealba_Database db; + AlertDialog alert; + Context context; + JourneyPlan counterimg_object = new JourneyPlan(); + int mYear, mMonth, mDay; + DatePickerDialog dpd; + Calendar c; + Dialog dialog1; + WebView webview; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_counter_profile); + context = this; + ((CounterProfileActivity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); + db = new Lorealba_Database(context); + db.open(); + getViewId(); + getSetData(); + } + + void getViewId() { + preferences = PrefHelper.getPrefs(context); + editor = preferences.edit(); + counter_id = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + username = preferences.getString(CommonString.KEY_USERNAME, ""); + user_type = preferences.getString(CommonString.KEY_USER_TYPE, ""); + + countersetup_date = (TextView) findViewById(R.id.storeProfile_dob); + edt_ageing = (TextView) findViewById(R.id.edt_ageing); + counter_type = (TextView) findViewById(R.id.counter_type); + edt_width = (EditText) findViewById(R.id.edt_width); + edt_hight = (EditText) findViewById(R.id.edt_hight); + + image1 = (ImageView) findViewById(R.id.image1); + image2 = (ImageView) findViewById(R.id.image2); + date = (ImageView) findViewById(R.id.date); + lay_counter_ageing = (LinearLayout) findViewById(R.id.lay_counter_ageing); + toolbar = findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + if (!CommonFunctions.isTablet(context)) { + toolbar.setTitleTextAppearance(context, R.style.changestext_sizefor_mobile); + } + getSupportActionBar().setHomeButtonEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + setTitle("Counter Profile - " + visit_date); + fab = findViewById(R.id.fab); + fab.setOnClickListener(this); + image1.setOnClickListener(this); + image2.setOnClickListener(this); + date.setOnClickListener(this); + image1.setImageDrawable(getResources().getDrawable(R.mipmap.camera_bs)); + } + + + @SuppressLint("UseCompatLoadingForDrawables") + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + Log.i("MakeMachine", "resultCode: " + resultCode); + switch (resultCode) { + + case 0: + Log.i("MakeMachine", "User cancelled"); + break; + + case -1: + if (_pathforcheck != null && !_pathforcheck.isEmpty()) { + if (new File(CommonString.getImagesFolder(context) + _pathforcheck).exists()) { + convertBitmap(CommonString.getImagesFolder(context) + _pathforcheck); + if (_pathforcheck.contains("_cp_img_one_")) { + image1.setImageDrawable(getResources().getDrawable(R.mipmap.camera_bsd)); + counterimg_object.setProfileImage1(_pathforcheck); + + } else if (_pathforcheck.contains("_cp_img_two_")) { + image2.setImageDrawable(getResources().getDrawable(R.mipmap.camera_bsd)); + counterimg_object.setProfileImage2(_pathforcheck); + } + + _pathforcheck = ""; + } + } + break; + } + super.onActivityResult(requestCode, resultCode, data); + } + + private boolean validateimg_str() { + boolean status = true; + if (counterimg_object.getProfileImage1() == null && counterimg_object.getProfileImage2() == null) { + AlertandMessages.showToastMsg(context, "Please Click Any Profile Imges"); + status = false; + } else if (edt_hight.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Fill Counter Dimensions Height In (Feet)"); + status = false; + } else if (edt_width.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Fill Counter Dimensions Width In (Feet)"); + status = false; + } else if (countersetup_date.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Select Counter Set Up Date"); + status = false; + + } + + return status; + } + + @SuppressLint("NonConstantResourceId") + @Override + public void onClick(View view) { + if (view.getId() == R.id.image1) { + _pathforcheck = counter_id + "_cp_img_one_" + visit_date.replace("/", "") + "_" + getCurrentTime().replace(":", "") + ".jpg"; + _path = CommonString.getImagesFolder(context) + _pathforcheck; + CommonFunctions.startAnncaCameraActivity(this, _path, null, + false, CommonString.CAMERA_FACE_REAR); + } else if (view.getId() == R.id.image2) { + _pathforcheck = counter_id + "_cp_img_two_" + visit_date.replace("/", "") + "_" + getCurrentTime().replace(":", "") + ".jpg"; + _path = CommonString.getImagesFolder(context) + _pathforcheck; + CommonFunctions.startAnncaCameraActivity(this, _path, null, false, CommonString.CAMERA_FACE_REAR); + } else if (view.getId() == R.id.date) { + c = Calendar.getInstance(); + mYear = c.get(Calendar.YEAR); + mMonth = c.get(Calendar.MONTH); + mDay = c.get(Calendar.DAY_OF_MONTH); + // Launch Date Picker Dialog + //mm dd yy + dpd = new DatePickerDialog(this, (_view, year, monthOfYear, dayOfMonth) -> { + dob = (monthOfYear + 1) + "/" + dayOfMonth + "/" + year; + lay_counter_ageing.setVisibility(View.VISIBLE); + Date counterAgeing_date = null, current_date = null; + @SuppressLint("SimpleDateFormat") SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy"); + if (!dob.isEmpty()) { + String str_monthofYears = "", str_dayofmonth = ""; + int monthofyears = monthOfYear + 1; + if (monthofyears < 10) { + str_monthofYears = "0" + monthofyears; + } else { + str_monthofYears = "" + monthofyears; + } + + if (dayOfMonth < 10) { + str_dayofmonth = "0" + dayOfMonth; + } else { + str_dayofmonth = "" + dayOfMonth; + } + + newvalueDate = str_monthofYears + "/" + str_dayofmonth + "/" + year; + countersetup_date.setText(newvalueDate); + } + try { + counterAgeing_date = dateFormat.parse(newvalueDate); + current_date = dateFormat.parse(visit_date); + printDifference(current_date, counterAgeing_date); + } catch (ParseException e) { + e.fillInStackTrace(); + } + }, mYear, mMonth, mDay); + dpd.getDatePicker().setMaxDate(System.currentTimeMillis()); + dpd.show(); + } else if (view.getId() == R.id.fab) { + if (validateimg_str()) { + AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle(R.string.dialog_title).setMessage(R.string.title_activity_save_data).setCancelable(false) + .setPositiveButton(android.R.string.yes, (dialog, id1) -> { + alert.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false); + db.open(); + counterimg_object.setSetupDate(newvalueDate); + double counter_width = 0.0, counter_lenth = 0.0; + String str_width = edt_width.getText().toString().trim().replaceAll("[(!@#$%^&*?)\"]", ""); + String str_lenth = edt_hight.getText().toString().trim().replaceAll("[(!@#$%^&*?)\"]", ""); + if (!str_width.isEmpty()) { + counter_width = Double.parseDouble(str_width); + } + + if (!str_lenth.isEmpty()) { + counter_lenth = Double.parseDouble(str_lenth); + } + + counterimg_object.setCounterwidth(counter_width); + counterimg_object.setCounterlength(counter_lenth); + String status = CommonString.KEY_N; + String uuid_Id = CommonFunctions.getUUID(context); + db.open(); + db.insertCounterProfiledata(counter_id, username, user_type, visit_date, counterimg_object, status, uuid_Id); + + //download service + Intent intent = new Intent(context, Downloader.class); + intent.putExtra(CommonString.KEY_CounterProfile, counterimg_object); + Downloader.enqueueWork(CounterProfileActivity.this, intent); + + AlertandMessages.showToastMsg(context, "Data saved successfully."); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + CounterProfileActivity.this.finish(); + + }).setNegativeButton(android.R.string.cancel, (dialog, id12) -> dialog.cancel()); + + alert = builder.create(); + alert.show(); + } + + } + + + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + if (id == android.R.id.home) { + AlertDialog.Builder builder = new AlertDialog.Builder(context).setMessage(CommonString.ONBACK_ALERT_MESSAGE).setCancelable(false).setPositiveButton("Ok", + (dialog, id1) -> { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + CounterProfileActivity.this.finish(); + }).setNegativeButton("Cancel", (dialog, id12) -> dialog.cancel()); + AlertDialog alert = builder.create(); + alert.show(); + } + return super.onOptionsItemSelected(item); + } + + @Override + public void onBackPressed() { + AlertDialog.Builder builder = new AlertDialog.Builder(context).setMessage(CommonString.ONBACK_ALERT_MESSAGE).setCancelable(false).setPositiveButton("Ok", + (dialog, id) -> { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + CounterProfileActivity.this.finish(); + }).setNegativeButton("Cancel", (dialog, id) -> dialog.cancel()); + AlertDialog alert = builder.create(); + alert.show(); + } + + + @SuppressLint("SetJavaScriptEnabled") + private void popup(final String window_image) { + dialog1 = new Dialog(CounterProfileActivity.this); + dialog1.requestWindowFeature(Window.FEATURE_NO_TITLE); + dialog1.setContentView(R.layout.dialog_refrence_image); + webview = (WebView) dialog1.findViewById(R.id.webview); + img_main = (ImageView) dialog1.findViewById(R.id.img_main); + // dialog1.setCancelable(false); + dialog1.setCanceledOnTouchOutside(true); + webview.setWebViewClient(new MyWebViewClient()); + webview.getSettings().setJavaScriptEnabled(true); + if (window_image != null) { + webview.loadUrl(window_image); + } + + dialog1.show(); + } + + private class MyWebViewClient extends WebViewClient { + @Override + public boolean shouldOverrideUrlLoading(WebView view, String url) { + view.loadUrl(url); + return true; + } + + @Override + public void onPageFinished(WebView view, String url) { + webview.setVisibility(View.VISIBLE); + super.onPageFinished(view, url); + view.clearCache(true); + } + + @Override + public void onPageStarted(WebView view, String url, Bitmap favicon) { + super.onPageStarted(view, url, favicon); + } + + } + + @SuppressLint({"SetTextI18n", "UseCompatLoadingForDrawables"}) + void getSetData() { + db.open(); + storelist = db.getStoreData(visit_date, null, counter_id); + counterimg_object = db.getCounterProfileData(null, visit_date, counter_id, true); + if (counterimg_object.getUserId() != null && !counterimg_object.getUserId().isEmpty()) { + edt_hight.setText("" + counterimg_object.getCounterlength()); + edt_width.setText("" + counterimg_object.getCounterwidth()); + if (counterimg_object.getProfileImage1() != null) { + image1.setImageDrawable(getResources().getDrawable(R.mipmap.camera_bsd)); + fab.setImageDrawable(ContextCompat.getDrawable(context, R.mipmap.edit)); + lay_counter_ageing.setVisibility(View.VISIBLE); + } + + edt_ageing.setText(counterimg_object.getStoreName() + " Days"); + counterimg_object.setStoreName(counterimg_object.getStoreName()); + countersetup_date.setText(counterimg_object.getSetupDate()); + newvalueDate = counterimg_object.getSetupDate(); + if (counterimg_object.getProfileImage2() != null) { + image2.setImageDrawable(getResources().getDrawable(R.mipmap.camera_bsd)); + } + + if (!storelist.isEmpty()) { + counter_type.setText(storelist.get(0).getStoreTypeName()); + } + + } else { + if (!storelist.isEmpty()) { + edt_hight.setText("" + storelist.get(0).getCounterlength()); + edt_width.setText("" + storelist.get(0).getCounterwidth()); + if (storelist.get(0).getStoreTypeName().isEmpty()) { + } else { + counter_type.setText(storelist.get(0).getStoreTypeName()); + } + if (storelist.get(0).getProfileImage1().isEmpty()) { + image1.setImageDrawable(getResources().getDrawable(R.mipmap.camera_bs)); + } else { + counterimg_object.setProfileImage1(storelist.get(0).getProfileImage1()); + image1.setImageDrawable(getResources().getDrawable(R.mipmap.camera_bsd)); + } + + if (storelist.get(0).getProfileImage2().isEmpty()) { + image2.setImageDrawable(getResources().getDrawable(R.mipmap.camera_bs)); + } else { + counterimg_object.setProfileImage2(storelist.get(0).getProfileImage2()); + image2.setImageDrawable(getResources().getDrawable(R.mipmap.camera_bsd)); + } + + + //////////parshing date and counter agaiging....... + if (!storelist.get(0).getSetupDate().isEmpty()) { + counterimg_object.setSetupDate(storelist.get(0).getSetupDate()); + countersetup_date.setText(storelist.get(0).getSetupDate()); + Date counterAgeing_date = null, current_date = null; + @SuppressLint("SimpleDateFormat") SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy"); + try { + counterAgeing_date = dateFormat.parse(storelist.get(0).getSetupDate()); + current_date = dateFormat.parse(visit_date); + printDifference(current_date, counterAgeing_date); + lay_counter_ageing.setVisibility(View.VISIBLE); + newvalueDate = storelist.get(0).getSetupDate(); + } catch (ParseException e) { + e.fillInStackTrace(); + } + } else { + edt_ageing.setText("0 Days"); + counterimg_object.setSetupDate(""); + countersetup_date.setText(""); + } + } + } + } + + public static long getDateDiff(SimpleDateFormat format, String oldDate, String newDate) { + try { + return TimeUnit.DAYS.convert(Objects.requireNonNull(format.parse(newDate)).getTime() - Objects.requireNonNull(format.parse(oldDate)).getTime(), TimeUnit.MILLISECONDS); + } catch (Exception e) { + e.fillInStackTrace(); + return 0; + } + } + + @SuppressLint("SetTextI18n") + public void printDifference(Date startDate, Date endDate) { + try { + long different = startDate.getTime() - endDate.getTime(); + long secondsInMilli = 1000; + long minutesInMilli = secondsInMilli * 60; + long hoursInMilli = minutesInMilli * 60; + long daysInMilli = hoursInMilli * 24; + long elapsedDays = different / daysInMilli; + different = different % daysInMilli; + long elapsedHours = different / hoursInMilli; + different = different % hoursInMilli; + long elapsedMinutes = different / minutesInMilli; + different = different % minutesInMilli; + long elapsedSeconds = different / secondsInMilli; + System.out.printf("%d days, %d hours, %d minutes, %d seconds%n", elapsedDays, elapsedHours, elapsedMinutes, elapsedSeconds); + edt_ageing.setText((int) elapsedDays + " Days "); + counterimg_object.setStoreName(String.valueOf(elapsedDays)); + + } catch (Exception e) { + e.fillInStackTrace(); + } + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/DamagedActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/DamagedActivity.java new file mode 100644 index 0000000..ca16919 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/DamagedActivity.java @@ -0,0 +1,1786 @@ +package com.cpm.lorealbaautomation.dailyactivity; + +import android.annotation.SuppressLint; +import android.app.Activity; +import android.app.AlertDialog; +import android.app.Dialog; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.SharedPreferences; +import android.graphics.drawable.ColorDrawable; +import android.os.AsyncTask; +import android.os.Build; +import android.os.Bundle; + +import androidx.annotation.NonNull; +import androidx.annotation.RequiresApi; + +import com.google.android.material.bottomsheet.BottomSheetDialog; +import com.google.android.material.floatingactionbutton.FloatingActionButton; + +import androidx.core.content.ContextCompat; +import androidx.appcompat.app.AppCompatActivity; +import androidx.cardview.widget.CardView; +import androidx.recyclerview.widget.GridLayoutManager; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; +import androidx.appcompat.widget.Toolbar; + +import android.text.Editable; +import android.text.TextWatcher; +import android.util.Log; +import android.view.Gravity; +import android.view.LayoutInflater; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; +import android.view.Window; +import android.view.WindowManager; +import android.view.inputmethod.InputMethodManager; +import android.widget.AbsListView; +import android.widget.AdapterView; +import android.widget.ArrayAdapter; +import android.widget.BaseExpandableListAdapter; +import android.widget.Button; +import android.widget.EditText; +import android.widget.ExpandableListView; +import android.widget.ImageView; +import android.widget.LinearLayout; +import android.widget.ProgressBar; +import android.widget.Spinner; +import android.widget.TextView; + +import com.google.zxing.integration.android.IntentIntegrator; +import com.google.zxing.integration.android.IntentResult; +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.constant.AlertandMessages; +import com.cpm.lorealbaautomation.constant.CommonFunctions; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.gettersetter.SaleableGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.JourneyPlan; +import com.cpm.lorealbaautomation.gsonGetterSetter.ProductMaster; + +import java.io.File; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Objects; +import java.util.UUID; + +import static com.cpm.lorealbaautomation.constant.CommonFunctions.getCurrentTime; +import static com.cpm.lorealbaautomation.constant.CommonFunctions.removeFirstChar; +import static com.cpm.lorealbaautomation.dailyactivity.StoreImageActivity.convertBitmap; + +public class DamagedActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemSelectedListener { + ArrayAdapter axe_name_adapter, sub_axe_name_adapter, brand_name_adapter, product_name_adapter; + Spinner sku_spin, brand_spin, sub_axe_spin, axe_spin; + ArrayList brandList = new ArrayList<>(); + ArrayList subAxeList = new ArrayList<>(); + ArrayList axeList = new ArrayList<>(); + + ExpandableListView lvExp_stock_check; + FloatingActionButton fab_save, return_fab; + Lorealba_Database db; + Context context; + AlertDialog alert; + private SharedPreferences preferences; + String counter_id, visit_date, username, _pathforcheck, _path; + ArrayList listDataHeader = new ArrayList<>(); + ArrayList childStockList = new ArrayList<>(); + HashMap> listDataChild; + boolean checkflag = true; + ArrayList checkHeaderArray = new ArrayList<>(); + ExpandableListAdapter listAdapter; + String brandName = ""; + String axeName = ""; + String subAxeName = ""; + + int groupPositionGlobal = -1; + ProductMaster globalHeaderObject = new ProductMaster(); + EditText et_search; + + //filter bottom sheet + ArrayList subBrandList = new ArrayList<>(); + ArrayList referenceList = new ArrayList<>(); + ArrayList signatureList = new ArrayList<>(); + ImageView img_filter, img_unfilled; + View sheetView; + ProductMaster selectedSignature, selectedBrand, selectedSubBrand, selectedReference; + final int FILTER_FOR_SIGNATURE = 4; + final int FILTER_FOR_SUB_BRAND = 5; + final int FILTER_FOR_REFERENCE = 6; + final int FILTER_FOR_BRAND = 1; + final int CLEAR_FILTER = 0; + + int childPositionGlobal = -1; + ProductMaster globalChildObject = new ProductMaster(); + + ImageView img_scan, img_clear_subaxe; + RecyclerView recSubAxe; + SubAxeValueAdapter subAxeValueAdapter; + ArrayList listSubAxe; + boolean flagScan = true; + private String counterGroupId, damaged_category_str = "", selectedSubAxe = ""; + TextView txt_total_qty, txt_total_value; + LinearLayout rl_total_qty; + + @SuppressLint("SetTextI18n") + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_damaged); + context = this; + ((DamagedActivity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); + db = new Lorealba_Database(context); + db.open(); + validateUIData(); + + String couter_code = preferences.getString(CommonString.KEY_COUNTER_CODE, ""); + TextView txt_counter_code = (TextView) findViewById(R.id.txt_counter_code); + txt_counter_code.setText("Counter Code - " + couter_code + " / Id - " + counter_id); + + new LoadAsync().execute(); + lvExp_stock_check.setOnScrollListener(new AbsListView.OnScrollListener() { + @Override + public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { + lvExp_stock_check.invalidate(); + + int lastItem = firstVisibleItem + visibleItemCount; + if (firstVisibleItem == 0) { + fab_save.show();//.setVisibility(View.VISIBLE); + } else if (lastItem == totalItemCount) { + fab_save.hide();//setVisibility(View.INVISIBLE); + } else { + fab_save.show();//setVisibility(View.VISIBLE); + } + } + + @Override + public void onScrollStateChanged(AbsListView arg0, int arg1) { + InputMethodManager inputManager = (InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE); + if (getCurrentFocus() != null) { + inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0); + getCurrentFocus().clearFocus(); + } + + lvExp_stock_check.invalidateViews(); + } + }); + + } + + private void validateUIData() { + preferences = PrefHelper.getPrefs(context); + counter_id = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + username = preferences.getString(CommonString.KEY_USERNAME, ""); + damaged_category_str = getIntent().getStringExtra(CommonString.TAG_OBJECT); + Toolbar toolbar = findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + + if (!CommonFunctions.isTablet(context)) { + toolbar.setTitleTextAppearance(context, R.style.changestext_sizefor_mobile); + } + getSupportActionBar().setHomeButtonEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + + sku_spin = (Spinner) findViewById(R.id.sku_spin); + brand_spin = (Spinner) findViewById(R.id.stock_brand_spin); + sub_axe_spin = (Spinner) findViewById(R.id.sub_axe_spin); + axe_spin = (Spinner) findViewById(R.id.axe_spin); + lvExp_stock_check = (ExpandableListView) findViewById(R.id.lvExp_stock_check); + fab_save = (FloatingActionButton) findViewById(R.id.save_fab); + + et_search = (EditText) findViewById(R.id.et_search); + img_scan = (ImageView) findViewById(R.id.img_scan); + img_clear_subaxe = (ImageView) findViewById(R.id.img_clear_subaxe); + + recSubAxe = (RecyclerView) findViewById(R.id.rec_subaxe); + ////for total QTY and Return value.......... + rl_total_qty = (LinearLayout) findViewById(R.id.rl_total_qty); + txt_total_qty = (TextView) findViewById(R.id.txt_total_qty); + txt_total_value = (TextView) findViewById(R.id.txt_total_value); + + img_scan.setOnClickListener(this); + fab_save.setOnClickListener(this); + img_clear_subaxe.setOnClickListener(this); + if (damaged_category_str != null && damaged_category_str.equals("1")) { + setTitle("Damaged Stock - " + visit_date); + } else { + setTitle("Return To distributor - " + visit_date); + fab_save.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.submit)); + } + + db.open(); + img_clear_subaxe.setVisibility(View.VISIBLE); + et_search.addTextChangedListener(new TextWatcher() { + @Override + public void beforeTextChanged(CharSequence s, int start, int count, int after) { + + } + + @Override + public void onTextChanged(CharSequence s, int start, int before, int count) { + String text = s.toString(); + if (text.equals("")) { + lvExp_stock_check.setAdapter(listAdapter); + listAdapter.notifyDataSetChanged(); + } else { + lvExp_stock_check.invalidate(); + setSearchFilter(listAdapter.get_listDataHeader(), text, listAdapter.get_listDataChild()); + } + } + + @Override + public void afterTextChanged(Editable s) { + String text = s.toString(); + } + }); + + + img_filter = (ImageView) findViewById(R.id.img_filter); + img_unfilled = (ImageView) findViewById(R.id.img_unfilled); + img_unfilled.setVisibility(View.INVISIBLE); + + img_filter.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + sheetView = showFilterBottomSheet(); + } + }); + } + + public void setSearchFilter(List originalList, String text, HashMap> listDataChild) { + HashMap> filterChildHashMap = new HashMap<>(); + ArrayList filterList = new ArrayList<>(); + for (int i = 0; i < originalList.size(); i++) { + ProductMaster parent = originalList.get(i); + List listChild = listDataChild.get(parent); + List listFilterChild = new ArrayList<>(); + for (int j = 0; j < listChild.size(); j++) { + if (listChild.get(j).getProductName().toLowerCase().contains(text.toLowerCase()) || (listChild.get(j).getEanCode() != null && listChild.get(j).getEanCode().contains(text))) { + listFilterChild.add(listChild.get(j)); + } else { + continue; + } + } + + if (listFilterChild.size() > 0) { + filterList.add(parent); + filterChildHashMap.put(parent, listFilterChild); + + } + + } + + ExpandableListAdapter listAdapter = new ExpandableListAdapter(context, filterList, filterChildHashMap); + lvExp_stock_check.setAdapter(listAdapter); + listAdapter.notifyDataSetChanged(); + for (int i = 0; i < listAdapter.getGroupCount(); i++) { + lvExp_stock_check.expandGroup(i); + } + + } + + private void prepareListData() { + db.open(); + //for filter bottom sheet + JourneyPlan jcp = db.getJCP(); + if (jcp != null) { + db.open(); + listSubAxe = db.getSubAxe(jcp.getCounterGroupId().toString(), true); + db.open(); + brandList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "BrandName", false); + db.open(); + subBrandList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "SubBrandName", false); + db.open(); + referenceList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "ReferenceName", false); + db.open(); + signatureList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "SignatureName", false); + } else { + db.open(); + brandList = db.getsub_brand_name("1", "BrandName", false); + db.open(); + subBrandList = db.getsub_brand_name("1", "SubBrandName", false); + db.open(); + referenceList = db.getsub_brand_name("1", "ReferenceName", false); + db.open(); + signatureList = db.getsub_brand_name("1", "SignatureName", false); + db.open(); + listSubAxe = db.getSubAxe("1", true); + } + + listDataHeader = new ArrayList<>(); + listDataChild = new HashMap<>(); + //inserted data + if (listDataHeader.size() == 0) { + jcp = db.getJCP(); + if (jcp != null) { + if (damaged_category_str != null) { + db.open(); + listDataHeader = db.getDamageBrandSubBrandReference(jcp.getCounterGroupId().toString(), counter_id, visit_date, damaged_category_str); + } + } else { + db.open(); + listDataHeader = db.getStockSignatureBrandSubBrandReference("1", false, false, null); + } + } + + if (listDataHeader.size() > 0) { + for (int i = 0; i < listDataHeader.size(); i++) { + if (damaged_category_str != null) { + db.open(); + childStockList = db.getDefaultDamageChildData(counter_id, visit_date, listDataHeader.get(i).getSubBrandName(), + listDataHeader.get(i).getReferenceName(), listDataHeader.get(i).getBrandName(), + CommonString.KEY_SaleableDamage, damaged_category_str, jcp.getCounterGroupId().toString()); + } + + listDataChild.put(listDataHeader.get(i), childStockList); // Header, Child data + } + } + } + + + private boolean isValid() { + boolean flag = true; + for (int i = 0; i < listDataHeader.size(); i++) { + List list = listDataChild.get(listDataHeader.get(i)); + for (int j = 0; j < list.size(); j++) { + if (list.get(j).getStock() > 0 && list.get(j).getImagePath().equals("")) { + flag = false; + break; + } + } + + if (!flag) { + break; + } + } + + return flag; + } + + + private void show_dialog_for_final_submit(final Context context, final boolean returntodistr) { + final MultiPurposeDialog final_save_dialog = new MultiPurposeDialog(context); + final_save_dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); + final_save_dialog.setContentView(R.layout.custom_dialog_final_save); + final WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); + lp.copyFrom(final_save_dialog.getWindow().getAttributes()); + lp.width = WindowManager.LayoutParams.MATCH_PARENT; + lp.height = WindowManager.LayoutParams.WRAP_CONTENT; + lp.gravity = Gravity.CENTER; + final_save_dialog.getWindow().setAttributes(lp); + final_save_dialog.setCancelable(false); + + final EditText txt_hint_yes = (EditText) final_save_dialog.findViewById(R.id.txt_hint_yes); + Button btn_cancel = (Button) final_save_dialog.findViewById(R.id.btn_cancel); + Button btn_okay = (Button) final_save_dialog.findViewById(R.id.btn_okay); + + TextView final_text = (TextView) final_save_dialog.findViewById(R.id.final_text); + if (returntodistr) { + final_text.setText(getString(R.string.want_to_final_savedamage)); + } else { + final_text.setText(getString(R.string.want_to_final_damage_save)); + } + + btn_okay.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + if (txt_hint_yes.getText().toString().equals("")) { + AlertandMessages.showToastMsg(context, "Please Enter Text"); + } else if (!txt_hint_yes.getText().toString().trim().equalsIgnoreCase("yes")) { + AlertandMessages.showToastMsg(context, "Please Enter 'Yes' Text"); + } else { + ////final submit + final_save_dialog.dismiss(); + if (returntodistr) { + dialog = new Dialog(context); + dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); + dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT)); + dialog.setContentView(R.layout.circular_progress_bar); + pb = (ProgressBar) dialog.findViewById(R.id.progressBar1); + dialog.setCancelable(false); + dialog.show(); + /*if (CommonFunctions.checkNetIsAvailable(context)) { + UploadDamageReturnToDistributor(); + } else {*/ + final SaleableGetterSetter stock = new SaleableGetterSetter(); + ArrayList data = new ArrayList<>(); + for (int i = 0; i < listDataHeader.size(); i++) { + List list = listDataChild.get(listDataHeader.get(i)); + for (int j = 0; j < list.size(); j++) { + if (list.get(j).getStock() > 0) { + data.add(list.get(j)); + } + } + } + + if (data.size() > 0) { + stock.setProductList(data); + String uuid = CommonFunctions.getUUID(context); + stock.setTransactionId(uuid); + } + + if (stock != null) { + db.open(); + db.updateTStockSaleableDamageReturnData(); + db.open(); + db.insertStockTransactionMasterData(counter_id, visit_date, username, CommonString.RETURNTO_DB, stock, "Regular_Stock"); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + CommonFunctions.call_upload(context); + DamagedActivity.this.finish(); + } + // } + } else { + dialog = new Dialog(context); + dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); + dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT)); + dialog.setContentView(R.layout.circular_progress_bar); + pb = (ProgressBar) dialog.findViewById(R.id.progressBar1); + dialog.setCancelable(false); + dialog.show(); + db.open(); + db.insertDamagedCapturedData(visit_date, counter_id, listDataChild, listDataHeader); + uploadData(); + } + } + } + }); + + btn_cancel.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + final_save_dialog.dismiss(); + } + }); + + final_save_dialog.show(); + } + + public class MultiPurposeDialog extends Dialog { + public MultiPurposeDialog(Context context) { + super(context); + // DIALOG USER_INTERFACE TEMPLATE + WindowManager.LayoutParams wmLayoutParams = getWindow().getAttributes(); + wmLayoutParams.gravity = Gravity.CENTER; + getWindow().setAttributes(wmLayoutParams); + setTitle(null); + setCancelable(false); + setOnCancelListener(null); + LinearLayout layout = new LinearLayout(context); + layout.setOrientation(LinearLayout.VERTICAL); + } + } + + + @Override + public void onClick(View view) { + + if (view.getId() == R.id.save_fab) { + lvExp_stock_check.clearFocus(); + lvExp_stock_check.invalidateViews(); + + if (damaged_category_str != null && damaged_category_str.equals("1")) { + if (isValid()) { + dialogFinalSubmit(false); + } else { + AlertandMessages.showToastMsg(context, getString(R.string.pls_click_image_damage)); + } + } else if (damaged_category_str != null && damaged_category_str.equals("0")) { + if (calculate_total_qty() > 0) { + dialogFinalSubmit(true); + } else { + AlertandMessages.showToastMsg(context, "Please Return To Distributor atleast one product"); + } + } + + } else if (view.getId() == R.id.card_signature) { + RecyclerView recSignature = sheetView.findViewById(R.id.rec_brand); + recSignature.setAdapter(new ValueAdapter(context, signatureList, CommonString.Signature)); + recSignature.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, true)); + setFilterSelected(sheetView, CommonString.Signature); + + } else if (view.getId() == R.id.card_brand) { + + RecyclerView recBrand = sheetView.findViewById(R.id.rec_brand); + recBrand.setAdapter(new ValueAdapter(context, brandList, CommonString.Brand)); + recBrand.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, true)); + setFilterSelected(sheetView, CommonString.Brand); + } else if (view.getId() == R.id.card_sub_brand) { + + RecyclerView recSubBrand = sheetView.findViewById(R.id.rec_brand); + recSubBrand.setAdapter(new ValueAdapter(context, subBrandList, CommonString.SubBrand)); + recSubBrand.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, true)); + recSubBrand.getAdapter().notifyDataSetChanged(); + setFilterSelected(sheetView, CommonString.SubBrand); + } else if (view.getId() == R.id.card_reference) { + + RecyclerView recReference = sheetView.findViewById(R.id.rec_brand); + recReference.setAdapter(new ValueAdapter(context, referenceList, CommonString.Reference)); + recReference.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, true)); + setFilterSelected(sheetView, CommonString.Reference); + } else if (view.getId() == R.id.img_scan) { + if (flagScan) { + openScanner(); + } else { + img_scan.setImageDrawable(getResources().getDrawable(R.mipmap.barcode_icon)); + flagScan = true; + et_search.setText(""); + } + + } else if (view.getId() == R.id.img_clear_subaxe) { + et_search.setText(""); + listAdapter = new ExpandableListAdapter(context, listDataHeader, listDataChild); + lvExp_stock_check.setAdapter(listAdapter); + listAdapter.notifyDataSetChanged(); + selectedSubAxe = ""; + subAxeValueAdapter.notifyDataSetChanged(); + + //clear filters also + selectedSignature = null; + selectedBrand = null; + selectedSubBrand = null; + selectedReference = null; + db.open(); + brandList = db.getsub_brand_name(counterGroupId, "BrandName", false, selectedSubAxe); + db.open(); + subBrandList = db.getsub_brand_name(counterGroupId, "SubBrandName", false, selectedSubAxe); + db.open(); + referenceList = db.getsub_brand_name(counterGroupId, "ReferenceName", false, selectedSubAxe); + db.open(); + signatureList = db.getsub_brand_name(counterGroupId, "SignatureName", false, selectedSubAxe); + + } + } + + @Override + public void onItemSelected(AdapterView adapterView, View view, int position, long l) { + if (adapterView.getId() == R.id.stock_brand_spin) { + if (position != 0) { + brandName = adapterView.getSelectedItem().toString(); + setFilter(FILTER_FOR_BRAND); + db.open(); + //for filter bottom sheet + JourneyPlan jcp = db.getJCP(); + if (jcp != null) { + db.open(); + axeList = db.getAxeNSubAxe(jcp.getCounterGroupId().toString(), "AxeName", brandName, null); + db.open(); + subAxeList = db.getAxeNSubAxe(jcp.getCounterGroupId().toString(), "SubAxeName", brandName, null); + } else { + db.open(); + axeList = db.getAxeNSubAxe("1", "AxeName", brandName, null); + db.open(); + subAxeList = db.getAxeNSubAxe("1", "SubAxeName", brandName, null); + } + setAxeSpinnerData(axeList); + setSubAxeSpinnerData(subAxeList); + + } else { + brandName = ""; + setFilter(CLEAR_FILTER); + db.open(); + //for filter bottom sheet + JourneyPlan jcp = db.getJCP(); + if (jcp != null) { + db.open(); + axeList = db.getAxeNSubAxe(jcp.getCounterGroupId().toString(), "AxeName", null, null); + db.open(); + subAxeList = db.getAxeNSubAxe(jcp.getCounterGroupId().toString(), "SubAxeName", null, null); + } else { + db.open(); + axeList = db.getAxeNSubAxe("1", "AxeName", null, null); + db.open(); + subAxeList = db.getAxeNSubAxe("1", "SubAxeName", null, null); + } + setAxeSpinnerData(axeList); + setSubAxeSpinnerData(subAxeList); + } + + } else if (adapterView.getId() == R.id.axe_spin) { + if (position != 0) { + axeName = adapterView.getSelectedItem().toString(); + setFilter(FILTER_FOR_AXE); + db.open(); + //for filter bottom sheet + JourneyPlan jcp = db.getJCP(); + if (jcp != null) { + db.open(); + subAxeList = db.getAxeNSubAxe(jcp.getCounterGroupId().toString(), "SubAxeName", "", axeName); + } else { + db.open(); + subAxeList = db.getAxeNSubAxe("1", "SubAxeName", "", axeName); + } + + setSubAxeSpinnerData(subAxeList); + } else { + axeName = ""; + if (brand_spin.getSelectedItemPosition() == 0) { + db.open(); + //for filter bottom sheet + JourneyPlan jcp = db.getJCP(); + if (jcp != null) { + subAxeList = db.getAxeNSubAxe(jcp.getCounterGroupId().toString(), "SubAxeName", null, null); + } else { + subAxeList = db.getAxeNSubAxe("1", "SubAxeName", null, null); + } + + setSubAxeSpinnerData(subAxeList); + setFilter(CLEAR_FILTER); + } else { + db.open(); + //for filter bottom sheet + JourneyPlan jcp = db.getJCP(); + if (jcp != null) { + subAxeList = db.getAxeNSubAxe(jcp.getCounterGroupId().toString(), "SubAxeName", brandName, null); + } else { + subAxeList = db.getAxeNSubAxe("1", "SubAxeName", brandName, null); + } + + setSubAxeSpinnerData(subAxeList); + setFilter(FILTER_FOR_BRAND); + } + } + + } else if (adapterView.getId() == R.id.sub_axe_spin) { + if (position != 0) { + subAxeName = adapterView.getSelectedItem().toString(); + setFilter(FILTER_FOR_SUBAXE); + } else { + subAxeName = ""; + if (axe_spin.getSelectedItemPosition() == 0) { + if (brand_spin.getSelectedItemPosition() == 0) { + setFilter(CLEAR_FILTER); + } else { + setFilter(FILTER_FOR_BRAND); + } + } else { + setFilter(FILTER_FOR_AXE); + } + } + + } + + } + + @Override + public void onNothingSelected(AdapterView adapterView) { + + } + + public ArrayList filterListForBrand(List originalList, String text) { + ArrayList filterList = new ArrayList<>(); + for (ProductMaster object : originalList) { + if (object.getBrandName().equalsIgnoreCase(text)) { + filterList.add(object); + } else { + continue; + } + } + return filterList; + } + + + public class ExpandableListAdapter extends BaseExpandableListAdapter { + private Context _context; + private List _listDataHeader; + private HashMap> _listDataChild; + + public ExpandableListAdapter(Context context, List listDataHeader, HashMap> listChildData) { + this._context = context; + this._listDataHeader = listDataHeader; + this._listDataChild = listChildData; + } + + public HashMap> get_listDataChild() { + return _listDataChild; + } + + public List get_listDataHeader() { + return _listDataHeader; + } + + @Override + public Object getChild(int groupPosition, int childPosititon) { + return this._listDataChild.get(this._listDataHeader.get(groupPosition)).get(childPosititon); + } + + @Override + public long getChildId(int groupPosition, int childPosition) { + return childPosition; + } + + @SuppressLint({"UseCompatLoadingForDrawables", "SetTextI18n"}) + @Override + public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { + + final ProductMaster childText = (ProductMaster) getChild(groupPosition, childPosition); + ViewHolder holder = null; + if (convertView == null) { + LayoutInflater infalInflater = (LayoutInflater) this._context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); + convertView = infalInflater.inflate(R.layout.item_damage_layout, null); + holder = new ViewHolder(); + holder.cardView = convertView.findViewById(R.id.card_view); + holder.ed_Stock = convertView.findViewById(R.id.ed_Stock); + holder.mrp = convertView.findViewById(R.id.mrp); + holder.stock_img_plus = convertView.findViewById(R.id.stock_img_plus); + holder.stock_img_minus = convertView.findViewById(R.id.stock_img_minus); + holder.tv_stock_saleable = convertView.findViewById(R.id.tv_stock); + holder.tv_damage = convertView.findViewById(R.id.tv_damage); + holder.imgCam = convertView.findViewById(R.id.img_cam); + convertView.setTag(holder); + + + } else { + + holder = (ViewHolder) convertView.getTag(); + } + + + holder.imgCam.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + groupPositionGlobal = groupPosition; + childPositionGlobal = groupPosition; + globalChildObject = childText; + _pathforcheck = counter_id + "_Damaged_stock_img_" + visit_date.replace("/", "") + "_" + getCurrentTime().replace(":", "") + ".jpg"; + _path = CommonString.getImagesFolder(context) + _pathforcheck; + CommonFunctions.startAnncaCameraActivity(DamagedActivity.this, _path, null, false, CommonString.CAMERA_FACE_REAR); + } + }); + + TextView txtListChild = convertView.findViewById(R.id.lblListItem); + txtListChild.setText(childText.getProductName() + " (MRP - ₹ " + childText.getMrp() + ")"); + + holder.stock_img_plus.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + ((ExpandableListAdapter) lvExp_stock_check.getExpandableListAdapter()).notifyDataSetChanged(); + int stock = childText.getStock(); + int receivedStock = childText.getStock_receive(); + int saleable_stock = childText.getSaleable_stock(); + + if (damaged_category_str != null && damaged_category_str.equals("0")) { + ++stock; + if (stock > receivedStock) { + stock--; + childText.setStock(stock); + isDataAdded = true; + childText.setSelected(true); + AlertandMessages.showToastMsg(context, "Damage cannot be greater than Received Stock"); + } else { + childText.setStock(stock); + isDataAdded = true; + childText.setSelected(true); + } + txt_total_qty.setText("Return Total QTY : " + calculate_total_qty()); + txt_total_value.setText("Return Total Values : " + calculate_total_sale_value()); + } else { + ++stock; + if (stock <= saleable_stock) { + childText.setStock(stock); + isDataAdded = true; + childText.setSelected(true); + } else { + stock--; + AlertandMessages.showToastMsg(context, "Damage cannot be greater than Stock."); + } + } + } + }); + + holder.stock_img_minus.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + ((ExpandableListAdapter) lvExp_stock_check.getExpandableListAdapter()).notifyDataSetChanged(); + int stock = childText.getStock(); + // int receivedStock = childText.getStock_receive(); + int damaged_stock = childText.getSaleable_stock(); + if (damaged_category_str != null && damaged_category_str.equals("0")) { + --stock; + if (stock >= 0) { + childText.setStock(stock); + isDataAdded = true; + childText.setSelected(true); + } else { + AlertandMessages.showToastMsg(context, "Stock cannot be less than Zero"); + } + + txt_total_qty.setText("Return Total QTY : " + calculate_total_qty()); + txt_total_value.setText("Return Total Values : " + calculate_total_sale_value()); + + } else { + --stock; + if (stock >= 0) { + isDataAdded = true; + childText.setStock(stock); + childText.setSelected(true); + } else { + AlertandMessages.showToastMsg(context, "Stock cannot be less than Zero"); + } + } + } + }); + + + if (childText.getImagePath().isEmpty()) { + holder.imgCam.setImageDrawable(getResources().getDrawable(R.mipmap.camera_bs)); + holder.imgCam.setId(childPosition); + } else { + holder.imgCam.setImageDrawable(getResources().getDrawable(R.mipmap.camera_bsd)); + holder.imgCam.setId(childPosition); + } + + holder.mrp.setText(" MRP = " + childText.getMrp()); + holder.mrp.setId(childPosition); + + ///availeble Damage Stock + if (damaged_category_str != null && damaged_category_str.equals("0")) { + holder.ed_Stock.setText("Damaged Stock : " + childText.getStock()); + holder.ed_Stock.setId(childPosition); + + holder.imgCam.setVisibility(View.GONE); + holder.imgCam.setId(childPosition); + + holder.tv_damage.setText("Return QTY : " + childText.getBlockproductId()); + holder.tv_damage.setId(childPosition); + + holder.tv_stock_saleable.setText("Saleable Damage : " + childText.getSaleable_stock()); + holder.tv_stock_saleable.setId(childPosition); + + } else if (damaged_category_str != null && damaged_category_str.equals("1")) { + holder.ed_Stock.setText("" + childText.getStock()); + holder.ed_Stock.setId(childPosition); + + holder.tv_stock_saleable.setText("Stock - " + childText.getSaleable_stock()); + holder.tv_stock_saleable.setId(childPosition); + + holder.tv_damage.setText("Dmg - " + childText.getStock_receive()); + holder.tv_damage.setId(childPosition); + + holder.imgCam.setVisibility(View.VISIBLE); + holder.imgCam.setId(childPosition); + } + + + if (damaged_category_str != null && damaged_category_str.equals("1") && childText.getBlockproductId() != 0) { + holder.stock_img_plus.setEnabled(false); + holder.stock_img_plus.setId(childPosition); + + holder.stock_img_minus.setEnabled(false); + holder.stock_img_minus.setId(childPosition); + + holder.imgCam.setImageResource(R.mipmap.exclam); + holder.imgCam.setEnabled(false); + holder.imgCam.setId(childPosition); + + } else { + holder.stock_img_plus.setEnabled(true); + holder.stock_img_plus.setId(childPosition); + + holder.stock_img_minus.setEnabled(true); + holder.stock_img_minus.setId(childPosition); + + holder.imgCam.setEnabled(true); + holder.imgCam.setId(childPosition); + } + + + return convertView; + } + + @Override + public int getChildrenCount(int groupPosition) { + return this._listDataChild.get(this._listDataHeader.get(groupPosition)).size(); + } + + @Override + public Object getGroup(int groupPosition) { + return this._listDataHeader.get(groupPosition); + } + + @Override + public int getGroupCount() { + return this._listDataHeader.size(); + } + + @Override + public long getGroupId(int groupPosition) { + return groupPosition; + } + + @Override + public View getGroupView(final int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { + final ProductMaster headerTitle = (ProductMaster) getGroup(groupPosition); + if (convertView == null) { + + LayoutInflater infalInflater = (LayoutInflater) this._context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); + convertView = infalInflater.inflate(R.layout.list_group_stock_entry, null); + } + TextView lblListHeader = (TextView) convertView.findViewById(R.id.lblListHeader); + ImageView stock_cam = (ImageView) convertView.findViewById(R.id.stock_cam); + + stock_cam.setVisibility(View.GONE); + stock_cam.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + groupPositionGlobal = groupPosition; + globalHeaderObject = headerTitle; + _pathforcheck = counter_id + "_Damage_header_img_" + visit_date.replace("/", "") + "_" + getCurrentTime().replace(":", "") + ".jpg"; + _path = CommonString.getImagesFolder(context) + _pathforcheck; + CommonFunctions.startAnncaCameraActivity(DamagedActivity.this, _path, null, false, CommonString.CAMERA_FACE_REAR); + } + }); + + if (headerTitle.getImagePath().isEmpty()) { + stock_cam.setImageDrawable(getResources().getDrawable(R.mipmap.camera)); + } else { + stock_cam.setImageDrawable(getResources().getDrawable(R.mipmap.camera_tick)); + } + + lblListHeader.setText(headerTitle.getSubBrandName() + " - " + headerTitle.getReferenceName() + " - " + headerTitle.getBrandName()); + if (!checkflag) { + if (checkHeaderArray.contains(groupPosition)) { + lblListHeader.setBackgroundColor(getResources().getColor(R.color.red)); + } else { + lblListHeader.setBackgroundColor(getResources().getColor(R.color.bright_red)); + } + + } else { + lblListHeader.setBackgroundColor(getResources().getColor(R.color.bright_red)); + } + return convertView; + } + + @Override + public boolean hasStableIds() { + return false; + } + + @Override + public boolean isChildSelectable(int groupPosition, int childPosition) { + return true; + } + } + + public class ViewHolder { + TextView ed_Stock, mrp, tv_stock_saleable, tv_damage; + Button stock_img_plus, stock_img_minus; + ImageView imgCam; + CardView cardView; + } + + @Override + public void onDestroy() { + super.onDestroy(); + } + + + private void setAxeSpinnerData(ArrayList axeList) { + axe_name_adapter = new ArrayAdapter<>(this, R.layout.spinner_custom_item); + axe_name_adapter.add("- Axe Name -"); + + for (int i = 0; i < axeList.size(); i++) { + axe_name_adapter.add(axeList.get(i).getBrandName()); + } + + axe_spin.setAdapter(axe_name_adapter); + axe_name_adapter.setDropDownViewResource(R.layout.spinner_custom_item); + + } + + private void setSubAxeSpinnerData(ArrayList subAxeList) { + sub_axe_name_adapter = new ArrayAdapter<>(this, R.layout.spinner_custom_item); + sub_axe_name_adapter.add("- Sub Axe Name -"); + + + for (int i = 0; i < subAxeList.size(); i++) { + sub_axe_name_adapter.add(subAxeList.get(i).getBrandName()); + } + + sub_axe_spin.setAdapter(sub_axe_name_adapter); + sub_axe_name_adapter.setDropDownViewResource(R.layout.spinner_custom_item); + + } + + + final int FILTER_FOR_AXE = 2; + final int FILTER_FOR_SUBAXE = 3; + + boolean isDataAdded = false; + + @Override + public void onBackPressed() { + //super.onBackPressed(); + isChanged(); + } + + void isChanged() { + if (isDataAdded) { + android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(this); + builder.setTitle("Parinaam"); + builder.setMessage(getResources().getString(R.string.data_will_be_lost)).setCancelable(false) + .setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { + + finish(); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + } + }) + .setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + + } + }); + android.app.AlertDialog alert = builder.create(); + alert.show(); + } else { + super.onBackPressed(); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + } + } + + @SuppressLint("UseCompatLoadingForDrawables") + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + Log.i("MakeMachine", "resultCode: " + resultCode); + + if (requestCode == 131) { + switch (resultCode) { + + case 0: + Log.i("MakeMachine", "User cancelled"); + break; + + case -1: + if (_pathforcheck != null && !_pathforcheck.isEmpty()) { + if (new File(CommonString.getImagesFolder(context) + _pathforcheck).exists()) { + convertBitmap(CommonString.getImagesFolder(context) + _pathforcheck); + isDataAdded = true; + globalChildObject.setImagePath(_pathforcheck); + groupPositionGlobal = -1; + childPositionGlobal = -1; + _pathforcheck = ""; + listAdapter.notifyDataSetChanged(); + } + } + break; + } + } else { + IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data); + switch (resultCode) { + case 0: + break; + + case -1: + db.open(); + ArrayList productList = db.getsku_fromproductusing_eancode(result.getContents(), false, visit_date, counter_id, null); + + if (productList.isEmpty()) { + db.open(); + productList = db.getsku_fromproductusing_eancode(removeFirstChar(result.getContents()), false, visit_date, counter_id, null); + } + + if (!productList.isEmpty()) { + flagScan = false; + img_scan.setImageDrawable(getResources().getDrawable(R.mipmap.ok)); + clearFilters(); + setScanFilter(productList); + + } else { + AlertandMessages.showToastMsg(context, "Unable To Scan Correct Data. Please Try Again."); + } + break; + } + } + + super.onActivityResult(requestCode, resultCode, data); + } + + //filter bottom sheet + View showFilterBottomSheet() { + String uniqueId = UUID.randomUUID().toString(); + final CardView cardSignature, cardBrand, cardSubBrand, cardReference; + final BottomSheetDialog mBottomSheetDialog = new BottomSheetDialog(this); + @SuppressLint("InflateParams") final View sheetView = getLayoutInflater().inflate(R.layout.filter_bottom_sheet, null); + mBottomSheetDialog.setContentView(sheetView); + View bottomSheet = mBottomSheetDialog.getWindow().findViewById(com.google.android.material.R.id.design_bottom_sheet); + if (bottomSheet != null) { + bottomSheet.setBackgroundResource(android.R.color.transparent); + } + mBottomSheetDialog.setCancelable(false); + + final RecyclerView recBrand = sheetView.findViewById(R.id.rec_brand); + ImageView img_cancel = sheetView.findViewById(R.id.img_cancel); + TextView tv_clear_filter = sheetView.findViewById(R.id.tv_clear_filter); + recBrand.setAdapter(new ValueAdapter(context, signatureList, CommonString.Signature)); + recBrand.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, true)); + + cardSignature = sheetView.findViewById(R.id.card_signature); + cardBrand = sheetView.findViewById(R.id.card_brand); + cardSubBrand = sheetView.findViewById(R.id.card_sub_brand); + cardReference = sheetView.findViewById(R.id.card_reference); + + cardSignature.setOnClickListener(this); + cardBrand.setOnClickListener(this); + cardSubBrand.setOnClickListener(this); + cardReference.setOnClickListener(this); + + cardSignature.setCardBackgroundColor(getResources().getColor(R.color.dashboard_ach)); + + if (selectedSignature != null) { + (sheetView.findViewById(R.id.img_filter_signature)).setVisibility(View.VISIBLE); + } + if (selectedBrand != null) { + (sheetView.findViewById(R.id.img_filter_brand)).setVisibility(View.VISIBLE); + } + if (selectedSubBrand != null) { + (sheetView.findViewById(R.id.img_filter_sub_brand)).setVisibility(View.VISIBLE); + } + if (selectedReference != null) { + (sheetView.findViewById(R.id.img_filter_reference)).setVisibility(View.VISIBLE); + } + + img_cancel.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + mBottomSheetDialog.cancel(); + } + }); + + tv_clear_filter.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + setFilter(CLEAR_FILTER); + selectedSignature = null; + selectedBrand = null; + selectedSubBrand = null; + selectedReference = null; + + cardSignature.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background)); + cardBrand.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background)); + cardSubBrand.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background)); + cardReference.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background)); + + (sheetView.findViewById(R.id.img_filter_signature)).setVisibility(View.GONE); + (sheetView.findViewById(R.id.img_filter_brand)).setVisibility(View.GONE); + (sheetView.findViewById(R.id.img_filter_sub_brand)).setVisibility(View.GONE); + (sheetView.findViewById(R.id.img_filter_reference)).setVisibility(View.GONE); + + db.open(); + brandList = db.getsub_brand_name(counterGroupId, "BrandName", false); + db.open(); + subBrandList = db.getsub_brand_name(counterGroupId, "SubBrandName", false); + db.open(); + referenceList = db.getsub_brand_name(counterGroupId, "ReferenceName", false); + db.open(); + signatureList = db.getsub_brand_name(counterGroupId, "SignatureName", false); + + Objects.requireNonNull(recBrand.getAdapter()).notifyDataSetChanged(); + } + }); + + mBottomSheetDialog.show(); + + return sheetView; + } + + private class ValueAdapter extends RecyclerView.Adapter { + LayoutInflater inflator; + List data; + String type; + + public ValueAdapter(Context context, List data, String type) { + inflator = LayoutInflater.from(context); + this.data = data; + this.type = type; + } + + @NonNull + @Override + public ValueAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) { + View view = inflator.inflate(R.layout.item_filter, parent, false); + return new ValueAdapter.MyViewHolder(view); + } + + @Override + public void onBindViewHolder(@NonNull final ValueAdapter.MyViewHolder holder, final int position) { + final ProductMaster current = data.get(position); + + final boolean[] selected = {false}; + final int[] filterId = {0}; + + switch (type) { + + case CommonString.Signature: + if (selectedSignature != null && selectedSignature == current) { + selected[0] = true; + } + + break; + + case CommonString.Brand: + if (selectedBrand != null && selectedBrand == current) { + selected[0] = true; + } + + break; + + case CommonString.SubBrand: + if (selectedSubBrand != null && selectedSubBrand == current) { + selected[0] = true; + } + + break; + + case CommonString.Reference: + if (selectedReference != null && selectedReference == current) { + selected[0] = true; + } + + break; + } + + holder.tv_item.setText(CommonFunctions.capitalizeFirstLetter(current.getBrandName())); + + holder.tv_item.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + et_search.setText(""); + switch (type) { + case CommonString.Signature: + selectedSignature = current; + filterId[0] = R.id.img_filter_signature; + + //clear other sub filters-- + selectedBrand = null; + selectedSubBrand = null; + selectedReference = null; + + (sheetView.findViewById(R.id.img_filter_brand)).setVisibility(View.GONE); + (sheetView.findViewById(R.id.img_filter_sub_brand)).setVisibility(View.GONE); + (sheetView.findViewById(R.id.img_filter_reference)).setVisibility(View.GONE); + //-- + + setFilter(FILTER_FOR_SIGNATURE); + db.open(); + brandList = db.getSubBrandOrReference(counterGroupId, "BrandName", current.getBrandName(), null, null, false); + db.open(); + subBrandList = db.getSubBrandOrReference(counterGroupId, "SubBrandName", current.getBrandName(), null, null, false); + db.open(); + referenceList = db.getSubBrandOrReference(counterGroupId, "ReferenceName", current.getBrandName(), null, null, false); + + break; + case CommonString.Brand: + selectedBrand = current; + filterId[0] = R.id.img_filter_brand; + + //clear other sub filters-- + selectedSubBrand = null; + selectedReference = null; + + (sheetView.findViewById(R.id.img_filter_sub_brand)).setVisibility(View.GONE); + (sheetView.findViewById(R.id.img_filter_reference)).setVisibility(View.GONE); + //-- + + setFilter(FILTER_FOR_BRAND); + db.open(); + subBrandList = db.getSubBrandOrReference(counterGroupId, "SubBrandName", "", current.getBrandName(), null, false); + db.open(); + referenceList = db.getSubBrandOrReference(counterGroupId, "ReferenceName", "", current.getBrandName(), null, false); + break; + case CommonString.SubBrand: + selectedSubBrand = current; + filterId[0] = R.id.img_filter_sub_brand; + //clear other sub filters-- + selectedReference = null; + (sheetView.findViewById(R.id.img_filter_reference)).setVisibility(View.GONE); + setFilter(FILTER_FOR_SUB_BRAND); + db.open(); + referenceList = db.getSubBrandOrReference(counterGroupId, "ReferenceName", "", null, current.getBrandName(), false); + break; + + case CommonString.Reference: + selectedReference = current; + filterId[0] = R.id.img_filter_reference; + + setFilter(FILTER_FOR_REFERENCE); + break; + } + + RecyclerView recSubBrand = sheetView.findViewById(R.id.rec_brand); + recSubBrand.getAdapter().notifyDataSetChanged(); + //show filter icon on filter selected + (sheetView.findViewById(filterId[0])).setVisibility(View.VISIBLE); + } + }); + + if (selected[0]) { + holder.card.setCardBackgroundColor(getResources().getColor(R.color.dashboard_ach)); + } else { + holder.card.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background)); + } + } + + @Override + public int getItemCount() { + return data.size(); + } + + class MyViewHolder extends RecyclerView.ViewHolder { + TextView tv_item; + CardView card; + + public MyViewHolder(View itemView) { + super(itemView); + tv_item = (TextView) itemView.findViewById(R.id.tv_item); + card = (CardView) itemView.findViewById(R.id.item_card); + } + } + } + + void setFilterSelected(View sheetView, String type) { + CardView cardSignature, cardBrand, cardSubBrand, cardReference; + cardSignature = sheetView.findViewById(R.id.card_signature); + cardBrand = sheetView.findViewById(R.id.card_brand); + cardSubBrand = sheetView.findViewById(R.id.card_sub_brand); + cardReference = sheetView.findViewById(R.id.card_reference); + + cardSignature.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background)); + cardBrand.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background)); + cardSubBrand.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background)); + cardReference.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background)); + + switch (type) { + case CommonString.Signature: + cardSignature.setCardBackgroundColor(getResources().getColor(R.color.dashboard_ach)); + break; + case CommonString.Brand: + cardBrand.setCardBackgroundColor(getResources().getColor(R.color.dashboard_ach)); + break; + case CommonString.SubBrand: + cardSubBrand.setCardBackgroundColor(getResources().getColor(R.color.dashboard_ach)); + break; + case CommonString.Reference: + cardReference.setCardBackgroundColor(getResources().getColor(R.color.dashboard_ach)); + break; + } + } + + public ArrayList filterListForSignature(List originalList, String text) { + ArrayList filterList = new ArrayList<>(); + for (ProductMaster object : originalList) { + if (object.getSignatureName().equalsIgnoreCase(text)) { + filterList.add(object); + } else { + continue; + } + } + return filterList; + } + + public ArrayList filterListForSubBrand(List originalList, String text) { + ArrayList filterList = new ArrayList<>(); + for (ProductMaster object : originalList) { + if (object.getSubBrandName().equalsIgnoreCase(text) && (selectedSignature == null || object.getSignatureName().equalsIgnoreCase(selectedSignature.getBrandName())) && (selectedBrand == null || object.getBrandName().equalsIgnoreCase(selectedBrand.getBrandName()))) { + filterList.add(object); + } else { + continue; + } + } + return filterList; + } + + public ArrayList filterListForReference(List originalList, String text) { + ArrayList filterList = new ArrayList<>(); + for (ProductMaster object : originalList) { + if (object.getReferenceName().equalsIgnoreCase(text) && (selectedSignature == null || object.getSignatureName().equalsIgnoreCase(selectedSignature.getBrandName())) + && (selectedBrand == null || object.getBrandName().equalsIgnoreCase(selectedBrand.getBrandName())) && (selectedSubBrand == null || object.getSubBrandName().equalsIgnoreCase(selectedSubBrand.getBrandName()))) { + filterList.add(object); + } else { + continue; + } + } + return filterList; + } + + public void setFilter(int filterType) { + if (filterType == FILTER_FOR_SIGNATURE) { + listAdapter = new ExpandableListAdapter(context, filterListForSignature(listDataHeader, selectedSignature.getBrandName()), listDataChild); + } else if (filterType == FILTER_FOR_BRAND) { + listAdapter = new ExpandableListAdapter(context, filterListForBrand(listDataHeader, selectedBrand.getBrandName()), listDataChild); + } else if (filterType == FILTER_FOR_SUB_BRAND) { + listAdapter = new ExpandableListAdapter(context, filterListForSubBrand(listDataHeader, selectedSubBrand.getBrandName()), listDataChild); + } else if (filterType == FILTER_FOR_REFERENCE) { + listAdapter = new ExpandableListAdapter(context, filterListForReference(listDataHeader, selectedReference.getBrandName()), listDataChild); + } else { + listAdapter = new ExpandableListAdapter(context, listDataHeader, listDataChild); + } + + lvExp_stock_check.setAdapter(listAdapter); + listAdapter.notifyDataSetChanged(); + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + getMenuInflater().inflate(R.menu.filter_menu, menu); + return super.onCreateOptionsMenu(menu); + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // Handle action bar item clicks here. The action bar will + // automatically handle clicks on the Home/Up button, so long + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + + if (id == android.R.id.home) { + isChanged(); + + } else if (id == R.id.filter_data) { + sheetView = showFilterBottomSheet(); + } + + return super.onOptionsItemSelected(item); + } + + private void openScanner() { + IntentIntegrator intentIntegrator = new IntentIntegrator((Activity) context); + intentIntegrator.setBeepEnabled(true); + intentIntegrator.setOrientationLocked(false); + intentIntegrator.setPrompt("Scan the barcode or QR code to get the data"); + intentIntegrator.initiateScan(); + } + + + public void setScanFilter(List scanList) { + + HashMap> filterChildHashMap = new HashMap<>(); + + ArrayList filterList = new ArrayList<>(); + for (int i = 0; i < listDataHeader.size(); i++) { + ProductMaster parent = listDataHeader.get(i); + List listChild = listDataChild.get(parent); + List listFilterChild = new ArrayList<>(); + for (int j = 0; j < listChild.size(); j++) { + if (containsProduct(scanList, listChild.get(j))) { + listFilterChild.add(listChild.get(j)); + } else { + continue; + } + } + + if (listFilterChild.size() > 0) { + filterList.add(parent); + filterChildHashMap.put(parent, listFilterChild); + + } + + } + + ExpandableListAdapter listAdapter1 = new ExpandableListAdapter(context, filterList, filterChildHashMap); + lvExp_stock_check.setAdapter(listAdapter1); + + for (int i = 0; i < listAdapter1.getGroupCount(); i++) { + lvExp_stock_check.expandGroup(i); + } + + listAdapter1.notifyDataSetChanged(); + + + } + + boolean containsProduct(List scanList, ProductMaster obj) { + boolean contains = false; + + for (int i = 0; i < scanList.size(); i++) { + if (scanList.get(i).getProductId().equals(obj.getProductId())) { + contains = true; + break; + } + } + + return contains; + } + + void clearFilters() { + et_search.setText(""); + + setFilter(CLEAR_FILTER); + selectedSignature = null; + selectedBrand = null; + selectedSubBrand = null; + selectedReference = null; + + if (sheetView != null) { + (sheetView.findViewById(R.id.img_filter_signature)).setVisibility(View.GONE); + (sheetView.findViewById(R.id.img_filter_brand)).setVisibility(View.GONE); + (sheetView.findViewById(R.id.img_filter_sub_brand)).setVisibility(View.GONE); + (sheetView.findViewById(R.id.img_filter_reference)).setVisibility(View.GONE); + } + + db.open(); + brandList = db.getsub_brand_name(counterGroupId, "BrandName", false); + db.open(); + subBrandList = db.getsub_brand_name(counterGroupId, "SubBrandName", false); + db.open(); + referenceList = db.getsub_brand_name(counterGroupId, "ReferenceName", false); + db.open(); + signatureList = db.getsub_brand_name(counterGroupId, "SignatureName", false); + } + + public void uploadData() { + //download service + // Intent intent = new Intent(context, Downloader.class); + SaleableGetterSetter stock = new SaleableGetterSetter(); + ArrayList data = new ArrayList<>(); + for (int i = 0; i < listDataHeader.size(); i++) { + List list = listDataChild.get(listDataHeader.get(i)); + for (int j = 0; j < list.size(); j++) { + if (list.get(j).isSelected()) { + list.get(j).setImagePath(listDataHeader.get(i).getImagePath()); + data.add(list.get(j)); + } + } + } + + if (data.size() > 0) { + stock.setProductList(data); + String uuid = CommonFunctions.getUUID(context); + stock.setTransactionId(uuid); + db.open(); + db.insertStockTransactionMasterData(counter_id, visit_date, username, CommonString.DAMAGE, stock, "Regular_Stock"); + + /*intent.putExtra(CommonString.DAMAGE, stock); + String status = null; + intent.putExtra(CommonString.KEY_STATUS, status); + Downloader.enqueueWork(context, intent);*/ + dialog.cancel(); + CommonFunctions.call_upload(context); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + DamagedActivity.this.finish(); + } + } + + private Dialog dialog; + ProgressBar pb; + + class LoadAsync extends AsyncTask { + @Override + protected void onPreExecute() { + dialog = new Dialog(context); + dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); + dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT)); + dialog.setContentView(R.layout.circular_progress_bar); + pb = (ProgressBar) dialog.findViewById(R.id.progressBar1); + dialog.setCancelable(false); + dialog.show(); + super.onPreExecute(); + } + + @Override + protected Void doInBackground(Void... voids) { + //validateUIData(); + prepareListData(); + return null; + } + + @Override + protected void onPostExecute(Void aVoid) { + dialog.cancel(); + recSubAxe.setLayoutManager(new GridLayoutManager(DamagedActivity.this, 3)); + subAxeValueAdapter = new SubAxeValueAdapter(context, listSubAxe, CommonString.Signature); + recSubAxe.setAdapter(subAxeValueAdapter); + recSubAxe.getAdapter().notifyDataSetChanged(); + + //validate_spin_ui_data(); + listAdapter = new ExpandableListAdapter(context, listDataHeader, listDataChild); + lvExp_stock_check.setAdapter(listAdapter); + + db.open(); + JourneyPlan jcp = db.getJCP(); + if (jcp != null) { + counterGroupId = jcp.getCounterGroupId().toString(); + } else { + counterGroupId = "1"; + } + + if (damaged_category_str != null && damaged_category_str.equals("0")) { + if (listDataHeader.size() > 0) { + rl_total_qty.setVisibility(View.VISIBLE); + txt_total_qty.setText("Return Total QTY : " + calculate_total_qty()); + txt_total_value.setText("Return Total Values : " + calculate_total_sale_value()); + } else { + rl_total_qty.setVisibility(View.GONE); + } + } else if (damaged_category_str != null && damaged_category_str.equals("1")) { + rl_total_qty.setVisibility(View.GONE); + } + + super.onPostExecute(aVoid); + } + } + + void dialogFinalSubmit(final boolean returntodistr) { + android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(DamagedActivity.this); + builder.setTitle(R.string.parinaam); + if (returntodistr) { + builder.setMessage(getResources().getString(R.string.want_to_final_savedamage)); + } else { + builder.setMessage(getResources().getString(R.string.want_to_final_damage_save)); + } + builder.setCancelable(false) + .setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog1, int id) { + show_dialog_for_final_submit(context, returntodistr); + + } + }).setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + dialog.dismiss(); + + } + }); + android.app.AlertDialog alert = builder.create(); + alert.show(); + } + + private class SubAxeValueAdapter extends RecyclerView.Adapter { + private LayoutInflater inflator; + List data; + String type; + + public String getType() { + return type; + } + + private SubAxeValueAdapter(Context context, List data, String type) { + inflator = LayoutInflater.from(context); + this.data = data; + this.type = type; + } + + @NonNull + @Override + public SubAxeValueAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) { + View view = inflator.inflate(R.layout.item_filter, parent, false); + return new SubAxeValueAdapter.MyViewHolder(view); + } + + @Override + public void onBindViewHolder(final SubAxeValueAdapter.MyViewHolder holder, final int position) { + final ProductMaster current = data.get(position); + + holder.tv_item.setText(CommonFunctions.capitalizeFirstLetter(current.getSubAxeName())); + + holder.tv_item.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + et_search.setText(""); + listAdapter = new ExpandableListAdapter(context, filterListForSubAxe(listDataHeader, current.getSubAxeName()), listDataChild); + lvExp_stock_check.setAdapter(listAdapter); + listAdapter.notifyDataSetChanged(); + + current.setSelected(true); + selectedSubAxe = current.getSubAxeName(); + subAxeValueAdapter.notifyDataSetChanged(); + + JourneyPlan jcp = db.getJCP(); + if (jcp != null) { + db.open(); + brandList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "BrandName", false, selectedSubAxe); + db.open(); + subBrandList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "SubBrandName", false, selectedSubAxe); + db.open(); + referenceList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "ReferenceName", false, selectedSubAxe); + db.open(); + signatureList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "SignatureName", false, selectedSubAxe); + } else { + db.open(); + brandList = db.getsub_brand_name("1", "BrandName", false, selectedSubAxe); + db.open(); + subBrandList = db.getsub_brand_name("1", "SubBrandName", false, selectedSubAxe); + db.open(); + referenceList = db.getsub_brand_name("1", "ReferenceName", false, selectedSubAxe); + db.open(); + signatureList = db.getsub_brand_name("1", "SignatureName", false, selectedSubAxe); + } + } + }); + + if (current.getSubAxeName().equalsIgnoreCase(selectedSubAxe)) { + holder.card.setCardBackgroundColor(getColor(R.color.dashboard_ach)); + } else { + holder.card.setCardBackgroundColor(getColor(R.color.grey_dark_background)); + } + + } + + @Override + public int getItemCount() { + return data.size(); + } + + class MyViewHolder extends RecyclerView.ViewHolder { + TextView tv_item; + CardView card; + + public MyViewHolder(View itemView) { + super(itemView); + tv_item = (TextView) itemView.findViewById(R.id.tv_item); + card = (CardView) itemView.findViewById(R.id.item_card); + + } + } + } + + public ArrayList filterListForSubAxe(List originalList, String text) { + ArrayList filterList = new ArrayList<>(); + for (ProductMaster object : originalList) { + if (object.getSubAxeName().equalsIgnoreCase(text)) { + filterList.add(object); + } else { + continue; + } + } + + return filterList; + } + + private int calculate_total_qty() { + int total_return_qty = 0; + if (listDataHeader.size() > 0) { + for (int i = 0; i < listDataHeader.size(); i++) { + List list = listDataChild.get(listDataHeader.get(i)); + for (int j = 0; j < list.size(); j++) { + + total_return_qty = total_return_qty + (list.get(j).getStock()); + } + } + } + + return total_return_qty; + } + + private int calculate_total_sale_value() { + int total_sale_value = 0; + if (listDataHeader.size() > 0) { + for (int i = 0; i < listDataHeader.size(); i++) { + List list = listDataChild.get(listDataHeader.get(i)); + for (int j = 0; j < list.size(); j++) { + total_sale_value = total_sale_value + (list.get(j).getStock() * list.get(j).getMrp()); + } + } + } + + return total_sale_value; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/DamagedCategoryActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/DamagedCategoryActivity.java new file mode 100644 index 0000000..52ae6b0 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/DamagedCategoryActivity.java @@ -0,0 +1,101 @@ +package com.cpm.lorealbaautomation.dailyactivity; + +import android.annotation.SuppressLint; +import android.app.AlertDialog; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; + +import androidx.appcompat.app.AppCompatActivity; + +import android.os.Bundle; + +import androidx.cardview.widget.CardView; +import androidx.appcompat.widget.Toolbar; + +import android.view.MenuItem; +import android.view.View; +import android.view.WindowManager; +import android.widget.TextView; + +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.constant.CommonFunctions; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.delegates.PrefHelper; + +public class DamagedCategoryActivity extends AppCompatActivity implements View.OnClickListener { + Lorealba_Database db; + Context context; + AlertDialog alert; + private SharedPreferences preferences; + CardView damaged_stock_img, returnto_distributor_damaged; + String counter_id, visit_date, username, _pathforcheck, _path; + + @SuppressLint("SetTextI18n") + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_damaged_category); + context = this; + ((DamagedCategoryActivity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); + preferences = PrefHelper.getPrefs(context); + counter_id = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + username = preferences.getString(CommonString.KEY_USERNAME, ""); + + returnto_distributor_damaged = (CardView) findViewById(R.id.returnto_distributor_damaged); + damaged_stock_img = (CardView) findViewById(R.id.damaged_stock_img); + + Toolbar toolbar = findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + + if (!CommonFunctions.isTablet(context)) { + toolbar.setTitleTextAppearance(context, R.style.changestext_sizefor_mobile); + } + + getSupportActionBar().setHomeButtonEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + setTitle("Damaged Stock Category - " + visit_date); + + + String couter_code = preferences.getString(CommonString.KEY_COUNTER_CODE, ""); + TextView txt_counter_code = (TextView) findViewById(R.id.txt_counter_code); + txt_counter_code.setText("Counter Code - " + couter_code + " / Id - " + counter_id); + damaged_stock_img.setOnClickListener(this); + returnto_distributor_damaged.setOnClickListener(this); + + } + + @Override + public void onClick(View view) { + if (view.getId() == R.id.damaged_stock_img) { + startActivity(new Intent(context, DamagedActivity.class).putExtra(CommonString.TAG_OBJECT, "1")); + } else if (view.getId() == R.id.returnto_distributor_damaged) { + startActivity(new Intent(context, DamagedActivity.class).putExtra(CommonString.TAG_OBJECT, "0")); + } + + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + if (id == android.R.id.home) { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + DamagedCategoryActivity.this.finish(); + + } + + + return super.onOptionsItemSelected(item); + } + + @Override + public void onBackPressed() { + super.onBackPressed(); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + DamagedCategoryActivity.this.finish(); + + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/FilledRegularStockDataActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/FilledRegularStockDataActivity.java new file mode 100644 index 0000000..1797b2b --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/FilledRegularStockDataActivity.java @@ -0,0 +1,1507 @@ +package com.cpm.lorealbaautomation.dailyactivity; + +import android.annotation.SuppressLint; +import android.app.Activity; +import android.app.AlertDialog; +import android.app.Dialog; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.graphics.drawable.ColorDrawable; +import android.os.AsyncTask; +import android.os.Build; + +import androidx.annotation.RequiresApi; + +import com.google.android.material.bottomsheet.BottomSheetDialog; +import com.google.android.material.floatingactionbutton.FloatingActionButton; + +import androidx.core.content.ContextCompat; +import androidx.appcompat.app.AppCompatActivity; + +import android.os.Bundle; + +import androidx.cardview.widget.CardView; +import androidx.recyclerview.widget.GridLayoutManager; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; +import androidx.appcompat.widget.Toolbar; + +import android.text.Editable; +import android.text.TextWatcher; +import android.util.Log; +import android.view.LayoutInflater; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; +import android.view.Window; +import android.view.WindowManager; +import android.view.inputmethod.InputMethodManager; +import android.widget.AbsListView; +import android.widget.AdapterView; +import android.widget.BaseExpandableListAdapter; +import android.widget.Button; +import android.widget.EditText; +import android.widget.ExpandableListView; +import android.widget.ImageView; +import android.widget.LinearLayout; +import android.widget.ProgressBar; +import android.widget.Spinner; +import android.widget.TextView; + +import com.google.zxing.integration.android.IntentIntegrator; +import com.google.zxing.integration.android.IntentResult; +import com.journeyapps.barcodescanner.CaptureActivity; +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.adapter.ReasonSpinnerAdapter; +import com.cpm.lorealbaautomation.constant.AlertandMessages; +import com.cpm.lorealbaautomation.constant.CommonFunctions; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.gsonGetterSetter.JourneyPlan; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterNonStockReason; +import com.cpm.lorealbaautomation.gsonGetterSetter.ProductMaster; + +import java.io.File; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +import static com.cpm.lorealbaautomation.constant.CommonFunctions.getCurrentTime; +import static com.cpm.lorealbaautomation.constant.CommonFunctions.removeFirstChar; +import static com.cpm.lorealbaautomation.dailyactivity.StoreImageActivity.convertBitmap; + +public class FilledRegularStockDataActivity extends AppCompatActivity implements View.OnClickListener { + Spinner sku_spin, brand_spin, sub_axe_spin, axe_spin; + ArrayList brandList = new ArrayList<>(); + ArrayList subBrandList = new ArrayList<>(); + ArrayList referenceList = new ArrayList<>(); + ArrayList signatureList = new ArrayList<>(); + ExpandableListView lvExp_stock_check; + FloatingActionButton fab_save, fab_draft; + Lorealba_Database db; + Context context; + AlertDialog alert; + private SharedPreferences preferences; + String counter_id, visit_date, username, _pathforcheck, _path; + ArrayList listDataHeader = new ArrayList<>(); + ArrayList childStockList = new ArrayList<>(); + HashMap> listDataChild; + boolean checkflag = true; + ArrayList checkHeaderArray = new ArrayList<>(); + ExpandableListAdapter listAdapter; + String brandName = ""; + String axeName = ""; + String subAxeName = ""; + + int groupPositionGlobal = -1; + ProductMaster globalHeaderObject = new ProductMaster(); + + EditText et_search; + boolean regularStockFlag = false; + View sheetView; + ProductMaster selectedSignature, selectedBrand, selectedSubBrand, selectedReference; + ImageView img_scan, img_clear_subaxe, img_unfilled; + boolean flagScan = true; + String counterGroupId; + RecyclerView recSubAxe; + String selectedSubAxe = "", activity_name = ""; + SubAxeValueAdapter subAxeValueAdapter; + ArrayList listSubAxe; + CardView card_view_only; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_filled_regular_stock_data); + context = this; + ((FilledRegularStockDataActivity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); + db = new Lorealba_Database(context); + db.open(); + + activity_name = getIntent().getStringExtra(CommonString.KEY_ACTIVITY); + + validateUIData(); + new LoadAsync().execute(); + } + + JourneyPlan jcp; + + private void validateUIData() { + preferences = PrefHelper.getPrefs(context); + counter_id = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + username = preferences.getString(CommonString.KEY_USERNAME, ""); + Toolbar toolbar = findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + + if (!CommonFunctions.isTablet(context)) { + toolbar.setTitleTextAppearance(context, R.style.changestext_sizefor_mobile); + } + + + getSupportActionBar().setHomeButtonEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + if (activity_name != null && !activity_name.equals("") && activity_name.equalsIgnoreCase("StockCheck")) { + setTitle("Filled Stock Check - " + visit_date); + } else { + setTitle("Filled Tester Check - " + visit_date); + } + + sku_spin = (Spinner) findViewById(R.id.sku_spin); + brand_spin = (Spinner) findViewById(R.id.stock_brand_spin); + sub_axe_spin = (Spinner) findViewById(R.id.sub_axe_spin); + axe_spin = (Spinner) findViewById(R.id.axe_spin); + lvExp_stock_check = (ExpandableListView) findViewById(R.id.lvExp_stock_check); + fab_save = (FloatingActionButton) findViewById(R.id.save_fab); + fab_draft = (FloatingActionButton) findViewById(R.id.draft_fab); + et_search = (EditText) findViewById(R.id.et_search); + img_scan = (ImageView) findViewById(R.id.img_scan); + img_unfilled = (ImageView) findViewById(R.id.img_unfilled); + img_clear_subaxe = (ImageView) findViewById(R.id.img_clear_subaxe); + ImageView img_filter = (ImageView) findViewById(R.id.img_filter); + recSubAxe = (RecyclerView) findViewById(R.id.rec_subaxe); + card_view_only = (CardView) findViewById(R.id.card_view_only); + fab_save.setOnClickListener(this); + fab_draft.setOnClickListener(this); + db.open(); + + img_filter.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + sheetView = showFilterBottomSheet(); + } + }); + + et_search.addTextChangedListener(new TextWatcher() { + @Override + public void beforeTextChanged(CharSequence s, int start, int count, int after) { + } + + @Override + public void onTextChanged(CharSequence s, int start, int before, int count) { + + String text = s.toString(); + if (text.equals("")) { + lvExp_stock_check.setAdapter(listAdapter); + listAdapter.notifyDataSetChanged(); + } else { + lvExp_stock_check.invalidate(); + setSearchFilter(listAdapter.get_listDataHeader(), text, listAdapter.get_listDataChild()); + } + } + + @Override + public void afterTextChanged(Editable s) { + String text = s.toString(); + } + }); + + img_scan.setOnClickListener(this); + ///changes icon + img_unfilled.setOnClickListener(this); + img_clear_subaxe.setOnClickListener(this); + img_unfilled.setVisibility(View.GONE); + + String status = ""; + if (activity_name != null && !activity_name.equals("") && activity_name.equalsIgnoreCase("StockCheck")) { + status = db.getStatus(CommonString.KEY_SaleableStatus, counter_id); + } else { + status = db.getStatus(CommonString.KEY_TesterStatus, counter_id); + } + + //if regular stock need to be captured after First stock capture + if (status != null && !status.equals("") && status.equalsIgnoreCase("Complete")) { + fab_save.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.save_icon)); + regularStockFlag = true; + fab_draft.hide(); + } + + card_view_only.setVisibility(View.VISIBLE); + } + + View showFilterBottomSheet() { + final CardView cardSignature, cardBrand, cardSubBrand, cardReference; + final BottomSheetDialog mBottomSheetDialog = new BottomSheetDialog(this); + final View sheetView = getLayoutInflater().inflate(R.layout.filter_bottom_sheet, null); + mBottomSheetDialog.setContentView(sheetView); + View bottomSheet = mBottomSheetDialog.getWindow().findViewById(com.google.android.material.R.id.design_bottom_sheet); + if (bottomSheet != null) { + bottomSheet.setBackgroundResource(android.R.color.transparent); + } + mBottomSheetDialog.setCancelable(false); + + final RecyclerView recBrand = sheetView.findViewById(R.id.rec_brand); + ImageView img_cancel = sheetView.findViewById(R.id.img_cancel); + TextView tv_clear_filter = sheetView.findViewById(R.id.tv_clear_filter); + recBrand.setAdapter(new ValueAdapter(context, signatureList, CommonString.Signature)); + recBrand.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, true)); + + cardSignature = sheetView.findViewById(R.id.card_signature); + cardBrand = sheetView.findViewById(R.id.card_brand); + cardSubBrand = sheetView.findViewById(R.id.card_sub_brand); + cardReference = sheetView.findViewById(R.id.card_reference); + + cardSignature.setOnClickListener(this); + cardBrand.setOnClickListener(this); + cardSubBrand.setOnClickListener(this); + cardReference.setOnClickListener(this); + + cardSignature.setCardBackgroundColor(getResources().getColor(R.color.dashboard_ach)); + + if (selectedSignature != null) { + (sheetView.findViewById(R.id.img_filter_signature)).setVisibility(View.VISIBLE); + } + if (selectedBrand != null) { + (sheetView.findViewById(R.id.img_filter_brand)).setVisibility(View.VISIBLE); + } + if (selectedSubBrand != null) { + (sheetView.findViewById(R.id.img_filter_sub_brand)).setVisibility(View.VISIBLE); + } + if (selectedReference != null) { + (sheetView.findViewById(R.id.img_filter_reference)).setVisibility(View.VISIBLE); + } + + img_cancel.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + mBottomSheetDialog.cancel(); + } + }); + + tv_clear_filter.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + clearFilters(); + cardSignature.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background)); + cardBrand.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background)); + cardSubBrand.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background)); + cardReference.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background)); + ValueAdapter adapter = (ValueAdapter) recBrand.getAdapter(); + String type = adapter.getType(); + ArrayList list = new ArrayList<>(); + switch (type) { + case CommonString.Signature: + list = signatureList; + break; + case CommonString.Brand: + list = brandList; + break; + case CommonString.SubBrand: + list = subBrandList; + break; + case CommonString.Reference: + list = referenceList; + break; + } + recBrand.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, true)); + recBrand.setAdapter(new ValueAdapter(context, list, CommonString.Signature)); + recBrand.getAdapter().notifyDataSetChanged(); + + } + }); + + mBottomSheetDialog.show(); + + return sheetView; + } + + private void prepareListData() { + db.open(); + jcp = db.getJCP(); + if (jcp != null) { + listSubAxe = db.getSubAxe(jcp.getCounterGroupId().toString(), true); + } else { + listSubAxe = db.getSubAxe("1", true); + } + + listDataHeader = new ArrayList<>(); + listDataChild = new HashMap<>(); + + //inserted data + db.open(); + db.open(); + jcp = db.getJCP(); + if (jcp != null) { + listDataHeader = db.getFunctionforFilledName(jcp.getCounterGroupId().toString(), selectedSubAxe, activity_name); + } else { + listDataHeader = db.getStockSignatureBrandSubBrandReferenceforfilled("1", activity_name); + } + + jcp = db.getJCP(); + if (jcp != null) { + db.open(); + brandList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "BrandName", false, selectedSubAxe); + subBrandList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "SubBrandName", false, selectedSubAxe); + referenceList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "ReferenceName", false, selectedSubAxe); + signatureList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "SignatureName", false, selectedSubAxe); + } else { + brandList = db.getsub_brand_name("1", "BrandName", false, selectedSubAxe); + subBrandList = db.getsub_brand_name("1", "SubBrandName", false, selectedSubAxe); + referenceList = db.getsub_brand_name("1", "ReferenceName", false, selectedSubAxe); + signatureList = db.getsub_brand_name("1", "SignatureName", false, selectedSubAxe); + } + + + if (listDataHeader.size() > 0) { + for (int i = 0; i < listDataHeader.size(); i++) { + db.open(); + JourneyPlan jcp = db.getJCP(); + if (jcp != null) { + db.open(); + childStockList = db.getDefaultStockOnFunctionDataforFilled(listDataHeader.get(i).getNuanceName(), counter_id, activity_name); + } else { + childStockList = db.getDefaultStockOnFunctionDataforFilled(listDataHeader.get(i).getNuanceName(), counter_id, activity_name); + } + + listDataChild.put(listDataHeader.get(i), childStockList); // Header, Child data + } + + } + + } + + void setFilterSelected(View sheetView, String type) { + CardView cardSignature, cardBrand, cardSubBrand, cardReference; + cardSignature = sheetView.findViewById(R.id.card_signature); + cardBrand = sheetView.findViewById(R.id.card_brand); + cardSubBrand = sheetView.findViewById(R.id.card_sub_brand); + cardReference = sheetView.findViewById(R.id.card_reference); + + cardSignature.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background)); + cardBrand.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background)); + cardSubBrand.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background)); + cardReference.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background)); + + switch (type) { + case CommonString.Signature: + cardSignature.setCardBackgroundColor(getResources().getColor(R.color.dashboard_ach)); + break; + case CommonString.Brand: + cardBrand.setCardBackgroundColor(getResources().getColor(R.color.dashboard_ach)); + break; + case CommonString.SubBrand: + cardSubBrand.setCardBackgroundColor(getResources().getColor(R.color.dashboard_ach)); + break; + case CommonString.Reference: + cardReference.setCardBackgroundColor(getResources().getColor(R.color.dashboard_ach)); + break; + } + } + + @Override + public void onClick(View view) { + + if (view.getId() == R.id.card_signature) { + RecyclerView recSignature = sheetView.findViewById(R.id.rec_brand); + recSignature.setAdapter(new ValueAdapter(context, signatureList, CommonString.Signature)); + recSignature.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, true)); + setFilterSelected(sheetView, CommonString.Signature); + } else if (view.getId() == R.id.card_brand) { + + RecyclerView recBrand = sheetView.findViewById(R.id.rec_brand); + recBrand.setAdapter(new ValueAdapter(context, brandList, CommonString.Brand)); + recBrand.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, true)); + setFilterSelected(sheetView, CommonString.Brand); + } else if (view.getId() == R.id.card_sub_brand) { + + RecyclerView recSubBrand = sheetView.findViewById(R.id.rec_brand); + recSubBrand.setAdapter(new ValueAdapter(context, subBrandList, CommonString.SubBrand)); + recSubBrand.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, true)); + recSubBrand.getAdapter().notifyDataSetChanged(); + setFilterSelected(sheetView, CommonString.SubBrand); + } else if (view.getId() == R.id.card_reference) { + + RecyclerView recReference = sheetView.findViewById(R.id.rec_brand); + recReference.setAdapter(new ValueAdapter(context, referenceList, CommonString.Reference)); + recReference.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, true)); + setFilterSelected(sheetView, CommonString.Reference); + } else if (view.getId() == R.id.img_scan) { + + if (flagScan) { + openScanner(); + } else { + img_scan.setImageDrawable(getResources().getDrawable(R.mipmap.barcode_icon)); + flagScan = true; + et_search.setText(""); + } + + } else if (view.getId() == R.id.img_unfilled) { + setUnFilledFilter(listAdapter.get_listDataHeader(), listAdapter.get_listDataChild()); + } else if (view.getId() == R.id.img_clear_subaxe) { + et_search.setText(""); + listAdapter = new ExpandableListAdapter(context, listDataHeader, listDataChild); + lvExp_stock_check.setAdapter(listAdapter); + listAdapter.notifyDataSetChanged(); + selectedSubAxe = ""; + subAxeValueAdapter.notifyDataSetChanged(); + //clear filters also + selectedSignature = null; + selectedBrand = null; + selectedSubBrand = null; + selectedReference = null; + db.open(); + brandList = db.getsub_brand_name(counterGroupId, "BrandName", false, selectedSubAxe); + subBrandList = db.getsub_brand_name(counterGroupId, "SubBrandName", false, selectedSubAxe); + referenceList = db.getsub_brand_name(counterGroupId, "ReferenceName", false, selectedSubAxe); + signatureList = db.getsub_brand_name(counterGroupId, "SignatureName", false, selectedSubAxe); + } + } + + + public ArrayList filterListForSignature(List originalList, String text) { + ArrayList filterList = new ArrayList<>(); + for (ProductMaster object : originalList) { + if (object.getSignatureName().equalsIgnoreCase(text)) { + filterList.add(object); + } else { + continue; + } + } + return filterList; + } + + public ArrayList filterListForBrand(List originalList, String text) { + ArrayList filterList = new ArrayList<>(); + for (ProductMaster object : originalList) { + + if (object.getBrandName().equalsIgnoreCase(text) && (selectedSignature == null || object.getSignatureName().equalsIgnoreCase(selectedSignature.getBrandName()))) { + filterList.add(object); + } else { + continue; + } + } + + return filterList; + } + + public ArrayList filterListForSubBrand(List originalList, String text) { + ArrayList filterList = new ArrayList<>(); + for (ProductMaster object : originalList) { + if (object.getSubBrandName().equalsIgnoreCase(text) && (selectedSignature == null || object.getSignatureName().equalsIgnoreCase(selectedSignature.getBrandName())) && (selectedBrand == null || object.getBrandName().equalsIgnoreCase(selectedBrand.getBrandName()))) { + filterList.add(object); + } else { + continue; + } + } + return filterList; + } + + public ArrayList filterListForReference(List originalList, String text) { + ArrayList filterList = new ArrayList<>(); + for (ProductMaster object : originalList) { + + if (object.getReferenceName().equalsIgnoreCase(text) && (selectedSignature == null || object.getSignatureName().equalsIgnoreCase(selectedSignature.getBrandName())) + && (selectedBrand == null || object.getBrandName().equalsIgnoreCase(selectedBrand.getBrandName())) && (selectedSubBrand == null || object.getSubBrandName().equalsIgnoreCase(selectedSubBrand.getBrandName()))) { + filterList.add(object); + } else { + continue; + } + } + return filterList; + } + + public ArrayList filterListForAxe(List originalList, String text, String brandName) { + ArrayList filterList = new ArrayList<>(); + for (ProductMaster object : originalList) { + if (object.getAxeName().equalsIgnoreCase(text) && (brandName.equals("") || object.getBrandName().equalsIgnoreCase(brandName))) { + filterList.add(object); + } else { + continue; + } + } + return filterList; + } + + public ArrayList filterListForSubAxe(List originalList, String text, String brandName, String axeName) { + ArrayList filterList = new ArrayList<>(); + for (ProductMaster object : originalList) { + if (object.getSubAxeName().equalsIgnoreCase(text) && (brandName.equals("") || object.getBrandName().equalsIgnoreCase(brandName)) && (axeName.equals("") || object.getAxeName().equalsIgnoreCase(axeName))) { + filterList.add(object); + } else { + continue; + } + } + return filterList; + } + + + public class ExpandableListAdapter extends BaseExpandableListAdapter { + private Context _context; + private List _listDataHeader; + private HashMap> _listDataChild; + + public ExpandableListAdapter(Context context, List listDataHeader, HashMap> listChildData) { + this._context = context; + this._listDataHeader = listDataHeader; + this._listDataChild = listChildData; + } + + public HashMap> get_listDataChild() { + return _listDataChild; + } + + public List get_listDataHeader() { + return _listDataHeader; + } + + @Override + public Object getChild(int groupPosition, int childPosititon) { + return this._listDataChild.get(this._listDataHeader.get(groupPosition)).get(childPosititon); + } + + @Override + public long getChildId(int groupPosition, int childPosition) { + return childPosition; + } + + @Override + public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { + + final ProductMaster childText = (ProductMaster) getChild(groupPosition, childPosition); + ViewHolder holder = null; + if (convertView == null) { + LayoutInflater infalInflater = (LayoutInflater) this._context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); + convertView = infalInflater.inflate(R.layout.item_stock_layout, null); + holder = new ViewHolder(); + holder.cardView = convertView.findViewById(R.id.card_view); + holder.ed_Stock = convertView.findViewById(R.id.ed_Stock); + holder.mrp = convertView.findViewById(R.id.mrp); + holder.stock_img_plus = convertView.findViewById(R.id.stock_img_plus); + holder.stock_img_minus = convertView.findViewById(R.id.stock_img_minus); + holder.reasonSpinner = convertView.findViewById(R.id.reason_spinner); + holder.reasonLayout = convertView.findViewById(R.id.reason_layout); + holder.et_stock = convertView.findViewById(R.id.et_stock); + convertView.setTag(holder); + + + } else { + + holder = (ViewHolder) convertView.getTag(); + } + + holder.stock_img_minus.setVisibility(View.INVISIBLE); + holder.stock_img_minus.setId(childPosition); + + holder.stock_img_plus.setVisibility(View.INVISIBLE); + holder.stock_img_plus.setId(childPosition); + + holder.reasonSpinner.setEnabled(false); + holder.reasonSpinner.setId(childPosition); + + TextView txtListChild = convertView.findViewById(R.id.lblListItem); + txtListChild.setText(childText.getProductName() + " (MRP - ₹ " + childText.getMrp() + ")"); + final ViewHolder finalHolder = holder; + + + holder.stock_img_plus.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + ((ExpandableListAdapter) lvExp_stock_check.getExpandableListAdapter()).notifyDataSetChanged(); + if (!regularStockFlag) { + String stot = finalHolder.et_stock.getText().toString().trim().replaceFirst("^0+(?!$)", ""); + if (!stot.equals("")) { + int st = Integer.parseInt(stot); + childText.setStock(st); + } + } + + int stock = childText.getStock(); + int receivedStock = childText.getStock_receive(); + + ++stock; + + if (regularStockFlag) { + if (receivedStock >= stock) { + childText.setStock(stock); + isDataAdded = true; + childText.setSelected(true); + if (receivedStock == stock) { + finalHolder.reasonLayout.setVisibility(View.GONE); + finalHolder.reasonSpinner.setSelection(0); + childText.setReasonId(0); + } + } else { + AlertandMessages.showToastMsg(context, "Stock cannot be greater than Received Stock"); + } + } else { + if (receivedStock == -1) { + childText.setStock_receive(0); + } + childText.setStock(stock); + isDataAdded = true; + childText.setSelected(true); + } + + } + }); + + + holder.stock_img_minus.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + //listAdapter.notifyDataSetChanged(); + ((ExpandableListAdapter) lvExp_stock_check.getExpandableListAdapter()).notifyDataSetChanged(); + if (!regularStockFlag) { + String stot = finalHolder.et_stock.getText().toString().trim().replaceFirst("^0+(?!$)", ""); + if (!stot.equals("")) { + int st = Integer.parseInt(stot); + childText.setStock(st); + } + } + + int stock = childText.getStock(); + int receivedStock = childText.getStock_receive(); + --stock; + if (stock >= 0) { + if (regularStockFlag && stock < receivedStock) { + finalHolder.reasonLayout.setVisibility(View.VISIBLE); + } + + childText.setStock(stock); + isDataAdded = true; + childText.setSelected(true); + + } else { + AlertandMessages.showToastMsg(context, "Stock cannot be less than 0"); + } + + } + }); + + holder.et_stock.setOnFocusChangeListener(new View.OnFocusChangeListener() { + @Override + public void onFocusChange(View v, boolean hasFocus) { + if (!hasFocus) { + final EditText caption = (EditText) v; + String stock = caption.getText().toString().replaceFirst("^0+(?!$)", ""); + if (!stock.equals("")) { + childText.setStock(Integer.parseInt(stock)); + isDataAdded = true; + childText.setSelected(true); + } else { + childText.setStock(0); + } + } + } + }); + + ArrayList reasonList = new ArrayList<>(); + db.open(); + reasonList = db.getReasonData(true); + holder.reasonSpinner.setAdapter(new ReasonSpinnerAdapter(_context, R.layout.spinner_text_view, reasonList)); + final ArrayList finalReasonList = reasonList; + holder.reasonSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { + @Override + public void onItemSelected(AdapterView adapterView, View view, int pos, long l) { + if (pos != 0) { + MasterNonStockReason obj = finalReasonList.get(pos); + childText.setReasonId(obj.getReasonId()); + } else { + childText.setReasonId(0); + } + } + + @Override + public void onNothingSelected(AdapterView adapterView) { + + } + }); + + + if (!finalReasonList.isEmpty()) { + for (int i = 0; i < finalReasonList.size(); i++) { + if (finalReasonList.get(i).getReasonId() == childText.getReasonId()) { + holder.reasonSpinner.setSelection(i); + break; + } + } + } + + + int stock = childText.getStock(); + if (!childText.isSelected() && childText.getStock() == 0) { + stock = childText.getStock_receive(); + childText.setStock(stock); + } + + if (childText.getStock() < childText.getStock_receive()) { + if (regularStockFlag) { + finalHolder.reasonLayout.setVisibility(View.VISIBLE); + finalHolder.reasonLayout.setId(childPosition); + } + } else { + finalHolder.reasonLayout.setVisibility(View.GONE); + finalHolder.reasonLayout.setId(childPosition); + } + + + holder.ed_Stock.setText("Stock - " + stock + ""); + holder.ed_Stock.setId(childPosition); + + holder.et_stock.setVisibility(View.GONE); + holder.ed_Stock.setVisibility(View.VISIBLE); + + holder.mrp.setText(" MRP = " + childText.getMrp() + ""); + holder.mrp.setId(childPosition); + + return convertView; + } + + @Override + public int getChildrenCount(int groupPosition) { + return this._listDataChild.get(this._listDataHeader.get(groupPosition)).size(); + } + + @Override + public Object getGroup(int groupPosition) { + return this._listDataHeader.get(groupPosition); + } + + @Override + public int getGroupCount() { + return this._listDataHeader.size(); + } + + @Override + public long getGroupId(int groupPosition) { + return groupPosition; + } + + @Override + public View getGroupView(final int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { + final ProductMaster headerTitle = (ProductMaster) getGroup(groupPosition); + if (convertView == null) { + + LayoutInflater infalInflater = (LayoutInflater) this._context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); + convertView = infalInflater.inflate(R.layout.list_group_stock_entry, null); + } + TextView lblListHeader = (TextView) convertView.findViewById(R.id.lblListHeader); + ImageView stock_cam = (ImageView) convertView.findViewById(R.id.stock_cam); + stock_cam.setEnabled(false); + + stock_cam.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + groupPositionGlobal = groupPosition; + globalHeaderObject = headerTitle; + _pathforcheck = counter_id + "_stock_check_img_" + visit_date.replace("/", "") + "_" + getCurrentTime().replace(":", "") + ".jpg"; + _path = CommonString.getImagesFolder(context) + _pathforcheck; + CommonFunctions.startAnncaCameraActivity(_context, _path, null, false, CommonString.CAMERA_FACE_REAR); + } + }); + + if (headerTitle.getImagePath().equals("")) { + stock_cam.setImageDrawable(getResources().getDrawable(R.mipmap.camera)); + } else { + stock_cam.setImageDrawable(getResources().getDrawable(R.mipmap.camera_tick)); + } + + lblListHeader.setText(headerTitle.getNuanceName()); + if (!checkflag) { + if (checkHeaderArray.contains(groupPosition)) { + lblListHeader.setBackgroundColor(getResources().getColor(R.color.red)); + } else { + lblListHeader.setBackgroundColor(getResources().getColor(R.color.bright_red)); + } + + } else { + lblListHeader.setBackgroundColor(getResources().getColor(R.color.bright_red)); + } + return convertView; + } + + @Override + public boolean hasStableIds() { + return false; + } + + @Override + public boolean isChildSelectable(int groupPosition, int childPosition) { + return true; + } + } + + public class ViewHolder { + TextView ed_Stock, mrp; + Button stock_img_plus, stock_img_minus; + CardView cardView; + Spinner reasonSpinner; + LinearLayout reasonLayout; + EditText et_stock; + } + + @Override + public void onDestroy() { + super.onDestroy(); + } + + + public void setFilter(int filterType) { + + if (filterType == FILTER_FOR_SIGNATURE) { + listAdapter = new ExpandableListAdapter(context, filterListForSignature(listDataHeader, selectedSignature.getBrandName()), listDataChild); + } else if (filterType == FILTER_FOR_BRAND) { + listAdapter = new ExpandableListAdapter(context, filterListForBrand(listDataHeader, selectedBrand.getBrandName()), listDataChild); + } else if (filterType == FILTER_FOR_SUB_BRAND) { + listAdapter = new ExpandableListAdapter(context, filterListForSubBrand(listDataHeader, selectedSubBrand.getBrandName()), listDataChild); + } else if (filterType == FILTER_FOR_REFERENCE) { + listAdapter = new ExpandableListAdapter(context, filterListForReference(listDataHeader, selectedReference.getBrandName()), listDataChild); + } else if (filterType == FILTER_FOR_AXE) { + listAdapter = new ExpandableListAdapter(context, filterListForAxe(listDataHeader, axeName, brandName), listDataChild); + } else if (filterType == FILTER_FOR_SUBAXE) { + listAdapter = new ExpandableListAdapter(context, filterListForSubAxe(listDataHeader, subAxeName, brandName, axeName), listDataChild); + } else { + listAdapter = new ExpandableListAdapter(context, filterListForSubAxe(listDataHeader, selectedSubAxe), listDataChild); + } + + lvExp_stock_check.setAdapter(listAdapter); + listAdapter.notifyDataSetChanged(); + } + + final int FILTER_FOR_SIGNATURE = 4; + final int FILTER_FOR_SUB_BRAND = 5; + final int FILTER_FOR_REFERENCE = 6; + final int FILTER_FOR_BRAND = 1; + final int FILTER_FOR_AXE = 2; + final int FILTER_FOR_SUBAXE = 3; + final int CLEAR_FILTER = 0; + + public void setSearchFilter(List originalList, String text, HashMap> listDataChild) { + + HashMap> filterChildHashMap = new HashMap<>(); + + ArrayList filterList = new ArrayList<>(); + for (int i = 0; i < originalList.size(); i++) { + ProductMaster parent = originalList.get(i); + List listChild = listDataChild.get(parent); + List listFilterChild = new ArrayList<>(); + for (int j = 0; j < listChild.size(); j++) { + if (listChild.get(j).getProductName().toLowerCase().contains(text.toLowerCase()) || (listChild.get(j).getEanCode() != null && listChild.get(j).getEanCode().contains(text))) { + listFilterChild.add(listChild.get(j)); + } else { + continue; + } + } + + if (listFilterChild.size() > 0) { + filterList.add(parent); + filterChildHashMap.put(parent, listFilterChild); + + } + + } + + ExpandableListAdapter listAdapter1 = new ExpandableListAdapter(context, filterList, filterChildHashMap); + lvExp_stock_check.setAdapter(listAdapter1); + for (int i = 0; i < listAdapter1.getGroupCount(); i++) { + lvExp_stock_check.expandGroup(i); + } + listAdapter1.notifyDataSetChanged(); + + + } + + boolean isDataAdded = false; + + @Override + public void onBackPressed() { + //super.onBackPressed(); + isChanged(); + } + + void isChanged() { + super.onBackPressed(); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + + } + + + @SuppressLint("UseCompatLoadingForDrawables") + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + Log.i("MakeMachine", "resultCode: " + resultCode); + if (requestCode == 131) { + switch (resultCode) { + case 0: + Log.i("MakeMachine", "User cancelled"); + break; + + case -1: + if (_pathforcheck != null && !_pathforcheck.isEmpty()) { + if (new File(CommonString.getImagesFolder(context) + _pathforcheck).exists()) { + convertBitmap(CommonString.getImagesFolder(context) + _pathforcheck); + + isDataAdded = true; + globalHeaderObject.setImagePath(_pathforcheck); + groupPositionGlobal = -1; + _pathforcheck = ""; + listAdapter.notifyDataSetChanged(); + } + } + break; + } + } else { + IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data); + switch (resultCode) { + case 0: + + break; + + case -1: + db.open(); + ArrayList productList = db.getsku_fromproductusing_eancode(result.getContents(), false, visit_date, counter_id, null); + if (productList.isEmpty()) { + db.open(); + productList = db.getsku_fromproductusing_eancode(removeFirstChar(result.getContents()), false, visit_date, counter_id, null); + } + + //test("Ean Code", result.getContents()); + if (!productList.isEmpty()) { + flagScan = false; + img_scan.setImageDrawable(getResources().getDrawable(R.mipmap.ok)); + clearFilters(); + setScanFilter(productList); + } else { + AlertandMessages.showToastMsg(context, "Unable To Scan Correct Data. Please Try Again."); + } + + break; + } + } + + super.onActivityResult(requestCode, resultCode, data); + } + + + public class ValueAdapter extends RecyclerView.Adapter { + private LayoutInflater inflator; + List data; + ProductMaster productMaster; + String type; + + public String getType() { + return type; + } + + public ValueAdapter(Context context, List data, String type) { + inflator = LayoutInflater.from(context); + this.data = data; + this.type = type; + } + + @Override + public ValueAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int i) { + View view = inflator.inflate(R.layout.item_filter, parent, false); + return new ValueAdapter.MyViewHolder(view); + } + + @RequiresApi(api = Build.VERSION_CODES.M) + @Override + public void onBindViewHolder(final ValueAdapter.MyViewHolder holder, final int position) { + final ProductMaster current = data.get(position); + + final boolean[] selected = {false}; + final int[] filterId = {0}; + + switch (type) { + + case CommonString.Signature: + if (selectedSignature != null && selectedSignature == current) { + selected[0] = true; + } + + break; + + case CommonString.Brand: + if (selectedBrand != null && selectedBrand == current) { + selected[0] = true; + } + + break; + + case CommonString.SubBrand: + if (selectedSubBrand != null && selectedSubBrand == current) { + selected[0] = true; + } + + break; + + case CommonString.Reference: + if (selectedReference != null && selectedReference == current) { + selected[0] = true; + } + + break; + } + + holder.tv_item.setText(current.getBrandName()); + + holder.card.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + + et_search.setText(""); + + switch (type) { + case CommonString.Signature: + selectedSignature = current; + filterId[0] = R.id.img_filter_signature; + + //clear other sub filters-- + selectedBrand = null; + selectedSubBrand = null; + selectedReference = null; + + (sheetView.findViewById(R.id.img_filter_brand)).setVisibility(View.GONE); + (sheetView.findViewById(R.id.img_filter_sub_brand)).setVisibility(View.GONE); + (sheetView.findViewById(R.id.img_filter_reference)).setVisibility(View.GONE); + //-- + + db.open(); + setBottomFilter(listAdapter.get_listDataHeader(), current.getBrandName(), listAdapter.get_listDataChild(), CommonString.Signature); + brandList = db.getSubBrandOrReference(counterGroupId, "BrandName", current.getBrandName(), null, null, false, selectedSubAxe); + subBrandList = db.getSubBrandOrReference(counterGroupId, "SubBrandName", current.getBrandName(), null, null, false, selectedSubAxe); + referenceList = db.getSubBrandOrReference(counterGroupId, "ReferenceName", current.getBrandName(), null, null, false, selectedSubAxe); + + break; + case CommonString.Brand: + selectedBrand = current; + filterId[0] = R.id.img_filter_brand; + + //clear other sub filters-- + selectedSubBrand = null; + selectedReference = null; + + (sheetView.findViewById(R.id.img_filter_sub_brand)).setVisibility(View.GONE); + (sheetView.findViewById(R.id.img_filter_reference)).setVisibility(View.GONE); + //-- + + setBottomFilter(listAdapter.get_listDataHeader(), current.getBrandName(), listAdapter.get_listDataChild(), CommonString.Brand); + //setFilter(FILTER_FOR_BRAND); + db.open(); + subBrandList = db.getSubBrandOrReference(counterGroupId, "SubBrandName", "", current.getBrandName(), null, false, selectedSubAxe); + referenceList = db.getSubBrandOrReference(counterGroupId, "ReferenceName", "", current.getBrandName(), null, false, selectedSubAxe); + + break; + case CommonString.SubBrand: + selectedSubBrand = current; + filterId[0] = R.id.img_filter_sub_brand; + + //clear other sub filters-- + selectedReference = null; + + (sheetView.findViewById(R.id.img_filter_reference)).setVisibility(View.GONE); + //-- + + + setBottomFilter(listAdapter.get_listDataHeader(), current.getBrandName(), listAdapter.get_listDataChild(), CommonString.SubBrand); + //setFilter(FILTER_FOR_SUB_BRAND); + db.open(); + referenceList = db.getSubBrandOrReference(counterGroupId, "ReferenceName", "", null, current.getBrandName(), false, selectedSubAxe); + break; + case CommonString.Reference: + selectedReference = current; + filterId[0] = R.id.img_filter_reference; + setBottomFilter(listAdapter.get_listDataHeader(), current.getBrandName(), listAdapter.get_listDataChild(), CommonString.Reference); + //setFilter(FILTER_FOR_REFERENCE); + break; + } + + RecyclerView recSubBrand = sheetView.findViewById(R.id.rec_brand); + recSubBrand.getAdapter().notifyDataSetChanged(); + //show filter icon on filter selected + (sheetView.findViewById(filterId[0])).setVisibility(View.VISIBLE); + } + }); + + if (selected[0]) { + holder.card.setCardBackgroundColor(getColor(R.color.dashboard_ach)); + } else { + holder.card.setCardBackgroundColor(getColor(R.color.grey_dark_background)); + } + } + + @Override + public int getItemCount() { + return data.size(); + } + + class MyViewHolder extends RecyclerView.ViewHolder { + TextView tv_item; + CardView card; + + public MyViewHolder(View itemView) { + super(itemView); + tv_item = (TextView) itemView.findViewById(R.id.tv_item); + card = (CardView) itemView.findViewById(R.id.item_card); + + } + } + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + getMenuInflater().inflate(R.menu.filter_menu_filled, menu); + return super.onCreateOptionsMenu(menu); + + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // Handle action bar item clicks here. The action bar will + // automatically handle clicks on the Home/Up button, so long + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + + if (id == android.R.id.home) { + isChanged(); + } else if (id == R.id.filter_data) { + sheetView = showFilterBottomSheet(); + } + + + return super.onOptionsItemSelected(item); + } + + private void openScanner() { + IntentIntegrator intentIntegrator = new IntentIntegrator((Activity) context); + intentIntegrator.setBeepEnabled(true); + intentIntegrator.setOrientationLocked(false); + intentIntegrator.setPrompt("Scan the barcode or QR code to get the data"); + intentIntegrator.setCaptureActivity(CaptureActivity.class); + intentIntegrator.initiateScan(); + } + + + public void setScanFilter(List scanList) { + + HashMap> filterChildHashMap = new HashMap<>(); + + ArrayList filterList = new ArrayList<>(); + for (int i = 0; i < listDataHeader.size(); i++) { + ProductMaster parent = listDataHeader.get(i); + List listChild = listDataChild.get(parent); + List listFilterChild = new ArrayList<>(); + for (int j = 0; j < listChild.size(); j++) { + if (containsProduct(scanList, listChild.get(j))) { + listFilterChild.add(listChild.get(j)); + } else { + continue; + } + } + + if (listFilterChild.size() > 0) { + filterList.add(parent); + filterChildHashMap.put(parent, listFilterChild); + + } + + } + + ExpandableListAdapter listAdapter1 = new ExpandableListAdapter(context, filterList, filterChildHashMap); + lvExp_stock_check.setAdapter(listAdapter1); + for (int i = 0; i < listAdapter1.getGroupCount(); i++) { + lvExp_stock_check.expandGroup(i); + } + listAdapter1.notifyDataSetChanged(); + + } + + boolean containsProduct(List scanList, ProductMaster obj) { + boolean contains = false; + + for (int i = 0; i < scanList.size(); i++) { + if (scanList.get(i).getProductId().equals(obj.getProductId())) { + contains = true; + break; + } + } + + return contains; + } + + void clearFilters() { + et_search.setText(""); + + setFilter(CLEAR_FILTER); + selectedSignature = null; + selectedBrand = null; + selectedSubBrand = null; + selectedReference = null; + + if (sheetView != null) { + (sheetView.findViewById(R.id.img_filter_signature)).setVisibility(View.GONE); + (sheetView.findViewById(R.id.img_filter_brand)).setVisibility(View.GONE); + (sheetView.findViewById(R.id.img_filter_sub_brand)).setVisibility(View.GONE); + (sheetView.findViewById(R.id.img_filter_reference)).setVisibility(View.GONE); + } + + db.open(); + brandList = db.getsub_brand_name(counterGroupId, "BrandName", false, selectedSubAxe); + subBrandList = db.getsub_brand_name(counterGroupId, "SubBrandName", false, selectedSubAxe); + referenceList = db.getsub_brand_name(counterGroupId, "ReferenceName", false, selectedSubAxe); + signatureList = db.getsub_brand_name(counterGroupId, "SignatureName", false, selectedSubAxe); + } + + private Dialog dialog; + ProgressBar pb; + + class LoadAsync extends AsyncTask { + + @Override + protected void onPreExecute() { + dialog = new Dialog(context); + dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); + dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT)); + dialog.setContentView(R.layout.circular_progress_bar); + pb = (ProgressBar) dialog.findViewById(R.id.progressBar1); + dialog.setCancelable(false); + dialog.show(); + super.onPreExecute(); + } + + @Override + protected Void doInBackground(Void... voids) { + prepareListData(); + //validate_spin_ui_data(); + + return null; + } + + @Override + protected void onPostExecute(Void aVoid) { + + dialog.cancel(); + + recSubAxe.setLayoutManager(new GridLayoutManager(context, 3)); + subAxeValueAdapter = new SubAxeValueAdapter(context, listSubAxe, CommonString.Signature); + recSubAxe.setAdapter(subAxeValueAdapter); + + recSubAxe.getAdapter().notifyDataSetChanged(); + + listAdapter = new ExpandableListAdapter(context, listDataHeader, listDataChild); + lvExp_stock_check.setAdapter(listAdapter); + + //validate_spin_ui_data(); + listAdapter = new ExpandableListAdapter(context, listDataHeader, listDataChild); + lvExp_stock_check.setAdapter(listAdapter); + + lvExp_stock_check.setOnScrollListener(new AbsListView.OnScrollListener() { + @Override + public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { + lvExp_stock_check.invalidate(); + } + + @Override + public void onScrollStateChanged(AbsListView arg0, int arg1) { + InputMethodManager inputManager = (InputMethodManager) getApplicationContext() + .getSystemService(Context.INPUT_METHOD_SERVICE); + if (getCurrentFocus() != null) { + inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0); + getCurrentFocus().clearFocus(); + } + + lvExp_stock_check.invalidateViews(); + } + }); + db.open(); + JourneyPlan jcp = db.getJCP(); + if (jcp != null) { + counterGroupId = jcp.getCounterGroupId().toString(); + } else { + counterGroupId = "1"; + } + + super.onPostExecute(aVoid); + } + } + + + public class SubAxeValueAdapter extends RecyclerView.Adapter { + private LayoutInflater inflator; + List data; + ProductMaster productMaster; + String type; + + public String getType() { + return type; + } + + public SubAxeValueAdapter(Context context, List data, String type) { + inflator = LayoutInflater.from(context); + this.data = data; + this.type = type; + } + + @Override + public SubAxeValueAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int i) { + View view = inflator.inflate(R.layout.item_filter, parent, false); + return new SubAxeValueAdapter.MyViewHolder(view); + } + + @RequiresApi(api = Build.VERSION_CODES.M) + @Override + public void onBindViewHolder(final SubAxeValueAdapter.MyViewHolder holder, final int position) { + final ProductMaster current = data.get(position); + + + holder.tv_item.setText(current.getSubAxeName()); + + holder.tv_item.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + + et_search.setText(""); + + listAdapter = new ExpandableListAdapter(context, filterListForSubAxe(listDataHeader, current.getSubAxeName()), listDataChild); + lvExp_stock_check.setAdapter(listAdapter); + listAdapter.notifyDataSetChanged(); + //setExpandableDataForSubAxe(current.getSubAxeName()); + current.setSelected(true); + selectedSubAxe = current.getSubAxeName(); + subAxeValueAdapter.notifyDataSetChanged(); + db.open(); + jcp = db.getJCP(); + if (jcp != null) { + brandList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "BrandName", false, selectedSubAxe); + subBrandList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "SubBrandName", false, selectedSubAxe); + referenceList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "ReferenceName", false, selectedSubAxe); + signatureList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "SignatureName", false, selectedSubAxe); + } else { + brandList = db.getsub_brand_name("1", "BrandName", false, selectedSubAxe); + subBrandList = db.getsub_brand_name("1", "SubBrandName", false, selectedSubAxe); + referenceList = db.getsub_brand_name("1", "ReferenceName", false, selectedSubAxe); + signatureList = db.getsub_brand_name("1", "SignatureName", false, selectedSubAxe); + } + } + }); + + //if (current.isSelected()) { + if (current.getSubAxeName().equalsIgnoreCase(selectedSubAxe)) { + holder.card.setCardBackgroundColor(getColor(R.color.dashboard_ach)); + } else { + holder.card.setCardBackgroundColor(getColor(R.color.grey_dark_background)); + } + } + + @Override + public int getItemCount() { + return data.size(); + } + + class MyViewHolder extends RecyclerView.ViewHolder { + TextView tv_item; + CardView card; + + public MyViewHolder(View itemView) { + super(itemView); + tv_item = (TextView) itemView.findViewById(R.id.tv_item); + card = (CardView) itemView.findViewById(R.id.item_card); + + } + } + } + + public ArrayList filterListForSubAxe(List originalList, String text) { + ArrayList filterList = new ArrayList<>(); + for (ProductMaster object : originalList) { + if (object.getSubAxeName().equalsIgnoreCase(text)) { + filterList.add(object); + } else { + continue; + } + } + return filterList; + } + + public void setBottomFilter(List originalList, String text, HashMap> listDataChild, String type) { + + HashMap> filterChildHashMap = new HashMap<>(); + + ArrayList filterList = new ArrayList<>(); + for (int i = 0; i < originalList.size(); i++) { + ProductMaster parent = originalList.get(i); + List listChild = listDataChild.get(parent); + List listFilterChild = new ArrayList<>(); + for (int j = 0; j < listChild.size(); j++) { + + switch (type) { + case CommonString.Signature: + if (listChild.get(j).getSignatureName().equalsIgnoreCase(text)) { + listFilterChild.add(listChild.get(j)); + } + break; + case CommonString.Brand: + if (listChild.get(j).getBrandName().equalsIgnoreCase(text)) { + listFilterChild.add(listChild.get(j)); + } + break; + case CommonString.SubBrand: + if (listChild.get(j).getSubBrandName().equalsIgnoreCase(text)) { + listFilterChild.add(listChild.get(j)); + } + break; + case CommonString.Reference: + if (listChild.get(j).getReferenceName().equalsIgnoreCase(text)) { + listFilterChild.add(listChild.get(j)); + } + break; + } + + } + + if (listFilterChild.size() > 0) { + filterList.add(parent); + filterChildHashMap.put(parent, listFilterChild); + + } + + } + + ExpandableListAdapter listAdapter1 = new ExpandableListAdapter(context, filterList, filterChildHashMap); + lvExp_stock_check.setAdapter(listAdapter1); + listAdapter1.notifyDataSetChanged(); + } + + public void setUnFilledFilter(List originalList, HashMap> listDataChild) { + + HashMap> filterChildHashMap = new HashMap<>(); + + ArrayList filterList = new ArrayList<>(); + for (int i = 0; i < originalList.size(); i++) { + ProductMaster parent = originalList.get(i); + List listChild = listDataChild.get(parent); + List listFilterChild = new ArrayList<>(); + for (int j = 0; j < listChild.size(); j++) { + if (listChild.get(j).getStock() == -1) { + listFilterChild.add(listChild.get(j)); + } else { + continue; + } + } + + if (listFilterChild.size() > 0) { + filterList.add(parent); + filterChildHashMap.put(parent, listFilterChild); + + } + + } + + ExpandableListAdapter listAdapter1 = new ExpandableListAdapter(context, filterList, filterChildHashMap); + lvExp_stock_check.setAdapter(listAdapter1); + + for (int i = 0; i < listAdapter1.getGroupCount(); i++) { + lvExp_stock_check.expandGroup(i); + } + + listAdapter1.notifyDataSetChanged(); + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/GWPActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/GWPActivity.java new file mode 100644 index 0000000..b921ab2 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/GWPActivity.java @@ -0,0 +1,1482 @@ +package com.cpm.lorealbaautomation.dailyactivity; + +import android.annotation.SuppressLint; +import android.app.Activity; +import android.app.AlertDialog; +import android.app.Dialog; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.SharedPreferences; +import android.graphics.drawable.ColorDrawable; +import android.os.AsyncTask; +import android.os.Bundle; + +import com.google.android.material.bottomsheet.BottomSheetDialog; +import com.google.android.material.floatingactionbutton.FloatingActionButton; + +import androidx.appcompat.app.AppCompatActivity; +import androidx.cardview.widget.CardView; +import androidx.recyclerview.widget.GridLayoutManager; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; +import androidx.appcompat.widget.Toolbar; + +import android.text.Editable; +import android.text.TextWatcher; +import android.util.Log; +import android.view.Gravity; +import android.view.LayoutInflater; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; +import android.view.Window; +import android.view.WindowManager; +import android.view.inputmethod.InputMethodManager; +import android.widget.AbsListView; +import android.widget.BaseExpandableListAdapter; +import android.widget.Button; +import android.widget.EditText; +import android.widget.ExpandableListView; +import android.widget.ImageView; +import android.widget.LinearLayout; +import android.widget.ProgressBar; +import android.widget.Spinner; +import android.widget.TextView; +import android.widget.Toast; + +import com.google.zxing.integration.android.IntentIntegrator; +import com.google.zxing.integration.android.IntentResult; +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.constant.AlertandMessages; +import com.cpm.lorealbaautomation.constant.CommonFunctions; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.gettersetter.SaleableGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.JourneyPlan; +import com.cpm.lorealbaautomation.gsonGetterSetter.ProductMaster; + +import java.io.File; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Objects; +import java.util.UUID; + +import static com.cpm.lorealbaautomation.constant.CommonFunctions.getCurrentTime; +import static com.cpm.lorealbaautomation.constant.CommonFunctions.removeFirstChar; +import static com.cpm.lorealbaautomation.dailyactivity.StoreImageActivity.convertBitmap; + +public class GWPActivity extends AppCompatActivity implements View.OnClickListener { + Spinner sku_spin, brand_spin, sub_axe_spin, axe_spin; + ArrayList brandList = new ArrayList<>(); + + ExpandableListView lvExp_stock_check; + FloatingActionButton fab_save, fab_draft; + Lorealba_Database db; + Context context; + AlertDialog alert; + private SharedPreferences preferences; + String counter_id, visit_date, username, user_type, _pathforcheck, _path; + ArrayList listDataHeader = new ArrayList<>(); + ArrayList childStockList = new ArrayList<>(); + HashMap> listDataChild; + boolean checkflag = true; + ArrayList checkHeaderArray = new ArrayList<>(); + ExpandableListAdapter listAdapter; + + + int groupPositionGlobal = -1; + int childPositionGlobal = -1; + ProductMaster globalChildObject = new ProductMaster(); + + EditText et_search; + + //filter bottom sheet + ArrayList subBrandList = new ArrayList<>(); + ArrayList referenceList = new ArrayList<>(); + ArrayList signatureList = new ArrayList<>(); + ImageView img_filter; + View sheetView; + ProductMaster selectedSignature, selectedBrand, selectedSubBrand, selectedReference; + final int FILTER_FOR_SIGNATURE = 4; + final int FILTER_FOR_SUB_BRAND = 5; + final int FILTER_FOR_REFERENCE = 6; + final int FILTER_FOR_BRAND = 1; + final int CLEAR_FILTER = 0; + + boolean regularStockFlag = false, check_flag = true; + ImageView img_scan; + boolean flagScan = true; + private String counterGroupId; + ArrayList listSubAxe; + RecyclerView recSubAxe; + ImageView img_clear_subaxe; + String selectedSubAxe = ""; + SubAxeValueAdapter subAxeValueAdapter; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_gwp); + context = this; + ((GWPActivity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); + db = new Lorealba_Database(context); + db.open(); + + validateUIData(); + + String couter_code = preferences.getString(CommonString.KEY_COUNTER_CODE, ""); + TextView txt_counter_code = (TextView) findViewById(R.id.txt_counter_code); + txt_counter_code.setText("Counter Code - " + couter_code + " / Id - " + counter_id); + + new LoadAsync().execute(); + lvExp_stock_check.setOnScrollListener(new AbsListView.OnScrollListener() { + @Override + public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { + lvExp_stock_check.invalidate(); + + int lastItem = firstVisibleItem + visibleItemCount; + if (firstVisibleItem == 0) { + fab_save.show();//.setVisibility(View.VISIBLE); + } else if (lastItem == totalItemCount) { + fab_save.hide();//setVisibility(View.INVISIBLE); + } else { + fab_save.show();//setVisibility(View.VISIBLE); + } + } + + @Override + public void onScrollStateChanged(AbsListView arg0, int arg1) { + InputMethodManager inputManager = (InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE); + if (getCurrentFocus() != null) { + inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0); + getCurrentFocus().clearFocus(); + } + + lvExp_stock_check.invalidateViews(); + } + }); + + } + + private void validateUIData() { + preferences = PrefHelper.getPrefs(context); + counter_id = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + username = preferences.getString(CommonString.KEY_USERNAME, ""); + + Toolbar toolbar = findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + getSupportActionBar().setHomeButtonEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + + if (!CommonFunctions.isTablet(context)) { + toolbar.setTitleTextAppearance(context, R.style.changestext_sizefor_mobile); + } + + setTitle("GWP - " + visit_date); + + sku_spin = (Spinner) findViewById(R.id.sku_spin); + brand_spin = (Spinner) findViewById(R.id.stock_brand_spin); + sub_axe_spin = (Spinner) findViewById(R.id.sub_axe_spin); + axe_spin = (Spinner) findViewById(R.id.axe_spin); + lvExp_stock_check = (ExpandableListView) findViewById(R.id.lvExp_stock_check); + et_search = (EditText) findViewById(R.id.et_search); + img_scan = (ImageView) findViewById(R.id.img_scan); + fab_save = (FloatingActionButton) findViewById(R.id.save_fab); + fab_draft = (FloatingActionButton) findViewById(R.id.draft_fab); + recSubAxe = (RecyclerView) findViewById(R.id.rec_subaxe); + img_clear_subaxe = (ImageView) findViewById(R.id.img_clear_subaxe); + img_clear_subaxe.setOnClickListener(this); + fab_save.setOnClickListener(this); + fab_draft.setOnClickListener(this); + img_scan.setOnClickListener(this); + db.open(); + + et_search.addTextChangedListener(new TextWatcher() { + @Override + public void beforeTextChanged(CharSequence s, int start, int count, int after) { + + } + + @Override + public void onTextChanged(CharSequence s, int start, int before, int count) { + + String text = s.toString(); + setSearchFilter(listAdapter.get_listDataHeader(), text, listAdapter.get_listDataChild()); + } + + @Override + public void afterTextChanged(Editable s) { + + String text = s.toString(); + + } + }); + + + img_filter = (ImageView) findViewById(R.id.img_filter); + ImageView img_unfilled = (ImageView) findViewById(R.id.img_unfilled); + img_unfilled.setVisibility(View.INVISIBLE); + + img_filter.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + sheetView = showFilterBottomSheet(); + } + }); + + db.open(); + String status = db.getStatus(CommonString.KEY_GwpStatus, counter_id); + //if regular stock need to be captured after First stock capture + if (status != null && !status.equals("") && status.equalsIgnoreCase("Complete")) { + regularStockFlag = true; + fab_draft.hide(); + } + + } + + public void setSearchFilter(List originalList, String text, HashMap> listDataChild) { + + HashMap> filterChildHashMap = new HashMap<>(); + + ArrayList filterList = new ArrayList<>(); + for (int i = 0; i < originalList.size(); i++) { + ProductMaster parent = originalList.get(i); + List listChild = listDataChild.get(parent); + List listFilterChild = new ArrayList<>(); + for (int j = 0; j < listChild.size(); j++) { + if (listChild.get(j).getProductName().toLowerCase().contains(text.toLowerCase()) || (listChild.get(j).getEanCode() != null && listChild.get(j).getEanCode().contains(text))) { + listFilterChild.add(listChild.get(j)); + } else { + continue; + } + } + + if (listFilterChild.size() > 0) { + filterList.add(parent); + filterChildHashMap.put(parent, listFilterChild); + + } + } + + ExpandableListAdapter listAdapter = new ExpandableListAdapter(context, filterList, filterChildHashMap); + lvExp_stock_check.setAdapter(listAdapter); + listAdapter.notifyDataSetChanged(); + for (int i = 0; i < listAdapter.getGroupCount(); i++) { + lvExp_stock_check.expandGroup(i); + } + + } + + private void prepareListData() { + db.open(); + + //for filter bottom sheet + JourneyPlan jcp = db.getJCP(); + if (jcp != null) { + db.open(); + listSubAxe = db.getSubAxe(jcp.getCounterGroupId().toString(), false); + db.open(); + brandList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "BrandName", true); + subBrandList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "SubBrandName", true); + referenceList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "ReferenceName", true); + signatureList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "SignatureName", true); + } else { + db.open(); + listSubAxe = db.getSubAxe("1", false); + db.open(); + brandList = db.getsub_brand_name("1", "BrandName", true); + subBrandList = db.getsub_brand_name("1", "SubBrandName", true); + referenceList = db.getsub_brand_name("1", "ReferenceName", true); + signatureList = db.getsub_brand_name("1", "SignatureName", true); + } + + listDataHeader = new ArrayList<>(); + listDataChild = new HashMap<>(); + //inserted data + db.open(); + // listDataHeader = db.getGWPHeaderInsertedData(visit_date, regularStockFlag, counter_id); + //// if (listDataHeader.size() == 0) { + jcp = db.getJCP(); + if (jcp != null) { + db.open(); + listDataHeader = db.getGWPSignatureBrandSubBrandReference(regularStockFlag, counter_id, visit_date); + } else { + listDataHeader = db.getStockSignatureBrandSubBrandReference("1", true, regularStockFlag, "GwpBalance"); + } + /// } + + + if (listDataHeader.size() > 0) { + for (int i = 0; i < listDataHeader.size(); i++) { + db.open(); + jcp = db.getJCP(); + if (jcp != null) { + childStockList = db.getDefaultGWPOnSignatureData(listDataHeader.get(i).getSubBrandName(), listDataHeader.get(i).getReferenceName(), + listDataHeader.get(i).getBrandName(), CommonString.KEY_GWP_BALANCE, regularStockFlag, visit_date, counter_id); + } else { + childStockList = db.getDefaultGWPOnSignatureData(listDataHeader.get(i).getSubBrandName(), + listDataHeader.get(i).getReferenceName(), listDataHeader.get(i).getBrandName(), CommonString.KEY_GWP_BALANCE, regularStockFlag, visit_date, counter_id); + } + + listDataChild.put(listDataHeader.get(i), childStockList); // Header, Child data + } + + } + } + + @Override + public void onClick(View view) { + if (view.getId() == R.id.save_fab) { + lvExp_stock_check.clearFocus(); + lvExp_stock_check.invalidateViews(); + if (regularStockFlag) { + dialogFinalSubmit(listDataChild, listDataHeader); + } else { + dialogFinalSubmit(listDataChild, listDataHeader); + } + + } else if (view.getId() == R.id.draft_fab) { + lvExp_stock_check.clearFocus(); + lvExp_stock_check.invalidateViews(); + db.open(); + db.insertGWPCapturedData(visit_date, listDataChild, listDataHeader, false, counter_id); + uploadData(false); + } else if (view.getId() == R.id.card_signature) { + RecyclerView recSignature = sheetView.findViewById(R.id.rec_brand); + recSignature.setAdapter(new ValueAdapter(context, signatureList, CommonString.Signature)); + recSignature.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, true)); + setFilterSelected(sheetView, CommonString.Signature); + } else if (view.getId() == R.id.card_brand) { + + RecyclerView recBrand = sheetView.findViewById(R.id.rec_brand); + recBrand.setAdapter(new ValueAdapter(context, brandList, CommonString.Brand)); + recBrand.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, true)); + setFilterSelected(sheetView, CommonString.Brand); + } else if (view.getId() == R.id.card_sub_brand) { + + RecyclerView recSubBrand = sheetView.findViewById(R.id.rec_brand); + recSubBrand.setAdapter(new ValueAdapter(context, subBrandList, CommonString.SubBrand)); + recSubBrand.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, true)); + recSubBrand.getAdapter().notifyDataSetChanged(); + setFilterSelected(sheetView, CommonString.SubBrand); + } else if (view.getId() == R.id.card_reference) { + + RecyclerView recReference = sheetView.findViewById(R.id.rec_brand); + recReference.setAdapter(new ValueAdapter(context, referenceList, CommonString.Reference)); + recReference.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, true)); + setFilterSelected(sheetView, CommonString.Reference); + } else if (view.getId() == R.id.img_scan) { + + if (flagScan) { + openScanner(); + } else { + img_scan.setImageDrawable(getResources().getDrawable(R.mipmap.barcode_icon)); + flagScan = true; + et_search.setText(""); + } + + } else if (view.getId() == R.id.img_clear_subaxe) { + et_search.setText(""); + listAdapter = new ExpandableListAdapter(context, listDataHeader, listDataChild); + lvExp_stock_check.setAdapter(listAdapter); + listAdapter.notifyDataSetChanged(); + selectedSubAxe = ""; + subAxeValueAdapter.notifyDataSetChanged(); + //clear filters also + selectedSignature = null; + selectedBrand = null; + selectedSubBrand = null; + selectedReference = null; + db.open(); + brandList = db.getsub_brand_name(counterGroupId, "BrandName", true, selectedSubAxe); + db.open(); + subBrandList = db.getsub_brand_name(counterGroupId, "SubBrandName", true, selectedSubAxe); + db.open(); + referenceList = db.getsub_brand_name(counterGroupId, "ReferenceName", true, selectedSubAxe); + db.open(); + signatureList = db.getsub_brand_name(counterGroupId, "SignatureName", true, selectedSubAxe); + + } + } + + + public ArrayList filterListForBrand(List originalList, String text) { + ArrayList filterList = new ArrayList<>(); + for (ProductMaster object : originalList) { + if (object.getBrandName().equalsIgnoreCase(text)) { + filterList.add(object); + } else { + continue; + } + } + return filterList; + } + + + public class ExpandableListAdapter extends BaseExpandableListAdapter { + private Context _context; + private List _listDataHeader; + private HashMap> _listDataChild; + + public ExpandableListAdapter(Context context, List listDataHeader, HashMap> listChildData) { + this._context = context; + this._listDataHeader = listDataHeader; + this._listDataChild = listChildData; + } + + @Override + public Object getChild(int groupPosition, int childPosititon) { + return this._listDataChild.get(this._listDataHeader.get(groupPosition)).get(childPosititon); + } + + @Override + public long getChildId(int groupPosition, int childPosition) { + return childPosition; + } + + public HashMap> get_listDataChild() { + return _listDataChild; + } + + public List get_listDataHeader() { + return _listDataHeader; + } + + @Override + public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { + + final ProductMaster childText = (ProductMaster) getChild(groupPosition, childPosition); + ViewHolder holder = null; + if (convertView == null) { + LayoutInflater infalInflater = (LayoutInflater) this._context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); + convertView = infalInflater.inflate(R.layout.gwp_item_layout, null); + holder = new ViewHolder(); + holder.cardView = convertView.findViewById(R.id.card_view); + holder.ed_Stock = convertView.findViewById(R.id.ed_Stock); + holder.mrp = convertView.findViewById(R.id.mrp); + holder.stock_img_plus = convertView.findViewById(R.id.stock_img_plus); + holder.stock_img_minus = convertView.findViewById(R.id.stock_img_minus); + holder.ed_Stock = convertView.findViewById(R.id.ed_Stock); + holder.et_stock = convertView.findViewById(R.id.et_stock); + convertView.setTag(holder); + + + } else { + holder = (ViewHolder) convertView.getTag(); + } + + ImageView imgCam = convertView.findViewById(R.id.img_cam); + imgCam.setVisibility(View.GONE); + imgCam.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + groupPositionGlobal = groupPosition; + childPositionGlobal = groupPosition; + globalChildObject = childText; + _pathforcheck = counter_id + "_GWP_IMG_" + visit_date.replace("/", "") + "_" + getCurrentTime().replace(":", "") + ".jpg"; + _path = CommonString.getImagesFolder(context) + _pathforcheck; + CommonFunctions.startAnncaCameraActivity(GWPActivity.this, _path, null, false, CommonString.CAMERA_FACE_REAR); + } + }); + + TextView txtListChild = convertView.findViewById(R.id.lblListItem); + txtListChild.setText(childText.getProductName() + " (MRP - ₹ " + childText.getMrp() + ")"); + final ViewHolder finalHolder = holder; + holder.stock_img_plus.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + ((ExpandableListAdapter) lvExp_stock_check.getExpandableListAdapter()).notifyDataSetChanged(); + if (!regularStockFlag) { + String stot = finalHolder.et_stock.getText().toString().trim().replaceFirst("^0+(?!$)", ""); + if (!stot.equals("")) { + int st = Integer.parseInt(stot); + childText.setStock(st); + } + } + + int stock = childText.getStock(); + int receivedStock = childText.getStock_receive(); + ++stock; + + if (regularStockFlag) { + if (receivedStock >= stock) { + childText.setStock(stock); + isDataAdded = true; + childText.setSelected(true); + + } else { + AlertandMessages.showToastMsg(context, "Stock cannot be greater than Received Stock"); + } + } else { + childText.setStock(stock); + isDataAdded = true; + childText.setSelected(true); + } + } + }); + + holder.stock_img_minus.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + ((ExpandableListAdapter) lvExp_stock_check.getExpandableListAdapter()).notifyDataSetChanged(); + if (!regularStockFlag) { + String stot = finalHolder.et_stock.getText().toString().trim().replaceFirst("^0+(?!$)", ""); + if (!stot.equals("")) { + int st = Integer.parseInt(stot); + childText.setStock(st); + } + } + + int stock = childText.getStock(); + --stock; + + if (stock >= 0) { + childText.setStock(stock); + isDataAdded = true; + childText.setSelected(true); + } else { + AlertandMessages.showToastMsg(context, "Stock cannot be less than 0"); + } + + } + }); + + holder.et_stock.setOnFocusChangeListener(new View.OnFocusChangeListener() { + @Override + public void onFocusChange(View v, boolean hasFocus) { + // if (!hasFocus) { + final EditText caption = (EditText) v; + String stock = caption.getText().toString().replaceFirst("^0+(?!$)", ""); + if (!stock.equals("")) { + childText.setStock(Integer.parseInt(stock)); + isDataAdded = true; + childText.setSelected(true); + } else { + childText.setStock(0); + } + + // } + + } + }); + + if (childText.getImagePath().equals("")) { + imgCam.setImageDrawable(getResources().getDrawable(R.mipmap.camera_bs)); + } else { + imgCam.setImageDrawable(getResources().getDrawable(R.mipmap.camera_bsd)); + } + + int stock = childText.getStock(); + if (!childText.isSelected() && childText.getStock() == 0) { + stock = childText.getStock_receive(); + childText.setStock(stock); + } + + if (regularStockFlag) { + holder.ed_Stock.setText(stock + ""); + holder.ed_Stock.setId(childPosition); + + holder.et_stock.setVisibility(View.GONE); + holder.ed_Stock.setVisibility(View.VISIBLE); + } else { + + if (stock == -1) { + holder.et_stock.setText(""); + } else { + holder.et_stock.setText(stock + ""); + } + + holder.et_stock.setId(childPosition); + + holder.ed_Stock.setVisibility(View.GONE); + holder.et_stock.setVisibility(View.VISIBLE); + } + + holder.mrp.setText(" MRP = " + childText.getMrp() + ""); + holder.mrp.setId(childPosition); + + return convertView; + } + + @Override + public int getChildrenCount(int groupPosition) { + return this._listDataChild.get(this._listDataHeader.get(groupPosition)).size(); + } + + @Override + public Object getGroup(int groupPosition) { + return this._listDataHeader.get(groupPosition); + } + + @Override + public int getGroupCount() { + return this._listDataHeader.size(); + } + + @Override + public long getGroupId(int groupPosition) { + return groupPosition; + } + + @SuppressLint({"SetTextI18n", "UseCompatLoadingForDrawables"}) + @Override + public View getGroupView(final int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { + final ProductMaster headerTitle = (ProductMaster) getGroup(groupPosition); + if (convertView == null) { + + LayoutInflater infalInflater = (LayoutInflater) this._context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); + convertView = infalInflater.inflate(R.layout.list_group_stock_entry, null); + } + TextView lblListHeader = (TextView) convertView.findViewById(R.id.lblListHeader); + ImageView stock_cam = (ImageView) convertView.findViewById(R.id.stock_cam); + stock_cam.setVisibility(View.GONE); + + if (headerTitle.getImagePath().isEmpty()) { + stock_cam.setImageDrawable(getResources().getDrawable(R.mipmap.camera)); + } else { + stock_cam.setImageDrawable(getResources().getDrawable(R.mipmap.camera_tick)); + } + + lblListHeader.setText(headerTitle.getSubBrandName() + " - " + headerTitle.getReferenceName() + " - " + headerTitle.getBrandName()); + if (!checkflag) { + if (checkHeaderArray.contains(groupPosition)) { + lblListHeader.setBackgroundColor(getResources().getColor(R.color.red)); + } else { + lblListHeader.setBackgroundColor(getResources().getColor(R.color.bright_red)); + } + + } else { + lblListHeader.setBackgroundColor(getResources().getColor(R.color.bright_red)); + } + return convertView; + } + + @Override + public boolean hasStableIds() { + return false; + } + + @Override + public boolean isChildSelectable(int groupPosition, int childPosition) { + return true; + } + } + + public class ViewHolder { + TextView ed_Stock, mrp; + Button stock_img_plus, stock_img_minus; + CardView cardView; + EditText et_stock; + } + + @Override + public void onDestroy() { + super.onDestroy(); + if (dialog != null && dialog.isShowing()) { + dialog.dismiss(); + } + } + + boolean isDataAdded = false; + + @Override + public void onBackPressed() { + //super.onBackPressed(); + isChanged(); + } + + void isChanged() { + if (isDataAdded) { + android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(this); + builder.setTitle("Parinaam"); + builder.setMessage(getResources().getString(R.string.data_will_be_lost)).setCancelable(false) + .setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { + + finish(); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + } + }) + .setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + + } + }); + android.app.AlertDialog alert = builder.create(); + alert.show(); + } else { + super.onBackPressed(); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + } + } + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + Log.i("MakeMachine", "resultCode: " + resultCode); + if (requestCode == 131) { + switch (resultCode) { + case 0: + Log.i("MakeMachine", "User cancelled"); + break; + + case -1: + if (_pathforcheck != null && !_pathforcheck.equals("")) { + if (new File(CommonString.getImagesFolder(context) + _pathforcheck).exists()) { + convertBitmap(CommonString.getImagesFolder(context) + _pathforcheck); + isDataAdded = true; + globalChildObject.setImagePath(_pathforcheck); + groupPositionGlobal = -1; + childPositionGlobal = -1; + _pathforcheck = ""; + listAdapter.notifyDataSetChanged(); + } + } + break; + } + } else { + IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data); + switch (resultCode) { + case 0: + + break; + + case -1: + db.open(); + ArrayList productList = db.getsku_fromproductusing_eancode(result.getContents(), false, visit_date, counter_id, null); + + if (productList.isEmpty()) { + productList = db.getsku_fromproductusing_eancode(removeFirstChar(result.getContents()), false, visit_date, counter_id, null); + } + + if (!productList.isEmpty()) { + flagScan = false; + img_scan.setImageDrawable(getResources().getDrawable(R.mipmap.ok)); + clearFilters(); + setScanFilter(productList); + } else { + + Toast.makeText(context, "Unable to scan currect data. Please try again", Toast.LENGTH_SHORT).show(); + } + break; + } + } + super.onActivityResult(requestCode, resultCode, data); + } + + //filter bottom sheet + View showFilterBottomSheet() { + + String uniqueId = UUID.randomUUID().toString(); + + final CardView cardSignature, cardBrand, cardSubBrand, cardReference; + + final BottomSheetDialog mBottomSheetDialog = new BottomSheetDialog(this); + final View sheetView = getLayoutInflater().inflate(R.layout.filter_bottom_sheet, null); + mBottomSheetDialog.setContentView(sheetView); + View bottomSheet = mBottomSheetDialog.getWindow().findViewById(com.google.android.material.R.id.design_bottom_sheet); + if (bottomSheet != null) { + bottomSheet.setBackgroundResource(android.R.color.transparent); + } + mBottomSheetDialog.setCancelable(false); + + final RecyclerView recBrand = sheetView.findViewById(R.id.rec_brand); + ImageView img_cancel = sheetView.findViewById(R.id.img_cancel); + TextView tv_clear_filter = sheetView.findViewById(R.id.tv_clear_filter); + recBrand.setAdapter(new ValueAdapter(context, signatureList, CommonString.Signature)); + recBrand.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, true)); + + cardSignature = sheetView.findViewById(R.id.card_signature); + cardBrand = sheetView.findViewById(R.id.card_brand); + cardSubBrand = sheetView.findViewById(R.id.card_sub_brand); + cardReference = sheetView.findViewById(R.id.card_reference); + + cardSignature.setOnClickListener(this); + cardBrand.setOnClickListener(this); + cardSubBrand.setOnClickListener(this); + cardReference.setOnClickListener(this); + + cardSignature.setCardBackgroundColor(getResources().getColor(R.color.dashboard_ach)); + + if (selectedSignature != null) { + (sheetView.findViewById(R.id.img_filter_signature)).setVisibility(View.VISIBLE); + } + if (selectedBrand != null) { + (sheetView.findViewById(R.id.img_filter_brand)).setVisibility(View.VISIBLE); + } + if (selectedSubBrand != null) { + (sheetView.findViewById(R.id.img_filter_sub_brand)).setVisibility(View.VISIBLE); + } + if (selectedReference != null) { + (sheetView.findViewById(R.id.img_filter_reference)).setVisibility(View.VISIBLE); + } + + img_cancel.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + mBottomSheetDialog.cancel(); + } + }); + + tv_clear_filter.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + setFilter(CLEAR_FILTER); + selectedSignature = null; + selectedBrand = null; + selectedSubBrand = null; + selectedReference = null; + + cardSignature.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background)); + cardBrand.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background)); + cardSubBrand.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background)); + cardReference.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background)); + + (sheetView.findViewById(R.id.img_filter_signature)).setVisibility(View.GONE); + (sheetView.findViewById(R.id.img_filter_brand)).setVisibility(View.GONE); + (sheetView.findViewById(R.id.img_filter_sub_brand)).setVisibility(View.GONE); + (sheetView.findViewById(R.id.img_filter_reference)).setVisibility(View.GONE); + + brandList = db.getsub_brand_name(counterGroupId, "BrandName", true); + subBrandList = db.getsub_brand_name(counterGroupId, "SubBrandName", true); + referenceList = db.getsub_brand_name(counterGroupId, "ReferenceName", true); + signatureList = db.getsub_brand_name(counterGroupId, "SignatureName", true); + + recBrand.getAdapter().notifyDataSetChanged(); + } + }); + + mBottomSheetDialog.show(); + + return sheetView; + } + + public class ValueAdapter extends RecyclerView.Adapter { + private LayoutInflater inflator; + List data; + ProductMaster productMaster; + String type; + + public ValueAdapter(Context context, List data, String type) { + inflator = LayoutInflater.from(context); + this.data = data; + this.type = type; + } + + @Override + public ValueAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int i) { + View view = inflator.inflate(R.layout.item_filter, parent, false); + return new ValueAdapter.MyViewHolder(view); + } + + @Override + public void onBindViewHolder(final ValueAdapter.MyViewHolder holder, final int position) { + final ProductMaster current = data.get(position); + + final boolean[] selected = {false}; + final int[] filterId = {0}; + + switch (type) { + + case CommonString.Signature: + if (selectedSignature != null && selectedSignature == current) { + selected[0] = true; + } + + break; + + case CommonString.Brand: + if (selectedBrand != null && selectedBrand == current) { + selected[0] = true; + } + + break; + + case CommonString.SubBrand: + if (selectedSubBrand != null && selectedSubBrand == current) { + selected[0] = true; + } + + break; + + case CommonString.Reference: + if (selectedReference != null && selectedReference == current) { + selected[0] = true; + } + + break; + } + + holder.tv_item.setText(CommonFunctions.capitalizeFirstLetter(current.getBrandName())); + + holder.tv_item.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + et_search.setText(""); + switch (type) { + case CommonString.Signature: + selectedSignature = current; + filterId[0] = R.id.img_filter_signature; + + //clear other sub filters-- + selectedBrand = null; + selectedSubBrand = null; + selectedReference = null; + + (sheetView.findViewById(R.id.img_filter_brand)).setVisibility(View.GONE); + (sheetView.findViewById(R.id.img_filter_sub_brand)).setVisibility(View.GONE); + (sheetView.findViewById(R.id.img_filter_reference)).setVisibility(View.GONE); + //-- + + setFilter(FILTER_FOR_SIGNATURE); + brandList = db.getSubBrandOrReference(counterGroupId, "BrandName", current.getBrandName(), null, null, true); + subBrandList = db.getSubBrandOrReference(counterGroupId, "SubBrandName", current.getBrandName(), null, null, true); + referenceList = db.getSubBrandOrReference(counterGroupId, "ReferenceName", current.getBrandName(), null, null, true); + + break; + case CommonString.Brand: + selectedBrand = current; + filterId[0] = R.id.img_filter_brand; + + //clear other sub filters-- + selectedSubBrand = null; + selectedReference = null; + + (sheetView.findViewById(R.id.img_filter_sub_brand)).setVisibility(View.GONE); + (sheetView.findViewById(R.id.img_filter_reference)).setVisibility(View.GONE); + //-- + + setFilter(FILTER_FOR_BRAND); + subBrandList = db.getSubBrandOrReference(counterGroupId, "SubBrandName", "", current.getBrandName(), null, true); + referenceList = db.getSubBrandOrReference(counterGroupId, "ReferenceName", "", current.getBrandName(), null, true); + break; + case CommonString.SubBrand: + selectedSubBrand = current; + filterId[0] = R.id.img_filter_sub_brand; + + //clear other sub filters-- + selectedReference = null; + + (sheetView.findViewById(R.id.img_filter_reference)).setVisibility(View.GONE); + //-- + + setFilter(FILTER_FOR_SUB_BRAND); + referenceList = db.getSubBrandOrReference(counterGroupId, "ReferenceName", "", null, current.getBrandName(), true); + break; + case CommonString.Reference: + selectedReference = current; + filterId[0] = R.id.img_filter_reference; + + setFilter(FILTER_FOR_REFERENCE); + break; + } + + RecyclerView recSubBrand = sheetView.findViewById(R.id.rec_brand); + recSubBrand.getAdapter().notifyDataSetChanged(); + //show filter icon on filter selected + (sheetView.findViewById(filterId[0])).setVisibility(View.VISIBLE); + } + }); + + if (selected[0]) { + holder.card.setCardBackgroundColor(getResources().getColor(R.color.dashboard_ach)); + } else { + holder.card.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background)); + } + } + + @Override + public int getItemCount() { + return data.size(); + } + + class MyViewHolder extends RecyclerView.ViewHolder { + TextView tv_item; + CardView card; + + public MyViewHolder(View itemView) { + super(itemView); + tv_item = (TextView) itemView.findViewById(R.id.tv_item); + card = (CardView) itemView.findViewById(R.id.item_card); + + } + } + } + + void setFilterSelected(View sheetView, String type) { + CardView cardSignature, cardBrand, cardSubBrand, cardReference; + cardSignature = sheetView.findViewById(R.id.card_signature); + cardBrand = sheetView.findViewById(R.id.card_brand); + cardSubBrand = sheetView.findViewById(R.id.card_sub_brand); + cardReference = sheetView.findViewById(R.id.card_reference); + + cardSignature.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background)); + cardBrand.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background)); + cardSubBrand.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background)); + cardReference.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background)); + + switch (type) { + case CommonString.Signature: + cardSignature.setCardBackgroundColor(getResources().getColor(R.color.dashboard_ach)); + break; + case CommonString.Brand: + cardBrand.setCardBackgroundColor(getResources().getColor(R.color.dashboard_ach)); + break; + case CommonString.SubBrand: + cardSubBrand.setCardBackgroundColor(getResources().getColor(R.color.dashboard_ach)); + break; + case CommonString.Reference: + cardReference.setCardBackgroundColor(getResources().getColor(R.color.dashboard_ach)); + break; + } + } + + public ArrayList filterListForSignature(List originalList, String text) { + ArrayList filterList = new ArrayList<>(); + for (ProductMaster object : originalList) { + if (object.getSignatureName().equalsIgnoreCase(text)) { + filterList.add(object); + } else { + continue; + } + } + return filterList; + } + + public ArrayList filterListForSubBrand(List originalList, String text) { + ArrayList filterList = new ArrayList<>(); + for (ProductMaster object : originalList) { + if (object.getSubBrandName().equalsIgnoreCase(text) && (selectedSignature == null || object.getSignatureName().equalsIgnoreCase(selectedSignature.getBrandName())) && (selectedBrand == null || object.getBrandName().equalsIgnoreCase(selectedBrand.getBrandName()))) { + filterList.add(object); + } else { + continue; + } + } + return filterList; + } + + public ArrayList filterListForReference(List originalList, String text) { + ArrayList filterList = new ArrayList<>(); + for (ProductMaster object : originalList) { + + if (object.getReferenceName().equalsIgnoreCase(text) && (selectedSignature == null || object.getSignatureName().equalsIgnoreCase(selectedSignature.getBrandName())) + && (selectedBrand == null || object.getBrandName().equalsIgnoreCase(selectedBrand.getBrandName())) && (selectedSubBrand == null || object.getSubBrandName().equalsIgnoreCase(selectedSubBrand.getBrandName()))) { + filterList.add(object); + } else { + continue; + } + } + return filterList; + } + + public void setFilter(int filterType) { + + if (filterType == FILTER_FOR_SIGNATURE) { + listAdapter = new ExpandableListAdapter(context, filterListForSignature(listDataHeader, selectedSignature.getBrandName()), listDataChild); + } else if (filterType == FILTER_FOR_BRAND) { + listAdapter = new ExpandableListAdapter(context, filterListForBrand(listDataHeader, selectedBrand.getBrandName()), listDataChild); + } else if (filterType == FILTER_FOR_SUB_BRAND) { + listAdapter = new ExpandableListAdapter(context, filterListForSubBrand(listDataHeader, selectedSubBrand.getBrandName()), listDataChild); + } else if (filterType == FILTER_FOR_REFERENCE) { + listAdapter = new ExpandableListAdapter(context, filterListForReference(listDataHeader, selectedReference.getBrandName()), listDataChild); + } else { + listAdapter = new ExpandableListAdapter(context, listDataHeader, listDataChild); + } + + lvExp_stock_check.setAdapter(listAdapter); + listAdapter.notifyDataSetChanged(); + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + getMenuInflater().inflate(R.menu.filter_menu, menu); + return super.onCreateOptionsMenu(menu); + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // Handle action bar item clicks here. The action bar will + // automatically handle clicks on the Home/Up button, so long + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + + if (id == android.R.id.home) { + isChanged(); + } else if (id == R.id.filter_data) { + sheetView = showFilterBottomSheet(); + + } + + return super.onOptionsItemSelected(item); + } + + public void uploadData(boolean finalFlag) { + //download service + // Intent intent = new Intent(context, Downloader.class); + SaleableGetterSetter stock = new SaleableGetterSetter(); + ArrayList data = new ArrayList<>(); + for (int i = 0; i < listDataHeader.size(); i++) { + List list = listDataChild.get(listDataHeader.get(i)); + for (int j = 0; j < list.size(); j++) { + //for final - complete data upload + if (finalFlag) { + data.add(list.get(j)); + } else { + if (list.get(j).isSelected()) { + data.add(list.get(j)); + } + } + } + } + + if (data.size() > 0) { + stock.setProductList(data); + String uuid = CommonFunctions.getUUID(context); + stock.setTransactionId(uuid); + ////changes by jeevan insert transaction for future use and handle master traction + if (regularStockFlag) { + db.open(); + db.insertStockTransactionMasterData(counter_id, visit_date, username, CommonString.GWP, stock, "Regular_Stock"); + } else { + if (finalFlag) { + db.open(); + db.insertStockTransactionMasterData(counter_id, visit_date, username, CommonString.GWP, stock, "FirstTime_Stock_Comp"); + } else { + db.open(); + db.insertStockTransactionMasterData(counter_id, visit_date, username, CommonString.GWP, stock, "FirstTime_Stock_Draft"); + } + } + + CommonFunctions.call_upload(context); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + GWPActivity.this.finish(); + } + } + + void dialogFinalSubmit(final HashMap> listDataChild, final ArrayList listDataHeader) { + android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(GWPActivity.this); + builder.setTitle(R.string.parinaam); + builder.setMessage(getResources().getString(R.string.want_to_final_save)).setCancelable(false) + .setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { + show_dialog_for_final_submit(context); + + } + }).setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + dialog.dismiss(); + } + }); + + android.app.AlertDialog alert = builder.create(); + alert.show(); + } + + + private void show_dialog_for_final_submit(final Context context) { + final MultiPurposeDialog final_save_dialog = new MultiPurposeDialog(context); + final_save_dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); + final_save_dialog.setContentView(R.layout.custom_dialog_final_save); + final WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); + lp.copyFrom(final_save_dialog.getWindow().getAttributes()); + lp.width = WindowManager.LayoutParams.MATCH_PARENT; + lp.height = WindowManager.LayoutParams.WRAP_CONTENT; + lp.gravity = Gravity.CENTER; + final_save_dialog.getWindow().setAttributes(lp); + final_save_dialog.setCancelable(false); + + final EditText txt_hint_yes = (EditText) final_save_dialog.findViewById(R.id.txt_hint_yes); + Button btn_cancel = (Button) final_save_dialog.findViewById(R.id.btn_cancel); + Button btn_okay = (Button) final_save_dialog.findViewById(R.id.btn_okay); + + btn_okay.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + if (txt_hint_yes.getText().toString().equals("")) { + AlertandMessages.showToastMsg(context, "Please Enter Text"); + } else if (!txt_hint_yes.getText().toString().trim().equalsIgnoreCase("yes")) { + AlertandMessages.showToastMsg(context, "Please Enter 'Yes' Text"); + } else { + final_save_dialog.dismiss(); + if (regularStockFlag) { + db.open(); + db.insertGWPCapturedData(visit_date, listDataChild, listDataHeader, false, counter_id); + uploadData(false); + } else { + db.open(); + db.insertGWPCapturedData(visit_date, listDataChild, listDataHeader, true, counter_id); + uploadData(true); + } + } + } + }); + + + btn_cancel.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + final_save_dialog.dismiss(); + } + }); + + final_save_dialog.show(); + } + + + public class MultiPurposeDialog extends Dialog { + public MultiPurposeDialog(Context context) { + super(context); + // DIALOG USER_INTERFACE TEMPLATE + WindowManager.LayoutParams wmLayoutParams = getWindow().getAttributes(); + wmLayoutParams.gravity = Gravity.CENTER; + getWindow().setAttributes(wmLayoutParams); + setTitle(null); + setCancelable(false); + setOnCancelListener(null); + LinearLayout layout = new LinearLayout(context); + layout.setOrientation(LinearLayout.VERTICAL); + } + } + + + private void openScanner() { + IntentIntegrator intentIntegrator = new IntentIntegrator((Activity) context); + intentIntegrator.setBeepEnabled(true); + intentIntegrator.setOrientationLocked(false); + intentIntegrator.setPrompt("Scan the barcode or QR code to get the data"); + intentIntegrator.initiateScan(); + } + + public void setScanFilter(List scanList) { + + HashMap> filterChildHashMap = new HashMap<>(); + + ArrayList filterList = new ArrayList<>(); + for (int i = 0; i < listDataHeader.size(); i++) { + ProductMaster parent = listDataHeader.get(i); + List listChild = listDataChild.get(parent); + List listFilterChild = new ArrayList<>(); + for (int j = 0; j < listChild.size(); j++) { + if (containsProduct(scanList, listChild.get(j))) { + listFilterChild.add(listChild.get(j)); + } else { + continue; + } + } + + if (listFilterChild.size() > 0) { + filterList.add(parent); + filterChildHashMap.put(parent, listFilterChild); + + } + + } + + ExpandableListAdapter listAdapter1 = new ExpandableListAdapter(context, filterList, filterChildHashMap); + lvExp_stock_check.setAdapter(listAdapter1); + for (int i = 0; i < listAdapter1.getGroupCount(); i++) { + lvExp_stock_check.expandGroup(i); + } + listAdapter1.notifyDataSetChanged(); + + /* if(filterList.size()>0){ + ExpandableListAdapter listAdapter = new ExpandableListAdapter(context, filterList, filterChildHashMap); + lvExp_stock_check.setAdapter(listAdapter); + listAdapter.notifyDataSetChanged(); + }*/ + + + } + + boolean containsProduct(List scanList, ProductMaster obj) { + boolean contains = false; + + for (int i = 0; i < scanList.size(); i++) { + if (scanList.get(i).getProductId().equals(obj.getProductId())) { + contains = true; + break; + } + } + + return contains; + } + + void clearFilters() { + et_search.setText(""); + + setFilter(CLEAR_FILTER); + selectedSignature = null; + selectedBrand = null; + selectedSubBrand = null; + selectedReference = null; + + if (sheetView != null) { + (sheetView.findViewById(R.id.img_filter_signature)).setVisibility(View.GONE); + (sheetView.findViewById(R.id.img_filter_brand)).setVisibility(View.GONE); + (sheetView.findViewById(R.id.img_filter_sub_brand)).setVisibility(View.GONE); + (sheetView.findViewById(R.id.img_filter_reference)).setVisibility(View.GONE); + } + db.open(); + brandList = db.getsub_brand_name(counterGroupId, "BrandName", true); + subBrandList = db.getsub_brand_name(counterGroupId, "SubBrandName", true); + referenceList = db.getsub_brand_name(counterGroupId, "ReferenceName", true); + signatureList = db.getsub_brand_name(counterGroupId, "SignatureName", true); + } + + private Dialog dialog; + ProgressBar pb; + + class LoadAsync extends AsyncTask { + + @Override + protected void onPreExecute() { + dialog = new Dialog(context); + dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); + dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT)); + dialog.setContentView(R.layout.circular_progress_bar); + pb = (ProgressBar) dialog.findViewById(R.id.progressBar1); + dialog.setCancelable(false); + dialog.show(); + + super.onPreExecute(); + } + + @Override + protected Void doInBackground(Void... voids) { + try { + prepareListData(); + } catch (Exception e) { + e.fillInStackTrace(); + prepareListData(); + } + + return null; + } + + @Override + protected void onPostExecute(Void aVoid) { + dialog.cancel(); + recSubAxe.setLayoutManager(new GridLayoutManager(context, 3)); + subAxeValueAdapter = new SubAxeValueAdapter(context, listSubAxe, CommonString.Signature); + recSubAxe.setAdapter(subAxeValueAdapter); + recSubAxe.getAdapter().notifyDataSetChanged(); + + listAdapter = new ExpandableListAdapter(context, listDataHeader, listDataChild); + lvExp_stock_check.setAdapter(listAdapter); + db.open(); + JourneyPlan jcp = db.getJCP(); + if (jcp != null) { + counterGroupId = jcp.getCounterGroupId().toString(); + } else { + counterGroupId = "1"; + } + + super.onPostExecute(aVoid); + } + } + + + public class SubAxeValueAdapter extends RecyclerView.Adapter { + private LayoutInflater inflator; + List data; + String type; + + public String getType() { + return type; + } + + public SubAxeValueAdapter(Context context, List data, String type) { + inflator = LayoutInflater.from(context); + this.data = data; + this.type = type; + } + + @Override + public SubAxeValueAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int i) { + View view = inflator.inflate(R.layout.item_filter, parent, false); + return new SubAxeValueAdapter.MyViewHolder(view); + } + + + @Override + public void onBindViewHolder(final SubAxeValueAdapter.MyViewHolder holder, final int position) { + final ProductMaster current = data.get(position); + holder.tv_item.setText(CommonFunctions.capitalizeFirstLetter(current.getSubAxeName())); + + holder.tv_item.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + et_search.setText(""); + listAdapter = new ExpandableListAdapter(context, filterListForSubAxe(listDataHeader, current.getSubAxeName()), listDataChild); + lvExp_stock_check.setAdapter(listAdapter); + listAdapter.notifyDataSetChanged(); + //setExpandableDataForSubAxe(current.getSubAxeName()); + current.setSelected(true); + selectedSubAxe = current.getSubAxeName(); + subAxeValueAdapter.notifyDataSetChanged(); + + JourneyPlan jcp = db.getJCP(); + if (jcp != null) { + db.open(); + brandList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "BrandName", true, selectedSubAxe); + db.open(); + subBrandList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "SubBrandName", true, selectedSubAxe); + db.open(); + referenceList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "ReferenceName", true, selectedSubAxe); + db.open(); + signatureList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "SignatureName", true, selectedSubAxe); + } else { + db.open(); + brandList = db.getsub_brand_name("1", "BrandName", true, selectedSubAxe); + subBrandList = db.getsub_brand_name("1", "SubBrandName", true, selectedSubAxe); + referenceList = db.getsub_brand_name("1", "ReferenceName", true, selectedSubAxe); + signatureList = db.getsub_brand_name("1", "SignatureName", true, selectedSubAxe); + } + } + }); + + if (current.getSubAxeName().equalsIgnoreCase(selectedSubAxe)) { + holder.card.setCardBackgroundColor(getResources().getColor(R.color.dashboard_ach)); + } else { + holder.card.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background)); + } + } + + @Override + public int getItemCount() { + return data.size(); + } + + class MyViewHolder extends RecyclerView.ViewHolder { + TextView tv_item; + CardView card; + + public MyViewHolder(View itemView) { + super(itemView); + tv_item = (TextView) itemView.findViewById(R.id.tv_item); + card = (CardView) itemView.findViewById(R.id.item_card); + + } + } + } + + public ArrayList filterListForSubAxe(List originalList, String text) { + ArrayList filterList = new ArrayList<>(); + for (ProductMaster object : originalList) { + if (object.getSubAxeName().equalsIgnoreCase(text)) { + filterList.add(object); + } else { + continue; + } + } + return filterList; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/GroomedActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/GroomedActivity.java new file mode 100644 index 0000000..c10cf3d --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/GroomedActivity.java @@ -0,0 +1,578 @@ +package com.cpm.lorealbaautomation.dailyactivity; + +import android.annotation.SuppressLint; +import android.app.AlertDialog; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.SharedPreferences; +import android.content.res.Resources; + +import com.google.android.material.floatingactionbutton.FloatingActionButton; + +import androidx.appcompat.app.AppCompatActivity; + +import android.os.Bundle; + +import androidx.cardview.widget.CardView; +import androidx.appcompat.widget.Toolbar; + +import android.util.Log; +import android.view.MenuItem; +import android.view.View; +import android.widget.ImageView; +import android.widget.TextView; + +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.constant.AlertandMessages; +import com.cpm.lorealbaautomation.constant.CommonFunctions; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.download.Downloader; +import com.cpm.lorealbaautomation.gsonGetterSetter.GroomingGetterSetter; + +import java.io.File; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.Locale; +import java.util.Objects; + +import static com.cpm.lorealbaautomation.constant.CommonFunctions.getCurrentTime_only; +import static com.cpm.lorealbaautomation.constant.CommonFunctions.show_image_preview; +import static com.cpm.lorealbaautomation.dailyactivity.StoreImageActivity.convertBitmap; + +public class GroomedActivity extends AppCompatActivity implements View.OnClickListener { + ImageView grooming_img_morng, grooming_img_noon, grooming_img_evning; + TextView time_morng_txt, time_noon_txt, time_evning_txt; + CardView cardview_evening, card_noon, card_morning; + FloatingActionButton btn_save; + TextView txt_login_tym; + Lorealba_Database db; + Context context; + AlertDialog alert; + String counter_id, visit_date, username, _pathforcheck, _path, loginTym = ""; + SimpleDateFormat simpleDateFormat; + boolean update_flag = false, clicked_flag = false; + GroomingGetterSetter groomedObject = new GroomingGetterSetter(); + boolean click_camera = false; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_groomed); + context = this; + Toolbar toolbar = findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + Objects.requireNonNull(getSupportActionBar()).setHomeButtonEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + if (!CommonFunctions.isTablet(context)) { + toolbar.setTitleTextAppearance(context, R.style.changestext_sizefor_mobile); + } + db = new Lorealba_Database(context); + db.open(); + validateuidata(); + validateinserted_data(); + } + + @SuppressLint("SetTextI18n") + private void validateuidata() { + SharedPreferences preferences = PrefHelper.getPrefs(context); + counter_id = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + username = preferences.getString(CommonString.KEY_USERNAME, ""); + grooming_img_morng = (ImageView) findViewById(R.id.grooming_img_morng); + grooming_img_noon = (ImageView) findViewById(R.id.grooming_img_noon); + grooming_img_evning = (ImageView) findViewById(R.id.grooming_img_evning); + btn_save = (FloatingActionButton) findViewById(R.id.btn_save); + txt_login_tym = (TextView) findViewById(R.id.txt_login_tym); + + cardview_evening = (CardView) findViewById(R.id.cardview_evening); + card_noon = (CardView) findViewById(R.id.card_noon); + card_morning = (CardView) findViewById(R.id.card_morning); + + ///for timer + time_morng_txt = (TextView) findViewById(R.id.time_morng_txt); + time_noon_txt = (TextView) findViewById(R.id.time_noon_txt); + time_evning_txt = (TextView) findViewById(R.id.time_evning_txt); + setTitle("Grooming Image -" + username); + + grooming_img_morng.setOnClickListener(this); + grooming_img_noon.setOnClickListener(this); + grooming_img_evning.setOnClickListener(this); + + btn_save.setOnClickListener(this); + db.open(); + loginTym = db.get_baLoginTym(visit_date, username).getUserLoginTym(); + if (loginTym != null && !loginTym.isEmpty()) { + loginTym = CommonFunctions.setTimeFormat(loginTym); + if (loginTym != null) { + txt_login_tym.setText("Login Time - " + loginTym); + } else { + txt_login_tym.setText("Login Time - " + CommonFunctions.getCurrentTime_only()); + } + } else { + txt_login_tym.setText("Login Time - " + CommonFunctions.getCurrentTime_only()); + } + add_time_for_showat_text(); + } + + @SuppressLint("SetTextI18n") + private void add_time_for_showat_text() { + try { + db.open(); + loginTym = db.get_baLoginTym(visit_date, username).getUserLoginTym(); + if (loginTym != null && !loginTym.isEmpty()) { + loginTym = CommonFunctions.setTimeFormat(loginTym); + if (loginTym != null && !loginTym.isEmpty()) { + time_morng_txt.setText("Before " + addtime_str(loginTym, 45, 0)); + } + db.open(); + loginTym = db.get_baLoginTym(visit_date, username).getUserLoginTym(); + if (loginTym != null && !loginTym.isEmpty()) { + loginTym = CommonFunctions.setTimeFormat(loginTym); + if (loginTym != null && !loginTym.isEmpty()) + time_noon_txt.setText("Between " + addtime_str(loginTym, 0, 03) + " - " + addtime_str(loginTym, 10, 03)); + } + db.open(); + loginTym = db.get_baLoginTym(visit_date, username).getUserLoginTym(); + if (loginTym != null && !loginTym.isEmpty()) { + loginTym = CommonFunctions.setTimeFormat(loginTym); + if (loginTym != null && !loginTym.isEmpty()) + time_evning_txt.setText("Between " + addtime_str(loginTym, 0, 06) + " - " + addtime_str(loginTym, 10, 06)); + } + } + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + if (id == android.R.id.home) { + if (clicked_flag) { + AlertDialog.Builder builder = new AlertDialog.Builder(context).setMessage(CommonString.ONBACK_ALERT_MESSAGE).setCancelable(false).setPositiveButton("Ok", + (dialog, id1) -> { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + GroomedActivity.this.finish(); + }).setNegativeButton("Cancel", (dialog, id12) -> dialog.cancel()); + AlertDialog alert = builder.create(); + alert.show(); + } else { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + GroomedActivity.this.finish(); + } + } + + return super.onOptionsItemSelected(item); + } + + @Override + public void onBackPressed() { + if (clicked_flag) { + AlertDialog.Builder builder = new AlertDialog.Builder(context).setMessage(CommonString.ONBACK_ALERT_MESSAGE).setCancelable(false).setPositiveButton("Ok", + (dialog, id) -> { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + GroomedActivity.this.finish(); + }).setNegativeButton("Cancel", (dialog, id) -> dialog.cancel()); + AlertDialog alert = builder.create(); + alert.show(); + } else { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + GroomedActivity.this.finish(); + } + } + + @SuppressLint("NonConstantResourceId") + @Override + public void onClick(View view) { + + if (view.getId() == R.id.grooming_img_morng) { + try { + SimpleDateFormat simpleDateFormat = null; + ////for morning tym after Added 45 minutes + db.open(); + loginTym = db.get_baLoginTym(visit_date, username).getUserLoginTym(); + if (loginTym != null && !loginTym.isEmpty()) { + loginTym = CommonFunctions.setTimeFormat(loginTym); + assert loginTym != null && !loginTym.isEmpty(); + String morngTym = addtime_str(loginTym, 59, 2); + assert !morngTym.isEmpty(); + simpleDateFormat = new SimpleDateFormat("hh:mm:ss a", Locale.ENGLISH); + Date date1 = simpleDateFormat.parse(morngTym); + Date date2 = simpleDateFormat.parse(getTime()); + assert date2 != null; + if (date2.before(date1)) { + if (groomedObject.getMorning_groom_img_str().equals("")) { + clicked_flag = true; + _pathforcheck = counter_id + "_groomed_img_mrng_" + visit_date.replace("/", "") + "_" + getCurrentTime_only().replace(":", "") + ".jpg"; + _path = CommonString.getImagesFolder(context) + _pathforcheck; + if (CommonFunctions.isTablet(context)) { + CommonFunctions.startAnncaCameraActivity(this, _path, null, false, CommonString.CAMERA_FACE_REAR); + } else { + CommonFunctions.startAnncaCameraActivity(this, _path, null, false, CommonString.CAMERA_FACE_FRONT); + } + } + } + if (!groomedObject.getMorning_groom_img_str().isEmpty()) { + show_image_preview(context, groomedObject.getMorning_groom_img_str()); + } + } + + } catch (NumberFormatException | ParseException e) { + e.fillInStackTrace(); + } + } else if (view.getId() == R.id.grooming_img_noon) { + try { + ////for nooo tym after adding 03:10 + db.open(); + loginTym = db.get_baLoginTym(visit_date, username).getUserLoginTym(); + loginTym = CommonFunctions.setTimeFormat(loginTym); + String noonTym = addtime_str(loginTym, 0, 03); + String endNoonTym = addtime_str(loginTym, 59, 05); + simpleDateFormat = new SimpleDateFormat("hh:mm:ss a", Locale.ENGLISH); + Date date1 = simpleDateFormat.parse(noonTym); + Date date2 = simpleDateFormat.parse(getTime()); + Date date3 = simpleDateFormat.parse(endNoonTym); + assert date2 != null; + if (date2.after(date1) && date2.before(date3)) { + if (groomedObject.getNoon_groom_img_str().equals("")) { + clicked_flag = true; + _pathforcheck = counter_id + "_groomed_img_noon_" + visit_date.replace("/", "") + "_" + getCurrentTime_only().replace(":", "") + ".jpg"; + _path = CommonString.getImagesFolder(context) + _pathforcheck; + if (CommonFunctions.isTablet(context)) { + CommonFunctions.startAnncaCameraActivity(this, _path, null, false, CommonString.CAMERA_FACE_REAR); + } else { + CommonFunctions.startAnncaCameraActivity(this, _path, null, false, CommonString.CAMERA_FACE_FRONT); + } + } + } + if (!groomedObject.getNoon_groom_img_str().equals("")) { + show_image_preview(context, groomedObject.getNoon_groom_img_str()); + } + } catch (NumberFormatException | ParseException e) { + e.fillInStackTrace(); + } + + } else if (view.getId() == R.id.grooming_img_evning) { + try { + ////for evenning tym after adding 03:10 + db.open(); + loginTym = db.get_baLoginTym(visit_date, username).getUserLoginTym(); + loginTym = CommonFunctions.setTimeFormat(loginTym); + String evngTym = addtime_str(loginTym, 0, 06); + String EndevngTym = addtime_str(loginTym, 59, 8); + simpleDateFormat = new SimpleDateFormat("hh:mm:ss a", Locale.ENGLISH); + Date date1 = simpleDateFormat.parse(evngTym); + Date date2 = simpleDateFormat.parse(getTime()); + Date date3 = simpleDateFormat.parse(EndevngTym); + assert date2 != null; + if (date2.after(date1) && date2.before(date3)) { + if (groomedObject.getEvenning_groom_img_str().equals("")) { + clicked_flag = true; + _pathforcheck = counter_id + "_groomed_img_evning_" + visit_date.replace("/", "") + "_" + getCurrentTime_only().replace(":", "") + ".jpg"; + _path = CommonString.getImagesFolder(context) + _pathforcheck; + if (CommonFunctions.isTablet(context)) { + CommonFunctions.startAnncaCameraActivity(this, _path, null, false, CommonString.CAMERA_FACE_REAR); + } else { + CommonFunctions.startAnncaCameraActivity(this, _path, null, false, CommonString.CAMERA_FACE_FRONT); + } + } + } + if (!groomedObject.getEvenning_groom_img_str().equals("")) { + show_image_preview(context, groomedObject.getEvenning_groom_img_str()); + } + } catch (NumberFormatException | ParseException e) { + e.fillInStackTrace(); + } + } else if (view.getId() == R.id.btn_save) { + if (validategroomedimg() && click_camera) { + AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle(R.string.dialog_title).setMessage(R.string.title_activity_save_data).setCancelable(false).setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { + alert.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false); + db.open(); + if (update_flag) { + db.open(); + db.update_Groomed_images(counter_id, username, visit_date, groomedObject, CommonFunctions.getUUID(context)); + } else { + db.open(); + db.inseetgroomingdata(counter_id, username, visit_date, groomedObject); + + } + //download service + Intent intent = new Intent(context, Downloader.class); + intent.putExtra(CommonString.KEY_Groomed_Image, groomedObject); + Downloader.enqueueWork(context, intent); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + AlertandMessages.showToastMsg(context, "Data saved successfully."); + GroomedActivity.this.finish(); + } + }).setNegativeButton(android.R.string.cancel, (dialog, id1) -> dialog.cancel()); + + alert = builder.create(); + alert.show(); + } + } + + } + + @SuppressLint("UseCompatLoadingForDrawables") + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + Log.i("MakeMachine", "resultCode: " + resultCode); + switch (resultCode) { + + case 0: + Log.i("MakeMachine", "User cancelled"); + break; + + case -1: + if (_pathforcheck != null && !_pathforcheck.equals("")) { + if (new File(CommonString.getImagesFolder(context) + _pathforcheck).exists()) { + try { + convertBitmap(CommonString.getImagesFolder(context) + _pathforcheck); + if (_pathforcheck.contains("_groomed_img_mrng_")) { + grooming_img_morng.setImageDrawable(getResources().getDrawable(R.mipmap.camera_bsd)); + groomedObject.setMorning_groom_img_str(_pathforcheck); + groomedObject.setMorning_groom_time_str(getCurrentTime_only()); + click_camera = true; + } else if (_pathforcheck.contains("_groomed_img_noon_")) { + grooming_img_noon.setImageDrawable(getResources().getDrawable(R.mipmap.camera_bsd)); + groomedObject.setNoon_groom_img_str(_pathforcheck); + groomedObject.setNoon_groom_time_str(getCurrentTime_only()); + click_camera = true; + } else if (_pathforcheck.contains("_groomed_img_evning_")) { + grooming_img_evning.setImageDrawable(getResources().getDrawable(R.mipmap.camera_bsd)); + groomedObject.setEvenning_groom_img_str(_pathforcheck); + groomedObject.setEvenning_groom_time_str(getCurrentTime_only()); + click_camera = true; + } + } catch (Exception e) { + // TODO Auto-generated catch block + e.fillInStackTrace(); + + AlertandMessages.showToastMsg(context, "Error"); + } + + _pathforcheck = ""; + } + } + + break; + } + super.onActivityResult(requestCode, resultCode, data); + } + + + private boolean validategroomedimg() { + boolean status = true; + try { + SimpleDateFormat simpleDateFormat = null; + ////for morning tym after Added 45 minutes + db.open(); + loginTym = db.get_baLoginTym(visit_date, username).getUserLoginTym(); + loginTym = CommonFunctions.setTimeFormat(loginTym); + String morngTym = addtime_str(loginTym, 59, 2); + simpleDateFormat = new SimpleDateFormat("hh:mm:ss a", Locale.ENGLISH); + Date date1 = simpleDateFormat.parse(morngTym); + Date date2 = simpleDateFormat.parse(getTime()); + + ////for nooo tym after adding 03:10 + String noonTym = addtime_str(loginTym, 0, 03); + String endNoonTym = addtime_str(loginTym, 59, 05); + simpleDateFormat = new SimpleDateFormat("hh:mm:ss a", Locale.ENGLISH); + Date noondate1 = simpleDateFormat.parse(noonTym); + Date noondate2 = simpleDateFormat.parse(getTime()); + Date noondate3 = simpleDateFormat.parse(endNoonTym); + + String evngTym = addtime_str(loginTym, 0, 06); + String EndevngTym = addtime_str(loginTym, 59, 8); + simpleDateFormat = new SimpleDateFormat("hh:mm:ss a", Locale.ENGLISH); + Date evngdate1 = simpleDateFormat.parse(evngTym); + Date evngdate2 = simpleDateFormat.parse(getTime()); + Date evngdate3 = simpleDateFormat.parse(EndevngTym); + + assert date2 != null; + if (date2.before(date1)) { + if (groomedObject.getMorning_groom_img_str().equals("")) { + AlertandMessages.showToastMsg(context, "Please Capture Full Grooming Image Before " + addtime_str(loginTym, 45, 0)); + status = false; + } + } else { + assert noondate2 != null; + if (noondate2.after(noondate1) && noondate2.before(noondate3)) { + if (groomedObject.getNoon_groom_img_str().equals("")) { + AlertandMessages.showToastMsg(context, "Please Capture Full Grooming Image Between " + addtime_str(loginTym, 0, 3) + " - " + addtime_str(loginTym, 59, 5)); + status = false; + } + } else { + assert evngdate2 != null; + if (evngdate2.after(evngdate1) && evngdate2.before(evngdate3)) { + if (groomedObject.getEvenning_groom_img_str().equals("")) { + AlertandMessages.showToastMsg(context, "Please Capture Full Grooming Image Between " + addtime_str(loginTym, 0, 6) + " - " + addtime_str(loginTym, 59, 8)); + status = false; + } + } + } + } + } catch (ParseException e) { + e.fillInStackTrace(); + } + + return status; + } + + @SuppressLint("UseCompatLoadingForDrawables") + private void validateinserted_data() { + db.open(); + groomedObject = db.getinserted_groomingdata(counter_id, username, visit_date); + if (!groomedObject.getMorning_groom_img_str().equals("") || !groomedObject.getNoon_groom_img_str().equals("") || !groomedObject.getEvenning_groom_img_str().equals("")) { + update_flag = true; + if (!groomedObject.getMorning_groom_img_str().equals("")) { + grooming_img_morng.setImageDrawable(getResources().getDrawable(R.mipmap.camera_bsd)); + } + if (!groomedObject.getNoon_groom_img_str().equals("")) { + grooming_img_noon.setImageDrawable(getResources().getDrawable(R.mipmap.camera_bsd)); + } + + if (!groomedObject.getEvenning_groom_img_str().equals("")) { + grooming_img_evning.setImageDrawable(getResources().getDrawable(R.mipmap.camera_bsd)); + } + + } +/////for disable + groomingimg_morng(); + groomedNoonImg(); + groomedeveningimg(); + } + + + private String addtime_str(String str, int minuts, int hours) { + SimpleDateFormat displayFormat = null; + SimpleDateFormat parseFormat = null; + Calendar calendar = null; + Date date = null; + try { + parseFormat = new SimpleDateFormat("hh:mm:ss a", Locale.ENGLISH); + displayFormat = new SimpleDateFormat("hh:mm:ss a", Locale.ENGLISH); + date = parseFormat.parse(str); + calendar = Calendar.getInstance(); + assert date != null; + calendar.setTime(date); + calendar.add(Calendar.HOUR, hours); + calendar.add(Calendar.MINUTE, minuts); + //test(displayFormat.format(calendar.getTime())); + } catch (ParseException e) { + e.fillInStackTrace(); + } + + assert calendar != null; + return displayFormat.format(calendar.getTime()); + } + + private String getTime() { + Calendar currnetDateTime = Calendar.getInstance(); + SimpleDateFormat df = new SimpleDateFormat("hh:mm:ss a", Locale.ENGLISH); + return df.format(currnetDateTime.getTime()); + } + + private void groomingimg_morng() { + try { + SimpleDateFormat simpleDateFormat = null; + ////for morning tym after Added 45 minutes + db.open(); + loginTym = db.get_baLoginTym(visit_date, username).getUserLoginTym(); + loginTym = CommonFunctions.setTimeFormat(loginTym); + String morngTym = addtime_str(loginTym, 59, 2); + simpleDateFormat = new SimpleDateFormat("hh:mm:ss a", Locale.ENGLISH); + Date date1 = simpleDateFormat.parse(morngTym); + Date date2 = simpleDateFormat.parse(getTime()); + assert date2 != null; + if (date2.before(date1)) { + + } else { + if (groomedObject.getMorning_groom_img_str().equals("")) { + card_morning.setCardBackgroundColor(getResources().getColor(R.color.light_red)); + grooming_img_morng.setImageResource(R.mipmap.red_camera_icon); + } + } + + } catch (ParseException e) { + e.fillInStackTrace(); + } + } + + private void groomedNoonImg() { + try { + SimpleDateFormat simpleDateFormat = null; + ////for nooo tym after adding 03:10 + db.open(); + loginTym = db.get_baLoginTym(visit_date, username).getUserLoginTym(); + loginTym = CommonFunctions.setTimeFormat(loginTym); + String noonTym = addtime_str(loginTym, 0, 03); + String endNoonTym = addtime_str(loginTym, 59, 05); + simpleDateFormat = new SimpleDateFormat("hh:mm:ss a", Locale.ENGLISH); + Date date1 = simpleDateFormat.parse(noonTym); + Date date2 = simpleDateFormat.parse(getTime()); + Date date3 = simpleDateFormat.parse(endNoonTym); + assert date2 != null; + if (date2.after(date1) && date2.before(date3)) { + + } else if (date2.before(date1) && date2.before(date3)) { + if (groomedObject.getEvenning_groom_img_str().equals("")) { + card_noon.setCardBackgroundColor(getResources().getColor(R.color.gray)); + grooming_img_noon.setImageResource(R.mipmap.camera); + } + } else { + if (groomedObject.getNoon_groom_img_str().equals("")) { + card_noon.setCardBackgroundColor(getResources().getColor(R.color.light_red)); + grooming_img_noon.setImageResource(R.mipmap.red_camera_icon); + } + } + } catch (ParseException e) { + e.fillInStackTrace(); + } catch (NumberFormatException e) { + e.fillInStackTrace(); + } catch (Resources.NotFoundException e) { + e.fillInStackTrace(); + } + } + + private void groomedeveningimg() { + try { + SimpleDateFormat simpleDateFormat = null; + ////for evenning tym after adding 03:10 + db.open(); + loginTym = db.get_baLoginTym(visit_date, username).getUserLoginTym(); + loginTym = CommonFunctions.setTimeFormat(loginTym); + String evngTym = addtime_str(loginTym, 0, 06); + String EndevngTym = addtime_str(loginTym, 59, 8); + simpleDateFormat = new SimpleDateFormat("hh:mm:ss a", Locale.ENGLISH); + Date date1 = simpleDateFormat.parse(evngTym); + Date date2 = simpleDateFormat.parse(getTime()); + Date date3 = simpleDateFormat.parse(EndevngTym); + + assert date2 != null; + if (date2.after(date1) && date2.before(date3)) { + + } else if (date2.before(date1) && date2.before(date3)) { + if (groomedObject.getEvenning_groom_img_str().equals("")) { + cardview_evening.setCardBackgroundColor(getResources().getColor(R.color.gray)); + grooming_img_evning.setImageResource(R.mipmap.camera); + } + } else { + if (groomedObject.getEvenning_groom_img_str().equals("")) { + cardview_evening.setCardBackgroundColor(getResources().getColor(R.color.light_red)); + grooming_img_evning.setImageResource(R.mipmap.red_camera_icon); + } + } + + } catch (ParseException e) { + e.fillInStackTrace(); + } + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/InWardStockActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/InWardStockActivity.java new file mode 100644 index 0000000..bb1c973 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/InWardStockActivity.java @@ -0,0 +1,252 @@ +package com.cpm.lorealbaautomation.dailyactivity; + +import android.annotation.SuppressLint; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.os.Bundle; + +import androidx.annotation.NonNull; + +import com.google.android.material.floatingactionbutton.FloatingActionButton; + +import androidx.appcompat.app.AppCompatActivity; +import androidx.cardview.widget.CardView; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; +import androidx.appcompat.widget.Toolbar; + +import android.view.LayoutInflater; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; +import android.widget.ImageView; +import android.widget.LinearLayout; +import android.widget.TextView; + +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.constant.CommonFunctions; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.gsonGetterSetter.TCounterInvoice; + +import java.util.ArrayList; +import java.util.Objects; + +public class InWardStockActivity extends AppCompatActivity implements View.OnClickListener { + Lorealba_Database db; + Context context; + SharedPreferences preferences; + String counter_id, visit_date, username; + ArrayList counterInvoiceList = new ArrayList<>(); + RecyclerView invoiceListView; + ValueAdapter adapter; + FloatingActionButton addBtn; + public ArrayList manualInwardStockList = new ArrayList<>(); + + @SuppressLint("SetTextI18n") + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_in_ward_stock); + context = this; + db = new Lorealba_Database(context); + db.open(); + validateUIData(); + db.open(); + addBtn.setVisibility(db.getHideManualInwordCount()? View.GONE : View.VISIBLE); + String couter_code = preferences.getString(CommonString.KEY_COUNTER_CODE, ""); + TextView txt_counter_code = (TextView) findViewById(R.id.txt_counter_code); + txt_counter_code.setText("Counter Code - " + couter_code + " / Id - " + counter_id); + } + + private void validateUIData() { + preferences = PrefHelper.getPrefs(context); + counter_id = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + username = preferences.getString(CommonString.KEY_USERNAME, ""); + invoiceListView = (RecyclerView) findViewById(R.id.invoice_list); + addBtn = (FloatingActionButton) findViewById(R.id.add_btn); + addBtn.setOnClickListener(this::onClick); + Toolbar toolbar = findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + Objects.requireNonNull(getSupportActionBar()).setHomeButtonEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + if (!CommonFunctions.isTablet(context)) { + toolbar.setTitleTextAppearance(context, R.style.changestext_sizefor_mobile); + } + setTitle("InWard Stock - " + visit_date); + invoiceListView.addOnScrollListener(new RecyclerView.OnScrollListener() { + @Override + public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) { + super.onScrolled(recyclerView, dx, dy); + } + }); + } + + @Override + protected void onResume() { + super.onResume(); + db.open(); + manualInwardStockList = db.getManualInwardStockData(counter_id, visit_date); + counterInvoiceList = db.getInwardStockData(counter_id, visit_date); + if (!counterInvoiceList.isEmpty()) { + if (!manualInwardStockList.isEmpty()) { + if (!manualInwardStockList.get(0).getNo_ofLine().equals("0")) { + counterInvoiceList.addAll(manualInwardStockList); + } + } + adapter = new ValueAdapter(counterInvoiceList, context); + invoiceListView.setAdapter(adapter); + invoiceListView.setLayoutManager(new LinearLayoutManager(context)); + } else { + adapter = new ValueAdapter(manualInwardStockList, context); + invoiceListView.setAdapter(adapter); + invoiceListView.setLayoutManager(new LinearLayoutManager(context)); + } + } + + @Override + public void onClick(View view) { + if (view.getId() == R.id.add_btn) { + Intent intent = new Intent(context, ManualInWardStockActivity.class); + intent.putExtra(CommonString.KEY_VALUE, "add"); + startActivity(intent); + } + } + + private class ValueAdapter extends RecyclerView.Adapter { + ArrayList counterInvoiceList; + LayoutInflater inflator; + Context context; + + public ValueAdapter(ArrayList counterInvoiceList, Context context) { + this.counterInvoiceList = counterInvoiceList; + inflator = LayoutInflater.from(context); + this.context = context; + } + + @NonNull + @Override + public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) { + View view = inflator.inflate(R.layout.invoice_detail_layout, parent, false); + return new ViewHolder(view); + } + @Override + public void onBindViewHolder(@NonNull final ViewHolder viewHolder, final int pos) { + TCounterInvoice object = counterInvoiceList.get(pos); + viewHolder.invoiceNumber.setText(object.getInvoiceNo()); + viewHolder.invoiceNumber.setId(pos); + viewHolder.invoiceDate.setText(object.getInvoiceDate()); + viewHolder.invoiceDate.setId(pos); + viewHolder.invoiceType.setText(object.getInvoiceType()); + viewHolder.invoiceType.setId(pos); + viewHolder.noOfLine.setText(object.getNo_ofLine()); + viewHolder.noOfLine.setId(pos); + viewHolder.approvedLine.setText(object.getApproved_line()); + viewHolder.approvedLine.setId(pos); + viewHolder.invoiceAmount.setText(object.getFinalAmount()); + viewHolder.invoiceAmount.setId(pos); + if (object.getSource().isEmpty()) { + viewHolder.inwardStockView.setCardBackgroundColor(getResources().getColor(R.color.light_blue)); + viewHolder.inwardStockView.setId(pos); + } else { + viewHolder.inwardStockView.setCardBackgroundColor(getResources().getColor(R.color.light_green)); + viewHolder.inwardStockView.setId(pos); + } + + if (object.getSource().isEmpty() || object.getSource().equalsIgnoreCase("DMS")) { + viewHolder.layout_background.setBackgroundColor(getResources().getColor(R.color.grey_dark_background)); + viewHolder.layout_background.setId(pos); + } else { + viewHolder.layout_background.setBackgroundColor(getResources().getColor(R.color.dark_light_gray)); + viewHolder.layout_background.setId(pos); + } + + ///for DMS Approved or not + if (!object.getNo_ofLine().equalsIgnoreCase(object.getApproved_line()) && (object.getSource().equalsIgnoreCase("DMS") + || object.getSource().isEmpty())) { + viewHolder.draftImg.setVisibility(View.VISIBLE); + viewHolder.draftImg.setBackgroundResource(R.drawable.incomplete_icon); + viewHolder.draftImg.setId(pos); + } else { + viewHolder.draftImg.setVisibility(View.VISIBLE); + viewHolder.draftImg.setBackgroundResource(R.drawable.complete_icon); + viewHolder.draftImg.setId(pos); + } + + ////for Manual Draft and compelete.... + if (object.getInvoiceStatus() && object.getSource().equalsIgnoreCase("Manual")) { + viewHolder.draftImg.setVisibility(View.VISIBLE); + viewHolder.draftImg.setBackgroundResource(R.drawable.complete_icon); + viewHolder.draftImg.setId(pos); + } else { + if (counterInvoiceList.get(pos).getSource().equalsIgnoreCase("Manual")) { + viewHolder.draftImg.setVisibility(View.VISIBLE); + viewHolder.draftImg.setBackgroundResource(R.mipmap.saved_draft); + viewHolder.draftImg.setId(pos); + } + } + + viewHolder.inwardStockView.setOnClickListener(view -> { + Intent intent; + if (object.getSource().isEmpty() || object.getSource().equalsIgnoreCase("DMS")) { + intent = new Intent(context, InwardStockDetailsActivity.class); + intent.putExtra(CommonString.TAG_OBJECT, object); + } else { + intent = new Intent(context, ManualInWardStockActivity.class); + intent.putExtra(CommonString.TAG_OBJECT, object); + intent.putExtra(CommonString.KEY_VALUE, "edit"); + } + startActivity(intent); + }); + } + + @Override + public int getItemCount() { + return counterInvoiceList.size(); + } + + public class ViewHolder extends RecyclerView.ViewHolder { + TextView invoiceNumber, invoiceDate, invoiceType, noOfLine, approvedLine, invoiceAmount; + LinearLayout layout_background; + CardView inwardStockView; + ImageView draftImg; + + public ViewHolder(@NonNull View itemView) { + super(itemView); + invoiceDate = (TextView) itemView.findViewById(R.id.date_txt); + draftImg = (ImageView) itemView.findViewById(R.id.draft_image); + noOfLine = (TextView) itemView.findViewById(R.id.no_of_lines_txt); + invoiceType = (TextView) itemView.findViewById(R.id.invoice_type_txt); + approvedLine = (TextView) itemView.findViewById(R.id.approved_line_txt); + invoiceAmount = (TextView) itemView.findViewById(R.id.invoice_amount_txt); + inwardStockView = (CardView) itemView.findViewById(R.id.inward_stock_view); + invoiceNumber = (TextView) itemView.findViewById(R.id.invoice_number_txt); + layout_background = (LinearLayout) itemView.findViewById(R.id.layout_background); + } + } + } + + + @Override + public void onBackPressed() { + super.onBackPressed(); + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // Handle action bar item clicks here. The action bar will + // automatically handle clicks on the Home/Up button, so long + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + if (id == android.R.id.home) { + finish(); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + } + + return super.onOptionsItemSelected(item); + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/InwardStockDetailsActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/InwardStockDetailsActivity.java new file mode 100644 index 0000000..1e02194 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/InwardStockDetailsActivity.java @@ -0,0 +1,1615 @@ +package com.cpm.lorealbaautomation.dailyactivity; + +import android.annotation.SuppressLint; +import android.app.Activity; +import android.app.AlertDialog; +import android.app.Dialog; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.content.res.ColorStateList; +import android.graphics.Color; +import android.graphics.drawable.ColorDrawable; +import android.os.AsyncTask; +import android.os.Build; +import android.os.Bundle; + +import androidx.annotation.NonNull; +import androidx.annotation.RequiresApi; + +import com.google.android.material.bottomsheet.BottomSheetDialog; +import com.google.android.material.floatingactionbutton.FloatingActionButton; + +import androidx.appcompat.app.AppCompatActivity; +import androidx.cardview.widget.CardView; +import androidx.recyclerview.widget.GridLayoutManager; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; +import androidx.appcompat.widget.Toolbar; + +import android.text.Editable; +import android.text.TextWatcher; +import android.view.Gravity; +import android.view.LayoutInflater; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; +import android.view.Window; +import android.view.WindowManager; +import android.widget.AbsListView; +import android.widget.AdapterView; +import android.widget.BaseExpandableListAdapter; +import android.widget.Button; +import android.widget.CheckBox; +import android.widget.EditText; +import android.widget.ExpandableListView; +import android.widget.ImageView; +import android.widget.LinearLayout; +import android.widget.ProgressBar; +import android.widget.Spinner; +import android.widget.TextView; + +import com.google.zxing.integration.android.IntentIntegrator; +import com.google.zxing.integration.android.IntentResult; +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.adapter.ReasonSpinnerAdapter; +import com.cpm.lorealbaautomation.constant.AlertandMessages; +import com.cpm.lorealbaautomation.constant.CommonFunctions; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.gsonGetterSetter.JourneyPlan; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterNonStockReason; +import com.cpm.lorealbaautomation.gsonGetterSetter.ProductMaster; +import com.cpm.lorealbaautomation.gsonGetterSetter.TCounterInvoice; +import com.cpm.lorealbaautomation.gsonGetterSetter.TStockSummary; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Objects; + +import static com.cpm.lorealbaautomation.constant.CommonFunctions.removeFirstChar; + +public class InwardStockDetailsActivity extends AppCompatActivity implements View.OnClickListener { + TextView invoiceNumber, invoiceType; + ArrayList brandList = new ArrayList<>(); + ExpandableListView lvExp_stock_check; + FloatingActionButton fab_save; + Lorealba_Database db; + Context context; + private SharedPreferences preferences; + String counter_id, visit_date, username, invoiceNo, type; + ArrayList listDataHeader = new ArrayList<>(); + ArrayList childStockList; + HashMap> listDataChild; + ExpandableListAdapter listAdapter; + String brandName = ""; + String axeName = ""; + String subAxeName = "", invDate = "", Error_Msg = ""; + TCounterInvoice tCounterInvoice; + CheckBox confirmationCheckAll; + boolean headerCheckedFlag = false; + boolean headerTransactionFlag = false; + boolean checkConfirmationAll = false; + boolean checkflag = true; + View sheetView; + EditText et_search; + ImageView bar_code_img, img_clear_subaxe; + String msg = ""; + ArrayList signatureList = new ArrayList<>(); + ProductMaster selectedSignature, selectedBrand, selectedSubBrand, selectedReference; + ArrayList subBrandList = new ArrayList<>(); + ArrayList referenceList = new ArrayList<>(); + List checkHeaderArray = new ArrayList(); + boolean flagScan = true; + final int FILTER_FOR_SIGNATURE = 4; + final int FILTER_FOR_SUB_BRAND = 5; + final int FILTER_FOR_REFERENCE = 6; + final int FILTER_FOR_BRAND = 1; + final int FILTER_FOR_AXE = 2; + final int FILTER_FOR_SUBAXE = 3; + final int CLEAR_FILTER = 0; + ////jp added sub axe + RecyclerView recSubAxe; + String selectedSubAxe = ""; + SubAxeValueAdapter subAxeValueAdapter; + ArrayList listSubAxe; + JourneyPlan jcp; + TextView txt_invoice_qty, txt_actual_qty; + + @SuppressLint({"SetTextI18n", "NotifyDataSetChanged"}) + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_inward_stock_details); + context = this; + ((InwardStockDetailsActivity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); + db = new Lorealba_Database(context); + db.open(); + + if (getIntent().getSerializableExtra(CommonString.TAG_OBJECT) != null) { + tCounterInvoice = (TCounterInvoice) getIntent().getSerializableExtra(CommonString.TAG_OBJECT); + assert tCounterInvoice != null; + invoiceNo = tCounterInvoice.getInvoiceNo(); + type = tCounterInvoice.getInvoiceType(); + invDate = tCounterInvoice.getInvoiceDate(); + } + + + validateUIData(); + prepareListData(); + String couter_code = preferences.getString(CommonString.KEY_COUNTER_CODE, ""); + TextView txt_counter_code = (TextView) findViewById(R.id.txt_counter_code); + txt_counter_code.setText("Counter Code - " + couter_code + " / Id - " + counter_id); + //validate_spin_ui_data(); + listAdapter = new ExpandableListAdapter(context, listDataHeader, listDataChild); + lvExp_stock_check.setAdapter(listAdapter); + ////added sub axe + recSubAxe.setLayoutManager(new GridLayoutManager(InwardStockDetailsActivity.this, 3)); + subAxeValueAdapter = new SubAxeValueAdapter(context, listSubAxe, CommonString.Signature); + recSubAxe.setAdapter(subAxeValueAdapter); + Objects.requireNonNull(recSubAxe.getAdapter()).notifyDataSetChanged(); + lvExp_stock_check.setOnScrollListener(new AbsListView.OnScrollListener() { + @Override + public void onScrollStateChanged(AbsListView absListView, int i) { + + } + + @Override + public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) { + int lastItem = firstVisibleItem + visibleItemCount; + if (firstVisibleItem == 0) { + fab_save.show();//.setVisibility(View.VISIBLE); + } else if (lastItem == totalItemCount) { + fab_save.hide();//setVisibility(View.INVISIBLE); + } else { + fab_save.show();//setVisibility(View.VISIBLE); + } + } + }); + + db.open(); + checkConfirmationAll = checkHeaderConfirmationValidation(listDataHeader, listDataChild); + if (checkConfirmationAll) { + confirmationCheckAll.setChecked(true); + confirmationCheckAll.setEnabled(false); + fab_save.setEnabled(false); + bar_code_img.setEnabled(false); + confirmationCheckAll.setButtonTintList(ColorStateList.valueOf(Color.parseColor("#FF739706"))); + } + + txt_invoice_qty.setText("Invoice QTY : " + calculate_invoice_qty()); + txt_actual_qty.setText("Actual QTY : " + calculate_actual_qty()); + } + + + @SuppressLint("UseCompatLoadingForDrawables") + private void validateUIData() { + preferences = PrefHelper.getPrefs(context); + counter_id = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + username = preferences.getString(CommonString.KEY_USERNAME, ""); + + Toolbar toolbar = findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + + if (!CommonFunctions.isTablet(context)) { + toolbar.setTitleTextAppearance(context, R.style.changestext_sizefor_mobile); + } + + Objects.requireNonNull(getSupportActionBar()).setHomeButtonEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + setTitle("DMS Stock - " + visit_date); + invoiceNumber = (TextView) findViewById(R.id.invoice_number); + invoiceType = (TextView) findViewById(R.id.invoice_type); + lvExp_stock_check = (ExpandableListView) findViewById(R.id.lvExp_stock_check); + confirmationCheckAll = (CheckBox) findViewById(R.id.confirmation_check_all); + fab_save = (FloatingActionButton) findViewById(R.id.save_fab); + bar_code_img = (ImageView) findViewById(R.id.img_scan); + img_clear_subaxe = (ImageView) findViewById(R.id.img_clear_subaxe); + recSubAxe = (RecyclerView) findViewById(R.id.rec_subaxe); + ///added actual and invoice qty + txt_invoice_qty = (TextView) findViewById(R.id.txt_invoice_qty); + txt_actual_qty = (TextView) findViewById(R.id.txt_actual_qty); + + invoiceNumber.setText(invoiceNo); + invoiceType.setText(type); + fab_save.setOnClickListener(this); + img_clear_subaxe.setOnClickListener(this); + et_search = (EditText) findViewById(R.id.et_search); + + + bar_code_img.setOnClickListener(view -> { + if (flagScan) { + openScanner(); + } else { + bar_code_img.setImageDrawable(getResources().getDrawable(R.mipmap.barcode_icon)); + flagScan = true; + et_search.setText(""); + } + + }); + + et_search.addTextChangedListener(new TextWatcher() { + @Override + public void beforeTextChanged(CharSequence s, int start, int count, int after) { + + } + + @Override + public void onTextChanged(CharSequence s, int start, int before, int count) { + String text = s.toString(); + setSearchFilter(listAdapter.get_listDataHeader(), text, listAdapter.get_listDataChild()); + } + + @Override + public void afterTextChanged(Editable s) { + String text = s.toString(); + } + }); + + + confirmationCheckAll.setOnCheckedChangeListener((compoundButton, b) -> { + if (compoundButton.isPressed()) { + setConfirmCheckedAllDataValidation(listDataHeader, listDataChild, compoundButton.isChecked()); + } + }); + + + loadingValueForFilter(); + db.open(); + + } + + + private void openScanner() { + IntentIntegrator intentIntegrator = new IntentIntegrator((Activity) context); + intentIntegrator.setBeepEnabled(true); + intentIntegrator.setOrientationLocked(false); + intentIntegrator.setPrompt("Scan the barcode or QR code to get the data"); + intentIntegrator.initiateScan(); + } + + + private void loadingValueForFilter() { + db.open(); + brandList = db.get_inward_sub_brand_name("BrandName", invoiceNo, type); + subBrandList = db.get_inward_sub_brand_name("SubBrandName", invoiceNo, type); + signatureList = db.get_inward_sub_brand_name("SignatureName", invoiceNo, type); + referenceList = db.get_inward_sub_brand_name("ReferenceName", invoiceNo, type); + } + + + @SuppressLint("UseCompatLoadingForDrawables") + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data); + switch (resultCode) { + case 0: + + break; + + case -1: + db.open(); + ArrayList productList = db.getsku_fromproductusing_eancode(result.getContents(), false, visit_date, counter_id, null); + + if (productList.isEmpty()) { + db.open(); + productList = db.getsku_fromproductusing_eancode(removeFirstChar(result.getContents()), false, visit_date, counter_id, null); + } + + if (!productList.isEmpty()) { + flagScan = false; + bar_code_img.setImageDrawable(getResources().getDrawable(R.mipmap.ok)); + clearFilters(); + setScanFilter(productList); + } else { + AlertandMessages.showToastMsg(context, "Unable To Scan Correct Data. Please Try Again."); + + } + + break; + } + + + super.onActivityResult(requestCode, resultCode, data); + } + + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + getMenuInflater().inflate(R.menu.filter_menu, menu); + return super.onCreateOptionsMenu(menu); + } + + + View showFilterBottomSheet() { + final CardView cardSignature, cardBrand, cardSubBrand, cardReference; + final BottomSheetDialog mBottomSheetDialog = new BottomSheetDialog(this); + @SuppressLint("InflateParams") final View sheetView = getLayoutInflater().inflate(R.layout.filter_bottom_sheet, null); + mBottomSheetDialog.setContentView(sheetView); + View bottomSheet = mBottomSheetDialog.getWindow().findViewById(com.google.android.material.R.id.design_bottom_sheet); + if (bottomSheet != null) { + bottomSheet.setBackgroundResource(android.R.color.transparent); + } + mBottomSheetDialog.setCancelable(false); + final RecyclerView recBrand = sheetView.findViewById(R.id.rec_brand); + ImageView img_cancel = sheetView.findViewById(R.id.img_cancel); + TextView tv_clear_filter = sheetView.findViewById(R.id.tv_clear_filter); + recBrand.setAdapter(new ValueAdapter(context, signatureList, CommonString.Signature)); + recBrand.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, true)); + cardSignature = sheetView.findViewById(R.id.card_signature); + cardBrand = sheetView.findViewById(R.id.card_brand); + cardSubBrand = sheetView.findViewById(R.id.card_sub_brand); + cardReference = sheetView.findViewById(R.id.card_reference); + cardSignature.setOnClickListener(this); + cardBrand.setOnClickListener(this); + cardSubBrand.setOnClickListener(this); + cardReference.setOnClickListener(this); + cardSignature.setCardBackgroundColor(getResources().getColor(R.color.dashboard_ach)); + if (selectedSignature != null) { + (sheetView.findViewById(R.id.img_filter_signature)).setVisibility(View.VISIBLE); + } + if (selectedBrand != null) { + (sheetView.findViewById(R.id.img_filter_brand)).setVisibility(View.VISIBLE); + } + if (selectedSubBrand != null) { + (sheetView.findViewById(R.id.img_filter_sub_brand)).setVisibility(View.VISIBLE); + } + if (selectedReference != null) { + (sheetView.findViewById(R.id.img_filter_reference)).setVisibility(View.VISIBLE); + } + + img_cancel.setOnClickListener(v -> mBottomSheetDialog.cancel()); + + + tv_clear_filter.setOnClickListener(v -> { + setFilter(CLEAR_FILTER); + selectedSignature = null; + selectedBrand = null; + selectedSubBrand = null; + selectedReference = null; + + cardSignature.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background)); + cardBrand.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background)); + cardSubBrand.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background)); + cardReference.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background)); + + (sheetView.findViewById(R.id.img_filter_signature)).setVisibility(View.GONE); + (sheetView.findViewById(R.id.img_filter_brand)).setVisibility(View.GONE); + (sheetView.findViewById(R.id.img_filter_sub_brand)).setVisibility(View.GONE); + (sheetView.findViewById(R.id.img_filter_reference)).setVisibility(View.GONE); + + loadingValueForFilter(); + recBrand.getAdapter().notifyDataSetChanged(); + }); + + + mBottomSheetDialog.show(); + return sheetView; + } + + + private void setConfirmCheckedAllDataValidation(ArrayList listDataHeader, HashMap> listDataChild, boolean checkFlag) { + if (!listDataHeader.isEmpty()) { + for (int i = 0; i < listDataHeader.size(); i++) { + if (checkFlag) { + listDataHeader.get(i).setInvoice_Status("1"); + } else { + listDataHeader.get(i).setInvoice_Status("0"); + } + for (int j = 0; j < listDataChild.get(listDataHeader.get(i)).size(); j++) { + if (checkFlag) { + listDataChild.get(listDataHeader.get(i)).get(j).setConfirmChecked(true); + } else { + if (listDataChild.get(listDataHeader.get(i)).get(j).getTransaction_Id().isEmpty()) { + listDataChild.get(listDataHeader.get(i)).get(j).setConfirmChecked(false); + } else { + listDataChild.get(listDataHeader.get(i)).get(j).setConfirmChecked(true); + } + } + } + } + } + listAdapter.notifyDataSetChanged(); + } + + private void prepareListData() { + db.open(); + listDataHeader = new ArrayList<>(); + listDataChild = new HashMap<>(); + listDataHeader = db.get_inwrad_stock_header_data(invoiceNo, type, counter_id); + db.open(); + jcp = db.getJCP(); + if (jcp != null) { + listSubAxe = db.getSubAxeforinward(jcp.getCounterGroupId().toString()); + } else { + listSubAxe = db.getSubAxeforinward("1"); + } + + if (!listDataHeader.isEmpty()) { + for (int i = 0; i < listDataHeader.size(); i++) { + childStockList = new ArrayList<>(); + db.open(); + childStockList = db.get_inward_stock_child_product_data(listDataHeader.get(i).getReferenceName(), listDataHeader.get(i).getBrandName(), + listDataHeader.get(i).getSubBrandName(), listDataHeader.get(i).getSignatureName(), invoiceNo, type, counter_id); + listDataChild.put(listDataHeader.get(i), childStockList); // Header, Child data + } + } + + } + + + @SuppressLint({"NonConstantResourceId", "NotifyDataSetChanged"}) + @Override + public void onClick(final View view) { + + if (view.getId() == R.id.save_fab) { + if (ValidationData(listDataHeader, listDataChild)) { + androidx.appcompat.app.AlertDialog.Builder builder = new androidx.appcompat.app.AlertDialog.Builder(context); + builder.setCancelable(false); + builder.setMessage(R.string.save_data_msg_new).setCancelable(false) + .setPositiveButton("OK", (dialog, id1) -> { + show_dialog_for_final_submit(context); + dialog.dismiss(); + }).setNegativeButton("Cancel", (dialog, which) -> dialog.dismiss()); + androidx.appcompat.app.AlertDialog alert = builder.create(); + alert.show(); + } else { + AlertandMessages.showToastMsg(context, Error_Msg); + } + + } else if (view.getId() == R.id.card_signature) { + RecyclerView recSignature = sheetView.findViewById(R.id.rec_brand); + recSignature.setAdapter(new ValueAdapter(context, signatureList, CommonString.Signature)); + recSignature.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, true)); + setFilterSelected(sheetView, CommonString.Signature); + } else if (view.getId() == R.id.card_brand) { + RecyclerView recBrand = sheetView.findViewById(R.id.rec_brand); + recBrand.setAdapter(new ValueAdapter(context, brandList, CommonString.Brand)); + recBrand.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, true)); + setFilterSelected(sheetView, CommonString.Brand); + } else if (view.getId() == R.id.card_sub_brand) { + RecyclerView recSubBrand = sheetView.findViewById(R.id.rec_brand); + recSubBrand.setAdapter(new ValueAdapter(context, subBrandList, CommonString.SubBrand)); + recSubBrand.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, true)); + Objects.requireNonNull(recSubBrand.getAdapter()).notifyDataSetChanged(); + setFilterSelected(sheetView, CommonString.SubBrand); + } else if (view.getId() == R.id.card_reference) { + RecyclerView recReference = sheetView.findViewById(R.id.rec_brand); + recReference.setAdapter(new ValueAdapter(context, referenceList, CommonString.Reference)); + recReference.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, true)); + setFilterSelected(sheetView, CommonString.Reference); + } else if (view.getId() == R.id.img_clear_subaxe) { + et_search.setText(""); + listAdapter = new ExpandableListAdapter(context, listDataHeader, listDataChild); + lvExp_stock_check.setAdapter(listAdapter); + listAdapter.notifyDataSetChanged(); + selectedSubAxe = ""; + subAxeValueAdapter.notifyDataSetChanged(); + //clear filters also + selectedSignature = null; + selectedBrand = null; + selectedSubBrand = null; + selectedReference = null; + db.open(); + jcp = db.getJCP(); + if (jcp != null) { + db.open(); + brandList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "BrandName", false, selectedSubAxe); + subBrandList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "SubBrandName", false, selectedSubAxe); + referenceList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "ReferenceName", false, selectedSubAxe); + signatureList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "SignatureName", false, selectedSubAxe); + } else { + brandList = db.getsub_brand_name("1", "BrandName", false, selectedSubAxe); + subBrandList = db.getsub_brand_name("1", "SubBrandName", false, selectedSubAxe); + referenceList = db.getsub_brand_name("1", "ReferenceName", false, selectedSubAxe); + signatureList = db.getsub_brand_name("1", "SignatureName", false, selectedSubAxe); + } + + } + } + + + private void show_dialog_for_final_submit(final Context context) { + final MultiPurposeDialog final_save_dialog = new MultiPurposeDialog(context); + final_save_dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); + final_save_dialog.setContentView(R.layout.custom_dialog_final_save); + final WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); + lp.copyFrom(Objects.requireNonNull(final_save_dialog.getWindow()).getAttributes()); + lp.width = WindowManager.LayoutParams.MATCH_PARENT; + lp.height = WindowManager.LayoutParams.WRAP_CONTENT; + lp.gravity = Gravity.CENTER; + final_save_dialog.getWindow().setAttributes(lp); + final_save_dialog.setCancelable(false); + + final EditText txt_hint_yes = (EditText) final_save_dialog.findViewById(R.id.txt_hint_yes); + Button btn_cancel = (Button) final_save_dialog.findViewById(R.id.btn_cancel); + Button btn_okay = (Button) final_save_dialog.findViewById(R.id.btn_okay); + + TextView final_text = (TextView) final_save_dialog.findViewById(R.id.final_text); + final_text.setText(getString(R.string.want_to_final_save)); + btn_okay.setOnClickListener(v -> { + if (txt_hint_yes.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter Text"); + } else if (!txt_hint_yes.getText().toString().trim().equalsIgnoreCase("yes")) { + AlertandMessages.showToastMsg(context, "Please Enter 'Yes' Text"); + } else { + final_save_dialog.dismiss(); + new InsertAsync().execute(true); + + } + }); + + btn_cancel.setOnClickListener(v -> final_save_dialog.dismiss()); + final_save_dialog.show(); + } + + public class MultiPurposeDialog extends Dialog { + public MultiPurposeDialog(Context context) { + super(context); + // DIALOG USER_INTERFACE TEMPLATE + WindowManager.LayoutParams wmLayoutParams = Objects.requireNonNull(getWindow()).getAttributes(); + wmLayoutParams.gravity = Gravity.CENTER; + getWindow().setAttributes(wmLayoutParams); + setTitle(null); + setCancelable(false); + setOnCancelListener(null); + LinearLayout layout = new LinearLayout(context); + layout.setOrientation(LinearLayout.VERTICAL); + } + } + + void setFilterSelected(View sheetView, String type) { + CardView cardSignature, cardBrand, cardSubBrand, cardReference; + cardSignature = sheetView.findViewById(R.id.card_signature); + cardBrand = sheetView.findViewById(R.id.card_brand); + cardSubBrand = sheetView.findViewById(R.id.card_sub_brand); + cardReference = sheetView.findViewById(R.id.card_reference); + + cardSignature.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background)); + cardBrand.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background)); + cardSubBrand.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background)); + cardReference.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background)); + + switch (type) { + case CommonString.Signature: + cardSignature.setCardBackgroundColor(getResources().getColor(R.color.dashboard_ach)); + break; + case CommonString.Brand: + cardBrand.setCardBackgroundColor(getResources().getColor(R.color.dashboard_ach)); + break; + case CommonString.SubBrand: + cardSubBrand.setCardBackgroundColor(getResources().getColor(R.color.dashboard_ach)); + break; + case CommonString.Reference: + cardReference.setCardBackgroundColor(getResources().getColor(R.color.dashboard_ach)); + break; + } + } + + private boolean ValidationData(ArrayList listDataHeader, HashMap> listDataChild) { + checkflag = true; + boolean flag_for_availability = false; + for (int i = 0; i < listDataHeader.size(); i++) { + for (int j = 0; j < listDataChild.get(listDataHeader.get(i)).size(); j++) { + if (listDataChild.get(listDataHeader.get(i)).get(j).isConfirmChecked()) { + flag_for_availability = true; + if (Integer.parseInt(listDataChild.get(listDataHeader.get(i)).get(j).getActualQty()) < Integer.parseInt(listDataChild.get(listDataHeader.get(i)).get(j).getConsumer_qty())) { + if (listDataChild.get(listDataHeader.get(i)).get(j).getReasonId() == 0) { + msg = getResources().getString(R.string.error_reason); + Error_Msg = msg; + checkflag = false; + break; + } + } + } else if (Integer.parseInt(listDataChild.get(listDataHeader.get(i)).get(j).getActualQty()) < Integer.parseInt(listDataChild.get(listDataHeader.get(i)).get(j).getConsumer_qty())) { + if (listDataChild.get(listDataHeader.get(i)).get(j).getReasonId() == 0) { + msg = getResources().getString(R.string.error_reason); + Error_Msg = msg; + checkflag = false; + break; + } else if (listDataChild.get(listDataHeader.get(i)).get(j).getReasonId() != 0) { + msg = getResources().getString(R.string.selected_item_checked_msg); + Error_Msg = msg; + checkflag = false; + break; + } + } + } + if (!checkflag) { + if (!checkHeaderArray.contains(i)) { + checkHeaderArray.add(i); + } + break; + } + } + + if (checkflag) { + Error_Msg = ""; + if (!flag_for_availability) { + msg = getResources().getString(R.string.error_confirmation); + Error_Msg = msg; + checkflag = false; + } + } + + listAdapter.notifyDataSetChanged(); + return checkflag; + } + + public ArrayList filterListForBrand(List originalList, String text) { + ArrayList filterList = new ArrayList<>(); + for (ProductMaster object : originalList) { + if (object.getBrandName().equalsIgnoreCase(text)) { + filterList.add(object); + } else { + continue; + } + } + return filterList; + } + + public ArrayList filterListForAxe(List originalList, String text, String brandName) { + ArrayList filterList = new ArrayList<>(); + for (ProductMaster object : originalList) { + if (object.getAxeName().equalsIgnoreCase(text) && (brandName.equals("") || object.getBrandName().equalsIgnoreCase(brandName))) { + filterList.add(object); + } else { + continue; + } + } + return filterList; + } + + public ArrayList filterListForSubAxe(List originalList, String text, String brandName, String axeName) { + ArrayList filterList = new ArrayList<>(); + for (ProductMaster object : originalList) { + if (object.getSubAxeName().equalsIgnoreCase(text) && (brandName.equals("") || object.getBrandName().equalsIgnoreCase(brandName)) && (axeName.equals("") || object.getAxeName().equalsIgnoreCase(axeName))) { + filterList.add(object); + } else { + continue; + } + } + return filterList; + } + + public ArrayList filterListForSubAxe(List originalList, String text) { + ArrayList filterList = new ArrayList<>(); + for (ProductMaster object : originalList) { + if (object.getSubAxeName().equalsIgnoreCase(text)) { + filterList.add(object); + } else { + continue; + } + } + + return filterList; + } + + public class ExpandableListAdapter extends BaseExpandableListAdapter { + Context _context; + List _listDataHeader; + HashMap> _listDataChild; + + public ExpandableListAdapter(Context context, List listDataHeader, HashMap> listChildData) { + this._context = context; + this._listDataHeader = listDataHeader; + this._listDataChild = listChildData; + } + + @Override + public Object getChild(int groupPosition, int childPosititon) { + return this._listDataChild.get(this._listDataHeader.get(groupPosition)).get(childPosititon); + } + + + public HashMap> get_listDataChild() { + return _listDataChild; + } + + public List get_listDataHeader() { + return _listDataHeader; + } + + @Override + public long getChildId(int groupPosition, int childPosition) { + return childPosition; + } + + @SuppressLint("SetTextI18n") + @Override + public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { + final ProductMaster childText = (ProductMaster) getChild(groupPosition, childPosition); + final ProductMaster headerData = (ProductMaster) getGroup(groupPosition); + ViewHolder holder = null; + if (convertView == null) { + LayoutInflater infalInflater = (LayoutInflater) this._context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); + convertView = infalInflater.inflate(R.layout.list_item_inward_stock, null); + holder = new ViewHolder(); + holder.cardView = convertView.findViewById(R.id.card_view); + holder.actual_qty = convertView.findViewById(R.id.actual_qty); + holder.stock_img_plus = convertView.findViewById(R.id.stock_img_plus); + holder.stock_img_minus = convertView.findViewById(R.id.stock_img_minus); + holder.confirmationCheck = convertView.findViewById(R.id.confirmation_check); + holder.invoice_qty = convertView.findViewById(R.id.invoice_qty); + holder.reasonSpinner = convertView.findViewById(R.id.reason_spinner); + holder.reasonLayout = convertView.findViewById(R.id.reason_layout); + convertView.setTag(holder); + + } else { + holder = (ViewHolder) convertView.getTag(); + } + + TextView txtListChild = convertView.findViewById(R.id.brand_name); + txtListChild.setText(childText.getProductName() + "( MRP - ₹ " + childText.getMrp() + ")"); + final ViewHolder finalHolder = holder; + + holder.stock_img_plus.setOnClickListener(v -> { + ((ExpandableListAdapter) lvExp_stock_check.getExpandableListAdapter()).notifyDataSetChanged(); + int minteger = Integer.parseInt(childText.getActualQty()); + ++minteger; + + if (minteger < Integer.parseInt(childText.getConsumer_qty())) { + childText.setActualQty(String.valueOf(minteger)); + isDataAdded = true; + } else if (minteger == Integer.parseInt(childText.getConsumer_qty())) { + childText.setActualQty(String.valueOf(minteger)); + finalHolder.reasonSpinner.setSelection(0); + childText.setReasonId(0); + finalHolder.reasonLayout.setVisibility(View.GONE); + isDataAdded = true; + } else { + AlertandMessages.showToastMsg(context, "Actual quantity cannot be greater than invoice quantity"); + } + }); + + ArrayList reasonList = new ArrayList<>(); + db.open(); + reasonList = db.getReasonData(false); + holder.reasonSpinner.setAdapter(new ReasonSpinnerAdapter(_context, R.layout.spinner_text_view, reasonList)); + final ArrayList finalReasonList = reasonList; + holder.reasonSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { + @Override + public void onItemSelected(AdapterView adapterView, View view, int pos, long l) { + if (pos != 0) { + MasterNonStockReason obj = finalReasonList.get(pos); + childText.setReasonId(obj.getReasonId()); + } else { + childText.setReasonId(0); + } + } + + @Override + public void onNothingSelected(AdapterView adapterView) { + + } + }); + + + if (!finalReasonList.isEmpty()) { + for (int i = 0; i < finalReasonList.size(); i++) { + if (finalReasonList.get(i).getReasonId() == childText.getReasonId()) { + holder.reasonSpinner.setSelection(i); + break; + } + } + } + + if (Integer.parseInt(childText.getActualQty()) < Integer.parseInt(childText.getConsumer_qty())) { + finalHolder.reasonLayout.setVisibility(View.VISIBLE); + } else { + finalHolder.reasonLayout.setVisibility(View.GONE); + } + + + holder.stock_img_minus.setOnClickListener(v -> { + ((ExpandableListAdapter) lvExp_stock_check.getExpandableListAdapter()).notifyDataSetChanged(); + int minteger = Integer.parseInt(childText.getActualQty()); + --minteger; + + if (minteger >= 0) { + finalHolder.reasonLayout.setVisibility(View.VISIBLE); + childText.setActualQty(String.valueOf(minteger)); + isDataAdded = true; + } else { + AlertandMessages.showToastMsg(context, "Actual quantity cannot be less than 0"); + } + }); + + + holder.confirmationCheck.setOnCheckedChangeListener((compoundButton, b) -> { + if (compoundButton.isPressed()) { + headerData.setInvoice_Status("0"); + if (compoundButton.isChecked()) { + childText.setConfirmChecked(true); + childCheckConfirmationDataValidation(childText); + checkConfirmationAll = checkHeaderConfirmationValidation(listDataHeader, listDataChild); + if (checkConfirmationAll) { + confirmationCheckAll.setChecked(true); + } else { + confirmationCheckAll.setChecked(false); + } + } else { + childText.setConfirmChecked(false); + childCheckConfirmationDataValidation(childText); + + } + } + }); + + + if (!childText.getTransaction_Id().equals("")) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { + holder.confirmationCheck.setButtonTintList(ColorStateList.valueOf(Color.parseColor("#FF739706"))); + } + + holder.confirmationCheck.setEnabled(false); + holder.stock_img_minus.setEnabled(false); + holder.stock_img_plus.setEnabled(false); + holder.reasonSpinner.setEnabled(false); + } else { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { + holder.confirmationCheck.setButtonTintList(ColorStateList.valueOf(Color.parseColor("#000000"))); + } + + holder.confirmationCheck.setEnabled(true); + holder.stock_img_minus.setEnabled(true); + holder.stock_img_plus.setEnabled(true); + holder.reasonSpinner.setEnabled(true); + } + + if (childText.isConfirmChecked()) { + holder.confirmationCheck.setChecked(true); + } else { + holder.confirmationCheck.setChecked(false); + } + + if (Integer.parseInt(childText.getActualQty()) < Integer.parseInt(childText.getConsumer_qty())) { + holder.actual_qty.setTextColor(Color.RED); + } else { + holder.actual_qty.setTextColor(Color.BLACK); + } + + holder.actual_qty.setText("" + childText.getActualQty()); + holder.actual_qty.setId(childPosition); + + holder.invoice_qty.setText("" + childText.getConsumer_qty()); + holder.invoice_qty.setId(childPosition); + + + if ((!childText.isConfirmChecked() && childText.getReasonId() == 0) || (childText.isConfirmChecked() && childText.getReasonId() == 0)) { + if (checkHeaderArray.contains(groupPosition)) { + if (!checkflag) { + holder.cardView.setCardBackgroundColor(getResources().getColor(R.color.light_red)); + } else + holder.cardView.setCardBackgroundColor(getResources().getColor(R.color.white)); + } else + holder.cardView.setCardBackgroundColor(getResources().getColor(R.color.white)); + } + + + return convertView; + } + + @Override + public int getChildrenCount(int groupPosition) { + return this._listDataChild.get(this._listDataHeader.get(groupPosition)).size(); + } + + @Override + public Object getGroup(int groupPosition) { + return this._listDataHeader.get(groupPosition); + } + + @Override + public int getGroupCount() { + return this._listDataHeader.size(); + } + + @Override + public long getGroupId(int groupPosition) { + return groupPosition; + } + + @SuppressLint({"RestrictedApi", "SetTextI18n"}) + @Override + public View getGroupView(final int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { + final ProductMaster headerTitle = (ProductMaster) getGroup(groupPosition); + if (convertView == null) { + + LayoutInflater infalInflater = (LayoutInflater) this._context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); + convertView = infalInflater.inflate(R.layout.list_group_inward_stock, null); + } + + + TextView lblListHeader = (TextView) convertView.findViewById(R.id.lblListHeader); + final CheckBox headerConfirmationCheckAll = (CheckBox) convertView.findViewById(R.id.header_confirmation_check_all); + lblListHeader.setText(headerTitle.getBrandName() + " - " + headerTitle.getSubBrandName() + " - " + headerTitle.getReferenceName()); + + headerConfirmationCheckAll.setOnCheckedChangeListener((compoundButton, b) -> { + if (compoundButton.isPressed()) { + if (compoundButton.isChecked()) { + headerCheckConfirmationDataValidation(headerTitle, true); + checkConfirmationAll = checkHeaderConfirmationValidation(listDataHeader, listDataChild); + if (checkConfirmationAll) { + confirmationCheckAll.setChecked(true); + setInvoiceStatus(listDataHeader, "1"); + } else { + setInvoiceStatus(listDataHeader, "0"); + confirmationCheckAll.setChecked(false); + } + } else { + confirmationCheckAll.setChecked(false); + headerCheckConfirmationDataValidation(headerTitle, false); + setInvoiceStatus(listDataHeader, "0"); + } + } + }); + + + headerCheckedFlag = childConfirmationCheckDataValidation(headerTitle); + + if (headerCheckedFlag) { + headerTransactionFlag = childTransactionCheckDataValidation(headerTitle); + if (headerTransactionFlag) { + headerConfirmationCheckAll.setEnabled(false); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { + headerConfirmationCheckAll.setButtonTintList(ColorStateList.valueOf(Color.parseColor("#FF739706"))); + } + } else { + headerConfirmationCheckAll.setEnabled(true); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { + headerConfirmationCheckAll.setButtonTintList(ColorStateList.valueOf(Color.parseColor("#000000"))); + } + } + headerConfirmationCheckAll.setChecked(true); + } else { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { + headerConfirmationCheckAll.setButtonTintList(ColorStateList.valueOf(Color.parseColor("#000000"))); + } + headerConfirmationCheckAll.setChecked(false); + } + + return convertView; + } + + @Override + public boolean hasStableIds() { + return false; + } + + @Override + public boolean isChildSelectable(int groupPosition, int childPosition) { + return true; + } + } + + private boolean childTransactionCheckDataValidation(ProductMaster headerTitle) { + boolean flag = true; + for (int i = 0; i < listDataChild.get(headerTitle).size(); i++) { + if (listDataChild.get(headerTitle).get(i).getTransaction_Id().equals("")) { + flag = false; + break; + } + } + return flag; + } + + private boolean checkHeaderConfirmationValidation(ArrayList listDataHeader, HashMap> listDataChild) { + boolean flag = true; + for (int i = 0; i < listDataHeader.size(); i++) { + for (int j = 0; j < listDataChild.get(listDataHeader.get(i)).size(); j++) { + if (!listDataChild.get(listDataHeader.get(i)).get(j).isConfirmChecked()) { + flag = false; + break; + } else { + if (listDataChild.get(listDataHeader.get(i)).get(j).getTransaction_Id().equals("")) { + flag = true; + } + } + } + if (!flag) { + break; + } + } + listAdapter.notifyDataSetChanged(); + return flag; + } + + + private boolean setInvoiceStatus(ArrayList listDataHeader, String invoice_status) { + boolean flag = true; + for (int i = 0; i < listDataHeader.size(); i++) { + listDataHeader.get(i).setInvoice_Status(invoice_status); + } + listAdapter.notifyDataSetChanged(); + return flag; + } + + private boolean childConfirmationCheckDataValidation(ProductMaster headerTitle) { + boolean flag = true; + for (int i = 0; i < listDataChild.get(headerTitle).size(); i++) { + if (!listDataChild.get(headerTitle).get(i).isConfirmChecked()) { + flag = false; + break; + } + } + return flag; + } + + + private void childCheckConfirmationDataValidation(ProductMaster childText) { + if (!childText.isConfirmChecked()) { + confirmationCheckAll.setChecked(false); + } + listAdapter.notifyDataSetChanged(); + } + + private void headerCheckConfirmationDataValidation(ProductMaster headerTitle, boolean flag) { + for (int i = 0; i < listDataChild.get(headerTitle).size(); i++) { + if (flag) { + listDataChild.get(headerTitle).get(i).setConfirmChecked(true); + } else { + if (listDataChild.get(headerTitle).get(i).getTransaction_Id().equals("")) { + listDataChild.get(headerTitle).get(i).setConfirmChecked(false); + } else { + listDataChild.get(headerTitle).get(i).setConfirmChecked(true); + } + } + } + listAdapter.notifyDataSetChanged(); + } + + + public class ViewHolder { + TextView actual_qty, invoice_qty; + Button stock_img_plus, stock_img_minus; + CardView cardView; + CheckBox confirmationCheck; + Spinner reasonSpinner; + LinearLayout reasonLayout; + } + + @Override + public void onDestroy() { + super.onDestroy(); + } + + + public class ValueAdapter extends RecyclerView.Adapter { + LayoutInflater inflator; + List data; + String type1; + + public ValueAdapter(Context context, List data, String type) { + inflator = LayoutInflater.from(context); + this.data = data; + this.type1 = type; + } + + @NonNull + @Override + public ValueAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) { + View view = inflator.inflate(R.layout.item_filter, parent, false); + return new ValueAdapter.MyViewHolder(view); + } + + @SuppressLint("NotifyDataSetChanged") + @Override + public void onBindViewHolder(@NonNull final ValueAdapter.MyViewHolder holder, final int position) { + final ProductMaster current = data.get(position); + final boolean[] selected = {false}; + final int[] filterId = {0}; + switch (type1) { + case CommonString.Signature: + if (selectedSignature != null && selectedSignature == current) { + selected[0] = true; + } + + break; + + case CommonString.Brand: + if (selectedBrand != null && selectedBrand == current) { + selected[0] = true; + } + + break; + + case CommonString.SubBrand: + if (selectedSubBrand != null && selectedSubBrand == current) { + selected[0] = true; + } + + break; + + case CommonString.Reference: + if (selectedReference != null && selectedReference == current) { + selected[0] = true; + } + + break; + } + + holder.tv_item.setText(current.getBrandName()); + + holder.tv_item.setOnClickListener(v -> { + switch (type1) { + case CommonString.Signature: + selectedSignature = current; + filterId[0] = R.id.img_filter_signature; + setFilter(FILTER_FOR_SIGNATURE); + db.open(); + brandList = db.getInwardSubBrandOrReference("BrandName", current.getBrandName(), null, null, invoiceNo, type); + subBrandList = db.getInwardSubBrandOrReference("SubBrandName", current.getBrandName(), null, null, invoiceNo, type); + referenceList = db.getInwardSubBrandOrReference("ReferenceName", current.getBrandName(), null, null, invoiceNo, type); + + break; + case CommonString.Brand: + db.open(); + selectedBrand = current; + filterId[0] = R.id.img_filter_brand; + setFilter(FILTER_FOR_BRAND); + subBrandList = db.getInwardSubBrandOrReference("SubBrandName", "", current.getBrandName(), null, invoiceNo, type); + referenceList = db.getInwardSubBrandOrReference("ReferenceName", "", current.getBrandName(), null, invoiceNo, type); + break; + case CommonString.SubBrand: + db.open(); + selectedSubBrand = current; + filterId[0] = R.id.img_filter_sub_brand; + setFilter(FILTER_FOR_SUB_BRAND); + referenceList = db.getInwardSubBrandOrReference("ReferenceName", "", null, current.getBrandName(), invoiceNo, type); + break; + case CommonString.Reference: + selectedReference = current; + filterId[0] = R.id.img_filter_reference; + + setFilter(FILTER_FOR_REFERENCE); + break; + } + + RecyclerView recSubBrand = sheetView.findViewById(R.id.rec_brand); + Objects.requireNonNull(recSubBrand.getAdapter()).notifyDataSetChanged(); + //show filter_menu icon on filter_menu selected + (sheetView.findViewById(filterId[0])).setVisibility(View.VISIBLE); + }); + + if (selected[0]) { + holder.card.setCardBackgroundColor(getResources().getColor(R.color.dashboard_ach)); + } else { + holder.card.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background)); + } + } + + @Override + public int getItemCount() { + return data.size(); + } + + class MyViewHolder extends RecyclerView.ViewHolder { + TextView tv_item; + CardView card; + + public MyViewHolder(View itemView) { + super(itemView); + tv_item = (TextView) itemView.findViewById(R.id.tv_item); + card = (CardView) itemView.findViewById(R.id.item_card); + + } + } + } + + public void setSearchFilter(List originalList, String text, HashMap> listDataChild) { + HashMap> filterChildHashMap = new HashMap<>(); + ArrayList filterList = new ArrayList<>(); + for (int i = 0; i < originalList.size(); i++) { + ProductMaster parent = originalList.get(i); + List listChild = listDataChild.get(parent); + List listFilterChild = new ArrayList<>(); + for (int j = 0; j < listChild.size(); j++) { + if (listChild.get(j).getProductName().toLowerCase().contains(text.toLowerCase())) { + listFilterChild.add(listChild.get(j)); + } + } + + if (listFilterChild.size() > 0) { + filterList.add(parent); + filterChildHashMap.put(parent, listFilterChild); + + } + + } + + ExpandableListAdapter listAdapter = new ExpandableListAdapter(context, filterList, filterChildHashMap); + lvExp_stock_check.setAdapter(listAdapter); + listAdapter.notifyDataSetChanged(); + for (int i = 0; i < listAdapter.getGroupCount(); i++) { + lvExp_stock_check.expandGroup(i); + } + + } + + public void setFilter(int filterType) { + if (filterType == FILTER_FOR_SIGNATURE) { + listAdapter = new ExpandableListAdapter(context, filterListForSignature(listDataHeader, selectedSignature.getBrandName()), listDataChild); + } else if (filterType == FILTER_FOR_BRAND) { + listAdapter = new ExpandableListAdapter(context, filterListForBrand(listDataHeader, selectedBrand.getBrandName()), listDataChild); + } else if (filterType == FILTER_FOR_SUB_BRAND) { + listAdapter = new ExpandableListAdapter(context, filterListForSubBrand(listDataHeader, selectedSubBrand.getBrandName()), listDataChild); + } else if (filterType == FILTER_FOR_REFERENCE) { + listAdapter = new ExpandableListAdapter(context, filterListForReference(listDataHeader, selectedReference.getBrandName()), listDataChild); + } else if (filterType == FILTER_FOR_AXE) { + listAdapter = new ExpandableListAdapter(context, filterListForAxe(listDataHeader, axeName, brandName), listDataChild); + } else if (filterType == FILTER_FOR_SUBAXE) { + listAdapter = new ExpandableListAdapter(context, filterListForSubAxe(listDataHeader, subAxeName, brandName, axeName), listDataChild); + } else { + listAdapter = new ExpandableListAdapter(context, listDataHeader, listDataChild); + } + + lvExp_stock_check.setAdapter(listAdapter); + listAdapter.notifyDataSetChanged(); + } + + + public ArrayList filterListForSubBrand(List originalList, String text) { + ArrayList filterList = new ArrayList<>(); + for (ProductMaster object : originalList) { + if (object.getSubBrandName().equalsIgnoreCase(text) && (selectedSignature == null || object.getSignatureName().equalsIgnoreCase(selectedSignature.getBrandName())) && (selectedBrand == null || object.getBrandName().equalsIgnoreCase(selectedBrand.getBrandName()))) { + filterList.add(object); + } + } + return filterList; + } + + public ArrayList filterListForReference(List originalList, String text) { + ArrayList filterList = new ArrayList<>(); + for (ProductMaster object : originalList) { + if (object.getReferenceName().equalsIgnoreCase(text) && (selectedSignature == null || object.getSignatureName().equalsIgnoreCase(selectedSignature.getBrandName())) + && (selectedBrand == null || object.getBrandName().equalsIgnoreCase(selectedBrand.getBrandName())) && (selectedSubBrand == null || object.getSubBrandName().equalsIgnoreCase(selectedSubBrand.getBrandName()))) { + filterList.add(object); + } + } + return filterList; + } + + public ArrayList filterListForSignature(List originalList, String text) { + ArrayList filterList = new ArrayList<>(); + for (ProductMaster object : originalList) { + if (object.getSignatureName().equalsIgnoreCase(text)) { + filterList.add(object); + } + } + return filterList; + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // Handle action bar item clicks here. The action bar will + // automatically handle clicks on the Home/Up button, so long + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + if (id == android.R.id.home) { + isChanged(); + + } else if (id == R.id.filter_data) { + sheetView = showFilterBottomSheet(); + } + + + return super.onOptionsItemSelected(item); + } + + boolean isDataAdded = false; + + @Override + public void onBackPressed() { + isChanged(); + } + + void isChanged() { + if (isDataAdded) { + AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle(getString(R.string.parinaam)); + builder.setMessage(getResources().getString(R.string.data_will_be_lost)).setCancelable(false) + .setPositiveButton(getString(R.string.ok), (dialog, id) -> { + + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + InwardStockDetailsActivity.this.finish(); + }).setNegativeButton(getString(R.string.cancel), (dialog, which) -> dialog.dismiss()); + AlertDialog alert = builder.create(); + alert.show(); + } else { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + InwardStockDetailsActivity.this.finish(); + } + } + + + public void setScanFilter(List scanList) { + + HashMap> filterChildHashMap = new HashMap<>(); + + ArrayList filterList = new ArrayList<>(); + for (int i = 0; i < listDataHeader.size(); i++) { + ProductMaster parent = listDataHeader.get(i); + List listChild = listDataChild.get(parent); + List listFilterChild = new ArrayList<>(); + for (int j = 0; j < listChild.size(); j++) { + if (containsProduct(scanList, listChild.get(j))) { + listFilterChild.add(listChild.get(j)); + } + } + + if (listFilterChild.size() > 0) { + filterList.add(parent); + filterChildHashMap.put(parent, listFilterChild); + + } + + } + + ExpandableListAdapter listAdapter1 = new ExpandableListAdapter(context, filterList, filterChildHashMap); + lvExp_stock_check.setAdapter(listAdapter1); + for (int i = 0; i < listAdapter1.getGroupCount(); i++) { + lvExp_stock_check.expandGroup(i); + } + listAdapter1.notifyDataSetChanged(); + + } + + + boolean containsProduct(List scanList, ProductMaster obj) { + boolean contains = false; + for (int i = 0; i < scanList.size(); i++) { + if (scanList.get(i).getProductId().equals(obj.getProductId())) { + contains = true; + break; + } + } + + return contains; + } + + + void clearFilters() { + et_search.setText(""); + + setFilter(CLEAR_FILTER); + selectedSignature = null; + selectedBrand = null; + selectedSubBrand = null; + selectedReference = null; + + if (sheetView != null) { + (sheetView.findViewById(R.id.img_filter_signature)).setVisibility(View.GONE); + (sheetView.findViewById(R.id.img_filter_brand)).setVisibility(View.GONE); + (sheetView.findViewById(R.id.img_filter_sub_brand)).setVisibility(View.GONE); + (sheetView.findViewById(R.id.img_filter_reference)).setVisibility(View.GONE); + } + db.open(); + brandList = db.getsub_brand_name("1", "BrandName", false); + subBrandList = db.getsub_brand_name("1", "SubBrandName", false); + referenceList = db.getsub_brand_name("1", "ReferenceName", false); + signatureList = db.getsub_brand_name("1", "SignatureName", false); + } + + public class SubAxeValueAdapter extends RecyclerView.Adapter { + LayoutInflater inflator; + List data; + String type; + + public String getType() { + return type; + } + + public SubAxeValueAdapter(Context context, List data, String type) { + inflator = LayoutInflater.from(context); + this.data = data; + this.type = type; + } + + @NonNull + @Override + public SubAxeValueAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) { + View view = inflator.inflate(R.layout.item_filter, parent, false); + return new SubAxeValueAdapter.MyViewHolder(view); + } + + @SuppressLint("NotifyDataSetChanged") + @RequiresApi(api = Build.VERSION_CODES.M) + @Override + public void onBindViewHolder(final SubAxeValueAdapter.MyViewHolder holder, final int position) { + final ProductMaster current = data.get(position); + holder.tv_item.setText(current.getSubAxeName()); + holder.tv_item.setOnClickListener(v -> { + et_search.setText(""); + listAdapter = new ExpandableListAdapter(context, filterListForSubAxe(listDataHeader, current.getSubAxeName()), listDataChild); + lvExp_stock_check.setAdapter(listAdapter); + listAdapter.notifyDataSetChanged(); + + current.setSelected(true); + selectedSubAxe = current.getSubAxeName(); + subAxeValueAdapter.notifyDataSetChanged(); + db.open(); + jcp = db.getJCP(); + if (jcp != null) { + db.open(); + brandList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "BrandName", false, selectedSubAxe); + subBrandList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "SubBrandName", false, selectedSubAxe); + referenceList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "ReferenceName", false, selectedSubAxe); + signatureList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "SignatureName", false, selectedSubAxe); + } else { + brandList = db.getsub_brand_name("1", "BrandName", false, selectedSubAxe); + subBrandList = db.getsub_brand_name("1", "SubBrandName", false, selectedSubAxe); + referenceList = db.getsub_brand_name("1", "ReferenceName", false, selectedSubAxe); + signatureList = db.getsub_brand_name("1", "SignatureName", false, selectedSubAxe); + } + }); + + try { + if (current.getSubAxeName().equalsIgnoreCase(selectedSubAxe)) { + holder.card.setCardBackgroundColor(getColor(R.color.dashboard_ach)); + } else { + holder.card.setCardBackgroundColor(getColor(R.color.grey_dark_background)); + } + } catch (Exception e) { + e.fillInStackTrace(); + } + } + + @Override + public int getItemCount() { + return data.size(); + } + + class MyViewHolder extends RecyclerView.ViewHolder { + TextView tv_item; + CardView card; + + public MyViewHolder(View itemView) { + super(itemView); + tv_item = (TextView) itemView.findViewById(R.id.tv_item); + card = (CardView) itemView.findViewById(R.id.item_card); + + } + } + } + + private int calculate_invoice_qty() { + int total_invoice_qty = 0; + if (!listDataHeader.isEmpty()) { + for (int i = 0; i < listDataHeader.size(); i++) { + List list = listDataChild.get(listDataHeader.get(i)); + for (int j = 0; j < list.size(); j++) { + if (list.get(j).getConsumer_qty() != null && !list.get(j).getConsumer_qty().equals("")) { + total_invoice_qty = total_invoice_qty + Integer.parseInt(list.get(j).getConsumer_qty()); + } + } + } + } + + return total_invoice_qty; + } + + private int calculate_actual_qty() { + int total_actual_qty = 0; + if (listDataHeader.size() > 0) { + for (int i = 0; i < listDataHeader.size(); i++) { + List list = listDataChild.get(listDataHeader.get(i)); + for (int j = 0; j < list.size(); j++) { + if (list.get(j).getActualQty() != null && !list.get(j).getActualQty().equals("")) { + total_actual_qty = total_actual_qty + Integer.parseInt(list.get(j).getActualQty()); + } + } + } + } + + return total_actual_qty; + } + + + class InsertAsync extends AsyncTask { + Dialog dialog = null; + ProgressBar pb = null; + + @Override + protected void onPreExecute() { + dialog = new Dialog(context); + dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); + Objects.requireNonNull(dialog.getWindow()).setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT)); + dialog.setContentView(R.layout.circular_progress_bar); + pb = (ProgressBar) dialog.findViewById(R.id.progressBar1); + dialog.setCancelable(false); + dialog.show(); + super.onPreExecute(); + } + + @Override + protected Void doInBackground(Boolean... bool) { + ////final submit + String TransactionId = CommonFunctions.getUUID(context); + db.open(); + boolean fornew_productchecked = newinwardproduct_Checked(listDataChild, listDataHeader); + ///Insert for New Inward Product + long val = db.insertNewInwardProductStockData(visit_date, listDataChild, listDataHeader, invoiceNo, type, invDate, counter_id, username, + "DMS", TransactionId, fornew_productchecked); + boolean checked_checkbox_flag = inwardproduct_Checked(listDataChild, listDataHeader); + ////Insert for Exist in T_Stock Summery Inward Product + TransactionId = CommonFunctions.getUUID(context); + long val2 = db.insertInwardStockData(visit_date, listDataChild, listDataHeader, invoiceNo, type, invDate, + counter_id, username, "DMS", TransactionId, checked_checkbox_flag); + + return null; + } + + @Override + protected void onPostExecute(Void aVoid) { + super.onPostExecute(aVoid); + dialog.cancel(); + if (CommonFunctions.checkNetIsAvailable(context)) { + CommonFunctions.call_upload(context); + } + AlertandMessages.showToastMsg(context, getResources().getString(R.string.data_saved_msg)); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + InwardStockDetailsActivity.this.finish(); + } + } + + private boolean newinwardproduct_Checked(HashMap> data, List save_listDataHeader) { + boolean status = false; + if (save_listDataHeader.size() > 0) { + for (int k = 0; k < save_listDataHeader.size(); k++) { + List child = data.get(save_listDataHeader.get(k)); + if (child != null && child.size() > 0) { + for (int j = 0; j < child.size(); j++) { + if (child.get(j).isConfirmChecked()) { + db.open(); + ProductMaster transactionList = db.getInwardStockCheckTransactionData(child.get(j).getProductId(), child.get(j).getInvId(), invoiceNo); + db.open(); + TStockSummary stockObj = db.getTStockSummaryProductDetails(child.get(j).getProductId()); + if (transactionList == null && stockObj == null) { + status = true; + break; + } + } + } + } + if (status) { + break; + } + } + } + return status; + } + + + private boolean inwardproduct_Checked(HashMap> data, List save_listDataHeader) { + boolean status = false; + if (save_listDataHeader.size() > 0) { + for (int k = 0; k < save_listDataHeader.size(); k++) { + List child = data.get(save_listDataHeader.get(k)); + if (child != null && child.size() > 0) { + for (int j = 0; j < child.size(); j++) { + if (child.get(j).isConfirmChecked()) { + db.open(); + ProductMaster transactionList = db.getInwardStockCheckTransactionData(child.get(j).getProductId(), child.get(j).getInvId(), invoiceNo); + TStockSummary stockObj = db.getTStockSummaryProductDetails(child.get(j).getProductId()); + if (transactionList == null && stockObj != null && stockObj.getProductId() != null) { + status = true; + break; + } + } + } + } + + if (status) { + break; + } + } + } + + return status; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/ManualInWardStockActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/ManualInWardStockActivity.java new file mode 100644 index 0000000..6309763 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/ManualInWardStockActivity.java @@ -0,0 +1,1720 @@ +package com.cpm.lorealbaautomation.dailyactivity; + +import android.annotation.SuppressLint; +import android.app.Activity; +import android.app.AlertDialog; +import android.app.DatePickerDialog; +import android.app.Dialog; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.graphics.Color; +import android.graphics.drawable.ColorDrawable; +import android.os.AsyncTask; +import android.os.Bundle; + +import com.google.android.material.floatingactionbutton.FloatingActionButton; + +import androidx.annotation.NonNull; +import androidx.appcompat.app.AppCompatActivity; +import androidx.cardview.widget.CardView; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; +import androidx.appcompat.widget.Toolbar; + +import android.text.Editable; +import android.text.InputFilter; +import android.text.TextWatcher; +import android.util.Log; +import android.view.Gravity; +import android.view.LayoutInflater; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; +import android.view.Window; +import android.view.WindowManager; +import android.widget.AdapterView; +import android.widget.ArrayAdapter; +import android.widget.Button; +import android.widget.CheckBox; +import android.widget.EditText; +import android.widget.ImageView; +import android.widget.LinearLayout; +import android.widget.ProgressBar; +import android.widget.Spinner; +import android.widget.TextView; +import android.widget.Toast; + +import com.google.firebase.crashlytics.FirebaseCrashlytics; +import com.google.zxing.integration.android.IntentIntegrator; +import com.google.zxing.integration.android.IntentResult; +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.adapter.InvoiceTypeSpinnerAdapter; +import com.cpm.lorealbaautomation.adapter.ReasonSpinnerAdapter; +import com.cpm.lorealbaautomation.constant.AlertandMessages; +import com.cpm.lorealbaautomation.constant.CommonFunctions; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.gsonGetterSetter.InvoiceGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterInvoiceType; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterNonStockReason; +import com.cpm.lorealbaautomation.gsonGetterSetter.ProductMaster; +import com.cpm.lorealbaautomation.gsonGetterSetter.TCounterInvoice; +import com.cpm.lorealbaautomation.gsonGetterSetter.TStockSummary; + +import java.io.File; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Collections; +import java.util.Date; +import java.util.List; +import java.util.Objects; + +import static com.cpm.lorealbaautomation.constant.CommonFunctions.getCurrentTime; +import static com.cpm.lorealbaautomation.constant.CommonFunctions.removeFirstChar; +import static com.cpm.lorealbaautomation.dailyactivity.StoreImageActivity.convertBitmap; + +public class ManualInWardStockActivity extends AppCompatActivity implements View.OnClickListener { + Lorealba_Database db; + Context context; + private SharedPreferences preferences; + String counter_id, visit_date, username, _pathforcheck = "", _path = "", str_img_invoice = ""; + RecyclerView invoiceListView; + ValueAdapter adapter; + FloatingActionButton draftBtn, saveBtn; + TextView invoice_date; + Spinner invoice_type_spin; + EditText invoice_number; + ImageView date_img; + TCounterInvoice tCounterInvoiceObj = new TCounterInvoice(); + ArrayList invoiceTypeList = new ArrayList<>(); + int mYear, mMonth, mDay; + DatePickerDialog dpd; + Calendar c; + Button btn_scan, btn_enter_code, btn_sku_list; + TextView qrcode_text, stock_text_value; + EditText edt_scan_code; + int minteger = 0; + RecyclerView drawer_layout_recycle_store; + InvoiceGetterSetter object; + String product_scan_code = "", demo_given_str = "", product_sold_str = ""; + public ArrayList selected_list = new ArrayList<>(); + public ArrayList selected_list2 = new ArrayList<>(); + public ArrayList dialog_product_list = new ArrayList<>(); + ArrayAdapter dialog_brand_adapter, dialog_sub_brand_adapter, dialog_frenchise_adapter, dialog_sku_adapter; + ArrayList reasonList = new ArrayList<>(); + final int CLEAR_FILTER = 0; + final int FILTER_FOR_BRAND = 1; + final int FILTER_FOR_SUB_BRAND = 2; + final int FILTER_FOR_REFERENCE_NAME = 3; + boolean flag_for_filter = false; + String invoiceNo = "", invDate = "", invType = ""; + TCounterInvoice tCounterInvoice; + boolean flag_filter_by_edt = false; + boolean flag = true; + int itemPos = 0; + public ArrayList dialog_product_using_searchlist = new ArrayList<>(); + String dialog_brand_Id = "", dialog_sub_brand_Id = "", dialog_reference_Id = "", product_name = "", product_Id = "0", product_mrp = "0", + dialog_reference = "", dialog_sub_brand = "", dialog_brand = "", store_name, store_address, Error_Msg = ""; + String value = ""; + ArrayList manualInwardStockList = new ArrayList<>(); + String month = "", dd = "", yy = ""; + MultiPurposeDialog dialog_final = null; + ImageView invoice_img; + TextView txt_invoice_qty, txt_actual_qty; + boolean isDataAdded = false; + String blockCharacterSet = "[';:-+{('},@=#$%^&*?)\"]"; + InputFilter filter = (source, start, end, dest, dstart, dend) -> { + if (source != null && blockCharacterSet.contains(("" + source))) { + return ""; + } + return null; + }; + + @SuppressLint("SetTextI18n") + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_manual_in_ward_stock); + context = this; + ((ManualInWardStockActivity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); + db = new Lorealba_Database(context); + db.open(); + invoiceTypeList = db.getInvoiceTypeList(); + reasonList = db.getReasonData(false); + db.open(); + dialog_product_list = db.getproduct_masterlist(null, visit_date, counter_id, null); + validateUIData(); + setDataToListView(); + invoice_number.setFilters(new InputFilter[]{filter, new InputFilter.LengthFilter(30)}); + String couter_code = preferences.getString(CommonString.KEY_COUNTER_CODE, ""); + TextView txt_counter_code = (TextView) findViewById(R.id.txt_counter_code); + txt_counter_code.setText("Counter Code - " + couter_code + " / Id - " + counter_id); + txt_invoice_qty.setText("Invoice QTY : " + calculate_invoice_qty()); + txt_actual_qty.setText("Actual QTY : " + calculate_actual_qty()); + } + + @SuppressLint("UseCompatLoadingForDrawables") + private void validateUIData() { + preferences = PrefHelper.getPrefs(context); + counter_id = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + username = preferences.getString(CommonString.KEY_USERNAME, ""); + btn_scan = (Button) findViewById(R.id.btn_scan); + btn_enter_code = (Button) findViewById(R.id.btn_enter_code); + btn_sku_list = (Button) findViewById(R.id.btn_sku_list); + invoiceListView = (RecyclerView) findViewById(R.id.invoice_list); + draftBtn = (FloatingActionButton) findViewById(R.id.draft_btn); + saveBtn = (FloatingActionButton) findViewById(R.id.save_btn); + invoice_date = (TextView) findViewById(R.id.invoice_date); + date_img = (ImageView) findViewById(R.id.date_img); + invoice_type_spin = (Spinner) findViewById(R.id.invoice_type); + invoice_number = (EditText) findViewById(R.id.invoice_no); + drawer_layout_recycle_store = (RecyclerView) findViewById(R.id.drawer_layout_recycle_store); + invoice_img = (ImageView) findViewById(R.id.manualinvoice_img); + ///added actual and invoice qty + txt_invoice_qty = (TextView) findViewById(R.id.txt_invoice_qty); + txt_actual_qty = (TextView) findViewById(R.id.txt_actual_qty); + + btn_enter_code.setOnClickListener(this); + btn_sku_list.setOnClickListener(this); + date_img.setOnClickListener(this); + saveBtn.setOnClickListener(this); + draftBtn.setOnClickListener(this); + btn_scan.setOnClickListener(this); + invoice_img.setOnClickListener(this); + + value = getIntent().getStringExtra(CommonString.KEY_VALUE); + + invoice_type_spin.setAdapter(new InvoiceTypeSpinnerAdapter(context, R.layout.spinner_text_view, invoiceTypeList)); + + invoice_type_spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { + @Override + public void onItemSelected(AdapterView adapterView, View view, int pos, long l) { + if (pos == 0) { + tCounterInvoiceObj.setInvoiceType(""); + } else { + tCounterInvoiceObj.setInvoiceType(invoiceTypeList.get(pos).getInvoiceType()); + } + } + + @Override + public void onNothingSelected(AdapterView adapterView) { + + } + }); + + + if (getIntent().getSerializableExtra(CommonString.TAG_OBJECT) != null) { + tCounterInvoice = (TCounterInvoice) getIntent().getSerializableExtra(CommonString.TAG_OBJECT); + assert tCounterInvoice != null; + invoiceNo = tCounterInvoice.getInvoiceNo(); + invType = tCounterInvoice.getInvoiceType(); + invDate = tCounterInvoice.getInvoiceDate(); + + if (tCounterInvoice.getUpload_status().equalsIgnoreCase(CommonString.KEY_U) || !tCounterInvoice.getTransactionId().equals("")) { + btn_scan.setEnabled(false); + draftBtn.setEnabled(false); + saveBtn.setEnabled(false); + date_img.setEnabled(false); + invoice_img.setEnabled(false); + btn_enter_code.setEnabled(false); + btn_sku_list.setEnabled(false); + invoice_number.setEnabled(false); + invoice_type_spin.setEnabled(false); + btn_scan.setBackground(getResources().getDrawable(R.drawable.rouded_corner_gray)); + btn_scan.setTextColor(getResources().getColor(R.color.list_odd)); + + btn_enter_code.setBackground(getResources().getDrawable(R.drawable.rouded_corner_gray)); + btn_enter_code.setTextColor(getResources().getColor(R.color.list_odd)); + + btn_sku_list.setBackground(getResources().getDrawable(R.drawable.rouded_corner_gray)); + btn_sku_list.setTextColor(getResources().getColor(R.color.list_odd)); + } + } + + for (int i = 0; i < invoiceTypeList.size(); i++) { + if (invType.equalsIgnoreCase(invoiceTypeList.get(i).getInvoiceType())) { + itemPos = i; + } + } + if (!invoiceNo.isEmpty()) { + invoice_number.setText(invoiceNo); + invoice_number.setEnabled(false); + } + if (!invDate.isEmpty()) { + invoice_date.setText(invDate); + date_img.setClickable(false); + } else { + date_img.setClickable(true); + } + + if (!invType.isEmpty()) { + invoice_type_spin.setEnabled(false); + invoice_type_spin.setSelection(itemPos); + } + + drawer_layout_recycle_store.addOnScrollListener(new RecyclerView.OnScrollListener() { + @Override + public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) { + super.onScrolled(recyclerView, dx, dy); + if (dy > 0) { + saveBtn.hide(); + } else if (dy < 0) { + saveBtn.show(); + } + + } + }); + + Toolbar toolbar = findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + Objects.requireNonNull(getSupportActionBar()).setHomeButtonEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + + if (!CommonFunctions.isTablet(context)) { + toolbar.setTitleTextAppearance(context, R.style.changestext_sizefor_mobile); + } + setTitle("Manual Stock - " + visit_date); + } + + + @SuppressLint("UseCompatLoadingForDrawables") + public void setDataToListView() { + try { + db.open(); + selected_list = db.getInsertedManualStockData(invoiceNo, invType, visit_date); + selected_list2 = db.getInsertedManualStockData(invoiceNo, invType, visit_date); + Collections.reverse(selected_list2); + Collections.reverse(selected_list); + if (!selected_list.isEmpty()) { + str_img_invoice = selected_list.get(0).getInvoice_img(); + if (!str_img_invoice.isEmpty()) { + invoice_img.setImageDrawable(getResources().getDrawable(R.mipmap.camera_bsd)); + } + adapter = new ValueAdapter(context, selected_list); + drawer_layout_recycle_store.setAdapter(adapter); + drawer_layout_recycle_store.setLayoutManager(new LinearLayoutManager(context)); + } + } catch (Exception e) { + FirebaseCrashlytics.getInstance().recordException(e); + //test("Exception when fetching", e.toString()); + } + } + + @SuppressLint("NonConstantResourceId") + @Override + public void onClick(View v) { + + if (v.getId() == R.id.manualinvoice_img) { + isDataAdded = true; + _pathforcheck = counter_id + "_minwordsimg_" + username + "_" + visit_date.replace("/", "") + "_" + getCurrentTime().replace(":", "") + ".jpg"; + _path = CommonString.getImagesFolder(context) + _pathforcheck; + CommonFunctions.startAnncaCameraActivity(context, _path, null, false, CommonString.CAMERA_FACE_REAR); + } else if (v.getId() == R.id.btn_scan) { + isDataAdded = true; + show_proforma_dialog(context, true); + } else if (v.getId() == R.id.btn_enter_code) { + isDataAdded = true; + show_proforma_dialog(context, false); + } else if (v.getId() == R.id.btn_sku_list) { + isDataAdded = true; + show_dialog_forsku_categorywise(context); + } else if (v.getId() == R.id.draft_btn) { + if (validateData()) { + saveDataInDraft(); + } else { + AlertandMessages.showToastMsg(context, Error_Msg); + } + + } else if (v.getId() == R.id.save_btn) { + if (validateData()) { + saveUpdateAndUploadData(); + } else { + AlertandMessages.showToastMsg(context, Error_Msg); + } + + } else if (v.getId() == R.id.date_img) { + c = Calendar.getInstance(); + mYear = c.get(Calendar.YEAR); + mMonth = c.get(Calendar.MONTH); + mDay = c.get(Calendar.DAY_OF_MONTH); + + c.add(Calendar.DAY_OF_MONTH, -6); + Date result = c.getTime(); + + // Launch Date Picker Dialog + dpd = new DatePickerDialog(ManualInWardStockActivity.this, (view, year, monthOfYear, dayOfMonth) -> { + if (monthOfYear + 1 < 10) { + month = "0" + (monthOfYear + 1); + } else { + month = String.valueOf(monthOfYear + 1); + } + + if (dayOfMonth < 10) { + dd = "0" + dayOfMonth; + } else { + dd = String.valueOf(dayOfMonth); + } + + String dob = month + "-" + dd + "-" + year; + invoice_date.setText(dob); + }, mYear, mMonth, mDay); + + // TODO Hide Future Date Here + // dpd.getDatePicker().setMaxDate(System.currentTimeMillis()); + // TODO Hide Past Date Here + dpd.getDatePicker().setMaxDate(System.currentTimeMillis()); + dpd.getDatePicker().setMinDate(result.getTime()); + dpd.show(); + + } + } + + public class MultiPurposeDialog extends Dialog { + public MultiPurposeDialog(Context context) { + super(context); + // DIALOG USER_INTERFACE TEMPLATE + WindowManager.LayoutParams wmLayoutParams + = Objects.requireNonNull(getWindow()).getAttributes(); + wmLayoutParams.gravity = Gravity.CENTER; + getWindow().setAttributes(wmLayoutParams); + setTitle(null); + setCancelable(false); + setOnCancelListener(null); + LinearLayout layout = new LinearLayout(context); + layout.setOrientation(LinearLayout.VERTICAL); + } + } + + private void show_dialog_for_final_submit(final Context context) { + final MultiPurposeDialog final_save_dialog = new MultiPurposeDialog(context); + final_save_dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); + final_save_dialog.setContentView(R.layout.custom_dialog_final_save); + final WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); + lp.copyFrom(Objects.requireNonNull(final_save_dialog.getWindow()).getAttributes()); + lp.width = WindowManager.LayoutParams.MATCH_PARENT; + lp.height = WindowManager.LayoutParams.WRAP_CONTENT; + lp.gravity = Gravity.CENTER; + final_save_dialog.getWindow().setAttributes(lp); + final_save_dialog.setCancelable(false); + final EditText txt_hint_yes = (EditText) final_save_dialog.findViewById(R.id.txt_hint_yes); + Button btn_cancel = (Button) final_save_dialog.findViewById(R.id.btn_cancel); + Button btn_okay = (Button) final_save_dialog.findViewById(R.id.btn_okay); + btn_okay.setOnClickListener(v -> { + if (txt_hint_yes.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter Text"); + } else if (!txt_hint_yes.getText().toString().trim().equalsIgnoreCase("yes")) { + AlertandMessages.showToastMsg(context, "Please Enter 'Yes' Text"); + } else { + new InsertAsync().execute(); + final_save_dialog.dismiss(); + } + }); + + + btn_cancel.setOnClickListener(v -> final_save_dialog.dismiss()); + + final_save_dialog.show(); + } + + + @SuppressLint("StaticFieldLeak") + class InsertAsync extends AsyncTask { + private Dialog dialog = null; + private ProgressBar pb = null; + + @Override + protected void onPreExecute() { + dialog = new Dialog(context); + dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); + Objects.requireNonNull(dialog.getWindow()).setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT)); + dialog.setContentView(R.layout.circular_progress_bar); + pb = (ProgressBar) dialog.findViewById(R.id.progressBar1); + dialog.setCancelable(false); + dialog.show(); + super.onPreExecute(); + } + + @Override + protected Void doInBackground(Boolean... bool) { + savedManualInward(); + return null; + } + + @Override + protected void onPostExecute(Void aVoid) { + super.onPostExecute(aVoid); + dialog.cancel(); + AlertandMessages.showToastMsg(context, getResources().getString(R.string.data_saved_msg)); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + if (CommonFunctions.checkNetIsAvailable(context)) CommonFunctions.call_upload(context); + ManualInWardStockActivity.this.finish(); + } + } + + private void savedManualInward() { + ////final submit + // invoice id is 0 for manual entry + // counter confirm will zero in draft mode + // invoice status is maintain to 0 till he/she save data as draft + // here user can save data and data is synced with server + String TransactionId = CommonFunctions.getUUID(context); + String counterType = tCounterInvoiceObj.getInvoiceType(); + ///for new Manual inward Products list for insert + boolean Newproduct = true; + ArrayList newproducts; + ArrayList existingproducts; + newproducts = newinwardproduct_Checked(selected_list, Newproduct); + Newproduct = false; + existingproducts = newinwardproduct_Checked(selected_list, Newproduct); + db.open(); + ////deleted record perticular invoice no.................. + db.deletemanualinwardbyInvoiceid(counter_id, visit_date, CommonFunctions.removed_special_char(invoice_number), counterType); + if (!newproducts.isEmpty()) { + db.open(); + Newproduct = true; + db.insertManualInwardStockData(newproducts, counter_id, username, + CommonFunctions.removed_special_char(invoice_number), counterType, + invoice_date.getText().toString(), visit_date, str_img_invoice, TransactionId, Newproduct); + } + + ///inserting for exsting product manual inward for interting + TransactionId = CommonFunctions.getUUID(context); + Newproduct = false; + if (!existingproducts.isEmpty()) { + db.open(); + db.insertManualInwardStockData(existingproducts, counter_id, username, + CommonFunctions.removed_special_char(invoice_number), counterType, + invoice_date.getText().toString(), visit_date, str_img_invoice, TransactionId, Newproduct); + } + } + + private ArrayList newinwardproduct_Checked(ArrayList selected_list, boolean flagfornewproduct) { + ArrayList nwproductlist = new ArrayList<>(); + if (!selected_list.isEmpty()) { + for (int k = 0; k < selected_list.size(); k++) { + db.open(); + TStockSummary stockObj = db.getTStockSummaryProductDetails(Integer.parseInt(selected_list.get(k).getProduct_Id())); + if (flagfornewproduct) { + if (stockObj == null) { + nwproductlist.add(selected_list.get(k)); + } + } else { + if (stockObj != null && stockObj.getProductId() != null) { + nwproductlist.add(selected_list.get(k)); + } + } + } + } + return nwproductlist; + } + + + private void saveUpdateAndUploadData() { + androidx.appcompat.app.AlertDialog.Builder builder = new androidx.appcompat.app.AlertDialog.Builder(context); + builder.setCancelable(false).setTitle(R.string.dialog_title); + builder.setMessage(R.string.save_data_msg_new).setCancelable(false) + .setPositiveButton("OK", (dialog, id) -> { + show_dialog_for_final_submit(context); + dialog.dismiss(); + }) + .setNegativeButton("Cancel", (dialog, which) -> dialog.dismiss()); + androidx.appcompat.app.AlertDialog alert = builder.create(); + alert.show(); + + } + + private void saveDataInDraft() { + androidx.appcompat.app.AlertDialog.Builder builder = new androidx.appcompat.app.AlertDialog.Builder(context); + builder.setCancelable(false).setTitle(R.string.dialog_title); + builder.setMessage(R.string.save_draft_data_msg).setCancelable(false) + .setPositiveButton("OK", (dialog, id) -> { + String counterType = tCounterInvoiceObj.getInvoiceType(); + db.open(); + // invoice id is 0 for manual entry + // counter confirm will zero in draft mode + // invoice status is maintain to 0 till he/she save data as draft + // here user can save data as draft but data is not synced with server + String invoice_status = "0", invoiceId = "0", counter_confirm = "0", draft_status = "1", source = "Manual"; + long val = db.insertmanualinwardinDraft(selected_list, invoice_status, invoiceId, counter_confirm, draft_status, counter_id, + username, CommonFunctions.removed_special_char(invoice_number), counterType, + invoice_date.getText().toString(), source, visit_date, str_img_invoice); + if (val > 0) { + AlertandMessages.showToastMsg(context, getResources().getString(R.string.data_saved_msg)); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + ManualInWardStockActivity.this.finish(); + } else { + AlertandMessages.showToastMsg(context, getResources().getString(R.string.data_not_saved_msg)); + } + dialog.dismiss(); + }).setNegativeButton("Cancel", (dialog, which) -> dialog.dismiss()); + + androidx.appcompat.app.AlertDialog alert = builder.create(); + alert.show(); + } + + + private boolean validateData() { + boolean entryFlag = false; + db.open(); + manualInwardStockList = db.getInsertedManualInwardStockData(counter_id, CommonFunctions.removed_special_char(invoice_number)); + if (invoice_number.getText().toString().isEmpty()) { + Error_Msg = getResources().getString(R.string.invoice_number_error_msg); + } else if (value.equalsIgnoreCase("add")) { + if (!manualInwardStockList.isEmpty()) { + Error_Msg = getResources().getString(R.string.duplicate_invoice_error_msg); + } else { + entryFlag = checkRestDataValidation(); + } + } else { + entryFlag = checkRestDataValidation(); + } + return entryFlag; + } + + private boolean checkRestDataValidation() { + boolean flag = false; + if (tCounterInvoiceObj.getInvoiceType().isEmpty()) { + Error_Msg = getResources().getString(R.string.invoice_type_error_msg); + } else if (invoice_date.getText().toString().isEmpty()) { + Error_Msg = getResources().getString(R.string.invoice_date_error_msg); + } else if (str_img_invoice.isEmpty()) { + Error_Msg = getResources().getString(R.string.invoice_img_error_msg); + } else if (selected_list.isEmpty()) { + Error_Msg = getResources().getString(R.string.sku_error_msg); + } else if (validateListData(selected_list)) { + flag = true; + } else { + flag = false; + } + + return flag; + } + + private boolean validateListData(ArrayList selected_list) { + flag = true; + for (int i = 0; i < selected_list.size(); i++) { + if (selected_list.get(i).getViewMode().equals("1")) { + if (!selected_list.get(i).isConfirmChecked()) { + Error_Msg = getResources().getString(R.string.edit_confirmation); + flag = false; + break; + } else { + if (Integer.parseInt(selected_list.get(i).getActualQty()) < Integer.parseInt(selected_list.get(i).getQuantity())) { + if (selected_list.get(i).getReasonId() == 0) { + Error_Msg = getResources().getString(R.string.error_reason); + flag = false; + break; + } else { + flag = true; + } + } else { + flag = true; + } + } + } else { + if (Integer.parseInt(selected_list.get(i).getActualQty()) < Integer.parseInt(selected_list.get(i).getQuantity())) { + if (selected_list.get(i).getReasonId() == 0) { + Error_Msg = getResources().getString(R.string.error_reason); + flag = false; + break; + } else { + flag = true; + } + } else { + flag = true; + } + } + } + + return flag; + } + + + @SuppressLint("SetTextI18n") + private void show_dialog_forsku_categorywise(final Context context) { + minteger = 0; + final MultiPurposeDialog multiPurposeDialog = new MultiPurposeDialog(context); + multiPurposeDialog.requestWindowFeature(Window.FEATURE_NO_TITLE); + multiPurposeDialog.setContentView(R.layout.custom_sku_list_with_category); + final WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); + lp.copyFrom(Objects.requireNonNull(multiPurposeDialog + .getWindow()).getAttributes()); + lp.width = WindowManager.LayoutParams.MATCH_PARENT; + lp.height = WindowManager.LayoutParams.WRAP_CONTENT; + lp.gravity = Gravity.CENTER; + multiPurposeDialog.getWindow().setAttributes(lp); + multiPurposeDialog.setCancelable(false); + ///new changes 19 aug + final Spinner dialog_brand_spin = (Spinner) multiPurposeDialog.findViewById(R.id.dialog_brand_spin); + final Spinner dialog_subbrand_spin = (Spinner) multiPurposeDialog.findViewById(R.id.dialog_subbrand_spin); + final Spinner dialog_reference_spin = (Spinner) multiPurposeDialog.findViewById(R.id.dialog_reference_spin); + final Spinner dialog_product_spin = (Spinner) multiPurposeDialog.findViewById(R.id.dialog_product_spin); + final EditText et_search = (EditText) multiPurposeDialog.findViewById(R.id.et_search); + final TextView stock_text_value = (TextView) multiPurposeDialog.findViewById(R.id.stock_text_value); + final Button stock_img_minus = (Button) multiPurposeDialog.findViewById(R.id.stock_img_minus); + Button stock_img_plus = (Button) multiPurposeDialog.findViewById(R.id.stock_img_plus); + ImageView cancet_btn = (ImageView) multiPurposeDialog.findViewById(R.id.cancet_btn); + final ImageView btn_add = (ImageView) multiPurposeDialog.findViewById(R.id.btn_add); + final LinearLayout rl_return_reason = (LinearLayout) multiPurposeDialog.findViewById(R.id.rl_return_reason); + rl_return_reason.setVisibility(View.GONE); + et_search.addTextChangedListener(new TextWatcher() { + @Override + public void beforeTextChanged(CharSequence s, int start, int count, int after) { + } + + @Override + public void onTextChanged(CharSequence s, int start, int before, int count) { + String text = s.toString(); + setSearchFilter(dialog_product_list, text, dialog_product_spin); + } + + @Override + public void afterTextChanged(Editable s) { + String text = s.toString(); + } + }); + db.open(); + validate_spin_ui_data(dialog_brand_spin, dialog_subbrand_spin, dialog_reference_spin, dialog_product_spin, + db.getproductdata_formanual_inwarddialog("BrandName", "BrandId"), + db.getproductdata_formanual_inwarddialog("SubBrandName", "SubBrandId"), + db.getproductdata_formanual_inwarddialog("ReferenceName", "ReferenceId"), + db.getbrand_wise_sku_fromproductformanual(), stock_text_value); + cancet_btn.setOnClickListener(v -> multiPurposeDialog.dismiss()); + stock_img_plus.setOnClickListener(v -> { + minteger = minteger + 1; + stock_text_value.setText("" + minteger); + }); + stock_img_minus.setOnClickListener(v -> { + if (minteger == 0) { + AlertandMessages.showToastMsg(context, "Product quantity should not be less than Zero ."); + } else { + minteger = minteger - 1; + stock_text_value.setText("" + minteger); + } + }); + + btn_add.setOnClickListener(v -> { + ((ManualInWardStockActivity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); + if (dialog_product_spin.getSelectedItemId() == 0) { + AlertandMessages.showToastMsg(context, "Please Select Product"); + } else if (stock_text_value.getText().toString().equals("0")) { + AlertandMessages.showToastMsg(context, "Quantity must be greater than zero"); + } else { + // get selected radio button from radioGroup + // find the radiobutton by returned id + object = new InvoiceGetterSetter(); + if (checkduplicate_entry(product_Id, product_mrp)) { + object.setProduct_rate(product_mrp); + object.setProduct(product_name); + object.setProduct_Id(product_Id); + object.setScan_ean_code_or_enterd_ean_code(product_scan_code); + object.setQuantity(stock_text_value.getText().toString()); + object.setActualQty(stock_text_value.getText().toString()); + object.setDraft_status("0"); + object.setViewMode(CommonString.ADD_NEW_ITEM_FROM_OPTION); + selected_list.add(object); + minteger = 0; + stock_text_value.setText("0"); + product_scan_code = ""; + dialog_brand_Id = ""; + dialog_sub_brand_Id = ""; + dialog_reference_Id = ""; + product_name = ""; + product_Id = "0"; + adapter = new ValueAdapter(context, selected_list); + drawer_layout_recycle_store.setAdapter(adapter); + drawer_layout_recycle_store.setLayoutManager(new LinearLayoutManager(context)); + multiPurposeDialog.dismiss(); + txt_invoice_qty.setText("Invoice QTY : " + calculate_invoice_qty()); + txt_actual_qty.setText("Actual QTY : " + calculate_actual_qty()); + } + } + }); + multiPurposeDialog.show(); + } + + + private void + validate_spin_ui_data(final Spinner dialog_brand_spin, final Spinner dialog_sub_brand_spin, + final Spinner dialog_franchise_spin, final Spinner dialog_product_spin, final ArrayList brandList, + final ArrayList subbrandList, + final ArrayList referenceList, + final ArrayList productList, final TextView stock_text_value) { + + dialog_brand_adapter = new ArrayAdapter<>(this, R.layout.spinner_custom_item); + dialog_brand_adapter.add("- Select Brand -"); + for (int i = 0; i < brandList.size(); i++) { + dialog_brand_adapter.add(brandList.get(i).getBrandName()); + } + dialog_brand_spin.setAdapter(dialog_brand_adapter); + dialog_brand_adapter.setDropDownViewResource(R.layout.spinner_custom_item); + setSubBrandSpinnerData(subbrandList, dialog_sub_brand_spin); + setReferenceSpinnerData(referenceList, dialog_franchise_spin); + setProductSpinnerData(productList, dialog_product_spin); + dialog_brand_spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { + @Override + public void onItemSelected(AdapterView adapterView, View view, int pos, long l) { + if (pos != 0) { + db.open(); + flag_for_filter = true; + flag_filter_by_edt = false; + try { + dialog_brand_Id = adapterView.getSelectedItem().toString(); + setFilter(FILTER_FOR_BRAND, dialog_product_spin); + setSubBrandSpinnerData(db.getsub_brand_using_brand_Id(dialog_brand_Id, "SubBrandName", "SubBrandId", + "BrandName", null, visit_date, counter_id, false, null), dialog_sub_brand_spin); + setReferenceSpinnerData(db.getsub_brand_using_brand_Id(dialog_brand_Id, "ReferenceName", "ReferenceId", + "BrandName", null, visit_date, counter_id, false, null), dialog_franchise_spin); + } catch (Exception e) { + throw new RuntimeException(e); + } + } else { + dialog_brand_Id = ""; + if (dialog_brand_spin.getSelectedItemPosition() != 0 || dialog_sub_brand_spin.getSelectedItemPosition() != 0 || + dialog_franchise_spin.getSelectedItemPosition() != 0) { + flag_for_filter = true; + } else { + setFilter(CLEAR_FILTER, dialog_product_spin); + flag_for_filter = false; + } + } + } + + @Override + public void onNothingSelected(AdapterView adapterView) { + } + }); + + dialog_sub_brand_spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { + @Override + public void onItemSelected(AdapterView adapterView, View view, int pos, long l) { + if (pos != 0) { + db.open(); + flag_for_filter = true; + flag_filter_by_edt = false; + try { + dialog_sub_brand_Id = adapterView.getSelectedItem().toString(); + setFilter(FILTER_FOR_SUB_BRAND, dialog_product_spin); + setReferenceSpinnerData(db.getsub_brand_using_brand_Id(dialog_sub_brand_Id, "ReferenceName", "ReferenceId", "SubBrandName", null, visit_date, counter_id, false, null), dialog_franchise_spin); + } catch (Exception e) { + throw new RuntimeException(e); + } + } else { + dialog_sub_brand_Id = ""; + if (dialog_brand_spin.getSelectedItemPosition() != 0 || dialog_sub_brand_spin.getSelectedItemPosition() != 0 || + dialog_franchise_spin.getSelectedItemPosition() != 0) { + flag_for_filter = true; + } else { + setFilter(CLEAR_FILTER, dialog_product_spin); + flag_for_filter = false; + } + } + } + + @Override + public void onNothingSelected(AdapterView adapterView) { + + } + }); + + dialog_franchise_spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { + @Override + public void onItemSelected(AdapterView adapterView, View view, int pos, long l) { + if (pos != 0) { + flag_for_filter = true; + flag_filter_by_edt = false; + try { + dialog_reference_Id = adapterView.getSelectedItem().toString(); + setFilter(FILTER_FOR_REFERENCE_NAME, dialog_product_spin); + } catch (Exception e) { + throw new RuntimeException(e); + } + } else { + dialog_reference_Id = ""; + if (dialog_brand_spin.getSelectedItemPosition() != 0 || dialog_sub_brand_spin.getSelectedItemPosition() != 0 || + dialog_franchise_spin.getSelectedItemPosition() != 0) { + flag_for_filter = true; + } else { + setFilter(CLEAR_FILTER, dialog_product_spin); + flag_for_filter = false; + } + } + } + + @Override + public void onNothingSelected(AdapterView adapterView) { + + } + }); + + + dialog_product_spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { + @Override + public void onItemSelected(AdapterView parent, View view, int position, long id) { + if (position != 0) { + try { + if (flag_filter_by_edt) { + product_name = dialog_product_using_searchlist.get(position - 1).getProductName(); + product_Id = dialog_product_using_searchlist.get(position - 1).getProductId().toString(); + product_mrp = dialog_product_using_searchlist.get(position - 1).getMrp().toString(); + product_scan_code = dialog_product_using_searchlist.get(position - 1).getEanCode(); + stock_text_value.setText("1"); + minteger = 1; + } else if (flag_for_filter) { + product_name = filterListForReferencename(dialog_product_list, dialog_reference_Id, dialog_brand_Id, dialog_sub_brand_Id).get(position - 1).getProductName(); + product_Id = filterListForReferencename(dialog_product_list, dialog_reference_Id, dialog_brand_Id, dialog_sub_brand_Id).get(position - 1).getProductId().toString(); + product_mrp = filterListForReferencename(dialog_product_list, dialog_reference_Id, dialog_brand_Id, dialog_sub_brand_Id).get(position - 1).getMrp().toString(); + product_scan_code = filterListForReferencename(dialog_product_list, dialog_reference_Id, dialog_brand_Id, dialog_sub_brand_Id).get(position - 1).getEanCode(); + stock_text_value.setText("1"); + minteger = 1; + } else { + product_name = productList.get(position - 1).getProductName(); + product_Id = productList.get(position - 1).getProductId().toString(); + product_mrp = productList.get(position - 1).getMrp().toString(); + product_scan_code = productList.get(position - 1).getEanCode(); + stock_text_value.setText("1"); + minteger = 1; + } + } catch (Exception e) { + throw new RuntimeException(e); + } + } else { + stock_text_value.setText("0"); + product_scan_code = ""; + product_mrp = "0"; + product_name = ""; + product_Id = "0"; + minteger = 0; + } + } + + @Override + public void onNothingSelected(AdapterView parent) { + + } + }); + + } + + + private void setSubBrandSpinnerData(ArrayList axeList, Spinner dialog_sub_brand_spin) { + dialog_sub_brand_adapter = new ArrayAdapter<>(this, R.layout.spinner_custom_item); + dialog_sub_brand_adapter.add("- Select Sub Brand -"); + for (int i = 0; i < axeList.size(); i++) { + dialog_sub_brand_adapter.add(axeList.get(i).getBrandName()); + } + dialog_sub_brand_spin.setAdapter(dialog_sub_brand_adapter); + dialog_sub_brand_adapter.setDropDownViewResource(R.layout.spinner_custom_item); + } + + + private void setReferenceSpinnerData(ArrayList referenceList, Spinner dialog_franchise_spin) { + dialog_frenchise_adapter = new ArrayAdapter<>(this, R.layout.spinner_custom_item); + dialog_frenchise_adapter.add("- Select Franchise -"); + for (int i = 0; i < referenceList.size(); i++) { + dialog_frenchise_adapter.add(referenceList.get(i).getBrandName()); + } + + dialog_franchise_spin.setAdapter(dialog_frenchise_adapter); + dialog_frenchise_adapter.setDropDownViewResource(R.layout.spinner_custom_item); + } + + private void setProductSpinnerData(ArrayList productList, Spinner dialog_product_spin) { + dialog_sku_adapter = new ArrayAdapter<>(this, R.layout.spinner_custom_item); + dialog_sku_adapter.add("- Select Product -"); + + for (int i = 0; i < productList.size(); i++) { + dialog_sku_adapter.add(productList.get(i).getProductName() + " - (MRP-" + productList.get(i).getMrp().toString() + ")"); + } + + dialog_product_spin.setAdapter(dialog_sku_adapter); + dialog_sku_adapter.setDropDownViewResource(R.layout.spinner_custom_item); + } + + + public void setFilter(int filterType, Spinner dialog_spin) { + if (filterType == FILTER_FOR_BRAND) { + dialog_sku_adapter = new ArrayAdapter<>(context, R.layout.spinner_custom_item); + dialog_sku_adapter.add("- Select Product -"); + + for (int i = 0; i < filterListForBrand(dialog_product_list, dialog_brand_Id).size(); i++) { + dialog_sku_adapter.add(filterListForBrand(dialog_product_list, dialog_brand_Id).get(i).getProductName() + " - (MRP-" + filterListForBrand(dialog_product_list, dialog_brand_Id).get(i).getMrp().toString() + ")"); + } + + dialog_spin.setAdapter(dialog_sku_adapter); + dialog_sku_adapter.setDropDownViewResource(R.layout.spinner_custom_item); + + } else if (filterType == FILTER_FOR_SUB_BRAND) { + dialog_sku_adapter = new ArrayAdapter<>(context, R.layout.spinner_custom_item); + dialog_sku_adapter.add("- Select Product -"); + + for (int i = 0; i < filterListForSubBrand(dialog_product_list, dialog_sub_brand_Id, dialog_brand_Id).size(); i++) { + dialog_sku_adapter.add(filterListForSubBrand(dialog_product_list, dialog_sub_brand_Id, dialog_brand_Id).get(i).getProductName() + " - (MRP-" + + filterListForSubBrand(dialog_product_list, dialog_sub_brand_Id, dialog_brand_Id).get(i).getMrp().toString() + ")"); + } + dialog_spin.setAdapter(dialog_sku_adapter); + dialog_sku_adapter.setDropDownViewResource(R.layout.spinner_custom_item); + } else if (filterType == FILTER_FOR_REFERENCE_NAME) { + + dialog_sku_adapter = new ArrayAdapter<>(context, R.layout.spinner_custom_item); + dialog_sku_adapter.add("- Select Product -"); + + for (int i = 0; i < filterListForReferencename(dialog_product_list, dialog_reference_Id, dialog_brand_Id, dialog_sub_brand_Id).size(); i++) { + dialog_sku_adapter.add(filterListForReferencename(dialog_product_list, dialog_reference_Id, dialog_brand_Id, dialog_sub_brand_Id).get(i).getProductName() + + " - (MRP-" + filterListForReferencename(dialog_product_list, dialog_reference_Id, dialog_brand_Id, dialog_sub_brand_Id).get(i).getMrp().toString() + ")"); + } + + dialog_spin.setAdapter(dialog_sku_adapter); + dialog_sku_adapter.setDropDownViewResource(R.layout.spinner_custom_item); + + } else { + dialog_sku_adapter = new ArrayAdapter<>(context, R.layout.spinner_custom_item); + dialog_sku_adapter.add("- Select Product -"); + + for (int i = 0; i < dialog_product_list.size(); i++) { + dialog_sku_adapter.add(dialog_product_list.get(i).getProductName() + " - (MRP-" + dialog_product_list.get(i).getMrp().toString() + ")"); + } + + dialog_spin.setAdapter(dialog_sku_adapter); + dialog_sku_adapter.setDropDownViewResource(R.layout.spinner_custom_item); + } + + dialog_spin.invalidate(); + } + + + public ArrayList filterListForBrand(List originalList, String text) { + ArrayList filterList = new ArrayList<>(); + for (ProductMaster object : originalList) { + if (object.getBrandName().equalsIgnoreCase(text)) { + filterList.add(object); + } + } + return filterList; + } + + public ArrayList filterListForSubBrand(List originalList, String sub_brand_name_id, String brand_Id) { + ArrayList filterList = new ArrayList<>(); + for (ProductMaster object : originalList) { + if (sub_brand_name_id.isEmpty() && object.getBrandName().equalsIgnoreCase(brand_Id)) { + filterList.add(object); + } else if (object.getSubBrandName().equalsIgnoreCase(sub_brand_name_id) && (brand_Id.isEmpty() || object.getBrandName().equalsIgnoreCase(brand_Id))) { + filterList.add(object); + } + } + + return filterList; + } + + + public ArrayList filterListForReferencename(List originalList, String franchise_Id, String brandName_Id, String sub_brand_name_Id) { + ArrayList filterList = new ArrayList<>(); + for (ProductMaster object : originalList) { + if (sub_brand_name_Id.isEmpty() && object.getBrandName().equalsIgnoreCase(brandName_Id)) { + filterList.add(object); + } else if (franchise_Id.isEmpty() && object.getSubBrandName().equalsIgnoreCase(sub_brand_name_Id)) { + filterList.add(object); + } else if (object.getReferenceName().equalsIgnoreCase(franchise_Id) && (brandName_Id.isEmpty() || object.getBrandName().equalsIgnoreCase(brandName_Id)) && (sub_brand_name_Id.isEmpty() || object.getSubBrandName().equalsIgnoreCase(sub_brand_name_Id))) { + filterList.add(object); + } + } + + return filterList; + } + + private void show_proforma_dialog(final Context context, final boolean flag_for_rl) { + minteger = 0; + dialog_final = new MultiPurposeDialog(context); + dialog_final.requestWindowFeature(Window.FEATURE_NO_TITLE); + dialog_final.setContentView(R.layout.custom_bar_code_dialog); + dialog_final.setCancelable(false); + WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); + lp.copyFrom(Objects.requireNonNull(dialog_final.getWindow()).getAttributes()); + lp.width = WindowManager.LayoutParams.MATCH_PARENT; + lp.height = WindowManager.LayoutParams.WRAP_CONTENT; + lp.gravity = Gravity.CENTER; + dialog_final.getWindow().setAttributes(lp); + dialog_final.setCancelable(false); + + LinearLayout rl_bar_code = (LinearLayout) dialog_final.findViewById(R.id.rl_bar_code); + LinearLayout RL_scan_code = (LinearLayout) dialog_final.findViewById(R.id.RL_scan_code); + Button check_exist_sku = (Button) dialog_final.findViewById(R.id.check_exist_sku); + TextView txt_bar_code = dialog_final.findViewById(R.id.txt_bar_code); + TextView txt_enterbar_code = dialog_final.findViewById(R.id.txt_enterbar_code); + + if (flag_for_rl) { + RL_scan_code.setVisibility(View.GONE); + rl_bar_code.setVisibility(View.VISIBLE); + txt_bar_code.setVisibility(View.VISIBLE); + txt_enterbar_code.setVisibility(View.GONE); + } else { + rl_bar_code.setVisibility(View.GONE); + txt_bar_code.setVisibility(View.GONE); + RL_scan_code.setVisibility(View.VISIBLE); + txt_enterbar_code.setVisibility(View.VISIBLE); + } + + qrcode_text = (TextView) dialog_final.findViewById(R.id.qrcode_text); + edt_scan_code = (EditText) dialog_final.findViewById(R.id.edt_scan_code); + stock_text_value = (TextView) dialog_final.findViewById(R.id.stock_text_value); + ImageView img_bar_code = (ImageView) dialog_final.findViewById(R.id.img_bar_code); + ImageView cancet_btn = (ImageView) dialog_final.findViewById(R.id.cancet_btn); + + cancet_btn.setOnClickListener(v -> dialog_final.dismiss()); + + check_exist_sku.setOnClickListener(v -> { + if (!flag_for_rl && edt_scan_code.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter Bar Code"); + } else { + db.open(); + ArrayList productList = db.getsku_fromproductusing_eancode(edt_scan_code.getText().toString(), false, visit_date, counter_id, null); + if (productList.isEmpty()) { + db.open(); + productList = db.getsku_fromproductusing_eancode(removeFirstChar(edt_scan_code.getText().toString()), false, visit_date, counter_id, null); + } + if (productList.isEmpty()) { + edt_scan_code.setText(""); + AlertandMessages.showToastMsg(context, "Invalid Bar Code.Please try again"); + } else { + show_dialog_forsku(context, productList); + } + } + }); + + img_bar_code.setOnClickListener(v -> openScanner()); + dialog_final.show(); + } + + private class AdapterforSku extends RecyclerView.Adapter { + LayoutInflater inflator; + List data; + MultiPurposeDialog multiPurposeDialog; + + public AdapterforSku(Context context, List data, MultiPurposeDialog multiPurposeDialog) { + inflator = LayoutInflater.from(context); + this.data = data; + this.multiPurposeDialog = multiPurposeDialog; + } + + @NonNull + @Override + public AdapterforSku.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) { + View view = inflator.inflate(R.layout.adapter_custom_manual_inword, parent, false); + return new AdapterforSku.MyViewHolder(view); + } + + @SuppressLint("SetTextI18n") + @Override + public void onBindViewHolder(final AdapterforSku.MyViewHolder holder, @SuppressLint("RecyclerView") final int position) { + final ProductMaster current = data.get(position); + holder.sale_card.setVisibility(View.VISIBLE); + holder.sale_card.setId(position); + + holder.sale_trcking_name.setText("(MRP - " + current.getMrp().toString() + ")"); + holder.sale_trcking_name.setId(position); + + holder.stock_img_plus.setId(position); + holder.stock_img_plus.setOnClickListener(v -> { + if (checkduplicate_entry(current.getProductId().toString(), current.getMrp().toString())) { + int value = 0; + if (!current.getActualQty().isEmpty()) { + value = Integer.parseInt(current.getActualQty()); + } + value = value + 1; + holder.edt_stock_text_value.setText("" + value); + holder.edt_stock_text_value.setId(position); + current.setActualQty("" + value); + } + }); + holder.stock_img_minus.setId(position); + holder.stock_img_minus.setOnClickListener(v -> { + int value = 0; + if (!current.getActualQty().isEmpty()) { + value = Integer.parseInt(current.getActualQty()); + } + if (value == 0) { + AlertandMessages.showToastMsg(context, "Product quantity should not be less than Zero"); + } else { + value = value - 1; + holder.edt_stock_text_value.setText("" + value); + holder.edt_stock_text_value.setId(position); + current.setActualQty("" + value); + } + }); + + + holder.edt_stock_text_value.setOnFocusChangeListener((view, b) -> { + final EditText Caption = (EditText) view; + String value = Caption.getText().toString().replaceFirst("^0+(?!$)", ""); + if (value.isEmpty()) { + current.setActualQty("0"); + holder.edt_stock_text_value.setText("0"); + holder.edt_stock_text_value.setId(position); + } else { + current.setActualQty(value); + holder.edt_stock_text_value.setText(value); + holder.edt_stock_text_value.setId(position); + } + }); + if (current.getActualQty().isEmpty()) { + holder.edt_stock_text_value.setText("0"); + holder.edt_stock_text_value.setId(position); + } else { + holder.edt_stock_text_value.setText(current.getActualQty()); + holder.edt_stock_text_value.setId(position); + } + } + + + @Override + public int getItemCount() { + return data.size(); + } + + class MyViewHolder extends RecyclerView.ViewHolder { + CardView sale_card; + LinearLayout rl_quantity; + // CheckBox check_inword_item; + Button stock_img_minus, stock_img_plus; + TextView sale_trcking_name; + EditText edt_stock_text_value; + + + public MyViewHolder(View itemView) { + super(itemView); + sale_card = (CardView) itemView.findViewById(R.id.sale_card); + sale_trcking_name = (TextView) itemView.findViewById(R.id.sale_trcking_name); + ////for consumer product + edt_stock_text_value = (EditText) itemView.findViewById(R.id.edt_stock_text_value); + stock_img_plus = (Button) itemView.findViewById(R.id.stock_img_plus); + stock_img_minus = (Button) itemView.findViewById(R.id.stock_img_minus); + rl_quantity = (LinearLayout) itemView.findViewById(R.id.rl_quantity); + } + } + } + + + private boolean checkduplicate_entry(String product_Id, String product_mrp) { + boolean status = true; + if (selected_list != null && !selected_list.isEmpty()) { + for (int k = 0; k < selected_list.size(); k++) { + if (selected_list.get(k).getProduct_Id().equals(product_Id) && selected_list.get(k).getProduct_rate().equals(product_mrp)) { + AlertandMessages.showToastMsg(context, "This Product Already Exists In The Current Invoice"); + status = false; + break; + } + } + } + + return status; + } + + + private void openScanner() { + IntentIntegrator intentIntegrator = new IntentIntegrator((Activity) context); + intentIntegrator.setBeepEnabled(true); + intentIntegrator.setOrientationLocked(false); + intentIntegrator.setPrompt("Scan the barcode or QR code to get the data"); + intentIntegrator.initiateScan(); + } + + + private class ValueAdapter extends RecyclerView.Adapter { + LayoutInflater inflator; + List selected_list; + + public ValueAdapter(Context context, List selected_list) { + inflator = LayoutInflater.from(context); + this.selected_list = selected_list; + } + + @NonNull + @Override + public ValueAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) { + View view = inflator.inflate(R.layout.list_item_manual_inward_stock, parent, false); + return new ValueAdapter.MyViewHolder(view); + } + + @SuppressLint({"SetTextI18n", "NotifyDataSetChanged"}) + @Override + public void onBindViewHolder(final ValueAdapter.MyViewHolder holder, @SuppressLint("RecyclerView") final int position) { + final int quantity = Integer.parseInt(selected_list.get(position).getQuantity()); + holder.text_item.setText(selected_list.get(position).getProduct() + "( MRP - ₹ " + selected_list.get(position).getProduct_rate() + ")"); + holder.invoice_qty.setText(selected_list.get(position).getQuantity()); + holder.actual_qty.setText(selected_list.get(position).getActualQty()); + + if (!selected_list.get(position).getInvoice_status().equals("1")) { + if (value.equalsIgnoreCase("add")) { + defaultElementVisibility(holder); + } else { + if (selected_list.get(position).getViewMode().equalsIgnoreCase(CommonString.ADD_NEW_ITEM_FROM_OPTION)) { + defaultElementVisibility(holder); + } else if (selected_list.get(position).getViewMode().equalsIgnoreCase(CommonString.KEY_DISABLE_EDIT_MODE)) { + holder.edit_existing_product.setVisibility(View.GONE); + holder.delete_added_product.setVisibility(View.GONE); + holder.cancel_product.setVisibility(View.VISIBLE); + holder.confirmation_check.setVisibility(View.VISIBLE); + if (!value.isEmpty() && value.equalsIgnoreCase("edit")) { + holder.delete_added_product.setVisibility(View.VISIBLE); + } + + enableElement(holder); + } else if (selected_list.get(position).getViewMode().equalsIgnoreCase(CommonString.KEY_ENABLE_EDIT_MODE)) { + holder.confirmation_check.setChecked(false); + selected_list.get(position).setConfirmChecked(false); + holder.delete_added_product.setVisibility(View.GONE); + holder.cancel_product.setVisibility(View.GONE); + holder.confirmation_check.setVisibility(View.GONE); + holder.edit_existing_product.setVisibility(View.VISIBLE); + if (!value.isEmpty() && value.equalsIgnoreCase("edit")) { + holder.delete_added_product.setVisibility(View.VISIBLE); + } + disablElement(holder); + } else { + holder.delete_added_product.setVisibility(View.VISIBLE); + holder.edit_existing_product.setVisibility(View.VISIBLE); + disablElement(holder); + } + } + } else { + holder.confirmation_check.setChecked(false); + selected_list.get(position).setConfirmChecked(false); + holder.delete_added_product.setVisibility(View.GONE); + holder.cancel_product.setVisibility(View.GONE); + holder.confirmation_check.setVisibility(View.GONE); + holder.edit_existing_product.setVisibility(View.VISIBLE); + if (!value.isEmpty() && value.equalsIgnoreCase("edit")) { + holder.delete_added_product.setVisibility(View.VISIBLE); + } + disablElement(holder); + } + + holder.edit_existing_product.setOnClickListener(view -> { + selected_list.get(position).setViewMode(CommonString.KEY_DISABLE_EDIT_MODE); + if (!value.isEmpty() && value.equalsIgnoreCase("edit")) { + holder.delete_added_product.setVisibility(View.VISIBLE); + } + holder.edit_existing_product.setVisibility(View.GONE); + holder.confirmation_check.setVisibility(View.VISIBLE); + holder.cancel_product.setVisibility(View.VISIBLE); + notifyDataSetChanged(); + }); + + holder.cancel_product.setOnClickListener(view -> { + selected_list.get(position).setViewMode(CommonString.KEY_ENABLE_EDIT_MODE); + holder.cancel_product.setVisibility(View.GONE); + holder.confirmation_check.setVisibility(View.GONE); + if (!value.isEmpty() && value.equalsIgnoreCase("edit")) { + holder.delete_added_product.setVisibility(View.VISIBLE); + } + selected_list.get(position).setActualQty(selected_list2.get(position).getActualQty()); + selected_list.get(position).setReasonId(selected_list2.get(position).getReasonId()); + notifyDataSetChanged(); + + }); + + holder.stock_img_plus.setOnClickListener(v -> { + notifyDataSetChanged(); + int minteger = Integer.parseInt(selected_list.get(position).getActualQty()); + ++minteger; + if (minteger < quantity) { + selected_list.get(position).setActualQty(String.valueOf(minteger)); + } else if (minteger == quantity) { + selected_list.get(position).setActualQty(String.valueOf(minteger)); + holder.reasonSpinner.setSelection(0); + selected_list.get(position).setReasonId(0); + holder.reasonLayout.setVisibility(View.GONE); + } else { + AlertandMessages.showToastMsg(context, "Actual quantity cannot be greater than invoice quantity."); + } + }); + + reasonList = new ArrayList<>(); + db.open(); + reasonList = db.getReasonData(false); + holder.reasonSpinner.setAdapter(new ReasonSpinnerAdapter(context, R.layout.spinner_text_view, reasonList)); + holder.reasonSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { + @Override + public void onItemSelected(AdapterView adapterView, View view, int pos, long l) { + if (pos == 0) { + selected_list.get(position).setReasonId(0); + } else { + if (pos < reasonList.size()) + selected_list.get(position).setReasonId(reasonList.get(pos).getReasonId()); + } + } + + @Override + public void onNothingSelected(AdapterView adapterView) { + } + }); + + + if (Integer.parseInt(selected_list.get(position).getActualQty()) < quantity) { + if (selected_list.get(position).getReasonId() == 0) { + holder.reasonSpinner.setSelection(0); + } else { + if (!reasonList.isEmpty()) { + for (int k = 0; k < reasonList.size(); k++) { + if (selected_list.get(position).getReasonId() == reasonList.get(k).getReasonId()) { + holder.reasonSpinner.setSelection(k); + break; + } + } + } + } + holder.reasonLayout.setVisibility(View.VISIBLE); + } else { + holder.reasonLayout.setVisibility(View.GONE); + } + + holder.stock_img_minus.setOnClickListener(v -> { + notifyDataSetChanged(); + int minteger = Integer.parseInt(selected_list.get(position).getActualQty()); + --minteger; + if (minteger >= 0) { + holder.reasonLayout.setVisibility(View.VISIBLE); + selected_list.get(position).setActualQty(String.valueOf(minteger)); + } else { + AlertandMessages.showToastMsg(context, "Actual quantity cannot be less than 0"); + } + }); + + + if (Integer.parseInt(selected_list.get(position).getActualQty()) < Integer.parseInt(selected_list.get(position).getQuantity())) { + holder.actual_qty.setTextColor(Color.RED); + } else { + holder.actual_qty.setTextColor(Color.BLACK); + } + + holder.actual_qty.setText(selected_list.get(position).getActualQty()); + + holder.invoice_qty.setText(selected_list.get(position).getQuantity()); + + holder.confirmation_check.setOnCheckedChangeListener((compoundButton, b) -> { + if (compoundButton.isPressed()) { + selected_list.get(position).setConfirmChecked(compoundButton.isChecked()); + adapter.notifyDataSetChanged(); + } + }); + + holder.delete_added_product.setOnClickListener(v -> { + AlertDialog.Builder builder = new AlertDialog.Builder(context).setMessage("Are you sure you want to Delete ?").setTitle(getString(R.string.password_rules)).setCancelable(false) + .setPositiveButton("Yes", + (dialog, id) -> { + if (value.equalsIgnoreCase("edit")) { + if (selected_list.get(position).getKeyId() != null) { + db.open(); + db.deleteManualStockWithKeyIdData(counter_id, visit_date, selected_list.get(position).getKeyId()); + selected_list2.remove(position); + } + } + + selected_list.remove(position); + if (!selected_list.isEmpty()) { + adapter = new ValueAdapter(context, selected_list); + drawer_layout_recycle_store.setAdapter(adapter); + notifyDataSetChanged(); + } + + txt_invoice_qty.setText("Invoice QTY : " + calculate_invoice_qty()); + txt_actual_qty.setText("Actual QTY : " + calculate_actual_qty()); + + notifyDataSetChanged(); + }) + .setNegativeButton("No", + (dialog, id) -> dialog.cancel()); + AlertDialog alert = builder.create(); + alert.show(); + }); + + if (tCounterInvoice != null && tCounterInvoice.getUpload_status() != null && !tCounterInvoice.getUpload_status().isEmpty() && + tCounterInvoice.getUpload_status().equalsIgnoreCase(CommonString.KEY_U) || tCounterInvoice != null && tCounterInvoice.getTransactionId() != null + && !tCounterInvoice.getTransactionId().isEmpty()) { + holder.edit_existing_product.setVisibility(View.GONE); + holder.edit_existing_product.setId(position); + holder.confirmation_check.setVisibility(View.GONE); + holder.confirmation_check.setId(position); + holder.cancel_product.setVisibility(View.GONE); + holder.cancel_product.setId(position); + holder.delete_added_product.setVisibility(View.GONE); + holder.delete_added_product.setId(position); + } + + } + + private void disablElement(MyViewHolder holder) { + holder.stock_img_plus.setEnabled(false); + holder.reasonSpinner.setEnabled(false); + holder.stock_img_minus.setEnabled(false); + } + + private void enableElement(MyViewHolder holder) { + holder.stock_img_plus.setEnabled(true); + holder.reasonSpinner.setEnabled(true); + holder.stock_img_minus.setEnabled(true); + } + + private void defaultElementVisibility(MyViewHolder holder) { + holder.delete_added_product.setVisibility(View.VISIBLE); + holder.edit_existing_product.setVisibility(View.GONE); + holder.cancel_product.setVisibility(View.GONE); + holder.confirmation_check.setVisibility(View.GONE); + holder.stock_img_plus.setEnabled(true); + holder.reasonSpinner.setEnabled(true); + holder.stock_img_minus.setEnabled(true); + } + + @Override + public int getItemCount() { + return selected_list.size(); + } + + class MyViewHolder extends RecyclerView.ViewHolder { + TextView text_item; + TextView actual_qty, invoice_qty; + Button stock_img_plus, stock_img_minus; + Spinner reasonSpinner; + LinearLayout reasonLayout; + CheckBox confirmation_check; + CardView card_view; + ImageView delete_added_product, edit_existing_product, cancel_product; + + public MyViewHolder(View itemView) { + super(itemView); + text_item = (TextView) itemView.findViewById(R.id.manual_brand_name); + actual_qty = (TextView) itemView.findViewById(R.id.manual_actual_qty); + stock_img_plus = (Button) itemView.findViewById(R.id.manual_stock_img_plus); + stock_img_minus = (Button) itemView.findViewById(R.id.manual_stock_img_minus); + invoice_qty = (TextView) itemView.findViewById(R.id.manual_invoice_qty); + reasonSpinner = (Spinner) itemView.findViewById(R.id.manual_reason_spinner); + reasonLayout = (LinearLayout) itemView.findViewById(R.id.manual_reason_layout); + delete_added_product = (ImageView) itemView.findViewById(R.id.manual_delete_added_product); + edit_existing_product = (ImageView) itemView.findViewById(R.id.manual_edit_product); + cancel_product = (ImageView) itemView.findViewById(R.id.manual_cancel_product); + confirmation_check = (CheckBox) itemView.findViewById(R.id.confirm_check); + card_view = (CardView) itemView.findViewById(R.id.card_view); + } + } + } + + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + super.onActivityResult(requestCode, resultCode, data); + IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data); + if (result == null) { + switch (resultCode) { + case 0: + Log.i("MakeMachine", "User cancelled"); + break; + case -1: + try { + if (_pathforcheck != null && !_pathforcheck.isEmpty()) { + if (new File(CommonString.getImagesFolder(context) + _pathforcheck).exists()) { + convertBitmap(CommonString.getImagesFolder(context) + _pathforcheck); + invoice_img.setImageResource(R.mipmap.camera_bsd); + str_img_invoice = _pathforcheck; + _pathforcheck = ""; + } + } + } catch (Exception e) { + e.fillInStackTrace(); + } + break; + } + } else { + if (result.getContents() == null) { + //test("ScanActivity", "Cancelled scan"); + Toast.makeText(this, "Cancelled", Toast.LENGTH_SHORT).show(); + } else { + db.open(); + ArrayList productList = db.getsku_fromproductusing_eancode(result.getContents(), false, visit_date, counter_id, null); + if (productList.isEmpty()) { + db.open(); + productList = db.getsku_fromproductusing_eancode(removeFirstChar(result.getContents()), false, visit_date, counter_id, null); + } + if (!productList.isEmpty()) { + show_dialog_forsku(context, productList); + } else { + product_name = ""; + product_scan_code = ""; + qrcode_text.setText(""); + AlertandMessages.showToastMsg(context, "Unable To Scan Correct Data. Please Try Again."); + } + } + + } + } + + void isChanged() { + if (isDataAdded) { + android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(context); + builder.setTitle(getString(R.string.parinaam)); + builder.setMessage(getResources().getString(R.string.data_will_be_lost)).setCancelable(false) + .setPositiveButton(getString(R.string.ok), (dialog, id) -> { + finish(); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + }).setNegativeButton(getString(R.string.cancel), (dialog, which) -> { + dialog.dismiss(); + }); + android.app.AlertDialog alert = builder.create(); + alert.show(); + } else { + super.onBackPressed(); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + } + } + + @Override + public void onBackPressed() { + isChanged(); + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + if (item.getItemId() == android.R.id.home) { + isChanged(); + } + return super.onOptionsItemSelected(item); + } + + + ////sku scannnnnnnnnnnn + @SuppressLint("SetTextI18n") + private void show_dialog_forsku(final Context context, final ArrayList skuList_with_eancode) { + final MultiPurposeDialog dialog_custom = new MultiPurposeDialog(context); + dialog_custom.requestWindowFeature(Window.FEATURE_NO_TITLE); + dialog_custom.setContentView(R.layout.custom_sku_adapter); + final WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); + lp.copyFrom(Objects.requireNonNull(dialog_custom.getWindow()).getAttributes()); + lp.width = WindowManager.LayoutParams.MATCH_PARENT; + lp.height = WindowManager.LayoutParams.WRAP_CONTENT; + lp.gravity = Gravity.CENTER; + dialog_custom.getWindow().setAttributes(lp); + dialog_custom.setCancelable(false); + ((ManualInWardStockActivity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); + TextView sale_trcking_name = (TextView) dialog_custom.findViewById(R.id.sale_trcking_name); + sale_trcking_name.setText(skuList_with_eancode.get(0).getProductName()); + RecyclerView recycl_sku = (RecyclerView) dialog_custom.findViewById(R.id.recycl_sku); + recycl_sku.setAdapter(new AdapterforSku(context, skuList_with_eancode, dialog_custom)); + recycl_sku.setLayoutManager(new LinearLayoutManager(context)); + ImageView dismiss_dialog = (ImageView) dialog_custom.findViewById(R.id.dismiss_dialog); + Button btn_submit = (Button) dialog_custom.findViewById(R.id.btn_submit); + btn_submit.setVisibility(View.VISIBLE); + + dismiss_dialog.setOnClickListener(v -> dialog_custom.dismiss()); + + btn_submit.setOnClickListener(view -> { + if (validate_entered_data(skuList_with_eancode)) { + for (int k = 0; k < skuList_with_eancode.size(); k++) { + if (!skuList_with_eancode.get(k).getActualQty().isEmpty() && !skuList_with_eancode.get(k).getActualQty().equals("0")) { + object = new InvoiceGetterSetter(); + object.setDraft_status("0"); + object.setStore_name(store_name); + object.setBrandName(dialog_brand); + object.setStore_address(store_address); + object.setSubBrandName(dialog_sub_brand); + object.setReferenceName(dialog_reference); + object.setDemo_given_str(demo_given_str); + object.setProduct_sold_str(product_sold_str); + object.setViewMode(CommonString.ADD_NEW_ITEM_FROM_OPTION); + + object.setQuantity(skuList_with_eancode.get(k).getActualQty()); + object.setActualQty(skuList_with_eancode.get(k).getActualQty()); + object.setProduct(skuList_with_eancode.get(k).getProductName()); + object.setProduct_Id(skuList_with_eancode.get(k).getProductId().toString()); + object.setProduct_rate(skuList_with_eancode.get(k).getMrp().toString()); + object.setScan_ean_code_or_enterd_ean_code(skuList_with_eancode.get(k).getEanCode()); + selected_list.add(object); + } + } + + adapter = new ValueAdapter(context, selected_list); + drawer_layout_recycle_store.setAdapter(adapter); + drawer_layout_recycle_store.setLayoutManager(new LinearLayoutManager(context)); + dialog_final.cancel(); + dialog_custom.cancel(); + txt_invoice_qty.setText("Invoice QTY : " + calculate_invoice_qty()); + txt_actual_qty.setText("Actual QTY : " + calculate_actual_qty()); + } else { + AlertandMessages.showToastMsg(context, "Please Add Atleast One Product, And Please Increase Quantity Of Product"); + } + }); + dialog_custom.show(); + } + + + public void setSearchFilter(ArrayList originalList, String text, Spinner dialog_product_spin) { + flag_filter_by_edt = true; + dialog_sku_adapter = new ArrayAdapter<>(context, R.layout.spinner_custom_item); + dialog_sku_adapter.add("- Select Product -"); + dialog_product_using_searchlist = new ArrayList<>(); + dialog_product_using_searchlist = filterListForProduct_edt(originalList, text); + + if (filterListForProduct_edt(originalList, text).isEmpty()) { + dialog_product_using_searchlist = originalList; + } + for (int i = 0; i < dialog_product_using_searchlist.size(); i++) { + dialog_sku_adapter.add(dialog_product_using_searchlist.get(i).getProductName() + " - (MRP-" + dialog_product_using_searchlist.get(i).getMrp().toString() + ")"); + } + + dialog_product_spin.setAdapter(dialog_sku_adapter); + dialog_sku_adapter.setDropDownViewResource(R.layout.spinner_custom_item); + dialog_product_spin.invalidate(); + } + + public ArrayList filterListForProduct_edt(List originalList, String text) { + ArrayList filterList = new ArrayList<>(); + for (ProductMaster object : originalList) { + if (object.getProductName().toLowerCase().contains(text.toLowerCase())) { + filterList.add(object); + } + } + + return filterList; + } + + + private boolean validate_entered_data(ArrayList skuList_with_eancode) { + boolean status = false; + for (int k = 0; k < skuList_with_eancode.size(); k++) { + if (!skuList_with_eancode.get(k).getActualQty().isEmpty() && !skuList_with_eancode.get(k).getActualQty().equals("0")) { + status = true; + break; + } + } + + return status; + } + + private int calculate_invoice_qty() { + int total_invoice_qty = 0; + if (!selected_list.isEmpty()) { + for (int i = 0; i < selected_list.size(); i++) { + if (selected_list.get(i).getActualQty() != null && !selected_list.get(i).getActualQty().isEmpty()) { + total_invoice_qty = total_invoice_qty + Integer.parseInt(selected_list.get(i).getActualQty()); + } + } + } + + return total_invoice_qty; + } + + private int calculate_actual_qty() { + int total_actual_qty = 0; + if (!selected_list.isEmpty()) { + for (int i = 0; i < selected_list.size(); i++) { + if (selected_list.get(i).getQuantity() != null && !selected_list.get(i).getQuantity().isEmpty()) { + total_actual_qty = total_actual_qty + Integer.parseInt(selected_list.get(i).getQuantity()); + } + } + } + + return total_actual_qty; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/MeQuizListActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/MeQuizListActivity.java new file mode 100644 index 0000000..25df099 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/MeQuizListActivity.java @@ -0,0 +1,170 @@ +package com.cpm.lorealbaautomation.dailyactivity; + +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; + +import androidx.annotation.NonNull; +import androidx.appcompat.app.AppCompatActivity; +import android.os.Bundle; +import androidx.cardview.widget.CardView; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; +import androidx.appcompat.widget.Toolbar; +import android.view.LayoutInflater; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; +import android.widget.ImageView; +import android.widget.TextView; + +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.constant.AlertandMessages; +import com.cpm.lorealbaautomation.constant.CommonFunctions; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.gsonGetterSetter.MEMEAuditQuestion; +import com.cpm.lorealbaautomation.makeupexpert.MEQuizActivity; + +import java.util.ArrayList; +import java.util.List; + +public class MeQuizListActivity extends AppCompatActivity { + List checkHeaderArray = new ArrayList<>(); + boolean checkflag = true; + private SharedPreferences preferences; + String username, date, counter_id = ""; + Lorealba_Database db; + Toolbar toolbar; + RecyclerView me_quiz_list; + ArrayList listDataHeader = new ArrayList<>(); + Context _context; + MEQuizListAdapter adapter; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_me_quiz_list); + _context = this; + preferences = PrefHelper.getPrefs(this); + date = preferences.getString(CommonString.KEY_DATE, null); + username = preferences.getString(CommonString.KEY_USERNAME, null); + counter_id = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + toolbar = (Toolbar) findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + if (!CommonFunctions.isTablet(_context)) { + toolbar.setTitleTextAppearance(_context, R.style.changestext_sizefor_mobile); + } + + getSupportActionBar().setHomeButtonEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + + setTitle("ME Quiz List - " + username); + me_quiz_list = (RecyclerView) findViewById(R.id.me_quiz_list); + db = new Lorealba_Database(_context); + db.open(); + + listDataHeader = db.getMeQuiz(); + if (listDataHeader.size()>0){ + + me_quiz_list.setAdapter(new MEQuizListAdapter(_context,listDataHeader)); + me_quiz_list.setLayoutManager(new LinearLayoutManager(_context)); + } + } + + private class MEQuizListAdapter extends RecyclerView.Adapter { + Context context; + ArrayList listDataHeader; + + public MEQuizListAdapter(Context context, ArrayList listDataHeader) { + this.context = context; + this.listDataHeader = listDataHeader; + } + + @NonNull + @Override + public MEQuizListAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) { + View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.content_ba_survey_list_view, parent, false); + return new ViewHolder(view); + } + + @Override + public void onBindViewHolder(@NonNull MEQuizListAdapter.ViewHolder holder, final int pos) { + final MEMEAuditQuestion object = listDataHeader.get(pos); + + holder.quiz_name.setText(object.getQuizName().trim() + " ID - " + object.getQuizId().toString()); + holder.quiz_name.setId(pos); + db.open(); + if (db.getme_quiz(username, date, counter_id, object.getQuizId().toString()).size() > 0) { + holder.complete_icon.setVisibility(View.VISIBLE); + holder.complete_icon.setId(pos); + db.open(); + } else if (db.getMeQuizUploadStatus(object.getQuizId().toString(), username,counter_id)) { + holder.complete_icon.setVisibility(View.VISIBLE); + holder.complete_icon.setId(pos); + } else { + holder.complete_icon.setVisibility(View.GONE); + holder.complete_icon.setId(pos); + } + + holder.cardView.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + db.open(); + if (db.getme_quiz(username, date, counter_id, object.getQuizId().toString()).size() > 0) { + AlertandMessages.showToastMsg(context, "ME Quiz Already Done"); + db.open(); + } else if (db.getMeQuizUploadStatus(object.getQuizId().toString(), username,counter_id)) { + AlertandMessages.showToastMsg(context, "ME Quiz Already Done"); + } else { + startActivity(new Intent(context, MEQuizActivity.class).putExtra(CommonString.TAG_OBJECT, object)); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + MeQuizListActivity.this.finish(); + } + } + }); + + } + + @Override + public int getItemCount() { + return listDataHeader.size(); + } + + public class ViewHolder extends RecyclerView.ViewHolder { + TextView quiz_name; + CardView cardView; + ImageView complete_icon; + + public ViewHolder(@NonNull View itemView) { + super(itemView); + quiz_name = (TextView) itemView.findViewById(R.id.survey_name); + cardView = (CardView) itemView.findViewById(R.id.survey_view); + complete_icon = (ImageView) itemView.findViewById(R.id.complete_img); + } + } + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // Handle action bar item clicks here. The action bar will + // automatically handle clicks on the Home/Up button, so long + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + if (id == android.R.id.home) { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + MeQuizListActivity.this.finish(); + } + + return super.onOptionsItemSelected(item); + } + + @Override + public void onBackPressed() { + super.onBackPressed(); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + MeQuizListActivity.this.finish(); + + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/NotificationAdapter.java b/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/NotificationAdapter.java new file mode 100644 index 0000000..33c21b1 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/NotificationAdapter.java @@ -0,0 +1,53 @@ +package com.cpm.lorealbaautomation.dailyactivity; + +import androidx.annotation.NonNull; +import androidx.recyclerview.widget.RecyclerView; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.TextView; + +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.gsonGetterSetter.NotificationData; + +import java.util.ArrayList; + + +public class NotificationAdapter extends RecyclerView.Adapter { + + ArrayList notificationList = new ArrayList<>(); + + public NotificationAdapter(ArrayList notificationList) { + this.notificationList = notificationList; + } + + @NonNull + @Override + public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) { + View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.notification_list, parent, false); + return new ViewHolder(view); + } + + @Override + public void onBindViewHolder(@NonNull ViewHolder viewHolder, int position) { + + viewHolder.title_txt.setText(notificationList.get(position).getTitle()); + viewHolder.body_txt.setText(notificationList.get(position).getBody()); + viewHolder.path_txt.setText(notificationList.get(position).getPath()); + } + + @Override + public int getItemCount() { + return notificationList.size(); + } + + public class ViewHolder extends RecyclerView.ViewHolder { + TextView title_txt,path_txt,body_txt; + public ViewHolder(@NonNull View itemView) { + super(itemView); + title_txt = (TextView)itemView.findViewById(R.id.title_txt); + body_txt = (TextView)itemView.findViewById(R.id.body_txt); + + } + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/NotificationDetailActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/NotificationDetailActivity.java new file mode 100644 index 0000000..643bf49 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/NotificationDetailActivity.java @@ -0,0 +1,121 @@ +package com.cpm.lorealbaautomation.dailyactivity; + +import android.app.Activity; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.os.Bundle; + +import com.google.android.material.floatingactionbutton.FloatingActionButton; +import androidx.appcompat.app.AppCompatActivity; +import androidx.cardview.widget.CardView; +import androidx.appcompat.widget.Toolbar; +import android.view.View; +import android.widget.ImageView; +import android.widget.TextView; +import android.widget.VideoView; + +import com.bumptech.glide.Glide; +import com.bumptech.glide.load.engine.DiskCacheStrategy; +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.constant.CommonFunctions; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.delegates.PrefHelper; + +public class NotificationDetailActivity extends AppCompatActivity { + String visit_date, username, counter_id, userType, title, body, path, type, keyId; + private SharedPreferences preferences = null; + private SharedPreferences.Editor editor = null; + TextView tv_title_text, tv_message; + Lorealba_Database db; + VideoView videoView; + CardView card_text; + ImageView imgview; + Context context; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_notification_detail); + context = this; + preferences = PrefHelper.getPrefs(context); + counter_id = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + username = preferences.getString(CommonString.KEY_USERNAME, ""); + userType = preferences.getString(CommonString.KEY_USER_TYPE, ""); + Toolbar toolbar = findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + + if (!CommonFunctions.isTablet(this)) { + toolbar.setTitleTextAppearance(this, R.style.changestext_sizefor_mobile); + } + + setTitle("Details"); + db = new Lorealba_Database(this); + + type = getIntent().getStringExtra("type"); + title = getIntent().getStringExtra("Title"); + body = getIntent().getStringExtra("Body"); + path = getIntent().getStringExtra("Path"); + + keyId = getIntent().getStringExtra("KEY_ID"); + db.open(); + db.updateNotificationDetails("1", keyId); + db.open(); + db.insertnotification_users(username,visit_date, counter_id,keyId); + + tv_title_text = (TextView) findViewById(R.id.tv_title); + tv_message = (TextView) findViewById(R.id.tv_message); + card_text = (CardView) findViewById(R.id.parent_text_msg); + + + imgview = (ImageView) findViewById(R.id.img_notification); + videoView = (VideoView) findViewById(R.id.video_view); + tv_title_text.setText(title); + tv_message.setText(body); + + if (type != null && type.equalsIgnoreCase("Image")) { + imgview.setVisibility(View.VISIBLE); + + Glide.with(this).load(path) + .diskCacheStrategy(DiskCacheStrategy.NONE) + .skipMemoryCache(true) + .into(imgview); + + } else if (type != null && type.equalsIgnoreCase("Video")) { + videoView.setVisibility(View.VISIBLE); + videoView.setVideoPath(path); + videoView.start(); + } else { + if (path != null) { + imgview.setVisibility(View.VISIBLE); + + Glide.with(this) + .load(path) + .diskCacheStrategy(DiskCacheStrategy.NONE) + .skipMemoryCache(true) + .into(imgview); + } else { + imgview.setVisibility(View.GONE); + } + + } + + FloatingActionButton fab = findViewById(R.id.fab); + fab.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + Intent resultIntent = new Intent(); +// TODO Add extras or a data URI to this intent as appropriate. + resultIntent.putExtra("some_key", "String data"); + setResult(Activity.RESULT_OK, resultIntent); + finish(); + } + }); + } + + @Override + public void onBackPressed() { + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/NotificationsActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/NotificationsActivity.java new file mode 100644 index 0000000..5c9f950 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/NotificationsActivity.java @@ -0,0 +1,195 @@ +package com.cpm.lorealbaautomation.dailyactivity; + +import android.content.Context; +import android.content.Intent; +import android.os.Bundle; +import androidx.annotation.NonNull; +import androidx.appcompat.app.AppCompatActivity; +import androidx.cardview.widget.CardView; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; +import androidx.appcompat.widget.Toolbar; +import android.view.LayoutInflater; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; +import android.widget.ImageView; +import android.widget.TextView; + +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.constant.CommonFunctions; +import com.cpm.lorealbaautomation.gsonGetterSetter.NotificationData; +import com.cpm.lorealbaautomation.gsonGetterSetter.NotificationsGetterSetter; + +import java.util.ArrayList; + + +public class NotificationsActivity extends AppCompatActivity { + NotificationsGetterSetter object = null; + Context context; + Lorealba_Database db; + RecyclerView notification_view; + NotificationAdapter mAdapter; + ArrayList notificationList = new ArrayList<>(); + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_notifications); + context = this; + db = new Lorealba_Database(context); + db.open(); + + Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + + if (!CommonFunctions.isTablet(context)) { + toolbar.setTitleTextAppearance(context, R.style.changestext_sizefor_mobile); + } + + getSupportActionBar().setHomeButtonEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + setTitle("Notifications"); + notification_view = (RecyclerView) findViewById(R.id.notification_view); + } + + + @Override + protected void onResume() { + super.onResume(); + createNotificationView(); + } + + private void createNotificationView() { + db.open(); + notificationList = db.getNotificationList(); + if (notificationList.size() > 0) { + mAdapter = new NotificationAdapter(notificationList); + RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext()); + notification_view.setLayoutManager(mLayoutManager); + notification_view.setAdapter(mAdapter); + } + } + + public class NotificationAdapter extends RecyclerView.Adapter { + + ArrayList notificationList = new ArrayList<>(); + + public NotificationAdapter(ArrayList notificationList) { + this.notificationList = notificationList; + } + + @NonNull + @Override + public NotificationAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) { + View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.notification_list, parent, false); + return new ViewHolder(view); + } + + @Override + public void onBindViewHolder(@NonNull NotificationAdapter.ViewHolder viewHolder, final int position) { + + viewHolder.title_txt.setText(notificationList.get(position).getTitle()); + viewHolder.body_txt.setText(notificationList.get(position).getBody()); + viewHolder.title_date.setText(notificationList.get(position).getVisited_date()); + + if(notificationList.get(position).getRead_status().equalsIgnoreCase("0")){ + viewHolder.notificationView.setCardBackgroundColor(getResources().getColor(R.color.white)); + viewHolder.title_txt.setTextColor(getResources().getColor(R.color.blue)); + }else{ + viewHolder.notificationView.setCardBackgroundColor(getResources().getColor(R.color.gray)); + viewHolder.title_txt.setTextColor(getResources().getColor(R.color.black)); + } + + if (notificationList.get(position).getType() != null) { + viewHolder.icon_image.setVisibility(View.VISIBLE); + if (notificationList.get(position).getType().equalsIgnoreCase("image")){ + viewHolder.icon_image.setBackgroundResource(R.mipmap.image); + }else if(notificationList.get(position).getType().equalsIgnoreCase("video")) { + viewHolder.icon_image.setBackgroundResource(R.mipmap.video); + } else{ + viewHolder.icon_image.setBackgroundResource(R.mipmap.text); + } + }else { + viewHolder.icon_image.setBackgroundResource(R.mipmap.text); + } + + viewHolder.notificationView.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + db.open(); + //db.updateNotificationDetails("1",notificationList.get(position).getId()); + Intent in = new Intent(getApplicationContext(), NotificationDetailActivity.class); + in.putExtra("type", notificationList.get(position).getType()); + in.putExtra("Title", notificationList.get(position).getTitle()); + in.putExtra("Date", notificationList.get(position).getVisited_date()); + in.putExtra("Body", notificationList.get(position).getBody()); + in.putExtra("Path", notificationList.get(position).getPath()); + in.putExtra("KEY_ID", notificationList.get(position).getId()); + startActivity(in); + } + }); + } + + @Override + public int getItemCount() { + return notificationList.size(); + } + + public class ViewHolder extends RecyclerView.ViewHolder { + TextView title_txt, body_txt,title_date; + ImageView icon_image; + CardView notificationView; + + public ViewHolder(@NonNull View itemView) { + super(itemView); + title_txt = (TextView) itemView.findViewById(R.id.title_txt); + title_date = (TextView) itemView.findViewById(R.id.title_date); + icon_image =(ImageView)itemView.findViewById(R.id.icon_image); + body_txt = (TextView) itemView.findViewById(R.id.body_txt); + notificationView = (CardView) itemView.findViewById(R.id.card_notification_view); + + } + } + } + + + + @Override + public void onBackPressed() { + finish(); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + } + + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + int id = item.getItemId(); + + if (id == android.R.id.home) { + // NavUtils.navigateUpFromSameTask(this); + finish(); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + + /* AlertDialog.Builder builder = new AlertDialog.Builder(NotificationsActivity.this); + builder.setMessage(CommonString.ONBACK_ALERT_MESSAGE) + .setCancelable(false) + .setPositiveButton("OK", new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { + finish(); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + } + }) + .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { + dialog.cancel(); + } + }); + AlertDialog alert = builder.create(); + alert.show();*/ + } + return super.onOptionsItemSelected(item); + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/RetailExcellenceActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/RetailExcellenceActivity.java new file mode 100644 index 0000000..43318c6 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/RetailExcellenceActivity.java @@ -0,0 +1,385 @@ +package com.cpm.lorealbaautomation.dailyactivity; + +import android.annotation.SuppressLint; +import android.app.AlertDialog; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.os.Bundle; +import android.view.LayoutInflater; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; +import android.view.inputmethod.InputMethodManager; +import android.widget.AbsListView; +import android.widget.AdapterView; +import android.widget.ArrayAdapter; +import android.widget.BaseExpandableListAdapter; +import android.widget.ExpandableListView; +import android.widget.Spinner; +import android.widget.TextView; + +import androidx.appcompat.app.AppCompatActivity; +import androidx.appcompat.widget.Toolbar; +import androidx.cardview.widget.CardView; +import androidx.recyclerview.widget.RecyclerView; + +import com.google.android.material.floatingactionbutton.FloatingActionButton; +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.constant.AlertandMessages; +import com.cpm.lorealbaautomation.constant.CommonFunctions; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.download.Downloader; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterRetailExcellence; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Objects; + +public class RetailExcellenceActivity extends AppCompatActivity implements View.OnClickListener { + String error_msg = "", visit_date, username, counter_Id; + HashMap> listDataChild; + ArrayList masterRetailExcellenceArrayList; + List checkHeaderArray = new ArrayList<>(); + List checkGroupArray = new ArrayList<>(); + ArrayList listDataHeader; + String[] retailSpinner = {"Select", "Yes", "No"}; + boolean checkflag = true, Singletouch = false, update_flag = false; + SharedPreferences preferences; + ExpandableListView expandableListView; + ExpandableListAdapter adapter; + FloatingActionButton fab; + MasterRetailExcellence obj = null; + Lorealba_Database db; + Toolbar toolbar; + Context context; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_retail_excellence); + context = this; + db = new Lorealba_Database(context); + db.open(); + + toolbar = (Toolbar) findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + preferences = PrefHelper.getPrefs(context); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + username = preferences.getString(CommonString.KEY_USERNAME, ""); + counter_Id = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + + if (!CommonFunctions.isTablet(context)) { + toolbar.setTitleTextAppearance(context, R.style.changestext_sizefor_mobile); + } + setTitle("Retail Excellence" + " - " + username); + + expandableListView = (ExpandableListView) findViewById(R.id.list); + fab = (FloatingActionButton) findViewById(R.id.fab); + fab.setOnClickListener(this); + validate_ui_data(); + } + + private void validate_ui_data() { + db.open(); + listDataHeader = db.getRetailExcellenceData(); + masterRetailExcellenceArrayList = new ArrayList<>(); + listDataChild = new HashMap<>(); + for (int i = 0; i < listDataHeader.size(); i++) { + db.open(); + masterRetailExcellenceArrayList = db.getRetailExcellencedata(listDataHeader.get(i).getItemCatId().toString(), username, visit_date, counter_Id); + if (masterRetailExcellenceArrayList.size() == 0) { + db.open(); + masterRetailExcellenceArrayList = db.getRetailCategoryWiseDataNew(listDataHeader.get(i).getItemCatId()); + } else { + update_flag = true; + } + ArrayList list = new ArrayList<>(); + if (masterRetailExcellenceArrayList.size() > 0) { + // Adding child data + list.addAll(masterRetailExcellenceArrayList); + } + + listDataChild.put(listDataHeader.get(i), list); + } + adapter = new ExpandableListAdapter(context, listDataHeader, listDataChild); + expandableListView.setAdapter(adapter); + + for (int i = 0; i < adapter.getGroupCount(); i++) { + expandableListView.expandGroup(i); + } + + expandableListView.setOnScrollListener(new AbsListView.OnScrollListener() { + @Override + public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { + expandableListView.invalidate(); + } + + @Override + public void onScrollStateChanged(AbsListView arg0, int arg1) { + InputMethodManager inputManager = (InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE); + if (getCurrentFocus() != null) { + inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0); + getCurrentFocus().clearFocus(); + } + expandableListView.invalidateViews(); + } + }); + + } + + @Override + public void onClick(View v) { + if (v.getId() == R.id.fab) { + expandableListView.clearFocus(); + if (validateData(listDataHeader, listDataChild)) { + AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle(R.string.dialog_title).setMessage(R.string.title_activity_Want_save) + .setCancelable(false).setPositiveButton(R.string.yes, (dialog, id) -> { + db.open(); + db.insertRetailExcellence_data(counter_Id, visit_date, username, listDataHeader, listDataChild, obj, CommonFunctions.getUUID(context)); + //download service + Intent intent = new Intent(context, Downloader.class); + intent.putExtra(CommonString.KEY_RETAIL_EXCELLENCE, listDataHeader); + Downloader.enqueueWork(context, intent); + AlertandMessages.showToastMsg(context, "Data Uploaded Successfully"); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + RetailExcellenceActivity.this.finish(); + dialog.dismiss(); + }).setNegativeButton(R.string.no, (dialog, id) -> dialog.cancel()); + AlertDialog alert = builder.create(); + alert.show(); + } else { + AlertandMessages.showToastMsg(context, error_msg); + } + } + + } + + private boolean validateData(ArrayList listDataHeader, HashMap> listDataChild) { + checkHeaderArray.clear(); + checkGroupArray.clear(); + checkflag = true; + for (int j = 0; j < listDataHeader.size(); j++) { + ArrayList data = listDataChild.get(listDataHeader.get(j)); + for (int i = 0; i < Objects.requireNonNull(data).size(); i++) { + if (data.get(i).getAnswer().equalsIgnoreCase("Select") || data.get(i).getAnswer().equals("")) { + error_msg = "Please Select Yes or No"; + checkflag = false; + break; + } + } + + } + return checkflag; + } + + public class ExpandableListAdapter extends BaseExpandableListAdapter { + Context _context; + ArrayList listDataHeader; // header titles + HashMap> listDataChild; + + public ExpandableListAdapter(Context context, ArrayList listDataHeader, HashMap> listDataChild) { + this._context = context; + this.listDataHeader = listDataHeader; + this.listDataChild = listDataChild; + } + + @Override + public Object getChild(int groupPosition, int childPosititon) { + return this.listDataChild.get(this.listDataHeader.get(groupPosition)).get(childPosititon); + } + + @Override + public long getChildId(int groupPosition, int childPosition) { + return childPosition; + } + + @SuppressLint({"NewApi", "ClickableViewAccessibility"}) + @Override + public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { + final MasterRetailExcellence checkList = (MasterRetailExcellence) getChild(groupPosition, childPosition); + ExpandableListAdapter.ViewHolder holder = null; + if (convertView == null) { + LayoutInflater infalInflater = (LayoutInflater) this._context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); + convertView = infalInflater.inflate(R.layout.retail_excellence_child_item, null); + holder = new ViewHolder(convertView); + convertView.setTag(holder); + } else { + holder = (ExpandableListAdapter.ViewHolder) convertView.getTag(); + } + + holder.data = checkList; + holder.txt_question.setText(holder.data.getItemName()); + holder.txt_question.setId(childPosition); + ArrayAdapter adapter = new ArrayAdapter(context, + R.layout.spinner_text_view, R.id.txt_sp_text, retailSpinner); + holder.sp_auditAnswer.setAdapter(adapter); + + holder.sp_auditAnswer.setOnTouchListener((view, motionEvent) -> { + Singletouch = true; + return false; + }); + + final ExpandableListAdapter.ViewHolder finalHolder = holder; + holder.sp_auditAnswer.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { + @Override + public void onItemSelected(AdapterView parent, View view, int position, long id) { + if (position != 0) { + finalHolder.data.setAnswer(retailSpinner[position]); + } else { + finalHolder.data.setAnswer(""); + } + } + + @Override + public void onNothingSelected(AdapterView parent) { + + } + }); + + for (int i = 0; i < retailSpinner.length; i++) { + if (holder.data.getAnswer().equalsIgnoreCase(retailSpinner[i])) { + holder.sp_auditAnswer.setSelection(i); + } + } + + if (!checkflag) { + if (checkGroupArray.contains(groupPosition) && checkHeaderArray.contains(childPosition)) { + holder.card_view.setBackgroundColor(getResources().getColor(R.color.red)); + holder.card_view.setId(childPosition); + } else { + holder.card_view.setBackgroundColor(getResources().getColor(R.color.white)); + holder.card_view.setId(childPosition); + } + } else { + holder.card_view.setBackgroundColor(getResources().getColor(R.color.white)); + holder.card_view.setId(childPosition); + } + + return convertView; + } + + @Override + public int getChildrenCount(int groupPosition) { + return this.listDataChild.get(this.listDataHeader.get(groupPosition)).size(); + } + + @Override + public Object getGroup(int groupPosition) { + return this.listDataHeader.get(groupPosition); + } + + @Override + public int getGroupCount() { + return this.listDataHeader.size(); + } + + @Override + public long getGroupId(int groupPosition) { + return groupPosition; + } + + @Override + public View getGroupView(final int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { + if (convertView == null) { + LayoutInflater infalInflater = (LayoutInflater) this._context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); + convertView = infalInflater.inflate(R.layout.item_header_retail_excellence, parent, false); + } + + final MasterRetailExcellence headerTitle = (MasterRetailExcellence) getGroup(groupPosition); + TextView lblListHeader = (TextView) convertView.findViewById(R.id.txt_header); + CardView cardView = (CardView) convertView.findViewById(R.id.cardview_exists); + lblListHeader.setText(headerTitle.getItemCatName()); + + cardView.setOnClickListener(v -> { + if (expandableListView.isGroupExpanded(groupPosition)) { + expandableListView.collapseGroup(groupPosition); + } else { + expandableListView.expandGroup(groupPosition); + } + }); + + if (!checkflag) { + if (checkGroupArray.contains(groupPosition)) { + cardView.setBackgroundColor(getResources().getColor(R.color.red)); + } else { + cardView.setBackgroundColor(getResources().getColor(R.color.bright_red)); + } + } else { + cardView.setBackgroundColor(getResources().getColor(R.color.bright_red)); + } + + return convertView; + } + + @Override + public boolean hasStableIds() { + return false; + } + + @Override + public boolean isChildSelectable(int groupPosition, int childPosition) { + return true; + } + + public class ViewHolder extends RecyclerView.ViewHolder { + public final View mView; + public final TextView txt_question; + public final Spinner sp_auditAnswer; + CardView card_view; + MasterRetailExcellence data; + + public ViewHolder(View view) { + super(view); + mView = view; + txt_question = (TextView) view.findViewById(R.id.txt_question); + sp_auditAnswer = (Spinner) view.findViewById(R.id.sp_auditAnswer); + card_view = (CardView) view.findViewById(R.id.card_view); + } + } + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // Handle action bar item clicks here. The action bar will + // automatically handle clicks on the Home/Up button, so long + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + if (id == android.R.id.home) { + if (checkflag) { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + RetailExcellenceActivity.this.finish(); + } else { + AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle(R.string.parinaam).setMessage(getResources().getString(R.string.data_will_be_lost)).setCancelable(false) + .setPositiveButton(getString(R.string.ok), (dialog, id1) -> { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + RetailExcellenceActivity.this.finish(); + }).setNegativeButton(getString(R.string.cancel), (dialog, which) -> dialog.dismiss()); + AlertDialog alert = builder.create(); + alert.show(); + } + } + return super.onOptionsItemSelected(item); + } + + @Override + public void onBackPressed() { + if (checkflag) { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + RetailExcellenceActivity.this.finish(); + } else { + AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle(R.string.parinaam).setMessage(getResources().getString(R.string.data_will_be_lost)).setCancelable(false) + .setPositiveButton(getString(R.string.ok), (dialog, id) -> { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + RetailExcellenceActivity.this.finish(); + }).setNegativeButton(getString(R.string.cancel), (dialog, which) -> dialog.dismiss()); + AlertDialog alert = builder.create(); + alert.show(); + } + } +} \ No newline at end of file diff --git a/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/SampleStockActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/SampleStockActivity.java new file mode 100644 index 0000000..8b102d7 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/SampleStockActivity.java @@ -0,0 +1,1917 @@ +package com.cpm.lorealbaautomation.dailyactivity; + +import android.app.Activity; +import android.app.AlertDialog; +import android.app.Dialog; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.SharedPreferences; +import android.graphics.drawable.ColorDrawable; +import android.os.AsyncTask; +import android.os.Build; +import android.os.Bundle; + +import androidx.annotation.NonNull; +import androidx.annotation.RequiresApi; + +import com.google.android.material.bottomsheet.BottomSheetDialog; +import com.google.android.material.floatingactionbutton.FloatingActionButton; + +import androidx.appcompat.app.AppCompatActivity; +import androidx.cardview.widget.CardView; +import androidx.recyclerview.widget.GridLayoutManager; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; +import androidx.appcompat.widget.Toolbar; + +import android.text.Editable; +import android.text.TextWatcher; +import android.util.Log; +import android.view.Gravity; +import android.view.LayoutInflater; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; +import android.view.Window; +import android.view.WindowManager; +import android.view.inputmethod.InputMethodManager; +import android.widget.AbsListView; +import android.widget.AdapterView; +import android.widget.ArrayAdapter; +import android.widget.BaseExpandableListAdapter; +import android.widget.Button; +import android.widget.EditText; +import android.widget.ExpandableListView; +import android.widget.ImageView; +import android.widget.LinearLayout; +import android.widget.ProgressBar; +import android.widget.Spinner; +import android.widget.TextView; + +import com.google.gson.JsonObject; +import com.google.zxing.integration.android.IntentIntegrator; +import com.google.zxing.integration.android.IntentResult; +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.constant.AlertandMessages; +import com.cpm.lorealbaautomation.constant.CommonFunctions; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.gettersetter.SaleableGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.JourneyPlan; +import com.cpm.lorealbaautomation.gsonGetterSetter.ProductMaster; +import com.cpm.lorealbaautomation.retrofit.PostApi; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.File; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.TimeUnit; + +import okhttp3.MediaType; +import okhttp3.OkHttpClient; +import okhttp3.RequestBody; +import retrofit2.Call; +import retrofit2.Callback; +import retrofit2.Response; +import retrofit2.Retrofit; +import retrofit2.converter.gson.GsonConverterFactory; + +import static com.cpm.lorealbaautomation.constant.CommonFunctions.getCurrentTime; +import static com.cpm.lorealbaautomation.constant.CommonFunctions.removeFirstChar; +import static com.cpm.lorealbaautomation.dailyactivity.StoreImageActivity.convertBitmap; + +public class SampleStockActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemSelectedListener { + ArrayAdapter axe_name_adapter, sub_axe_name_adapter, brand_name_adapter, product_name_adapter; + Spinner sku_spin, brand_spin, sub_axe_spin, axe_spin; + ArrayList brandList = new ArrayList<>(); + ArrayList subAxeList = new ArrayList<>(); + ArrayList axeList = new ArrayList<>(); + + ExpandableListView lvExp_stock_check; + FloatingActionButton fab_save, fab_draft; + Lorealba_Database db; + Context context; + AlertDialog alert; + private SharedPreferences preferences; + String counter_id, visit_date, username, _pathforcheck, _path; + ArrayList listDataHeader = new ArrayList<>(); + ArrayList childStockList = new ArrayList<>(); + HashMap> listDataChild; + boolean checkflag = true; + ArrayList checkHeaderArray = new ArrayList<>(); + ExpandableListAdapter listAdapter; + String brandName = ""; + String axeName = ""; + String subAxeName = ""; + + int groupPositionGlobal = -1; + ProductMaster globalHeaderObject = new ProductMaster(); + + EditText et_search; + + //filter bottom sheet + ArrayList subBrandList = new ArrayList<>(); + ArrayList referenceList = new ArrayList<>(); + ArrayList signatureList = new ArrayList<>(); + ImageView img_filter; + View sheetView; + ProductMaster selectedSignature, selectedBrand, selectedSubBrand, selectedReference; + final int FILTER_FOR_SIGNATURE = 4; + final int FILTER_FOR_SUB_BRAND = 5; + final int FILTER_FOR_REFERENCE = 6; + final int FILTER_FOR_BRAND = 1; + final int CLEAR_FILTER = 0; + + boolean regularStockFlag = false, check_flag = true; + + ImageView img_scan; + + boolean flagScan = true; + private String counterGroupId; + + RecyclerView recSubAxe; + + String selectedSubAxe = ""; + SubAxeValueAdapter subAxeValueAdapter; + ArrayList listSubAxe; + ImageView img_clear_subaxe; + JourneyPlan jcp; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_sample_stock); + context = this; + ((SampleStockActivity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); + db = new Lorealba_Database(context); + db.open(); + + validateUIData(); + + String couter_code = preferences.getString(CommonString.KEY_COUNTER_CODE, ""); + TextView txt_counter_code = (TextView) findViewById(R.id.txt_counter_code); + txt_counter_code.setText("Counter Code - " + couter_code + " / Id - " + counter_id); + + new LoadAsync().execute(); + lvExp_stock_check.setOnScrollListener(new AbsListView.OnScrollListener() { + @Override + public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { + lvExp_stock_check.invalidate(); + + int lastItem = firstVisibleItem + visibleItemCount; + if (firstVisibleItem == 0) { + fab_save.show();//.setVisibility(View.VISIBLE); + } else if (lastItem == totalItemCount) { + fab_save.hide();//setVisibility(View.INVISIBLE); + } else { + fab_save.show();//setVisibility(View.VISIBLE); + } + } + + @Override + public void onScrollStateChanged(AbsListView arg0, int arg1) { + InputMethodManager inputManager = (InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE); + if (getCurrentFocus() != null) { + inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0); + getCurrentFocus().clearFocus(); + } + + lvExp_stock_check.invalidateViews(); + } + }); + + } + + private void validateUIData() { + preferences = PrefHelper.getPrefs(context); + counter_id = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + username = preferences.getString(CommonString.KEY_USERNAME, ""); + + Toolbar toolbar = findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + if (!CommonFunctions.isTablet(context)) { + toolbar.setTitleTextAppearance(context, R.style.changestext_sizefor_mobile); + } + + getSupportActionBar().setHomeButtonEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + setTitle("Sample Stock - " + visit_date); + sku_spin = (Spinner) findViewById(R.id.sku_spin); + brand_spin = (Spinner) findViewById(R.id.stock_brand_spin); + sub_axe_spin = (Spinner) findViewById(R.id.sub_axe_spin); + axe_spin = (Spinner) findViewById(R.id.axe_spin); + lvExp_stock_check = (ExpandableListView) findViewById(R.id.lvExp_stock_check); + fab_save = (FloatingActionButton) findViewById(R.id.save_fab); + fab_draft = (FloatingActionButton) findViewById(R.id.draft_fab); + et_search = (EditText) findViewById(R.id.et_search); + img_scan = (ImageView) findViewById(R.id.img_scan); + recSubAxe = (RecyclerView) findViewById(R.id.rec_subaxe); + img_clear_subaxe = (ImageView) findViewById(R.id.img_clear_subaxe); + fab_save.setOnClickListener(this); + fab_draft.setOnClickListener(this); + img_scan.setOnClickListener(this); + img_clear_subaxe.setOnClickListener(this); + db.open(); + + et_search.addTextChangedListener(new TextWatcher() { + @Override + public void beforeTextChanged(CharSequence s, int start, int count, int after) { + + } + + @Override + public void onTextChanged(CharSequence s, int start, int before, int count) { + + String text = s.toString(); + if (text.equals("")) { + lvExp_stock_check.setAdapter(listAdapter); + listAdapter.notifyDataSetChanged(); + } else { + lvExp_stock_check.invalidate(); + setSearchFilter(listAdapter.get_listDataHeader(), text, listAdapter.get_listDataChild()); + } + } + + @Override + public void afterTextChanged(Editable s) { + + String text = s.toString(); + + } + }); + + ImageView img_unfilled = (ImageView) findViewById(R.id.img_unfilled); + img_unfilled.setVisibility(View.INVISIBLE); + db.open(); + String status = db.getStatus(CommonString.KEY_SampleStatus, counter_id); + + //if regular stock need to be captured after First stock capture + if (status != null && !status.equals("") && status.equalsIgnoreCase("Complete")) { + regularStockFlag = true; + fab_draft.hide(); + } + } + + private void prepareListData() { + db.open(); + jcp = db.getJCP(); + if (jcp != null) { + db.open(); + listSubAxe = db.getSubAxe(jcp.getCounterGroupId().toString(), true); + } else { + listSubAxe = db.getSubAxe("1", true); + } + + //for filter bottom sheet + JourneyPlan jcp = db.getJCP(); + if (jcp != null) { + db.open(); + brandList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "BrandName", false, selectedSubAxe); + db.open(); + subBrandList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "SubBrandName", false, selectedSubAxe); + db.open(); + referenceList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "ReferenceName", false, selectedSubAxe); + db.open(); + signatureList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "SignatureName", false, selectedSubAxe); + } else { + db.open(); + brandList = db.getsub_brand_name("1", "BrandName", false, selectedSubAxe); + subBrandList = db.getsub_brand_name("1", "SubBrandName", false, selectedSubAxe); + referenceList = db.getsub_brand_name("1", "ReferenceName", false, selectedSubAxe); + signatureList = db.getsub_brand_name("1", "SignatureName", false, selectedSubAxe); + } + + img_filter = (ImageView) findViewById(R.id.img_filter); + img_filter.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + sheetView = showFilterBottomSheet(); + } + }); + + + listDataHeader = new ArrayList<>(); + listDataChild = new HashMap<>(); + //inserted data + db.open(); + listDataHeader = db.getSampleHeaderInsertedData(visit_date, counter_id, regularStockFlag); + if (listDataHeader.size() == 0) { + jcp = db.getJCP(); + if (jcp != null) { + db.open(); + listDataHeader = db.getFunctionName(jcp.getCounterGroupId().toString(), selectedSubAxe, regularStockFlag, "SampleBalance", counter_id, visit_date); + } else { + db.open(); + listDataHeader = db.getStockSignatureBrandSubBrandReference("1", false, regularStockFlag, "SampleBalance"); + } + } + + if (listDataHeader.size() > 0) { + for (int i = 0; i < listDataHeader.size(); i++) { + db.open(); + jcp = db.getJCP(); + if (jcp != null) { + db.open(); + childStockList = db.getDefaultStockOnFunctionData(listDataHeader.get(i).getNuanceName(), CommonString.KEY_SampleBalance, counter_id, regularStockFlag, visit_date); + } else { + db.open(); + childStockList = db.getDefaultStockOnFunctionData(listDataHeader.get(i).getNuanceName(), CommonString.KEY_SampleBalance, counter_id, regularStockFlag, visit_date); + } + + listDataChild.put(listDataHeader.get(i), childStockList); // Header, Child data + } + + } + } + + + @Override + public void onClick(View v) { + if (v.getId() == R.id.save_fab) { + lvExp_stock_check.clearFocus(); + lvExp_stock_check.invalidateViews(); + if (regularStockFlag) { + dialogFinalSubmit(listDataChild, listDataHeader); + } else { + dialogFinalSubmit(listDataChild, listDataHeader); + } + + } else if (v.getId() == R.id.draft_fab) { + lvExp_stock_check.clearFocus(); + lvExp_stock_check.invalidateViews(); + new InsertAsync().execute(false); + } else if (v.getId() == R.id.card_signature) { + RecyclerView recSignature = sheetView.findViewById(R.id.rec_brand); + recSignature.setAdapter(new ValueAdapter(context, signatureList, CommonString.Signature)); + recSignature.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, true)); + setFilterSelected(sheetView, CommonString.Signature); + } else if (v.getId() == R.id.card_brand) { + RecyclerView recBrand = sheetView.findViewById(R.id.rec_brand); + recBrand.setAdapter(new ValueAdapter(context, brandList, CommonString.Brand)); + recBrand.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, true)); + setFilterSelected(sheetView, CommonString.Brand); + } else if (v.getId() == R.id.card_sub_brand) { + RecyclerView recSubBrand = sheetView.findViewById(R.id.rec_brand); + recSubBrand.setAdapter(new ValueAdapter(context, subBrandList, CommonString.SubBrand)); + recSubBrand.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, true)); + recSubBrand.getAdapter().notifyDataSetChanged(); + setFilterSelected(sheetView, CommonString.SubBrand); + } else if (v.getId() == R.id.card_reference) { + RecyclerView recReference = sheetView.findViewById(R.id.rec_brand); + recReference.setAdapter(new ValueAdapter(context, referenceList, CommonString.Reference)); + recReference.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, true)); + setFilterSelected(sheetView, CommonString.Reference); + } else if (v.getId() == R.id.img_scan) { + if (flagScan) { + openScanner(); + } else { + img_scan.setImageDrawable(getResources().getDrawable(R.mipmap.barcode_icon)); + flagScan = true; + et_search.setText(""); + } + + } else if (v.getId() == R.id.img_clear_subaxe) { + et_search.setText(""); + listAdapter = new ExpandableListAdapter(context, listDataHeader, listDataChild); + lvExp_stock_check.setAdapter(listAdapter); + listAdapter.notifyDataSetChanged(); + //setExpandableDataForSubAxe(current.getSubAxeName()); + + selectedSubAxe = ""; + subAxeValueAdapter.notifyDataSetChanged(); + + //clear filters also + selectedSignature = null; + selectedBrand = null; + selectedSubBrand = null; + selectedReference = null; + db.open(); + brandList = db.getsub_brand_name(counterGroupId, "BrandName", false, selectedSubAxe); + db.open(); + subBrandList = db.getsub_brand_name(counterGroupId, "SubBrandName", false, selectedSubAxe); + db.open(); + referenceList = db.getsub_brand_name(counterGroupId, "ReferenceName", false, selectedSubAxe); + db.open(); + signatureList = db.getsub_brand_name(counterGroupId, "SignatureName", false, selectedSubAxe); + + } + } + + @Override + public void onItemSelected(AdapterView adapterView, View view, int position, long l) { + + if (adapterView.getId() == R.id.stock_brand_spin) { + if (position != 0) { + brandName = adapterView.getSelectedItem().toString(); + setFilter(FILTER_FOR_BRAND); + axeList = db.getAxeNSubAxe("1", "AxeName", brandName, null); + subAxeList = db.getAxeNSubAxe("1", "SubAxeName", brandName, null); + setAxeSpinnerData(axeList); + setSubAxeSpinnerData(subAxeList); + + } else { + brandName = ""; + setFilter(CLEAR_FILTER); + axeList = db.getAxeNSubAxe("1", "AxeName", null, null); + subAxeList = db.getAxeNSubAxe("1", "SubAxeName", null, null); + setAxeSpinnerData(axeList); + setSubAxeSpinnerData(subAxeList); + } + + } else if (adapterView.getId() == R.id.axe_spin) { + + if (position != 0) { + axeName = adapterView.getSelectedItem().toString(); + setFilter(FILTER_FOR_AXE); + subAxeList = db.getAxeNSubAxe("1", "SubAxeName", "", axeName); + setSubAxeSpinnerData(subAxeList); + } else { + axeName = ""; + if (brand_spin.getSelectedItemPosition() == 0) { + subAxeList = db.getAxeNSubAxe("1", "SubAxeName", null, null); + setSubAxeSpinnerData(subAxeList); + setFilter(CLEAR_FILTER); + } else { + subAxeList = db.getAxeNSubAxe("1", "SubAxeName", brandName, null); + setSubAxeSpinnerData(subAxeList); + setFilter(FILTER_FOR_BRAND); + } + } + + } else if (adapterView.getId() == R.id.sub_axe_spin) { + + if (position != 0) { + subAxeName = adapterView.getSelectedItem().toString(); + setFilter(FILTER_FOR_SUBAXE); + } else { + subAxeName = ""; + if (axe_spin.getSelectedItemPosition() == 0) { + if (brand_spin.getSelectedItemPosition() == 0) { + setFilter(CLEAR_FILTER); + } else { + setFilter(FILTER_FOR_BRAND); + } + } else { + setFilter(FILTER_FOR_AXE); + } + } + + } + + } + + @Override + public void onNothingSelected(AdapterView adapterView) { + + } + + public ArrayList filterListForBrand(List originalList, String text) { + ArrayList filterList = new ArrayList<>(); + for (ProductMaster object : originalList) { + if (object.getBrandName().equalsIgnoreCase(text)) { + filterList.add(object); + } else { + continue; + } + } + return filterList; + } + + + public void setSearchFilter(List originalList, String text, HashMap> listDataChild) { + + HashMap> filterChildHashMap = new HashMap<>(); + + ArrayList filterList = new ArrayList<>(); + for (int i = 0; i < originalList.size(); i++) { + ProductMaster parent = originalList.get(i); + List listChild = listDataChild.get(parent); + List listFilterChild = new ArrayList<>(); + for (int j = 0; j < listChild.size(); j++) { + if (listChild.get(j).getProductName().toLowerCase().contains(text.toLowerCase()) || (listChild.get(j).getEanCode() != null && listChild.get(j).getEanCode().contains(text))) { + listFilterChild.add(listChild.get(j)); + } else { + continue; + } + } + + if (listFilterChild.size() > 0) { + filterList.add(parent); + filterChildHashMap.put(parent, listFilterChild); + + } + + } + + ExpandableListAdapter listAdapter = new ExpandableListAdapter(context, filterList, filterChildHashMap); + lvExp_stock_check.setAdapter(listAdapter); + listAdapter.notifyDataSetChanged(); + for (int i = 0; i < listAdapter.getGroupCount(); i++) { + lvExp_stock_check.expandGroup(i); + } + /* if(filterList.size()>0){ + ExpandableListAdapter listAdapter = new ExpandableListAdapter(context, filterList, filterChildHashMap); + lvExp_stock_check.setAdapter(listAdapter); + listAdapter.notifyDataSetChanged(); + }*/ + + + } + + public class ExpandableListAdapter extends BaseExpandableListAdapter { + private Context _context; + private List _listDataHeader; + private HashMap> _listDataChild; + + public ExpandableListAdapter(Context context, List listDataHeader, HashMap> listChildData) { + this._context = context; + this._listDataHeader = listDataHeader; + this._listDataChild = listChildData; + } + + @Override + public Object getChild(int groupPosition, int childPosititon) { + return this._listDataChild.get(this._listDataHeader.get(groupPosition)).get(childPosititon); + } + + @Override + public long getChildId(int groupPosition, int childPosition) { + return childPosition; + } + + public HashMap> get_listDataChild() { + return _listDataChild; + } + + public List get_listDataHeader() { + return _listDataHeader; + } + + @Override + public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { + + final ProductMaster childText = (ProductMaster) getChild(groupPosition, childPosition); + ViewHolder holder = null; + if (convertView == null) { + LayoutInflater infalInflater = (LayoutInflater) this._context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); + convertView = infalInflater.inflate(R.layout.item_stock_layout, null); + holder = new ViewHolder(); + holder.cardView = convertView.findViewById(R.id.card_view); + holder.ed_Stock = convertView.findViewById(R.id.ed_Stock); + holder.mrp = convertView.findViewById(R.id.mrp); + holder.stock_img_plus = convertView.findViewById(R.id.stock_img_plus); + holder.stock_img_minus = convertView.findViewById(R.id.stock_img_minus); + holder.et_stock = convertView.findViewById(R.id.et_stock); + convertView.setTag(holder); + + + } else { + + holder = (ViewHolder) convertView.getTag(); + } + + TextView txtListChild = convertView.findViewById(R.id.lblListItem); + txtListChild.setText(childText.getProductName() + " (MRP - ₹ " + childText.getMrp() + ")"); + + final ViewHolder finalHolder = holder; + holder.stock_img_plus.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + ((ExpandableListAdapter) lvExp_stock_check.getExpandableListAdapter()).notifyDataSetChanged(); + if (!regularStockFlag) { + String stot = finalHolder.et_stock.getText().toString().trim().replaceFirst("^0+(?!$)", ""); + if (!stot.equals("")) { + int st = Integer.parseInt(stot); + childText.setStock(st); + } + } + + int stock = childText.getStock(); + int receivedStock = childText.getStock_receive(); + ++stock; + + if (regularStockFlag) { + if (receivedStock >= stock) { + childText.setStock(stock); + isDataAdded = true; + childText.setSelected(true); + + } else { + AlertandMessages.showToastMsg(context, "Stock cannot be greater than Received Stock"); + } + } else { + childText.setStock(stock); + isDataAdded = true; + childText.setSelected(true); + } + } + }); + + holder.stock_img_minus.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + ((ExpandableListAdapter) lvExp_stock_check.getExpandableListAdapter()).notifyDataSetChanged(); + if (!regularStockFlag) { + String stot = finalHolder.et_stock.getText().toString().trim().replaceFirst("^0+(?!$)", ""); + if (!stot.equals("")) { + int st = Integer.parseInt(stot); + childText.setStock(st); + } + } + + int minteger = childText.getStock(); + --minteger; + + if (minteger >= 0) { + childText.setStock(minteger); + isDataAdded = true; + childText.setSelected(true); + } else { + AlertandMessages.showToastMsg(context, "Stock cannot be less than 0"); + } + + } + }); + + holder.et_stock.setOnFocusChangeListener(new View.OnFocusChangeListener() { + @Override + public void onFocusChange(View v, boolean hasFocus) { + // if (!hasFocus) { + final EditText caption = (EditText) v; + String stock = caption.getText().toString().replaceFirst("^0+(?!$)", ""); + if (!stock.equals("")) { + childText.setStock(Integer.parseInt(stock)); + isDataAdded = true; + childText.setSelected(true); + } else { + childText.setStock(0); + } + + // } + + } + }); + + int stock = childText.getStock(); + if (!childText.isSelected() && childText.getStock() == 0) { + stock = childText.getStock_receive(); + childText.setStock(stock); + } + + if (regularStockFlag) { + holder.ed_Stock.setText(stock + ""); + holder.ed_Stock.setId(childPosition); + + holder.et_stock.setVisibility(View.GONE); + holder.ed_Stock.setVisibility(View.VISIBLE); + } else { + + if (stock == -1) { + holder.et_stock.setText(""); + } else { + holder.et_stock.setText(stock + ""); + } + + holder.et_stock.setId(childPosition); + + holder.ed_Stock.setVisibility(View.GONE); + holder.et_stock.setVisibility(View.VISIBLE); + } + + holder.mrp.setText(" MRP = " + childText.getMrp() + ""); + holder.mrp.setId(childPosition); + + return convertView; + } + + @Override + public int getChildrenCount(int groupPosition) { + return this._listDataChild.get(this._listDataHeader.get(groupPosition)).size(); + } + + @Override + public Object getGroup(int groupPosition) { + return this._listDataHeader.get(groupPosition); + } + + @Override + public int getGroupCount() { + return this._listDataHeader.size(); + } + + @Override + public long getGroupId(int groupPosition) { + return groupPosition; + } + + @Override + public View getGroupView(final int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { + final ProductMaster headerTitle = (ProductMaster) getGroup(groupPosition); + if (convertView == null) { + + LayoutInflater infalInflater = (LayoutInflater) this._context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); + convertView = infalInflater.inflate(R.layout.list_group_stock_entry, null); + } + TextView lblListHeader = (TextView) convertView.findViewById(R.id.lblListHeader); + ImageView stock_cam = (ImageView) convertView.findViewById(R.id.stock_cam); + + stock_cam.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + groupPositionGlobal = groupPosition; + globalHeaderObject = headerTitle; + _pathforcheck = counter_id + "_Sample_stock_img" + visit_date.replace("/", "") + "_" + getCurrentTime().replace(":", "") + ".jpg"; + _path = CommonString.getImagesFolder(context) + _pathforcheck; + CommonFunctions.startAnncaCameraActivity(SampleStockActivity.this, _path, null, false, CommonString.CAMERA_FACE_REAR); + } + }); + + if (headerTitle.getImagePath().equals("")) { + stock_cam.setImageDrawable(getResources().getDrawable(R.mipmap.camera)); + } else { + stock_cam.setImageDrawable(getResources().getDrawable(R.mipmap.camera_tick)); + } + + //lblListHeader.setText(headerTitle.getSubBrandName() + " - " + headerTitle.getReferenceName() + " - " + headerTitle.getBrandName()); + lblListHeader.setText(headerTitle.getNuanceName()); + if (!checkflag) { + if (checkHeaderArray.contains(groupPosition)) { + lblListHeader.setBackgroundColor(getResources().getColor(R.color.red)); + } else { + lblListHeader.setBackgroundColor(getResources().getColor(R.color.bright_red)); + } + + } else { + lblListHeader.setBackgroundColor(getResources().getColor(R.color.bright_red)); + } + return convertView; + } + + @Override + public boolean hasStableIds() { + return false; + } + + @Override + public boolean isChildSelectable(int groupPosition, int childPosition) { + return true; + } + } + + public class ViewHolder { + TextView ed_Stock, mrp; + Button stock_img_plus, stock_img_minus; + CardView cardView; + EditText et_stock; + } + + @Override + public void onDestroy() { + if (dialog != null && dialog.isShowing()) { + dialog.dismiss(); + } + + super.onDestroy(); + } + + + private void setAxeSpinnerData(ArrayList axeList) { + axe_name_adapter = new ArrayAdapter<>(this, R.layout.spinner_custom_item); + axe_name_adapter.add("- Axe Name -"); + + for (int i = 0; i < axeList.size(); i++) { + axe_name_adapter.add(axeList.get(i).getBrandName()); + } + + axe_spin.setAdapter(axe_name_adapter); + axe_name_adapter.setDropDownViewResource(R.layout.spinner_custom_item); + + } + + private void setSubAxeSpinnerData(ArrayList subAxeList) { + sub_axe_name_adapter = new ArrayAdapter<>(this, R.layout.spinner_custom_item); + sub_axe_name_adapter.add("- Sub Axe Name -"); + + + for (int i = 0; i < subAxeList.size(); i++) { + sub_axe_name_adapter.add(subAxeList.get(i).getBrandName()); + } + + sub_axe_spin.setAdapter(sub_axe_name_adapter); + sub_axe_name_adapter.setDropDownViewResource(R.layout.spinner_custom_item); + + } + + + final int FILTER_FOR_AXE = 2; + final int FILTER_FOR_SUBAXE = 3; + + boolean isDataAdded = false; + + @Override + public void onBackPressed() { + //super.onBackPressed(); + isChanged(); + } + + void isChanged() { + if (isDataAdded) { + android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(this); + builder.setTitle("Parinaam"); + builder.setMessage(getResources().getString(R.string.data_will_be_lost)).setCancelable(false) + .setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { + + finish(); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + } + }) + .setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + + } + }); + android.app.AlertDialog alert = builder.create(); + alert.show(); + } else { + super.onBackPressed(); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + } + } + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + Log.i("MakeMachine", "resultCode: " + resultCode); + if (requestCode == 131) { + switch (resultCode) { + + case 0: + Log.i("MakeMachine", "User cancelled"); + break; + + case -1: + if (_pathforcheck != null && !_pathforcheck.equals("")) { + if (new File(CommonString.getImagesFolder(context) + _pathforcheck).exists()) { + convertBitmap(CommonString.getImagesFolder(context) + _pathforcheck); + isDataAdded = true; + globalHeaderObject.setImagePath(_pathforcheck); + groupPositionGlobal = -1; + _pathforcheck = ""; + listAdapter.notifyDataSetChanged(); + } + } + break; + } + } else { + IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data); + switch (resultCode) { + case 0: + + break; + + case -1: + db.open(); + ArrayList productList = db.getsku_fromproductusing_eancode(result.getContents(), false, visit_date, counter_id, null); + if (productList.isEmpty()) { + db.open(); + productList = db.getsku_fromproductusing_eancode(removeFirstChar(result.getContents()), false, visit_date, counter_id, null); + } + + if (!productList.isEmpty()) { + flagScan = false; + img_scan.setImageDrawable(getResources().getDrawable(R.mipmap.ok)); + clearFilters(); + setScanFilter(productList); + } else { + + AlertandMessages.showToastMsg(context, "Unable To Scan Correct Data. Please Try Again."); + } + break; + } + } + super.onActivityResult(requestCode, resultCode, data); + } + + //filter bottom sheet + View showFilterBottomSheet() { + + String uniqueId = UUID.randomUUID().toString(); + + final CardView cardSignature, cardBrand, cardSubBrand, cardReference; + + final BottomSheetDialog mBottomSheetDialog = new BottomSheetDialog(this); + final View sheetView = getLayoutInflater().inflate(R.layout.filter_bottom_sheet, null); + mBottomSheetDialog.setContentView(sheetView); + View bottomSheet = mBottomSheetDialog.getWindow().findViewById(com.google.android.material.R.id.design_bottom_sheet); + if (bottomSheet != null) { + bottomSheet.setBackgroundResource(android.R.color.transparent); + } + mBottomSheetDialog.setCancelable(false); + + final RecyclerView recBrand = sheetView.findViewById(R.id.rec_brand); + ImageView img_cancel = sheetView.findViewById(R.id.img_cancel); + TextView tv_clear_filter = sheetView.findViewById(R.id.tv_clear_filter); + recBrand.setAdapter(new ValueAdapter(context, signatureList, CommonString.Signature)); + recBrand.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, true)); + + cardSignature = sheetView.findViewById(R.id.card_signature); + cardBrand = sheetView.findViewById(R.id.card_brand); + cardSubBrand = sheetView.findViewById(R.id.card_sub_brand); + cardReference = sheetView.findViewById(R.id.card_reference); + + cardSignature.setOnClickListener(this); + cardBrand.setOnClickListener(this); + cardSubBrand.setOnClickListener(this); + cardReference.setOnClickListener(this); + + cardSignature.setCardBackgroundColor(getResources().getColor(R.color.dashboard_ach)); + + if (selectedSignature != null) { + (sheetView.findViewById(R.id.img_filter_signature)).setVisibility(View.VISIBLE); + } + if (selectedBrand != null) { + (sheetView.findViewById(R.id.img_filter_brand)).setVisibility(View.VISIBLE); + } + if (selectedSubBrand != null) { + (sheetView.findViewById(R.id.img_filter_sub_brand)).setVisibility(View.VISIBLE); + } + if (selectedReference != null) { + (sheetView.findViewById(R.id.img_filter_reference)).setVisibility(View.VISIBLE); + } + + img_cancel.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + mBottomSheetDialog.cancel(); + } + }); + + tv_clear_filter.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + setFilter(CLEAR_FILTER); + selectedSignature = null; + selectedBrand = null; + selectedSubBrand = null; + selectedReference = null; + + cardSignature.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background)); + cardBrand.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background)); + cardSubBrand.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background)); + cardReference.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background)); + + (sheetView.findViewById(R.id.img_filter_signature)).setVisibility(View.GONE); + (sheetView.findViewById(R.id.img_filter_brand)).setVisibility(View.GONE); + (sheetView.findViewById(R.id.img_filter_sub_brand)).setVisibility(View.GONE); + (sheetView.findViewById(R.id.img_filter_reference)).setVisibility(View.GONE); + db.open(); + brandList = db.getsub_brand_name(counterGroupId, "BrandName", false, selectedSubAxe); + db.open(); + subBrandList = db.getsub_brand_name(counterGroupId, "SubBrandName", false, selectedSubAxe); + db.open(); + referenceList = db.getsub_brand_name(counterGroupId, "ReferenceName", false, selectedSubAxe); + db.open(); + signatureList = db.getsub_brand_name(counterGroupId, "SignatureName", false, selectedSubAxe); + + ValueAdapter adapter = (ValueAdapter) recBrand.getAdapter(); + String type = adapter.getType(); + + ArrayList list = new ArrayList<>(); + + switch (type) { + case CommonString.Signature: + list = signatureList; + break; + case CommonString.Brand: + list = brandList; + break; + case CommonString.SubBrand: + list = subBrandList; + break; + case CommonString.Reference: + list = referenceList; + break; + } + recBrand.setLayoutManager(new LinearLayoutManager(SampleStockActivity.this, LinearLayoutManager.VERTICAL, true)); + recBrand.setAdapter(new ValueAdapter(context, list, CommonString.Signature)); + + recBrand.getAdapter().notifyDataSetChanged(); + } + }); + + mBottomSheetDialog.show(); + + return sheetView; + } + + private class ValueAdapter extends RecyclerView.Adapter { + private LayoutInflater inflator; + List data; + ProductMaster productMaster; + String type; + + public String getType() { + return type; + } + + private ValueAdapter(Context context, List data, String type) { + inflator = LayoutInflater.from(context); + this.data = data; + this.type = type; + } + + @NonNull + @Override + public ValueAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) { + View view = inflator.inflate(R.layout.item_filter, parent, false); + return new ValueAdapter.MyViewHolder(view); + } + + @Override + public void onBindViewHolder(@NonNull final ValueAdapter.MyViewHolder holder, final int position) { + final ProductMaster current = data.get(position); + + final boolean[] selected = {false}; + final int[] filterId = {0}; + + switch (type) { + + case CommonString.Signature: + if (selectedSignature != null && selectedSignature == current) { + selected[0] = true; + } + + break; + + case CommonString.Brand: + if (selectedBrand != null && selectedBrand == current) { + selected[0] = true; + } + + break; + + case CommonString.SubBrand: + if (selectedSubBrand != null && selectedSubBrand == current) { + selected[0] = true; + } + + break; + + case CommonString.Reference: + if (selectedReference != null && selectedReference == current) { + selected[0] = true; + } + + break; + } + + holder.tv_item.setText(CommonFunctions.capitalizeFirstLetter(current.getBrandName())); + + holder.tv_item.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + + et_search.setText(""); + + switch (type) { + case CommonString.Signature: + selectedSignature = current; + filterId[0] = R.id.img_filter_signature; + + //clear other sub filters-- + selectedBrand = null; + selectedSubBrand = null; + selectedReference = null; + + (sheetView.findViewById(R.id.img_filter_brand)).setVisibility(View.GONE); + (sheetView.findViewById(R.id.img_filter_sub_brand)).setVisibility(View.GONE); + (sheetView.findViewById(R.id.img_filter_reference)).setVisibility(View.GONE); + //-- + + setBottomFilter(listAdapter.get_listDataHeader(), current.getBrandName(), listAdapter.get_listDataChild(), CommonString.Signature); + db.open(); + brandList = db.getSubBrandOrReference(counterGroupId, "BrandName", current.getBrandName(), null, null, false, selectedSubAxe); + db.open(); + subBrandList = db.getSubBrandOrReference(counterGroupId, "SubBrandName", current.getBrandName(), null, null, false, selectedSubAxe); + db.open(); + referenceList = db.getSubBrandOrReference(counterGroupId, "ReferenceName", current.getBrandName(), null, null, false, selectedSubAxe); + + break; + case CommonString.Brand: + selectedBrand = current; + filterId[0] = R.id.img_filter_brand; + + //clear other sub filters-- + selectedSubBrand = null; + selectedReference = null; + + (sheetView.findViewById(R.id.img_filter_sub_brand)).setVisibility(View.GONE); + (sheetView.findViewById(R.id.img_filter_reference)).setVisibility(View.GONE); + //-- + + setBottomFilter(listAdapter.get_listDataHeader(), current.getBrandName(), listAdapter.get_listDataChild(), CommonString.Brand); + //setFilter(FILTER_FOR_BRAND); + db.open(); + subBrandList = db.getSubBrandOrReference(counterGroupId, "SubBrandName", "", current.getBrandName(), null, false, selectedSubAxe); + referenceList = db.getSubBrandOrReference(counterGroupId, "ReferenceName", "", current.getBrandName(), null, false, selectedSubAxe); + break; + case CommonString.SubBrand: + selectedSubBrand = current; + filterId[0] = R.id.img_filter_sub_brand; + + //clear other sub filters-- + selectedReference = null; + + (sheetView.findViewById(R.id.img_filter_reference)).setVisibility(View.GONE); + //-- + setBottomFilter(listAdapter.get_listDataHeader(), current.getBrandName(), listAdapter.get_listDataChild(), CommonString.SubBrand); + //setFilter(FILTER_FOR_SUB_BRAND); + db.open(); + referenceList = db.getSubBrandOrReference(counterGroupId, "ReferenceName", "", null, current.getBrandName(), false, selectedSubAxe); + break; + case CommonString.Reference: + selectedReference = current; + filterId[0] = R.id.img_filter_reference; + + setBottomFilter(listAdapter.get_listDataHeader(), current.getBrandName(), listAdapter.get_listDataChild(), CommonString.Reference); + //setFilter(FILTER_FOR_REFERENCE); + break; + } + + RecyclerView recSubBrand = sheetView.findViewById(R.id.rec_brand); + recSubBrand.getAdapter().notifyDataSetChanged(); + //show filter icon on filter selected + (sheetView.findViewById(filterId[0])).setVisibility(View.VISIBLE); + } + }); + + if (selected[0]) { + holder.card.setCardBackgroundColor(getResources().getColor(R.color.dashboard_ach)); + } else { + holder.card.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background)); + } + } + + @Override + public int getItemCount() { + return data.size(); + } + + class MyViewHolder extends RecyclerView.ViewHolder { + TextView tv_item; + CardView card; + + public MyViewHolder(View itemView) { + super(itemView); + tv_item = (TextView) itemView.findViewById(R.id.tv_item); + card = (CardView) itemView.findViewById(R.id.item_card); + + } + } + } + + void setFilterSelected(View sheetView, String type) { + CardView cardSignature, cardBrand, cardSubBrand, cardReference; + cardSignature = sheetView.findViewById(R.id.card_signature); + cardBrand = sheetView.findViewById(R.id.card_brand); + cardSubBrand = sheetView.findViewById(R.id.card_sub_brand); + cardReference = sheetView.findViewById(R.id.card_reference); + + cardSignature.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background)); + cardBrand.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background)); + cardSubBrand.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background)); + cardReference.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background)); + + switch (type) { + case CommonString.Signature: + cardSignature.setCardBackgroundColor(getResources().getColor(R.color.dashboard_ach)); + break; + case CommonString.Brand: + cardBrand.setCardBackgroundColor(getResources().getColor(R.color.dashboard_ach)); + break; + case CommonString.SubBrand: + cardSubBrand.setCardBackgroundColor(getResources().getColor(R.color.dashboard_ach)); + break; + case CommonString.Reference: + cardReference.setCardBackgroundColor(getResources().getColor(R.color.dashboard_ach)); + break; + } + } + + public ArrayList filterListForSignature(List originalList, String text) { + ArrayList filterList = new ArrayList<>(); + for (ProductMaster object : originalList) { + if (object.getSignatureName().equalsIgnoreCase(text)) { + filterList.add(object); + } else { + continue; + } + } + return filterList; + } + + public ArrayList filterListForSubBrand(List originalList, String text) { + ArrayList filterList = new ArrayList<>(); + for (ProductMaster object : originalList) { + if (object.getSubBrandName().equalsIgnoreCase(text) && (selectedSignature == null || object.getSignatureName().equalsIgnoreCase(selectedSignature.getBrandName())) && (selectedBrand == null || object.getBrandName().equalsIgnoreCase(selectedBrand.getBrandName()))) { + filterList.add(object); + } else { + continue; + } + } + return filterList; + } + + public ArrayList filterListForReference(List originalList, String text) { + ArrayList filterList = new ArrayList<>(); + for (ProductMaster object : originalList) { + + if (object.getReferenceName().equalsIgnoreCase(text) && (selectedSignature == null || object.getSignatureName().equalsIgnoreCase(selectedSignature.getBrandName())) + && (selectedBrand == null || object.getBrandName().equalsIgnoreCase(selectedBrand.getBrandName())) && (selectedSubBrand == null || object.getSubBrandName().equalsIgnoreCase(selectedSubBrand.getBrandName()))) { + filterList.add(object); + } else { + continue; + } + } + return filterList; + } + + public void setFilter(int filterType) { + + if (filterType == FILTER_FOR_SIGNATURE) { + listAdapter = new ExpandableListAdapter(context, filterListForSignature(listDataHeader, selectedSignature.getBrandName()), listDataChild); + } else if (filterType == FILTER_FOR_BRAND) { + listAdapter = new ExpandableListAdapter(context, filterListForBrand(listDataHeader, selectedBrand.getBrandName()), listDataChild); + } else if (filterType == FILTER_FOR_SUB_BRAND) { + listAdapter = new ExpandableListAdapter(context, filterListForSubBrand(listDataHeader, selectedSubBrand.getBrandName()), listDataChild); + } else if (filterType == FILTER_FOR_REFERENCE) { + listAdapter = new ExpandableListAdapter(context, filterListForReference(listDataHeader, selectedReference.getBrandName()), listDataChild); + } else { + listAdapter = new ExpandableListAdapter(context, filterListForSubAxe(listDataHeader, selectedSubAxe), listDataChild); + } + + lvExp_stock_check.setAdapter(listAdapter); + listAdapter.notifyDataSetChanged(); + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + getMenuInflater().inflate(R.menu.filter_menu, menu); + return super.onCreateOptionsMenu(menu); + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // Handle action bar item clicks here. The action bar will + // automatically handle clicks on the Home/Up button, so long + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + + if (id == android.R.id.home) { + isChanged(); + } else if (id == R.id.filter_data) { + sheetView = showFilterBottomSheet(); + + } + + return super.onOptionsItemSelected(item); + } + + public void uploadData(boolean finalFlag) { + //download service + //Intent intent = new Intent(context, Downloader.class); + SaleableGetterSetter stock = new SaleableGetterSetter(); + ArrayList data = new ArrayList<>(); + for (int i = 0; i < listDataHeader.size(); i++) { + List list = listDataChild.get(listDataHeader.get(i)); + for (int j = 0; j < list.size(); j++) { + //for final - complete data upload + if (finalFlag) { + list.get(j).setImagePath(listDataHeader.get(i).getImagePath()); + data.add(list.get(j)); + } else { + if (list.get(j).isSelected()) { + list.get(j).setImagePath(listDataHeader.get(i).getImagePath()); + data.add(list.get(j)); + } + } + } + } + + if (data.size() > 0) { + stock.setProductList(data); + String uuid = CommonFunctions.getUUID(context); + stock.setTransactionId(uuid); + ////changes by jeevan insert transaction for future use and handle master traction + if (regularStockFlag) { + db.open(); + db.insertStockTransactionMasterData(counter_id, visit_date, username, CommonString.SAMPLE, stock, "Regular_Stock"); + } else { + if (finalFlag) { + db.open(); + db.insertStockTransactionMasterData(counter_id, visit_date, username, CommonString.SAMPLE, stock, "FirstTime_Stock_Comp"); + } else { + db.open(); + db.insertStockTransactionMasterData(counter_id, visit_date, username, CommonString.SAMPLE, stock, "FirstTime_Stock_Draft"); + } + } + + dialog.cancel(); + CommonFunctions.call_upload(context); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + SampleStockActivity.this.finish(); + +/* + //for complete upload + if (finalFlag) { + if (CommonFunctions.checkNetIsAvailable(context)) { + int endIndex = 0; + int startIndex = endIndex; + if (startIndex + 200 < stock.getProductList().size()) { + endIndex = startIndex + 200; + } else { + endIndex = stock.getProductList().size(); + } + + UploadStockRecursive(CommonString.KEY_COMPLETE, 0, endIndex, stock); + } + } else { + intent.putExtra(CommonString.SAMPLE, stock); + + String status; + if (regularStockFlag) { + status = null; + } else { + if (finalFlag) { + status = CommonString.KEY_COMPLETE; + } else { + status = CommonString.KEY_DRAFT; + } + + } + + intent.putExtra(CommonString.KEY_STATUS, status); + Downloader.enqueueWork(SampleStockActivity.this, intent); + dialog.cancel(); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + SampleStockActivity.this.finish(); + + }*/ + + } + } + + void dialogFinalSubmit(final HashMap> listDataChild, final ArrayList listDataHeader) { + android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(SampleStockActivity.this); + builder.setTitle("Parinaam"); + builder.setMessage(getResources().getString(R.string.want_to_final_save)).setCancelable(false) + .setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { + show_dialog_for_final_submit(context); + } + }) + .setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + dialog.dismiss(); + + } + }); + android.app.AlertDialog alert = builder.create(); + alert.show(); + } + + private void show_dialog_for_final_submit(final Context context) { + final MultiPurposeDialog final_save_dialog = new MultiPurposeDialog(context); + final_save_dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); + final_save_dialog.setContentView(R.layout.custom_dialog_final_save); + final WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); + lp.copyFrom(final_save_dialog.getWindow().getAttributes()); + lp.width = WindowManager.LayoutParams.MATCH_PARENT; + lp.height = WindowManager.LayoutParams.WRAP_CONTENT; + lp.gravity = Gravity.CENTER; + final_save_dialog.getWindow().setAttributes(lp); + final_save_dialog.setCancelable(false); + + final EditText txt_hint_yes = (EditText) final_save_dialog.findViewById(R.id.txt_hint_yes); + Button btn_cancel = (Button) final_save_dialog.findViewById(R.id.btn_cancel); + Button btn_okay = (Button) final_save_dialog.findViewById(R.id.btn_okay); + + btn_okay.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + if (txt_hint_yes.getText().toString().equals("")) { + AlertandMessages.showToastMsg(context, "Please Enter Text"); + } else if (!txt_hint_yes.getText().toString().trim().equalsIgnoreCase("yes")) { + AlertandMessages.showToastMsg(context, "Please Enter 'Yes' Text"); + } else { + final_save_dialog.dismiss(); + if (regularStockFlag) { + new InsertAsync().execute(false); + } else { + new InsertAsync().execute(true); + } + } + } + }); + + + btn_cancel.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + final_save_dialog.dismiss(); + } + }); + + final_save_dialog.show(); + } + + + public class MultiPurposeDialog extends Dialog { + public MultiPurposeDialog(Context context) { + super(context); + // DIALOG USER_INTERFACE TEMPLATE + WindowManager.LayoutParams wmLayoutParams = getWindow().getAttributes(); + wmLayoutParams.gravity = Gravity.CENTER; + getWindow().setAttributes(wmLayoutParams); + setTitle(null); + setCancelable(false); + setOnCancelListener(null); + LinearLayout layout = new LinearLayout(context); + layout.setOrientation(LinearLayout.VERTICAL); + } + } + + + private void openScanner() { + IntentIntegrator intentIntegrator = new IntentIntegrator((Activity) context); + intentIntegrator.setBeepEnabled(true); + intentIntegrator.setOrientationLocked(false); + intentIntegrator.setPrompt("Scan the barcode or QR code to get the data"); + intentIntegrator.initiateScan(); + } + + + public void setScanFilter(List scanList) { + + HashMap> filterChildHashMap = new HashMap<>(); + + ArrayList filterList = new ArrayList<>(); + for (int i = 0; i < listDataHeader.size(); i++) { + ProductMaster parent = listDataHeader.get(i); + List listChild = listDataChild.get(parent); + List listFilterChild = new ArrayList<>(); + for (int j = 0; j < listChild.size(); j++) { + if (containsProduct(scanList, listChild.get(j))) { + listFilterChild.add(listChild.get(j)); + } else { + continue; + } + } + + if (listFilterChild.size() > 0) { + filterList.add(parent); + filterChildHashMap.put(parent, listFilterChild); + + } + + } + + ExpandableListAdapter listAdapter1 = new ExpandableListAdapter(context, filterList, filterChildHashMap); + lvExp_stock_check.setAdapter(listAdapter1); + for (int i = 0; i < listAdapter1.getGroupCount(); i++) { + lvExp_stock_check.expandGroup(i); + } + listAdapter1.notifyDataSetChanged(); + + + } + + boolean containsProduct(List scanList, ProductMaster obj) { + boolean contains = false; + + for (int i = 0; i < scanList.size(); i++) { + if (scanList.get(i).getProductId().equals(obj.getProductId())) { + contains = true; + break; + } + } + + return contains; + } + + void clearFilters() { + et_search.setText(""); + + setFilter(CLEAR_FILTER); + selectedSignature = null; + selectedBrand = null; + selectedSubBrand = null; + selectedReference = null; + + if (sheetView != null) { + (sheetView.findViewById(R.id.img_filter_signature)).setVisibility(View.GONE); + (sheetView.findViewById(R.id.img_filter_brand)).setVisibility(View.GONE); + (sheetView.findViewById(R.id.img_filter_sub_brand)).setVisibility(View.GONE); + (sheetView.findViewById(R.id.img_filter_reference)).setVisibility(View.GONE); + } + db.open(); + brandList = db.getsub_brand_name(counterGroupId, "BrandName", false, selectedSubAxe); + db.open(); + subBrandList = db.getsub_brand_name(counterGroupId, "SubBrandName", false, selectedSubAxe); + db.open(); + referenceList = db.getsub_brand_name(counterGroupId, "ReferenceName", false, selectedSubAxe); + db.open(); + signatureList = db.getsub_brand_name(counterGroupId, "SignatureName", false, selectedSubAxe); + } + + private Dialog dialog; + ProgressBar pb; + + class LoadAsync extends AsyncTask { + + @Override + protected void onPreExecute() { + + dialog = new Dialog(context); + dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); + dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT)); + dialog.setContentView(R.layout.circular_progress_bar); + pb = (ProgressBar) dialog.findViewById(R.id.progressBar1); + dialog.setCancelable(false); + dialog.show(); + + super.onPreExecute(); + } + + @Override + protected Void doInBackground(Void... voids) { + prepareListData(); + //validate_spin_ui_data(); + + return null; + } + + @Override + protected void onPostExecute(Void aVoid) { + + dialog.cancel(); + + recSubAxe.setLayoutManager(new GridLayoutManager(SampleStockActivity.this, 3)); + subAxeValueAdapter = new SubAxeValueAdapter(context, listSubAxe, CommonString.Signature); + recSubAxe.setAdapter(subAxeValueAdapter); + + recSubAxe.getAdapter().notifyDataSetChanged(); + + listAdapter = new ExpandableListAdapter(context, listDataHeader, listDataChild); + lvExp_stock_check.setAdapter(listAdapter); + + db.open(); + JourneyPlan jcp = db.getJCP(); + if (jcp != null) { + counterGroupId = jcp.getCounterGroupId().toString(); + } else { + counterGroupId = "1"; + } + + super.onPostExecute(aVoid); + } + } + + private class SubAxeValueAdapter extends RecyclerView.Adapter { + private LayoutInflater inflator; + List data; + + String type; + + public String getType() { + return type; + } + + private SubAxeValueAdapter(Context context, List data, String type) { + inflator = LayoutInflater.from(context); + this.data = data; + this.type = type; + } + + @NonNull + @Override + public SubAxeValueAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) { + View view = inflator.inflate(R.layout.item_filter, parent, false); + return new SubAxeValueAdapter.MyViewHolder(view); + } + + @Override + public void onBindViewHolder(final SubAxeValueAdapter.MyViewHolder holder, final int position) { + final ProductMaster current = data.get(position); + + + holder.tv_item.setText(CommonFunctions.capitalizeFirstLetter(current.getSubAxeName())); + + holder.tv_item.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + + /* et_search.setText(""); + + RecyclerView recSubBrand = sheetView.findViewById(R.id.rec_brand); + recSubBrand.getAdapter().notifyDataSetChanged();*/ + et_search.setText(""); + + listAdapter = new ExpandableListAdapter(context, filterListForSubAxe(listDataHeader, current.getSubAxeName()), listDataChild); + lvExp_stock_check.setAdapter(listAdapter); + listAdapter.notifyDataSetChanged(); + //setExpandableDataForSubAxe(current.getSubAxeName()); + current.setSelected(true); + selectedSubAxe = current.getSubAxeName(); + subAxeValueAdapter.notifyDataSetChanged(); + + jcp = db.getJCP(); + if (jcp != null) { + db.open(); + brandList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "BrandName", false, selectedSubAxe); + db.open(); + subBrandList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "SubBrandName", false, selectedSubAxe); + db.open(); + referenceList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "ReferenceName", false, selectedSubAxe); + db.open(); + signatureList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "SignatureName", false, selectedSubAxe); + } else { + brandList = db.getsub_brand_name("1", "BrandName", false, selectedSubAxe); + subBrandList = db.getsub_brand_name("1", "SubBrandName", false, selectedSubAxe); + referenceList = db.getsub_brand_name("1", "ReferenceName", false, selectedSubAxe); + signatureList = db.getsub_brand_name("1", "SignatureName", false, selectedSubAxe); + } + } + }); + + //if (current.isSelected()) { + if (current.getSubAxeName().equalsIgnoreCase(selectedSubAxe)) { + holder.card.setCardBackgroundColor(getColor(R.color.dashboard_ach)); + } else { + holder.card.setCardBackgroundColor(getColor(R.color.grey_dark_background)); + } + } + + @Override + public int getItemCount() { + return data.size(); + } + + class MyViewHolder extends RecyclerView.ViewHolder { + TextView tv_item; + CardView card; + + public MyViewHolder(View itemView) { + super(itemView); + tv_item = (TextView) itemView.findViewById(R.id.tv_item); + card = (CardView) itemView.findViewById(R.id.item_card); + + } + } + } + + public ArrayList filterListForSubAxe(List originalList, String text) { + ArrayList filterList = new ArrayList<>(); + for (ProductMaster object : originalList) { + if (object.getSubAxeName().equalsIgnoreCase(text)) { + filterList.add(object); + } else { + continue; + } + } + return filterList; + } + + public void setBottomFilter(List originalList, String text, HashMap> listDataChild, String type) { + + HashMap> filterChildHashMap = new HashMap<>(); + + ArrayList filterList = new ArrayList<>(); + for (int i = 0; i < originalList.size(); i++) { + ProductMaster parent = originalList.get(i); + List listChild = listDataChild.get(parent); + List listFilterChild = new ArrayList<>(); + for (int j = 0; j < listChild.size(); j++) { + + switch (type) { + case CommonString.Signature: + if (listChild.get(j).getSignatureName().equalsIgnoreCase(text)) { + listFilterChild.add(listChild.get(j)); + } + break; + case CommonString.Brand: + if (listChild.get(j).getBrandName().equalsIgnoreCase(text)) { + listFilterChild.add(listChild.get(j)); + } + break; + case CommonString.SubBrand: + if (listChild.get(j).getSubBrandName().equalsIgnoreCase(text)) { + listFilterChild.add(listChild.get(j)); + } + break; + case CommonString.Reference: + if (listChild.get(j).getReferenceName().equalsIgnoreCase(text)) { + listFilterChild.add(listChild.get(j)); + } + break; + } + + } + + if (listFilterChild.size() > 0) { + filterList.add(parent); + filterChildHashMap.put(parent, listFilterChild); + + } + + } + + ExpandableListAdapter listAdapter1 = new ExpandableListAdapter(context, filterList, filterChildHashMap); + lvExp_stock_check.setAdapter(listAdapter1); + /* for (int i = 0; i < listAdapter1.getGroupCount(); i++) { + lvExp_stock_check.expandGroup(i); + }*/ + listAdapter1.notifyDataSetChanged(); + } + + private void UploadStockRecursive(final String status, final int startIndex, final int endIndex, final SaleableGetterSetter stock) { + try { + + JSONArray topUpArray = new JSONArray(); + + String key = "SampleData"; + int mid = 0; + if (stock != null) { + + if (jcp != null) { + mid = jcp.getMID(); + } + for (int j = startIndex; j < endIndex; j++) { + JSONObject obj = new JSONObject(); + obj.put("ProductId", stock.getProductList().get(j).getProductId()); + obj.put("MID", mid); + obj.put("TranId", stock.getTransactionId()); + obj.put("UserId", username); + obj.put("CounterId", counter_id); + + if (status != null) { + int stk = stock.getProductList().get(j).getStock(); + if (stk == -1) { + stk = 0; + } + + obj.put("STOCK", stk); + obj.put("Status", status); + //different key for first time data + key = "SampleFData"; + } else { + obj.put("STOCK", stock.getProductList().get(j).getStock_receive() - stock.getProductList().get(j).getStock()); + } + + + topUpArray.put(obj); + } + } + + JSONObject jsonObject = new JSONObject(); + jsonObject.put("MID", mid); + jsonObject.put("Keys", key); + jsonObject.put("JsonData", topUpArray.toString()); + jsonObject.put("UserId", username); + + String jsonString = jsonObject.toString(); + + OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(20, TimeUnit.SECONDS).writeTimeout(20, TimeUnit.SECONDS).connectTimeout(20, TimeUnit.SECONDS).build(); + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsonString); + Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build(); + PostApi api = adapter.create(PostApi.class); + Call call = api.getGeotag(jsonData); + call.enqueue(new Callback() { + @Override + public void onResponse(Call call, Response response) { + String responseBody = response.body().get("UploadJsonResult").toString(); + String data = null; + if (responseBody != null && response.isSuccessful()) { + try { + data = response.body().get("UploadJsonResult").toString(); + if (data.equals("")) { + } else { + data = data.substring(1, data.length() - 1).replace("\\", ""); + if (data.equalsIgnoreCase(CommonString.KEY_SUCCESS)) { + if (endIndex < stock.getProductList().size()) { + int startIndex1 = endIndex; + int endIndex1 = 0; + if (startIndex1 + 200 < stock.getProductList().size()) { + endIndex1 = startIndex1 + 200; + } else { + endIndex1 = stock.getProductList().size(); + } + UploadStockRecursive(status, startIndex1, endIndex1, stock); + } else { + db.open(); + db.updateStockTransactionDataStatus(stock.getTransactionId()); + dialog.cancel(); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + SampleStockActivity.this.finish(); + } + } + } + } catch (Exception e) { + db.open(); + dialog.cancel(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE + " - " + e.toString() + " - Please Try Again"); + } + } else { + dialog.cancel(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_NO_RESPONSE_SERVER + " - Please Try Again"); + } + } + + @Override + public void onFailure(Call call, Throwable t) { + dialog.cancel(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE + " - Please Try Again"); + } + }); + + + } catch (JSONException e) { + e.fillInStackTrace(); + dialog.cancel(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INVALID_JSON + " - Please Try Again"); + } + } + + class InsertAsync extends AsyncTask { + boolean flag = false; + + @Override + protected void onPreExecute() { + dialog = new Dialog(context); + dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); + dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT)); + dialog.setContentView(R.layout.circular_progress_bar); + pb = (ProgressBar) dialog.findViewById(R.id.progressBar1); + dialog.setCancelable(false); + dialog.show(); + super.onPreExecute(); + } + + @Override + protected Void doInBackground(Boolean... bool) { + flag = bool[0]; + db.open(); + db.insertSampleCapturedData(visit_date, listDataChild, listDataHeader, bool[0], counter_id); + uploadData(bool[0]); + return null; + } + + @Override + protected void onPostExecute(Void aVoid) { + super.onPostExecute(aVoid); + dialog.cancel(); + finish(); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + } + } + + private boolean validate_regular_stock() { + check_flag = true; + if (listDataHeader.size() > 0) { + for (int k = 0; k < listDataHeader.size(); k++) { + List child_list = listDataChild.get(listDataHeader.get(k)); + for (int i = 0; i < child_list.size(); i++) { + if (child_list.get(i).isSelected() && child_list.get(i).getStock_receive() != child_list.get(i).getStock()) { + if (child_list.get(i).getReasonId() == 0) { + check_flag = false; + AlertandMessages.showToastMsg(context, "Please Select Reason"); + break; + } + } + + } + if (!check_flag) { + break; + } + } + } + + return check_flag; + + } + + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/ServiceActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/ServiceActivity.java new file mode 100644 index 0000000..b3b0bf3 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/ServiceActivity.java @@ -0,0 +1,227 @@ +package com.cpm.lorealbaautomation.dailyactivity; + +import android.annotation.SuppressLint; +import android.app.Activity; +import android.app.AlertDialog; +import android.content.Context; +import android.content.SharedPreferences; +import android.os.Bundle; +import android.os.Environment; + +import androidx.appcompat.app.AppCompatActivity; +import androidx.appcompat.widget.Toolbar; + +import android.view.MenuItem; +import android.view.View; +import android.widget.ImageView; +import android.widget.Toast; + +import com.cpm.lorealbaautomation.BuildConfig; +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.constant.AlertandMessages; +import com.cpm.lorealbaautomation.constant.CommonFunctions; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.retrofit.PostApiForUpload; +import com.cpm.lorealbaautomation.retrofit.StringConverterFactory; +import com.squareup.okhttp.MediaType; +import com.squareup.okhttp.MultipartBuilder; +import com.squareup.okhttp.RequestBody; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.nio.channels.FileChannel; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Objects; + +import retrofit.Call; +import retrofit.Callback; +import retrofit.Response; +import retrofit.Retrofit; + +public class ServiceActivity extends AppCompatActivity implements View.OnClickListener { + SharedPreferences preferences; + ImageView btn_is_present; + Context context; + String date, user_name; + + @SuppressLint("NewApi") + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_service); + context = this; + Toolbar toolbar = findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + Objects.requireNonNull(getSupportActionBar()).setHomeButtonEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + if (!CommonFunctions.isTablet(this)) { + toolbar.setTitleTextAppearance(this, R.style.changestext_sizefor_mobile); + } + + setTitle("Export Database"); + + //preference data + preferences = PrefHelper.getPrefs(context); + date = preferences.getString(CommonString.KEY_DATE, ""); + user_name = preferences.getString(CommonString.KEY_USERNAME, ""); + btn_is_present = (ImageView) findViewById(R.id.btn_is_present); + btn_is_present.setOnClickListener(this); + + } + + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // Handle action bar item clicks here. The action bar will + // automatically handle clicks on the Home/Up button, so long + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + if (id == android.R.id.home) { + finish(); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + } + + return super.onOptionsItemSelected(item); + } + + + @Override + public void onBackPressed() { + super.onBackPressed(); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + } + + @Override + protected void onResume() { + super.onResume(); + } + + @SuppressLint("NonConstantResourceId") + @Override + public void onClick(View view) { + if (view.getId() == R.id.btn_is_present) { + showExportDialog(); + // restoreBackup(); + } + } + + public void restoreBackup() { + + try { + File sd = Environment.getExternalStorageDirectory(); + File data = Environment.getDataDirectory(); + + if (sd.canWrite()) { + String currentDBPath = "//data//" + BuildConfig.APPLICATION_ID + "//databases//" + Lorealba_Database.DATABASE_NAME; + String backupDBPath = "shama.baLorealBa_BackupMar_22_21145440.db"; + File currentDB = new File(data, currentDBPath); + File backupDB = new File(sd, backupDBPath); + + if (currentDB.exists()) { + FileChannel src = new FileInputStream(backupDB).getChannel(); + FileChannel dst = new FileOutputStream(currentDB).getChannel(); + dst.transferFrom(src, 0, src.size()); + src.close(); + dst.close(); + Toast.makeText(getApplicationContext(), "Database Restored successfully", Toast.LENGTH_SHORT).show(); + } + } + } catch (Exception e) { + //test(e.getMessage()); + } + } + + public void showExportDialog() { + android.app.AlertDialog.Builder builder1 = new android.app.AlertDialog.Builder(context).setTitle(R.string.dialog_title); + builder1.setMessage(R.string.Areyou_sure_take_backup) + .setCancelable(false) + .setPositiveButton(R.string.ok, (dialog, id) -> { + try { + File sd = context.getExternalFilesDir(""); + File data = Environment.getDataDirectory(); + assert sd != null; + if (sd.canWrite()) { + long date = System.currentTimeMillis(); + @SuppressLint("SimpleDateFormat") SimpleDateFormat sdf = new SimpleDateFormat("MMM/dd/yy"); + String dateString = sdf.format(date); + String currentDBPath = "//data//" + BuildConfig.APPLICATION_ID + "//databases//" + Lorealba_Database.DATABASE_NAME; + String backupDBPath = user_name + CommonString.BACKUP_FOLDER_NAME + dateString.replace('/', '_') + CommonFunctions.getCurrentTime_only().replace(":", "") + ".db"; + String path = CommonString.getBackupFolder(context); + File currentDB = new File(data, currentDBPath); + File backupDB = new File(path, backupDBPath); + if (currentDB.exists()) { + @SuppressWarnings("resource") + FileChannel src = new FileInputStream(currentDB).getChannel(); + FileChannel dst = new FileOutputStream(backupDB).getChannel(); + dst.transferFrom(src, 0, src.size()); + src.close(); + dst.close(); + } + + File dir = new File(CommonString.getBackupFolder(context)); + ArrayList list; + list = getFileNames(Objects.requireNonNull(dir.listFiles())); + if (!list.isEmpty()) { + for (int i1 = 0; i1 < list.size(); i1++) { + if (list.get(i1).contains(CommonString.BACKUP_FOLDER_NAME)) { + File originalFile = new File(CommonString.getBackupFolder(context) + list.get(i1)); + uploadBackup(context, originalFile.getName(), "DBBackup"); + } + } + } + } + } catch (Exception e) { + e.fillInStackTrace(); + AlertandMessages.showAlert((Activity) context, context.getString(R.string.errordatabase_not_exporting), true); + } + }).setNegativeButton(android.R.string.cancel, (dialog, id) -> dialog.cancel()); + AlertDialog alert1 = builder1.create(); + alert1.show(); + } + + + public ArrayList getFileNames(File[] file) { + ArrayList arrayFiles = new ArrayList(); + if (file.length > 0) { + for (File value : file) arrayFiles.add(value.getName()); + } + + return arrayFiles; + } + + public static void uploadBackup(final Context context, String file_name, String folder_name) { + RequestBody body1; + final File originalFile = new File(CommonString.getBackupFolder(context) + file_name); + RequestBody photo = RequestBody.create(MediaType.parse("application/octet-stream"), originalFile); + body1 = new MultipartBuilder().type(MultipartBuilder.FORM).addFormDataPart("file", originalFile.getName(), photo).addFormDataPart("Foldername", folder_name).addFormDataPart("Path", "1111111").build(); + Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URLGORIMAG).addConverterFactory(new StringConverterFactory()).build(); + PostApiForUpload api = adapter.create(PostApiForUpload.class); + Call call = api.getUploadImageRetrofitOne(body1); + call.enqueue(new Callback() { + @Override + public void onResponse(Response response) { + String responseBody = response.body(); + if (responseBody != null && response.isSuccess()) { + if (response.body().contains(CommonString.KEY_SUCCESS)) { + try { + originalFile.delete(); + } catch (Exception e) { + throw new RuntimeException(e); + } + AlertandMessages.showToastMsg(context, "Database Exported And Uploaded Successfully"); + } + } + } + + @Override + public void onFailure(Throwable t) { + AlertandMessages.showToastMsg(context, originalFile.getName() + " not uploaded"); + } + }); + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/SkinGeniusCategoryActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/SkinGeniusCategoryActivity.java new file mode 100644 index 0000000..0021802 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/SkinGeniusCategoryActivity.java @@ -0,0 +1,138 @@ +package com.cpm.lorealbaautomation.dailyactivity; + +import android.content.ActivityNotFoundException; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.net.Uri; + +import androidx.appcompat.app.AppCompatActivity; + +import android.os.Bundle; + +import androidx.cardview.widget.CardView; +import androidx.appcompat.widget.Toolbar; + +import android.view.MenuItem; +import android.view.View; + +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.constant.AlertandMessages; +import com.cpm.lorealbaautomation.constant.CommonFunctions; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.delegates.PrefHelper; + +public class SkinGeniusCategoryActivity extends AppCompatActivity implements View.OnClickListener { + CardView skingenius_uploadscreenshot_img, skin_genius_img, skin_maybeline_img; + String CounterId, visit_date, username, skingenius_url = "", maybelline_ur = ""; + private SharedPreferences preferences; + private SharedPreferences.Editor editor = null; + Lorealba_Database db; + Context context; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_skin_genius_category); + context = this; + db = new Lorealba_Database(context); + db.open(); + iduserinterface(); + Toolbar toolbar = findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + getSupportActionBar().setHomeButtonEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + if (!CommonFunctions.isTablet(context)) { + toolbar.setTitleTextAppearance(context, R.style.changestext_sizefor_mobile); + } + + setTitle("Skin Genius Category - " + username); + + } + + private void iduserinterface() { + preferences = PrefHelper.getPrefs(context); + editor = preferences.edit(); + CounterId = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + username = preferences.getString(CommonString.KEY_USERNAME, ""); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + skingenius_url = preferences.getString(CommonString.KEY_SKIN_GENIUS_URL, ""); + maybelline_ur = preferences.getString(CommonString.KEY_SKIN_MAYBELLINE_URL, ""); + skingenius_uploadscreenshot_img = (CardView) findViewById(R.id.skingenius_uploadscreenshot_img); + skin_genius_img = (CardView) findViewById(R.id.skin_genius_img); + skin_maybeline_img = (CardView) findViewById(R.id.skin_maybeline_img); + skingenius_uploadscreenshot_img.setOnClickListener(this); + skin_genius_img.setOnClickListener(this); + skin_maybeline_img.setOnClickListener(this); + } + + void openUrlInChrome(String url) { + try { + try { + Uri uri = Uri.parse("googlechrome://navigate?url=" + url); + Intent i = new Intent(Intent.ACTION_VIEW, uri); + i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + startActivity(i); + } catch (ActivityNotFoundException e) { + Uri uri = Uri.parse(url); + // Chrome is probably not installed + // OR not selected as default browser OR if no Browser is selected as default browser + Intent i = new Intent(Intent.ACTION_VIEW, uri); + i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + startActivity(i); + } + } catch (Exception ex) { + ex.fillInStackTrace(); + } + } + + @Override + public void onClick(View v) { + + if (v.getId() == R.id.skingenius_uploadscreenshot_img) { + context.startActivity(new Intent(context, SkinGeniusScreenshotActivity.class)); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + } else if (v.getId() == R.id.skin_genius_img) { + if (skingenius_url != null && !skingenius_url.equals("")) { + openUrlInChrome(skingenius_url); + db.open(); + int openskingenius_count = 1; + long l = db.insertOpenSkinGeniusdata(username, visit_date, CounterId, CommonFunctions.getUUID(context), openskingenius_count); + } else { + AlertandMessages.showToastMsg(context, "Skin Genius URL not found"); + } + + } else if (v.getId() == R.id.skin_maybeline_img) { + if (maybelline_ur != null && !maybelline_ur.equals("")) { + openUrlInChrome(maybelline_ur); + db.open(); + int open_maybelline_count = 1; + long l = db.insertOpenMaybellineNVdata(username, visit_date, CounterId, CommonFunctions.getUUID(context), open_maybelline_count); + } else { + AlertandMessages.showToastMsg(context, "Maybelline URL not found"); + } + } + } + + @Override + public void onBackPressed() { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + SkinGeniusCategoryActivity.this.finish(); + } + + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + if (id == android.R.id.home) { + + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + SkinGeniusCategoryActivity.this.finish(); + } + return super.onOptionsItemSelected(item); + } + + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/SkinGeniusScreenshotActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/SkinGeniusScreenshotActivity.java new file mode 100644 index 0000000..37eac17 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/SkinGeniusScreenshotActivity.java @@ -0,0 +1,263 @@ +package com.cpm.lorealbaautomation.dailyactivity; + +import android.annotation.SuppressLint; +import android.app.Activity; +import android.app.AlertDialog; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.database.Cursor; +import android.graphics.Bitmap; +import android.net.ConnectivityManager; +import android.net.NetworkInfo; +import android.net.Uri; + +import com.google.android.material.floatingactionbutton.FloatingActionButton; + +import androidx.appcompat.app.AppCompatActivity; + +import android.os.Bundle; + +import androidx.appcompat.widget.Toolbar; + +import android.view.MenuItem; +import android.view.View; +import android.widget.ImageView; +import android.widget.TextView; + +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.constant.AlertandMessages; +import com.cpm.lorealbaautomation.constant.CommonFunctions; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.constant.FileUtils; +import com.cpm.lorealbaautomation.delegates.PrefHelper; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.file.Files; +import java.util.Objects; + +import static com.cpm.lorealbaautomation.constant.CommonFunctions.getCurrentTime; +import static com.cpm.lorealbaautomation.dailyactivity.StoreImageActivity.convertBitmap; + +public class SkinGeniusScreenshotActivity extends AppCompatActivity implements View.OnClickListener { + String CounterId, visit_date, username, skingenius_uploadTym = ""; + private SharedPreferences preferences; + private SharedPreferences.Editor editor = null; + Lorealba_Database db; + Context context; + + ImageView img_cam, img_clicked; + FloatingActionButton save_skin_genius; + TextView skingenius_capturedTym; + String img_str = ""; + private final boolean clicked_flag = false; + int FILE_PICKER_CODE = 3; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_skin_genius_screenshot); + context = this; + db = new Lorealba_Database(context); + db.open(); + iduserinterface(); + Toolbar toolbar = findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + Objects.requireNonNull(getSupportActionBar()).setHomeButtonEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + if (!CommonFunctions.isTablet(context)) { + toolbar.setTitleTextAppearance(context, R.style.changestext_sizefor_mobile); + } + + setTitle("Skin Genius Screenshot - " + username); + + } + + @SuppressLint("SetTextI18n") + private void iduserinterface() { + preferences = PrefHelper.getPrefs(context); + editor = preferences.edit(); + CounterId = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + username = preferences.getString(CommonString.KEY_USERNAME, ""); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + skingenius_uploadTym = preferences.getString(CommonString.KEY_SKIN_GENIUS_UPLOADTYM, ""); + + img_cam = (ImageView) findViewById(R.id.img_selfie); + img_clicked = (ImageView) findViewById(R.id.img_cam_selfie); + skingenius_capturedTym = (TextView) findViewById(R.id.skingenius_capturedTym); + save_skin_genius = (FloatingActionButton) findViewById(R.id.save_skin_genius); + + if (skingenius_uploadTym != null && !skingenius_uploadTym.isEmpty()) { + skingenius_capturedTym.setText("Last Skin Genius Uploaded Time : " + skingenius_uploadTym); + } + + img_cam.setOnClickListener(this); + img_clicked.setOnClickListener(this); + save_skin_genius.setOnClickListener(this); + } + + + @Override + public void onBackPressed() { + if (clicked_flag) { + AlertDialog.Builder builder = new AlertDialog.Builder(context).setMessage(CommonString.ONBACK_ALERT_MESSAGE).setCancelable(false).setPositiveButton("Ok", + (dialog, id) -> { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + SkinGeniusScreenshotActivity.this.finish(); + }).setNegativeButton("Cancel", (dialog, id) -> dialog.cancel()); + AlertDialog alert = builder.create(); + alert.show(); + } else { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + SkinGeniusScreenshotActivity.this.finish(); + } + } + + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + if (id == android.R.id.home) { + if (clicked_flag) { + AlertDialog.Builder builder = new AlertDialog.Builder(context).setMessage(CommonString.ONBACK_ALERT_MESSAGE).setCancelable(false).setPositiveButton("Ok", + (dialog, id1) -> { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + SkinGeniusScreenshotActivity.this.finish(); + }).setNegativeButton("Cancel", (dialog, id12) -> dialog.cancel()); + AlertDialog alert = builder.create(); + alert.show(); + } else { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + SkinGeniusScreenshotActivity.this.finish(); + } + } + return super.onOptionsItemSelected(item); + } + + + @SuppressLint("NonConstantResourceId") + @Override + public void onClick(View v) { + + if (v.getId() == R.id.img_cam_selfie) { + browseDocuments(); + } else if (v.getId() == R.id.save_skin_genius) { + if (img_str != null && !img_str.isEmpty()) { + AlertDialog.Builder alert = new AlertDialog.Builder(context).setTitle(R.string.parinaam).setMessage(getString(R.string.alertsaveData)) + .setCancelable(false).setPositiveButton(android.R.string.yes, (dialogInterface, i) -> { + db.open(); + long l = db.insertSkinGeniusdata(username, visit_date, CounterId, CommonFunctions.getUUID(context), img_str, CommonFunctions.getCurrentTime_only()); + if (l > 0) { + editor = preferences.edit(); + editor.putString(CommonString.KEY_SKIN_GENIUS_UPLOADTYM, visit_date + " : " + CommonFunctions.getCurrentTime_only()); + editor.commit(); + AlertandMessages.showToastMsg(context, "Data saved successfully."); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + SkinGeniusScreenshotActivity.this.finish(); + CommonFunctions.call_upload(context); + } else { + AlertandMessages.showToastMsg(context, "Data not inserted"); + } + }).setNegativeButton(android.R.string.cancel, (dialogInterface, i) -> dialogInterface.dismiss()); + + alert.show(); + + } else { + AlertandMessages.showToastMsg(context, "Please Pickup Skin Genius Screenshot"); + } + + } + + } + + public boolean checkNetIsAvailable() { + ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); + NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); + return activeNetwork != null && activeNetwork.isConnectedOrConnecting(); + } + + + private void browseDocuments() { + String[] mimeTypes = + {"application/msword", "application/vnd.openxmlformats-officedocument.wordprocessingml.document", + "image/jpeg", + "image/jpg", "image/png"}; + + Intent intent = new Intent(Intent.ACTION_GET_CONTENT); + intent.setType("*/*"); + intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes); + startActivityForResult(Intent.createChooser(intent, "Choose Skin Genius Screenshot"), FILE_PICKER_CODE); + + } + + @Override + public void onActivityResult(int requestCode, int resultCode, Intent data) { + // TODO Auto-generated method stub + if (resultCode == Activity.RESULT_OK) { + if (requestCode == FILE_PICKER_CODE) { + Uri uri = data.getData(); + assert uri != null; + String uriString = uri.toString(); + String displayName = null; + + if (uriString.startsWith("content://")) { + try (Cursor cursor = getContentResolver().query(uri, null, null, null, null)) { + if (cursor != null && cursor.moveToFirst()) { + displayName = CounterId + username.replace(".", "") + "-SkinGenius-" + visit_date.replace("/", "") + "_" + getCurrentTime().replace(":", "") + ".jpg"; + } + } + } else if (uriString.startsWith("file://")) { + displayName = CounterId + username.replace(".", "") + "-SkinGenius-" + visit_date.replace("/", "") + "_" + getCurrentTime().replace(":", "") + ".jpg"; + } + try { + File sourceLocation = null; + sourceLocation = FileUtils.getFile(context, uri); + File targetLocation = new File(CommonString.getImagesFolder(context) + displayName); + if (sourceLocation != null) { + InputStream in = null; + if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) { + in = Files.newInputStream(sourceLocation.toPath()); + } else { + in = new FileInputStream(sourceLocation); + } + OutputStream out = null; + if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) { + out = Files.newOutputStream(targetLocation.toPath()); + } else out = new FileOutputStream(targetLocation); + // Copy the bits from instream to outstream + byte[] buf = new byte[1024]; + int len; + while ((len = in.read(buf)) > 0) { + out.write(buf, 0, len); + } + in.close(); + out.close(); + img_str = displayName; + if (new File(CommonString.getImagesFolder(context) + img_str).exists()) { + try { + Bitmap bmp = convertBitmap(CommonString.getImagesFolder(context) + img_str); + img_cam.setImageBitmap(bmp); + } catch (OutOfMemoryError ex) { + CommonFunctions.setScaledImage(img_cam, CommonString.getImagesFolder(context) + img_str); + } + img_clicked.setVisibility(View.GONE); + img_cam.setVisibility(View.VISIBLE); + } + } else { + AlertandMessages.showToastMsg(context, "Unable to retrieve the path. Please try again"); + } + } catch (IOException e) { + e.fillInStackTrace(); + } + } + } + super.onActivityResult(requestCode, resultCode, data); + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/StockCheckActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/StockCheckActivity.java new file mode 100644 index 0000000..fb4a7c7 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/StockCheckActivity.java @@ -0,0 +1,1749 @@ +package com.cpm.lorealbaautomation.dailyactivity; + +import android.annotation.SuppressLint; +import android.app.Activity; +import android.app.Dialog; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.graphics.drawable.ColorDrawable; +import android.os.AsyncTask; +import android.os.Build; +import android.os.Bundle; + +import androidx.annotation.NonNull; +import androidx.annotation.RequiresApi; + +import com.google.android.material.bottomsheet.BottomSheetDialog; +import com.google.android.material.floatingactionbutton.FloatingActionButton; + +import androidx.core.content.ContextCompat; +import androidx.appcompat.app.AppCompatActivity; +import androidx.cardview.widget.CardView; +import androidx.recyclerview.widget.GridLayoutManager; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; +import androidx.appcompat.widget.Toolbar; + +import android.text.Editable; +import android.text.TextWatcher; +import android.util.Log; +import android.view.Gravity; +import android.view.LayoutInflater; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; +import android.view.Window; +import android.view.WindowManager; +import android.view.inputmethod.InputMethodManager; +import android.widget.AbsListView; +import android.widget.AdapterView; +import android.widget.BaseExpandableListAdapter; +import android.widget.Button; +import android.widget.EditText; +import android.widget.ExpandableListView; +import android.widget.ImageView; +import android.widget.LinearLayout; +import android.widget.ProgressBar; +import android.widget.Spinner; +import android.widget.TextView; + +import com.google.gson.JsonObject; +import com.google.zxing.integration.android.IntentIntegrator; +import com.google.zxing.integration.android.IntentResult; +import com.journeyapps.barcodescanner.CaptureActivity; +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.adapter.ReasonSpinnerAdapter; +import com.cpm.lorealbaautomation.constant.AlertandMessages; +import com.cpm.lorealbaautomation.constant.CommonFunctions; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.gettersetter.SaleableGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.JourneyPlan; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterNonStockReason; +import com.cpm.lorealbaautomation.gsonGetterSetter.ProductMaster; + +import com.cpm.lorealbaautomation.retrofit.PostApi; + + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.File; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.TimeUnit; + +import okhttp3.MediaType; +import okhttp3.OkHttpClient; +import okhttp3.RequestBody; +import retrofit2.Call; +import retrofit2.Callback; +import retrofit2.Response; +import retrofit2.Retrofit; +import retrofit2.converter.gson.GsonConverterFactory; + +import static com.cpm.lorealbaautomation.constant.CommonFunctions.getCurrentTime; +import static com.cpm.lorealbaautomation.constant.CommonFunctions.removeFirstChar; +import static com.cpm.lorealbaautomation.dailyactivity.StoreImageActivity.convertBitmap; + +public class StockCheckActivity extends AppCompatActivity implements View.OnClickListener { + Spinner sku_spin, brand_spin, sub_axe_spin, axe_spin; + ArrayList brandList = new ArrayList<>(); + ArrayList subBrandList = new ArrayList<>(); + ArrayList referenceList = new ArrayList<>(); + ArrayList signatureList = new ArrayList<>(); + ExpandableListView lvExp_stock_check; + FloatingActionButton fab_save, fab_draft; + Lorealba_Database db; + Context context; + private SharedPreferences preferences; + String counter_id, visit_date, username, _pathforcheck, _path; + ArrayList listDataHeader = new ArrayList<>(); + ArrayList childStockList = new ArrayList<>(); + HashMap> listDataChild; + boolean checkflag = true; + ArrayList checkHeaderArray = new ArrayList<>(); + ExpandableListAdapter listAdapter; + String brandName = ""; + String axeName = ""; + String subAxeName = ""; + int groupPositionGlobal = -1; + ProductMaster globalHeaderObject = new ProductMaster(); + EditText et_search; + boolean regularStockFlag = false, check_flag = true; + View sheetView; + ProductMaster selectedSignature, selectedBrand, selectedSubBrand, selectedReference; + ImageView img_scan, img_clear_subaxe, img_unfilled; + boolean flagScan = true; + String counterGroupId; + RecyclerView recSubAxe; + String selectedSubAxe = ""; + SubAxeValueAdapter subAxeValueAdapter; + ArrayList listSubAxe; + + @SuppressLint("SetTextI18n") + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_stock_check); + context = this; + ((StockCheckActivity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); + db = new Lorealba_Database(context); + db.open(); + validateUIData(); + + String couter_code = preferences.getString(CommonString.KEY_COUNTER_CODE, ""); + TextView txt_counter_code = (TextView) findViewById(R.id.txt_counter_code); + txt_counter_code.setText("Counter Code - " + couter_code + " / Id - " + counter_id); + new LoadAsync().execute(); + + lvExp_stock_check.setOnScrollListener(new AbsListView.OnScrollListener() { + @Override + public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { + lvExp_stock_check.invalidate(); + int lastItem = firstVisibleItem + visibleItemCount; + if (firstVisibleItem == 0) { + fab_save.show();//.setVisibility(View.VISIBLE); + } else if (lastItem == totalItemCount) { + fab_save.hide();//setVisibility(View.INVISIBLE); + } else { + fab_save.show();//setVisibility(View.VISIBLE); + } + } + + @Override + public void onScrollStateChanged(AbsListView arg0, int arg1) { + InputMethodManager inputManager = (InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE); + if (getCurrentFocus() != null) { + inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0); + getCurrentFocus().clearFocus(); + } + + lvExp_stock_check.invalidateViews(); + } + }); + } + + JourneyPlan jcp; + + private void validateUIData() { + preferences = PrefHelper.getPrefs(context); + counter_id = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + username = preferences.getString(CommonString.KEY_USERNAME, ""); + Toolbar toolbar = findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + if (!CommonFunctions.isTablet(context)) { + toolbar.setTitleTextAppearance(context, R.style.changestext_sizefor_mobile); + } + Objects.requireNonNull(getSupportActionBar()).setHomeButtonEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + setTitle("Stock Check - " + visit_date); + sku_spin = (Spinner) findViewById(R.id.sku_spin); + brand_spin = (Spinner) findViewById(R.id.stock_brand_spin); + sub_axe_spin = (Spinner) findViewById(R.id.sub_axe_spin); + axe_spin = (Spinner) findViewById(R.id.axe_spin); + lvExp_stock_check = (ExpandableListView) findViewById(R.id.lvExp_stock_check); + fab_save = (FloatingActionButton) findViewById(R.id.save_fab); + fab_draft = (FloatingActionButton) findViewById(R.id.draft_fab); + et_search = (EditText) findViewById(R.id.et_search); + img_scan = (ImageView) findViewById(R.id.img_scan); + img_unfilled = (ImageView) findViewById(R.id.img_unfilled); + img_clear_subaxe = (ImageView) findViewById(R.id.img_clear_subaxe); + ImageView img_filter = (ImageView) findViewById(R.id.img_filter); + recSubAxe = (RecyclerView) findViewById(R.id.rec_subaxe); + fab_save.setOnClickListener(this); + fab_draft.setOnClickListener(this); + db.open(); + img_filter.setOnClickListener(v -> sheetView = showFilterBottomSheet()); + et_search.addTextChangedListener(new TextWatcher() { + @Override + public void beforeTextChanged(CharSequence s, int start, int count, int after) { + + } + + @Override + public void onTextChanged(CharSequence s, int start, int before, int count) { + String text = s.toString(); + if (text.equals("")) { + if (lvExp_stock_check != null && listAdapter != null) { + lvExp_stock_check.setAdapter(listAdapter); + listAdapter.notifyDataSetChanged(); + } + } else { + lvExp_stock_check.invalidate(); + setSearchFilter(listAdapter.get_listDataHeader(), text, listAdapter.get_listDataChild()); + } + } + + @Override + public void afterTextChanged(Editable s) { + String text = s.toString(); + } + }); + + img_scan.setOnClickListener(this); + ///changes icon + img_unfilled.setOnClickListener(this); + img_clear_subaxe.setOnClickListener(this); + db.open(); + String status = db.getStatus(CommonString.KEY_SaleableStatus, counter_id); + //if regular stock need to be captured after First stock capture + if (status != null && !status.equals("") && status.equalsIgnoreCase("Complete")) { + fab_save.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.save_icon)); + regularStockFlag = true; + fab_draft.hide(); + } + } + + @SuppressLint("NotifyDataSetChanged") + View showFilterBottomSheet() { + final CardView cardSignature, cardBrand, cardSubBrand, cardReference; + final BottomSheetDialog mBottomSheetDialog = new BottomSheetDialog(this); + @SuppressLint("InflateParams") final View sheetView = getLayoutInflater().inflate(R.layout.filter_bottom_sheet, null); + mBottomSheetDialog.setContentView(sheetView); + View bottomSheet = mBottomSheetDialog.getWindow().findViewById(com.google.android.material.R.id.design_bottom_sheet); + if (bottomSheet != null) { + bottomSheet.setBackgroundResource(android.R.color.transparent); + } + mBottomSheetDialog.setCancelable(false); + final RecyclerView recBrand = sheetView.findViewById(R.id.rec_brand); + ImageView img_cancel = sheetView.findViewById(R.id.img_cancel); + TextView tv_clear_filter = sheetView.findViewById(R.id.tv_clear_filter); + recBrand.setAdapter(new ValueAdapter(context, signatureList, CommonString.Signature)); + recBrand.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, true)); + cardSignature = sheetView.findViewById(R.id.card_signature); + cardBrand = sheetView.findViewById(R.id.card_brand); + cardSubBrand = sheetView.findViewById(R.id.card_sub_brand); + cardReference = sheetView.findViewById(R.id.card_reference); + cardSignature.setOnClickListener(this); + cardBrand.setOnClickListener(this); + cardSubBrand.setOnClickListener(this); + cardReference.setOnClickListener(this); + cardSignature.setCardBackgroundColor(getResources().getColor(R.color.dashboard_ach)); + if (selectedSignature != null) { + (sheetView.findViewById(R.id.img_filter_signature)).setVisibility(View.VISIBLE); + } + if (selectedBrand != null) { + (sheetView.findViewById(R.id.img_filter_brand)).setVisibility(View.VISIBLE); + } + if (selectedSubBrand != null) { + (sheetView.findViewById(R.id.img_filter_sub_brand)).setVisibility(View.VISIBLE); + } + if (selectedReference != null) { + (sheetView.findViewById(R.id.img_filter_reference)).setVisibility(View.VISIBLE); + } + + img_cancel.setOnClickListener(v -> mBottomSheetDialog.cancel()); + + tv_clear_filter.setOnClickListener(v -> { + clearFilters(); + cardSignature.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background)); + cardBrand.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background)); + cardSubBrand.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background)); + cardReference.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background)); + ValueAdapter adapter = (ValueAdapter) recBrand.getAdapter(); + assert adapter != null; + String type = adapter.getType(); + ArrayList list = new ArrayList<>(); + switch (type) { + case CommonString.Signature: + list = signatureList; + break; + case CommonString.Brand: + list = brandList; + break; + case CommonString.SubBrand: + list = subBrandList; + break; + case CommonString.Reference: + list = referenceList; + break; + } + recBrand.setLayoutManager(new LinearLayoutManager(StockCheckActivity.this, LinearLayoutManager.VERTICAL, true)); + recBrand.setAdapter(new ValueAdapter(context, list, CommonString.Signature)); + recBrand.getAdapter().notifyDataSetChanged(); + + }); + + mBottomSheetDialog.show(); + return sheetView; + } + + private void prepareListData() { + db.open(); + jcp = db.getJCP(); + if (jcp != null) { + db.open(); + listSubAxe = db.getSubAxe(jcp.getCounterGroupId().toString(), true); + } else { + db.open(); + listSubAxe = db.getSubAxe("1", true); + } + + //inserted data + listDataHeader = new ArrayList<>(); + listDataChild = new HashMap<>(); + db.open(); + jcp = db.getJCP(); + if (jcp != null) { + db.open(); + listDataHeader = db.getFunctionName(jcp.getCounterGroupId().toString(), selectedSubAxe, regularStockFlag, CommonString.KEY_SaleableBalance, counter_id, visit_date); + } else { + db.open(); + listDataHeader = db.getStockSignatureBrandSubBrandReference("1", false, regularStockFlag, CommonString.KEY_SaleableBalance); + } + + jcp = db.getJCP(); + if (jcp != null) { + db.open(); + brandList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "BrandName", false, selectedSubAxe); + subBrandList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "SubBrandName", false, selectedSubAxe); + referenceList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "ReferenceName", false, selectedSubAxe); + signatureList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "SignatureName", false, selectedSubAxe); + } else { + db.open(); + brandList = db.getsub_brand_name("1", "BrandName", false, selectedSubAxe); + subBrandList = db.getsub_brand_name("1", "SubBrandName", false, selectedSubAxe); + referenceList = db.getsub_brand_name("1", "ReferenceName", false, selectedSubAxe); + signatureList = db.getsub_brand_name("1", "SignatureName", false, selectedSubAxe); + + } + if (listDataHeader != null && !listDataHeader.isEmpty()) { + for (int i = 0; i < listDataHeader.size(); i++) { + JourneyPlan jcp = db.getJCP(); + if (jcp != null) { + db.open(); + childStockList = db.getDefaultStockOnFunctionData(listDataHeader.get(i).getNuanceName(), CommonString.KEY_SaleableBalance, counter_id, regularStockFlag, visit_date); + } else { + db.open(); + childStockList = db.getDefaultStockOnFunctionData(listDataHeader.get(i).getNuanceName(), CommonString.KEY_SaleableBalance, counter_id, regularStockFlag, visit_date); + } + listDataChild.put(listDataHeader.get(i), childStockList); // Header, Child data + } + } + } + + void setFilterSelected(View sheetView, String type) { + CardView cardSignature, cardBrand, cardSubBrand, cardReference; + cardSignature = sheetView.findViewById(R.id.card_signature); + cardBrand = sheetView.findViewById(R.id.card_brand); + cardSubBrand = sheetView.findViewById(R.id.card_sub_brand); + cardReference = sheetView.findViewById(R.id.card_reference); + + cardSignature.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background)); + cardBrand.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background)); + cardSubBrand.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background)); + cardReference.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background)); + switch (type) { + case CommonString.Signature: + cardSignature.setCardBackgroundColor(getResources().getColor(R.color.dashboard_ach)); + break; + case CommonString.Brand: + cardBrand.setCardBackgroundColor(getResources().getColor(R.color.dashboard_ach)); + break; + case CommonString.SubBrand: + cardSubBrand.setCardBackgroundColor(getResources().getColor(R.color.dashboard_ach)); + break; + case CommonString.Reference: + cardReference.setCardBackgroundColor(getResources().getColor(R.color.dashboard_ach)); + break; + } + } + + @SuppressLint({"NonConstantResourceId", "NotifyDataSetChanged", "UseCompatLoadingForDrawables"}) + @Override + public void onClick(View view) { + int id = view.getId(); + + if (id == R.id.save_fab) { + ////for final submit stock using regular stock flag + lvExp_stock_check.clearFocus(); + lvExp_stock_check.invalidateViews(); + if (regularStockFlag) { + if (validate_regular_stock()) { + dialogFinalSubmit(); + } + } else { + dialogFinalSubmit(); + } + + } else if (id == R.id.draft_fab) { + try { + ///save draft stock.... + lvExp_stock_check.clearFocus(); + lvExp_stock_check.invalidateViews(); + for (int i = 0; i < listAdapter.getGroupCount(); i++) + lvExp_stock_check.collapseGroup(i); + new InsertAsync().execute(false); + } catch (Exception e) { + throw new RuntimeException(e); + } + } else if (id == R.id.card_signature) { + RecyclerView recSignature = sheetView.findViewById(R.id.rec_brand); + recSignature.setAdapter(new ValueAdapter(context, signatureList, CommonString.Signature)); + recSignature.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, true)); + setFilterSelected(sheetView, CommonString.Signature); + } else if (id == R.id.card_brand) { + + RecyclerView recBrand = sheetView.findViewById(R.id.rec_brand); + recBrand.setAdapter(new ValueAdapter(context, brandList, CommonString.Brand)); + recBrand.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, true)); + setFilterSelected(sheetView, CommonString.Brand); + } else if (id == R.id.card_sub_brand) { + RecyclerView recSubBrand = sheetView.findViewById(R.id.rec_brand); + recSubBrand.setAdapter(new ValueAdapter(context, subBrandList, CommonString.SubBrand)); + recSubBrand.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, true)); + Objects.requireNonNull(recSubBrand.getAdapter()).notifyDataSetChanged(); + setFilterSelected(sheetView, CommonString.SubBrand); + } else if (id == R.id.card_reference) { + + RecyclerView recReference = sheetView.findViewById(R.id.rec_brand); + recReference.setAdapter(new ValueAdapter(context, referenceList, CommonString.Reference)); + recReference.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, true)); + setFilterSelected(sheetView, CommonString.Reference); + } else if (id == R.id.img_scan) { + + if (flagScan) { + openScanner(); + } else { + img_scan.setImageDrawable(getResources().getDrawable(R.mipmap.barcode_icon)); + flagScan = true; + et_search.setText(""); + } + + } else if (id == R.id.img_unfilled) { + setUnFilledFilter(listAdapter.get_listDataHeader(), listAdapter.get_listDataChild()); + } else if (id == R.id.img_clear_subaxe) { + et_search.setText(""); + listAdapter = new ExpandableListAdapter(context, listDataHeader, listDataChild); + lvExp_stock_check.setAdapter(listAdapter); + listAdapter.notifyDataSetChanged(); + //setExpandableDataForSubAxe(current.getSubAxeName()); + + selectedSubAxe = ""; + subAxeValueAdapter.notifyDataSetChanged(); + + //clear filters also + selectedSignature = null; + selectedBrand = null; + selectedSubBrand = null; + selectedReference = null; + db.open(); + brandList = db.getsub_brand_name(counterGroupId, "BrandName", false, selectedSubAxe); + subBrandList = db.getsub_brand_name(counterGroupId, "SubBrandName", false, selectedSubAxe); + referenceList = db.getsub_brand_name(counterGroupId, "ReferenceName", false, selectedSubAxe); + signatureList = db.getsub_brand_name(counterGroupId, "SignatureName", false, selectedSubAxe); + } + } + + public void uploadData(boolean finalFlag) { + SaleableGetterSetter stock = new SaleableGetterSetter(); + ArrayList data = new ArrayList<>(); + if (listDataHeader != null && !listDataHeader.isEmpty()) { + for (int i = 0; i < listDataHeader.size(); i++) { + List list = listDataChild.get(listDataHeader.get(i)); + for (int j = 0; j < Objects.requireNonNull(list).size(); j++) { + //for final - complete data upload + if (finalFlag) { + list.get(j).setImagePath(listDataHeader.get(i).getImagePath()); + data.add(list.get(j)); + } else { + if (list.get(j).isSelected()) { + list.get(j).setImagePath(listDataHeader.get(i).getImagePath()); + data.add(list.get(j)); + } + } + } + } + } + if (data.size() > 0) { + stock.setProductList(data); + String uuid = CommonFunctions.getUUID(context); + stock.setTransactionId(uuid); + db.open(); + ////changes by jeevan insert transaction for future use and handle master transaction + if (regularStockFlag) { + db.open(); + db.insertStockTransactionMasterData(counter_id, visit_date, username, CommonString.SALEABLE, stock, "Regular_Stock"); + } else { + if (finalFlag) { + db.open(); + db.insertStockTransactionMasterData(counter_id, visit_date, username, CommonString.SALEABLE, stock, "FirstTime_Stock_Comp"); + } else { + db.open(); + db.insertStockTransactionMasterData(counter_id, visit_date, username, CommonString.SALEABLE, stock, "FirstTime_Stock_Draft"); + } + } + + dialog.cancel(); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + StockCheckActivity.this.finish(); + CommonFunctions.call_upload(context); + } + } + + + public ArrayList filterListForSignature(List originalList, String text) { + ArrayList filterList = new ArrayList<>(); + for (ProductMaster object : originalList) { + if (object.getSignatureName().equalsIgnoreCase(text)) { + filterList.add(object); + } + } + + return filterList; + } + + public ArrayList filterListForBrand(List originalList, String text) { + ArrayList filterList = new ArrayList<>(); + for (ProductMaster object : originalList) { + if (object.getBrandName().equalsIgnoreCase(text) && (selectedSignature == null || object.getSignatureName().equalsIgnoreCase(selectedSignature.getBrandName()))) { + filterList.add(object); + } + } + return filterList; + } + + public ArrayList filterListForSubBrand(List originalList, String text) { + ArrayList filterList = new ArrayList<>(); + for (ProductMaster object : originalList) { + if (object.getSubBrandName().equalsIgnoreCase(text) && (selectedSignature == null || object.getSignatureName().equalsIgnoreCase(selectedSignature.getBrandName())) && (selectedBrand == null || object.getBrandName().equalsIgnoreCase(selectedBrand.getBrandName()))) { + filterList.add(object); + } + } + + return filterList; + } + + public ArrayList filterListForReference(List originalList, String text) { + ArrayList filterList = new ArrayList<>(); + for (ProductMaster object : originalList) { + if (object.getReferenceName().equalsIgnoreCase(text) && (selectedSignature == null || object.getSignatureName().equalsIgnoreCase(selectedSignature.getBrandName())) && (selectedBrand == null || object.getBrandName().equalsIgnoreCase(selectedBrand.getBrandName())) && (selectedSubBrand == null || object.getSubBrandName().equalsIgnoreCase(selectedSubBrand.getBrandName()))) { + filterList.add(object); + } + } + + return filterList; + } + + public ArrayList filterListForAxe(List originalList, String text, String brandName) { + ArrayList filterList = new ArrayList<>(); + for (ProductMaster object : originalList) { + if (object.getAxeName().equalsIgnoreCase(text) && (brandName.equals("") || object.getBrandName().equalsIgnoreCase(brandName))) { + filterList.add(object); + } + } + return filterList; + } + + public ArrayList filterListForSubAxe(List originalList, String text, String brandName, String axeName) { + ArrayList filterList = new ArrayList<>(); + for (ProductMaster object : originalList) { + if (object.getSubAxeName().equalsIgnoreCase(text) && (brandName.equals("") || object.getBrandName().equalsIgnoreCase(brandName)) && (axeName.equals("") || object.getAxeName().equalsIgnoreCase(axeName))) { + filterList.add(object); + } + } + return filterList; + } + + + public class ExpandableListAdapter extends BaseExpandableListAdapter { + private final Context _context; + private final List _listDataHeader; + private final HashMap> _listDataChild; + + public ExpandableListAdapter(Context context, List listDataHeader, HashMap> listChildData) { + this._context = context; + this._listDataHeader = listDataHeader; + this._listDataChild = listChildData; + } + + public HashMap> get_listDataChild() { + return _listDataChild; + } + + public List get_listDataHeader() { + return _listDataHeader; + } + + @Override + public Object getChild(int groupPosition, int childPosititon) { + return this._listDataChild.get(this._listDataHeader.get(groupPosition)).get(childPosititon); + } + + @Override + public long getChildId(int groupPosition, int childPosition) { + return childPosition; + } + + @SuppressLint("SetTextI18n") + @Override + public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { + + final ProductMaster childText = (ProductMaster) getChild(groupPosition, childPosition); + ViewHolder holder = null; + if (convertView == null) { + LayoutInflater infalInflater = (LayoutInflater) this._context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); + convertView = infalInflater.inflate(R.layout.item_stock_layout, null); + holder = new ViewHolder(); + holder.cardView = convertView.findViewById(R.id.card_view); + holder.ed_Stock = convertView.findViewById(R.id.ed_Stock); + holder.mrp = convertView.findViewById(R.id.mrp); + holder.stock_img_plus = convertView.findViewById(R.id.stock_img_plus); + holder.stock_img_minus = convertView.findViewById(R.id.stock_img_minus); + holder.reasonSpinner = convertView.findViewById(R.id.reason_spinner); + holder.reasonLayout = convertView.findViewById(R.id.reason_layout); + holder.et_stock = convertView.findViewById(R.id.et_stock); + convertView.setTag(holder); + } else { + holder = (ViewHolder) convertView.getTag(); + } + + + TextView txtListChild = convertView.findViewById(R.id.lblListItem); + txtListChild.setText(childText.getProductName() + " (MRP - ₹ " + childText.getMrp() + ")"); + final ViewHolder finalHolder = holder; + holder.stock_img_plus.setOnClickListener(v -> { + ((ExpandableListAdapter) lvExp_stock_check.getExpandableListAdapter()).notifyDataSetChanged(); + if (!regularStockFlag) { + String stot = finalHolder.et_stock.getText().toString().trim().replaceFirst("^0+(?!$)", ""); + if (!stot.equals("")) { + int st = Integer.parseInt(stot); + childText.setStock(st); + } + } + + int stock = childText.getStock(); + int receivedStock = childText.getStock_receive(); + ++stock; + + if (regularStockFlag) { + if (receivedStock >= stock) { + childText.setStock(stock); + isDataAdded = true; + childText.setSelected(true); + if (receivedStock == stock) { + finalHolder.reasonLayout.setVisibility(View.GONE); + finalHolder.reasonSpinner.setSelection(0); + childText.setReasonId(0); + } + } else { + AlertandMessages.showToastMsg(context, "Stock cannot be greater than Received Stock"); + } + } else { + if (receivedStock == -1) { + childText.setStock_receive(0); + } + childText.setStock(stock); + isDataAdded = true; + childText.setSelected(true); + } + + }); + + + holder.stock_img_minus.setOnClickListener(v -> { + ((ExpandableListAdapter) lvExp_stock_check.getExpandableListAdapter()).notifyDataSetChanged(); + if (!regularStockFlag) { + String stot = finalHolder.et_stock.getText().toString().trim().replaceFirst("^0+(?!$)", ""); + if (!stot.equals("")) { + int st = Integer.parseInt(stot); + childText.setStock(st); + } + } + int stock = childText.getStock(); + int receivedStock = childText.getStock_receive(); + --stock; + if (stock >= 0) { + if (regularStockFlag && stock < receivedStock) { + finalHolder.reasonLayout.setVisibility(View.VISIBLE); + } + + childText.setStock(stock); + isDataAdded = true; + childText.setSelected(true); + + } else { + AlertandMessages.showToastMsg(context, "Stock cannot be less than 0"); + } + + }); + + holder.et_stock.setOnFocusChangeListener((v, hasFocus) -> { + final EditText caption = (EditText) v; + String stock = caption.getText().toString().replaceFirst("^0+(?!$)", ""); + if (!stock.equals("")) { + childText.setStock(Integer.parseInt(stock)); + isDataAdded = true; + childText.setSelected(true); + } else { + childText.setStock(0); + } + }); + + ArrayList reasonList = new ArrayList<>(); + db.open(); + reasonList = db.getReasonData(true); + holder.reasonSpinner.setAdapter(new ReasonSpinnerAdapter(_context, R.layout.spinner_text_view, reasonList)); + final ArrayList finalReasonList = reasonList; + holder.reasonSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { + @Override + public void onItemSelected(AdapterView adapterView, View view, int pos, long l) { + if (pos != 0) { + MasterNonStockReason obj = finalReasonList.get(pos); + childText.setReasonId(obj.getReasonId()); + } else { + childText.setReasonId(0); + } + } + + @Override + public void onNothingSelected(AdapterView adapterView) { + + } + }); + + if (!finalReasonList.isEmpty()) { + for (int i = 0; i < finalReasonList.size(); i++) { + if (finalReasonList.get(i).getReasonId() == childText.getReasonId()) { + holder.reasonSpinner.setSelection(i); + break; + } + } + } + + int stock = childText.getStock(); + if (!childText.isSelected() && childText.getStock() == 0) { + stock = childText.getStock_receive(); + childText.setStock(stock); + } + + + if (childText.getStock() < childText.getStock_receive()) { + if (regularStockFlag) { + finalHolder.reasonLayout.setVisibility(View.VISIBLE); + finalHolder.reasonLayout.setId(childPosition); + } + } else { + finalHolder.reasonLayout.setVisibility(View.GONE); + finalHolder.reasonLayout.setId(childPosition); + } + + if (regularStockFlag) { + holder.ed_Stock.setText(stock + ""); + holder.ed_Stock.setId(childPosition); + + holder.et_stock.setVisibility(View.GONE); + holder.ed_Stock.setVisibility(View.VISIBLE); + } else { + if (stock == -1) { + holder.et_stock.setText(""); + } else { + holder.et_stock.setText(stock + ""); + } + + holder.et_stock.setId(childPosition); + + holder.ed_Stock.setVisibility(View.GONE); + holder.et_stock.setVisibility(View.VISIBLE); + } + + + holder.mrp.setText(" MRP = " + childText.getMrp() + ""); + holder.mrp.setId(childPosition); + + return convertView; + } + + @Override + public int getChildrenCount(int groupPosition) { + return this._listDataChild.get(this._listDataHeader.get(groupPosition)).size(); + } + + @Override + public Object getGroup(int groupPosition) { + return this._listDataHeader.get(groupPosition); + } + + @Override + public int getGroupCount() { + return this._listDataHeader.size(); + } + + @Override + public long getGroupId(int groupPosition) { + return groupPosition; + } + + @SuppressLint("UseCompatLoadingForDrawables") + @Override + public View getGroupView(final int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { + final ProductMaster headerTitle = (ProductMaster) getGroup(groupPosition); + if (convertView == null) { + + LayoutInflater infalInflater = (LayoutInflater) this._context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); + convertView = infalInflater.inflate(R.layout.list_group_stock_entry, null); + } + TextView lblListHeader = (TextView) convertView.findViewById(R.id.lblListHeader); + ImageView stock_cam = (ImageView) convertView.findViewById(R.id.stock_cam); + + stock_cam.setOnClickListener(v -> { + groupPositionGlobal = groupPosition; + globalHeaderObject = headerTitle; + _pathforcheck = counter_id + "_stock_check_img_" + visit_date.replace("/", "") + "_" + getCurrentTime().replace(":", "") + ".jpg"; + _path = CommonString.getImagesFolder(context) + _pathforcheck; + CommonFunctions.startAnncaCameraActivity(StockCheckActivity.this, _path, null, false, CommonString.CAMERA_FACE_REAR); + }); + + if (headerTitle.getImagePath().equals("")) { + stock_cam.setImageDrawable(getResources().getDrawable(R.mipmap.camera)); + } else { + stock_cam.setImageDrawable(getResources().getDrawable(R.mipmap.camera_tick)); + } + + lblListHeader.setText(headerTitle.getNuanceName()); + if (!checkflag) { + if (checkHeaderArray.contains(groupPosition)) { + lblListHeader.setBackgroundColor(getResources().getColor(R.color.red)); + } else { + lblListHeader.setBackgroundColor(getResources().getColor(R.color.bright_red)); + } + + } else { + lblListHeader.setBackgroundColor(getResources().getColor(R.color.bright_red)); + } + + return convertView; + } + + @Override + public boolean hasStableIds() { + return false; + } + + @Override + public boolean isChildSelectable(int groupPosition, int childPosition) { + return true; + } + } + + public class ViewHolder { + TextView ed_Stock, mrp; + Button stock_img_plus, stock_img_minus; + CardView cardView; + Spinner reasonSpinner; + LinearLayout reasonLayout; + EditText et_stock; + } + + + public void setFilter(int filterType) { + if (filterType == FILTER_FOR_SIGNATURE) { + listAdapter = new ExpandableListAdapter(context, filterListForSignature(listDataHeader, selectedSignature.getBrandName()), listDataChild); + } else if (filterType == FILTER_FOR_BRAND) { + listAdapter = new ExpandableListAdapter(context, filterListForBrand(listDataHeader, selectedBrand.getBrandName()), listDataChild); + } else if (filterType == FILTER_FOR_SUB_BRAND) { + listAdapter = new ExpandableListAdapter(context, filterListForSubBrand(listDataHeader, selectedSubBrand.getBrandName()), listDataChild); + } else if (filterType == FILTER_FOR_REFERENCE) { + listAdapter = new ExpandableListAdapter(context, filterListForReference(listDataHeader, selectedReference.getBrandName()), listDataChild); + } else if (filterType == FILTER_FOR_AXE) { + listAdapter = new ExpandableListAdapter(context, filterListForAxe(listDataHeader, axeName, brandName), listDataChild); + } else if (filterType == FILTER_FOR_SUBAXE) { + listAdapter = new ExpandableListAdapter(context, filterListForSubAxe(listDataHeader, subAxeName, brandName, axeName), listDataChild); + } else { + listAdapter = new ExpandableListAdapter(context, filterListForSubAxe(listDataHeader, selectedSubAxe), listDataChild); + } + + lvExp_stock_check.setAdapter(listAdapter); + listAdapter.notifyDataSetChanged(); + } + + final int FILTER_FOR_SIGNATURE = 4; + final int FILTER_FOR_SUB_BRAND = 5; + final int FILTER_FOR_REFERENCE = 6; + final int FILTER_FOR_BRAND = 1; + final int FILTER_FOR_AXE = 2; + final int FILTER_FOR_SUBAXE = 3; + final int CLEAR_FILTER = 0; + + public void setSearchFilter(List originalList, String text, HashMap> listDataChild) { + HashMap> filterChildHashMap = new HashMap<>(); + ArrayList filterList = new ArrayList<>(); + for (int i = 0; i < originalList.size(); i++) { + ProductMaster parent = originalList.get(i); + List listChild = listDataChild.get(parent); + List listFilterChild = new ArrayList<>(); + for (int j = 0; j < Objects.requireNonNull(listChild).size(); j++) { + if (listChild.get(j).getProductName().toLowerCase().contains(text.toLowerCase()) || (listChild.get(j).getEanCode() != null && listChild.get(j).getEanCode().contains(text))) { + listFilterChild.add(listChild.get(j)); + } + } + + if (listFilterChild.size() > 0) { + filterList.add(parent); + filterChildHashMap.put(parent, listFilterChild); + } + } + + ExpandableListAdapter listAdapter1 = new ExpandableListAdapter(context, filterList, filterChildHashMap); + lvExp_stock_check.setAdapter(listAdapter1); + for (int i = 0; i < listAdapter1.getGroupCount(); i++) { + lvExp_stock_check.expandGroup(i); + } + + listAdapter1.notifyDataSetChanged(); + } + + boolean isDataAdded = false; + + @Override + public void onBackPressed() { + isChanged(); + } + + void isChanged() { + if (isDataAdded) { + android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(StockCheckActivity.this); + builder.setTitle(R.string.parinaam); + builder.setMessage(getResources().getString(R.string.data_will_be_lost)).setCancelable(false).setPositiveButton(getString(R.string.ok), (dialog, id) -> { + finish(); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + }).setNegativeButton(getString(R.string.cancel), (dialog, which) -> { + dialog.dismiss(); + }); + android.app.AlertDialog alert = builder.create(); + alert.show(); + } else { + super.onBackPressed(); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + } + } + + void dialogFinalSubmit() { + android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(StockCheckActivity.this); + builder.setTitle(R.string.parinaam); + builder.setMessage(getResources().getString(R.string.want_to_final_save)).setCancelable(false).setPositiveButton(getString(R.string.ok), (dialog, id) -> { + show_dialog_for_final_submit(context); + dialog.dismiss(); + }).setNegativeButton(getString(R.string.cancel), (dialog, which) -> dialog.dismiss()); + + android.app.AlertDialog alert = builder.create(); + alert.show(); + } + + private void show_dialog_for_final_submit(final Context context) { + final MultiPurposeDialog final_save_dialog = new MultiPurposeDialog(context); + final_save_dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); + final_save_dialog.setContentView(R.layout.custom_dialog_final_save); + final WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); + lp.copyFrom(Objects.requireNonNull(final_save_dialog.getWindow()).getAttributes()); + lp.width = WindowManager.LayoutParams.MATCH_PARENT; + lp.height = WindowManager.LayoutParams.WRAP_CONTENT; + lp.gravity = Gravity.CENTER; + final_save_dialog.getWindow().setAttributes(lp); + final_save_dialog.setCancelable(false); + + final EditText txt_hint_yes = (EditText) final_save_dialog.findViewById(R.id.txt_hint_yes); + Button btn_cancel = (Button) final_save_dialog.findViewById(R.id.btn_cancel); + Button btn_okay = (Button) final_save_dialog.findViewById(R.id.btn_okay); + + btn_okay.setOnClickListener(v -> { + if (txt_hint_yes.getText().toString().equals("")) { + AlertandMessages.showToastMsg(context, "Please Enter Text"); + } else if (!txt_hint_yes.getText().toString().trim().equalsIgnoreCase("yes")) { + AlertandMessages.showToastMsg(context, "Please Enter 'Yes' Text"); + } else { + try { + for (int i = 0; i < listAdapter.getGroupCount(); i++) + lvExp_stock_check.collapseGroup(i); + + final_save_dialog.dismiss(); + if (regularStockFlag) { + new InsertAsync().execute(false); + } else { + new InsertAsync().execute(true); + } + } catch (Exception e) { + e.fillInStackTrace(); + } + } + }); + + + btn_cancel.setOnClickListener(v -> final_save_dialog.dismiss()); + + final_save_dialog.show(); + } + + public class MultiPurposeDialog extends Dialog { + public MultiPurposeDialog(Context context) { + super(context); + // DIALOG USER_INTERFACE TEMPLATE + WindowManager.LayoutParams wmLayoutParams = Objects.requireNonNull(getWindow()).getAttributes(); + wmLayoutParams.gravity = Gravity.CENTER; + getWindow().setAttributes(wmLayoutParams); + setTitle(null); + setCancelable(false); + setOnCancelListener(null); + LinearLayout layout = new LinearLayout(context); + layout.setOrientation(LinearLayout.VERTICAL); + } + } + + + @SuppressLint("UseCompatLoadingForDrawables") + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + Log.i("MakeMachine", "resultCode: " + resultCode); + if (requestCode == 131) { + switch (resultCode) { + case 0: + Log.i("MakeMachine", "User cancelled"); + break; + + case -1: + if (_pathforcheck != null && !_pathforcheck.equals("")) { + if (new File(CommonString.getImagesFolder(context) + _pathforcheck).exists()) { + convertBitmap(CommonString.getImagesFolder(context) + _pathforcheck); + isDataAdded = true; + globalHeaderObject.setImagePath(_pathforcheck); + groupPositionGlobal = -1; + _pathforcheck = ""; + listAdapter.notifyDataSetChanged(); + } + } + break; + } + } else { + IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data); + switch (resultCode) { + case 0: + break; + case -1: + db.open(); + ArrayList productList = db.getsku_fromproductusing_eancode(result.getContents(), false, visit_date, counter_id, null); + if (productList.isEmpty()) { + db.open(); + productList = db.getsku_fromproductusing_eancode(removeFirstChar(result.getContents()), false, visit_date, counter_id, null); + } + //test("Ean Code", result.getContents()); + if (!productList.isEmpty()) { + flagScan = false; + img_scan.setImageDrawable(getResources().getDrawable(R.mipmap.ok)); + clearFilters(); + setScanFilter(productList); + } else { + AlertandMessages.showToastMsg(context, "Unable To Scan Correct Data. Please Try Again."); + } + + break; + } + } + + super.onActivityResult(requestCode, resultCode, data); + } + + + private class ValueAdapter extends RecyclerView.Adapter { + private final LayoutInflater inflator; + List data; + String type; + + public String getType() { + return type; + } + + private ValueAdapter(Context context, List data, String type) { + inflator = LayoutInflater.from(context); + this.data = data; + this.type = type; + } + + @NonNull + @Override + public ValueAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) { + View view = inflator.inflate(R.layout.item_filter, parent, false); + return new ValueAdapter.MyViewHolder(view); + } + + @SuppressLint("NotifyDataSetChanged") + @RequiresApi(api = Build.VERSION_CODES.M) + @Override + public void onBindViewHolder(final ValueAdapter.MyViewHolder holder, final int position) { + final ProductMaster current = data.get(position); + final boolean[] selected = {false}; + final int[] filterId = {0}; + switch (type) { + case CommonString.Signature: + if (selectedSignature != null && selectedSignature == current) { + selected[0] = true; + } + + break; + + case CommonString.Brand: + if (selectedBrand != null && selectedBrand == current) { + selected[0] = true; + } + + break; + + case CommonString.SubBrand: + if (selectedSubBrand != null && selectedSubBrand == current) { + selected[0] = true; + } + + break; + + case CommonString.Reference: + if (selectedReference != null && selectedReference == current) { + selected[0] = true; + } + + break; + } + + holder.tv_item.setText(CommonFunctions.capitalizeFirstLetter(current.getBrandName())); + + holder.card.setOnClickListener(v -> { + + et_search.setText(""); + + switch (type) { + case CommonString.Signature: + selectedSignature = current; + filterId[0] = R.id.img_filter_signature; + //clear other sub filters-- + selectedBrand = null; + selectedSubBrand = null; + selectedReference = null; + + (sheetView.findViewById(R.id.img_filter_brand)).setVisibility(View.GONE); + (sheetView.findViewById(R.id.img_filter_sub_brand)).setVisibility(View.GONE); + (sheetView.findViewById(R.id.img_filter_reference)).setVisibility(View.GONE); + + setBottomFilter(listAdapter.get_listDataHeader(), current.getBrandName(), listAdapter.get_listDataChild(), CommonString.Signature); + db.open(); + brandList = db.getSubBrandOrReference(counterGroupId, "BrandName", current.getBrandName(), null, null, false, selectedSubAxe); + db.open(); + subBrandList = db.getSubBrandOrReference(counterGroupId, "SubBrandName", current.getBrandName(), null, null, false, selectedSubAxe); + db.open(); + referenceList = db.getSubBrandOrReference(counterGroupId, "ReferenceName", current.getBrandName(), null, null, false, selectedSubAxe); + + break; + case CommonString.Brand: + selectedBrand = current; + filterId[0] = R.id.img_filter_brand; + + //clear other sub filters-- + selectedSubBrand = null; + selectedReference = null; + + (sheetView.findViewById(R.id.img_filter_sub_brand)).setVisibility(View.GONE); + (sheetView.findViewById(R.id.img_filter_reference)).setVisibility(View.GONE); + //-- + + setBottomFilter(listAdapter.get_listDataHeader(), current.getBrandName(), listAdapter.get_listDataChild(), CommonString.Brand); + //setFilter(FILTER_FOR_BRAND); + db.open(); + subBrandList = db.getSubBrandOrReference(counterGroupId, "SubBrandName", "", current.getBrandName(), null, false, selectedSubAxe); + db.open(); + referenceList = db.getSubBrandOrReference(counterGroupId, "ReferenceName", "", current.getBrandName(), null, false, selectedSubAxe); + + break; + case CommonString.SubBrand: + selectedSubBrand = current; + filterId[0] = R.id.img_filter_sub_brand; + + //clear other sub filters-- + selectedReference = null; + + (sheetView.findViewById(R.id.img_filter_reference)).setVisibility(View.GONE); + //-- + + setBottomFilter(listAdapter.get_listDataHeader(), current.getBrandName(), listAdapter.get_listDataChild(), CommonString.SubBrand); + //setFilter(FILTER_FOR_SUB_BRAND); + db.open(); + referenceList = db.getSubBrandOrReference(counterGroupId, "ReferenceName", "", null, current.getBrandName(), false, selectedSubAxe); + break; + case CommonString.Reference: + selectedReference = current; + filterId[0] = R.id.img_filter_reference; + + setBottomFilter(listAdapter.get_listDataHeader(), current.getBrandName(), listAdapter.get_listDataChild(), CommonString.Reference); + //setFilter(FILTER_FOR_REFERENCE); + break; + } + + RecyclerView recSubBrand = sheetView.findViewById(R.id.rec_brand); + Objects.requireNonNull(recSubBrand.getAdapter()).notifyDataSetChanged(); + //show filter icon on filter selected + (sheetView.findViewById(filterId[0])).setVisibility(View.VISIBLE); + }); + + if (selected[0]) { + holder.card.setCardBackgroundColor(getColor(R.color.dashboard_ach)); + } else { + holder.card.setCardBackgroundColor(getColor(R.color.grey_dark_background)); + } + } + + @Override + public int getItemCount() { + return data.size(); + } + + class MyViewHolder extends RecyclerView.ViewHolder { + TextView tv_item; + CardView card; + + public MyViewHolder(View itemView) { + super(itemView); + tv_item = (TextView) itemView.findViewById(R.id.tv_item); + card = (CardView) itemView.findViewById(R.id.item_card); + + } + } + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + getMenuInflater().inflate(R.menu.filter_menu_stock, menu); + return super.onCreateOptionsMenu(menu); + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // Handle action bar item clicks here. The action bar will + // automatically handle clicks on the Home/Up button, so long + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + + if (id == android.R.id.home) { + isChanged(); + } else if (id == R.id.filter_data) { + sheetView = showFilterBottomSheet(); + + } else if (id == R.id.filled_history) { + startActivity(new Intent(context, FilledRegularStockDataActivity.class).putExtra(CommonString.KEY_ACTIVITY, "StockCheck")); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + } + + return super.onOptionsItemSelected(item); + } + + private void openScanner() { + IntentIntegrator intentIntegrator = new IntentIntegrator((Activity) context); + intentIntegrator.setBeepEnabled(true); + intentIntegrator.setOrientationLocked(false); + intentIntegrator.setPrompt("Scan the barcode or QR code to get the data"); + intentIntegrator.setCaptureActivity(CaptureActivity.class); + intentIntegrator.initiateScan(); + } + + + public void setScanFilter(List scanList) { + HashMap> filterChildHashMap = new HashMap<>(); + ArrayList filterList = new ArrayList<>(); + for (int i = 0; i < listDataHeader.size(); i++) { + ProductMaster parent = listDataHeader.get(i); + List listChild = listDataChild.get(parent); + List listFilterChild = new ArrayList<>(); + for (int j = 0; j < Objects.requireNonNull(listChild).size(); j++) { + if (containsProduct(scanList, listChild.get(j))) { + listFilterChild.add(listChild.get(j)); + } + } + + if (listFilterChild.size() > 0) { + filterList.add(parent); + filterChildHashMap.put(parent, listFilterChild); + + } + + } + + ExpandableListAdapter listAdapter1 = new ExpandableListAdapter(context, filterList, filterChildHashMap); + lvExp_stock_check.setAdapter(listAdapter1); + for (int i = 0; i < listAdapter1.getGroupCount(); i++) { + lvExp_stock_check.expandGroup(i); + } + listAdapter1.notifyDataSetChanged(); + } + + boolean containsProduct(List scanList, ProductMaster obj) { + boolean contains = false; + for (int i = 0; i < scanList.size(); i++) { + if (scanList.get(i).getProductId().equals(obj.getProductId())) { + contains = true; + break; + } + } + + return contains; + } + + void clearFilters() { + et_search.setText(""); + + setFilter(CLEAR_FILTER); + selectedSignature = null; + selectedBrand = null; + selectedSubBrand = null; + selectedReference = null; + + if (sheetView != null) { + (sheetView.findViewById(R.id.img_filter_signature)).setVisibility(View.GONE); + (sheetView.findViewById(R.id.img_filter_brand)).setVisibility(View.GONE); + (sheetView.findViewById(R.id.img_filter_sub_brand)).setVisibility(View.GONE); + (sheetView.findViewById(R.id.img_filter_reference)).setVisibility(View.GONE); + } + db.open(); + brandList = db.getsub_brand_name(counterGroupId, "BrandName", false, selectedSubAxe); + subBrandList = db.getsub_brand_name(counterGroupId, "SubBrandName", false, selectedSubAxe); + referenceList = db.getsub_brand_name(counterGroupId, "ReferenceName", false, selectedSubAxe); + signatureList = db.getsub_brand_name(counterGroupId, "SignatureName", false, selectedSubAxe); + } + + private Dialog dialog; + ProgressBar pb; + + class LoadAsync extends AsyncTask { + + @Override + protected void onPreExecute() { + + dialog = new Dialog(context); + dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); + Objects.requireNonNull(dialog.getWindow()).setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT)); + dialog.setContentView(R.layout.circular_progress_bar); + pb = (ProgressBar) dialog.findViewById(R.id.progressBar1); + dialog.setCancelable(false); + dialog.show(); + super.onPreExecute(); + } + + @Override + protected Void doInBackground(Void... voids) { + prepareListData(); + return null; + } + + @SuppressLint("NotifyDataSetChanged") + @Override + protected void onPostExecute(Void aVoid) { + dialog.cancel(); + recSubAxe.setLayoutManager(new GridLayoutManager(StockCheckActivity.this, 3)); + subAxeValueAdapter = new SubAxeValueAdapter(context, listSubAxe, CommonString.Signature); + recSubAxe.setAdapter(subAxeValueAdapter); + Objects.requireNonNull(recSubAxe.getAdapter()).notifyDataSetChanged(); + listAdapter = new ExpandableListAdapter(context, listDataHeader, listDataChild); + lvExp_stock_check.setAdapter(listAdapter); + //lvExp_stock_check.expandGroup(0); + db.open(); + JourneyPlan jcp = db.getJCP(); + if (jcp != null) { + counterGroupId = jcp.getCounterGroupId().toString(); + } else { + counterGroupId = "1"; + } + + super.onPostExecute(aVoid); + } + } + + + private void UploadStockRecursive(final String status, final int startIndex, final int endIndex, final SaleableGetterSetter stock) { + try { + JSONArray topUpArray = new JSONArray(); + String key = "SaleableData"; + int mid = 0; + if (stock != null) { + if (jcp != null) { + mid = jcp.getMID(); + } + for (int j = startIndex; j < endIndex; j++) { + JSONObject obj = new JSONObject(); + obj.put("ProductId", stock.getProductList().get(j).getProductId()); + obj.put("MID", mid); + obj.put("REASON_ID", stock.getProductList().get(j).getReasonId()); + obj.put("TranId", stock.getTransactionId()); + obj.put("UserId", username); + obj.put("CounterId", counter_id); + //header image + String img = stock.getProductList().get(j).getImagePath(); + if (img == null) { + img = ""; + } + + obj.put("Image", img); + ////for uploaded first time data if status is not null + if (status != null) { + int stk = stock.getProductList().get(j).getStock(); + if (stk == -1) { + stk = 0; + } + obj.put("STOCK", stk); + obj.put("Status", status); + //different key for first time data + key = "SaleableFData"; + } else { + obj.put("STOCK", stock.getProductList().get(j).getStock_receive() - stock.getProductList().get(j).getStock()); + } + + topUpArray.put(obj); + } + } + + JSONObject jsonObject = new JSONObject(); + jsonObject.put("MID", mid); + jsonObject.put("Keys", key); + jsonObject.put("JsonData", topUpArray.toString()); + jsonObject.put("UserId", username); + String jsonString = jsonObject.toString(); + OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(20, TimeUnit.SECONDS).writeTimeout(20, TimeUnit.SECONDS).connectTimeout(20, TimeUnit.SECONDS).build(); + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsonString); + Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build(); + PostApi api = adapter.create(PostApi.class); + Call call = api.getGeotag(jsonData); + call.enqueue(new Callback() { + @Override + public void onResponse(@NonNull Call call, @NonNull Response response) { + assert response.body() != null; + String responseBody = response.body().get("UploadJsonResult").toString(); + String data = null; + if (response.isSuccessful()) { + try { + data = response.body().get("UploadJsonResult").toString(); + if (!data.equals("")) { + data = data.substring(1, data.length() - 1).replace("\\", ""); + if (data.equalsIgnoreCase(CommonString.KEY_SUCCESS)) { + assert stock != null; + if (endIndex < stock.getProductList().size()) { + int startIndex1 = endIndex; + int endIndex1 = 0; + if (startIndex1 + 200 < stock.getProductList().size()) { + endIndex1 = startIndex1 + 200; + } else { + endIndex1 = stock.getProductList().size(); + } + UploadStockRecursive(status, startIndex1, endIndex1, stock); + } else { + db.open(); + db.updateStockTransactionDataStatus(stock.getTransactionId()); + db.updateMasterTransactionDataStatus(stock.getTransactionId()); + dialog.cancel(); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + StockCheckActivity.this.finish(); + } + } + } + } catch (Exception e) { + db.open(); + dialog.cancel(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE + " - " + e.toString() + " - Please Try Again"); + } + } else { + dialog.cancel(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_NO_RESPONSE_SERVER + " - Please Try Again"); + } + } + + @Override + public void onFailure(@NonNull Call call, @NonNull Throwable t) { + dialog.cancel(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE + " - Please Try Again"); + } + }); + } catch (JSONException e) { + e.fillInStackTrace(); + dialog.cancel(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INVALID_JSON + " - Please Try Again"); + } + } + + + @Override + public void onDestroy() { + if (dialog != null && dialog.isShowing()) { + dialog.dismiss(); + } + super.onDestroy(); + } + + private class SubAxeValueAdapter extends RecyclerView.Adapter { + LayoutInflater inflator; + List data; + String type; + + public String getType() { + return type; + } + + public SubAxeValueAdapter(Context context, List data, String type) { + inflator = LayoutInflater.from(context); + this.data = data; + this.type = type; + } + + @NonNull + @Override + public SubAxeValueAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) { + View view = inflator.inflate(R.layout.item_filter, parent, false); + return new SubAxeValueAdapter.MyViewHolder(view); + } + + @SuppressLint("NotifyDataSetChanged") + @Override + public void onBindViewHolder(final SubAxeValueAdapter.MyViewHolder holder, final int position) { + final ProductMaster current = data.get(position); + holder.tv_item.setText(CommonFunctions.capitalizeFirstLetter(current.getSubAxeName())); + holder.tv_item.setOnClickListener(v -> { + et_search.setText(""); + listAdapter = new ExpandableListAdapter(context, filterListForSubAxe(listDataHeader, current.getSubAxeName()), listDataChild); + lvExp_stock_check.setAdapter(listAdapter); + listAdapter.notifyDataSetChanged(); + current.setSelected(true); + selectedSubAxe = current.getSubAxeName(); + assert subAxeValueAdapter != null; + subAxeValueAdapter.notifyDataSetChanged(); + db.open(); + jcp = db.getJCP(); + if (jcp != null) { + db.open(); + brandList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "BrandName", false, selectedSubAxe); + subBrandList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "SubBrandName", false, selectedSubAxe); + referenceList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "ReferenceName", false, selectedSubAxe); + signatureList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "SignatureName", false, selectedSubAxe); + } else { + db.open(); + brandList = db.getsub_brand_name("1", "BrandName", false, selectedSubAxe); + subBrandList = db.getsub_brand_name("1", "SubBrandName", false, selectedSubAxe); + referenceList = db.getsub_brand_name("1", "ReferenceName", false, selectedSubAxe); + signatureList = db.getsub_brand_name("1", "SignatureName", false, selectedSubAxe); + } + }); + + //if (current.isSelected()) { + if (current.getSubAxeName().equalsIgnoreCase(selectedSubAxe)) { + holder.card.setCardBackgroundColor(getResources().getColor(R.color.dashboard_ach)); + } else { + holder.card.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background)); + } + } + + @Override + public int getItemCount() { + return data.size(); + } + + private class MyViewHolder extends RecyclerView.ViewHolder { + TextView tv_item; + CardView card; + + private MyViewHolder(View itemView) { + super(itemView); + tv_item = (TextView) itemView.findViewById(R.id.tv_item); + card = (CardView) itemView.findViewById(R.id.item_card); + + } + } + } + + public ArrayList filterListForSubAxe(List originalList, String text) { + ArrayList filterList = new ArrayList<>(); + for (ProductMaster object : originalList) { + if (object.getSubAxeName().equalsIgnoreCase(text)) { + filterList.add(object); + } + } + + return filterList; + } + + public void setBottomFilter(List originalList, String text, HashMap> listDataChild, String type) { + HashMap> filterChildHashMap = new HashMap<>(); + ArrayList filterList = new ArrayList<>(); + for (int i = 0; i < originalList.size(); i++) { + ProductMaster parent = originalList.get(i); + List listChild = listDataChild.get(parent); + List listFilterChild = new ArrayList<>(); + for (int j = 0; j < Objects.requireNonNull(listChild).size(); j++) { + switch (type) { + case CommonString.Signature: + if (listChild.get(j).getSignatureName().equalsIgnoreCase(text)) { + listFilterChild.add(listChild.get(j)); + } + break; + case CommonString.Brand: + if (listChild.get(j).getBrandName().equalsIgnoreCase(text)) { + listFilterChild.add(listChild.get(j)); + } + + break; + case CommonString.SubBrand: + if (listChild.get(j).getSubBrandName().equalsIgnoreCase(text)) { + listFilterChild.add(listChild.get(j)); + } + + break; + case CommonString.Reference: + if (listChild.get(j).getReferenceName().equalsIgnoreCase(text)) { + listFilterChild.add(listChild.get(j)); + } + + break; + } + + } + + if (listFilterChild.size() > 0) { + filterList.add(parent); + filterChildHashMap.put(parent, listFilterChild); + + } + + } + + ExpandableListAdapter listAdapter1 = new ExpandableListAdapter(context, filterList, filterChildHashMap); + lvExp_stock_check.setAdapter(listAdapter1); + listAdapter1.notifyDataSetChanged(); + } + + class InsertAsync extends AsyncTask { + boolean flag = false; + + @Override + protected void onPreExecute() { + dialog = new Dialog(context); + dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); + Objects.requireNonNull(dialog.getWindow()).setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT)); + dialog.setContentView(R.layout.circular_progress_bar); + pb = (ProgressBar) dialog.findViewById(R.id.progressBar1); + dialog.setCancelable(false); + dialog.show(); + super.onPreExecute(); + } + + @Override + protected Void doInBackground(Boolean... bool) { + flag = bool[0]; + db.open(); + db.insertStockCapturedData(visit_date, listDataChild, listDataHeader, flag, counter_id); + uploadData(flag); + //validate_spin_ui_data(); + return null; + } + + @Override + protected void onPostExecute(Void aVoid) { + super.onPostExecute(aVoid); + dialog.cancel(); + finish(); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + } + } + + public void setUnFilledFilter(List originalList, HashMap> listDataChild) { + HashMap> filterChildHashMap = new HashMap<>(); + ArrayList filterList = new ArrayList<>(); + for (int i = 0; i < originalList.size(); i++) { + ProductMaster parent = originalList.get(i); + List listChild = listDataChild.get(parent); + List listFilterChild = new ArrayList<>(); + for (int j = 0; j < Objects.requireNonNull(listChild).size(); j++) { + if (listChild.get(j).getStock() == -1) { + listFilterChild.add(listChild.get(j)); + } + } + + if (listFilterChild.size() > 0) { + filterList.add(parent); + filterChildHashMap.put(parent, listFilterChild); + + } + } + + ExpandableListAdapter listAdapter1 = new ExpandableListAdapter(context, filterList, filterChildHashMap); + lvExp_stock_check.setAdapter(listAdapter1); + for (int i = 0; i < listAdapter1.getGroupCount(); i++) { + lvExp_stock_check.expandGroup(i); + } + listAdapter1.notifyDataSetChanged(); + + } + + private boolean validate_regular_stock() { + check_flag = true; + if (listDataHeader.size() > 0) { + for (int k = 0; k < listDataHeader.size(); k++) { + List child_list = listDataChild.get(listDataHeader.get(k)); + for (int i = 0; i < Objects.requireNonNull(child_list).size(); i++) { + if (child_list.get(i).isSelected() && child_list.get(i).getStock_receive() != child_list.get(i).getStock()) { + if (child_list.get(i).getReasonId() == 0) { + check_flag = false; + AlertandMessages.showToastMsg(context, "Please Select Reason"); + break; + } + } + + } + + if (!check_flag) { + break; + } + } + } + + return check_flag; + + } + +} \ No newline at end of file diff --git a/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/StoreImageActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/StoreImageActivity.java new file mode 100644 index 0000000..dea9bb8 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/StoreImageActivity.java @@ -0,0 +1,897 @@ +package com.cpm.lorealbaautomation.dailyactivity; + +import static com.cpm.lorealbaautomation.constant.CommonFunctions.checkNetIsAvailable; +import static com.cpm.lorealbaautomation.constant.CommonFunctions.getCurrentTime; + +import android.Manifest; +import android.annotation.SuppressLint; +import android.app.Activity; +import android.app.AlertDialog; +import android.app.ProgressDialog; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.IntentSender; +import android.content.SharedPreferences; +import android.content.pm.PackageManager; +import android.graphics.Bitmap; +import android.graphics.BitmapFactory; +import android.location.Location; +import android.location.LocationManager; +import android.os.Bundle; +import android.os.Environment; + +import androidx.annotation.NonNull; +import androidx.core.app.ActivityCompat; +import androidx.core.content.ContextCompat; +import androidx.appcompat.app.AppCompatActivity; +import androidx.appcompat.widget.Toolbar; + +import android.os.Looper; +import android.util.Log; +import android.view.KeyEvent; +import android.view.MenuItem; +import android.view.View; +import android.view.WindowManager; +import android.widget.Button; +import android.widget.ImageView; +import android.widget.Toast; + +import com.google.android.gms.common.api.ResolvableApiException; +import com.google.android.gms.location.FusedLocationProviderClient; +import com.google.android.gms.location.LocationCallback; +import com.google.android.gms.location.LocationRequest; +import com.google.android.gms.location.LocationResult; +import com.google.android.gms.location.LocationServices; +import com.google.android.gms.location.LocationSettingsRequest; +import com.google.android.gms.location.Priority; +import com.google.android.gms.location.SettingsClient; +import com.google.gson.Gson; +import com.cpm.lorealbaautomation.BuildConfig; +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.DealarBoardActivity; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.constant.AlertandMessages; +import com.cpm.lorealbaautomation.constant.CommonFunctions; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.geotag.GeoTaggingActivity; +import com.cpm.lorealbaautomation.gsonGetterSetter.JCPGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.JourneyPlan; +import com.cpm.lorealbaautomation.gsonGetterSetter.NotificationData; +import com.cpm.lorealbaautomation.retrofit.PostApi; +import com.cpm.lorealbaautomation.timer.TimerActivity; +import com.cpm.lorealbaautomation.utils.AppUtils; +import com.cpm.lorealbaautomation.utils.DistanceUtils; + +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.nio.channels.FileChannel; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.TimeUnit; + +import okhttp3.MediaType; +import okhttp3.OkHttpClient; +import okhttp3.RequestBody; +import okhttp3.ResponseBody; +import retrofit2.Call; +import retrofit2.Callback; +import retrofit2.Response; +import retrofit2.Retrofit; +import retrofit2.converter.gson.GsonConverterFactory; + +public class StoreImageActivity extends AppCompatActivity implements View.OnClickListener { + private static final int PERMISSION_ALL = 99; + Button btn_save; + ImageView img_cam, img_clicked; + String _pathforcheck, _path, str, img_str, selfie_imge, visit_date, username, counter_id, userType; + private Lorealba_Database db; + Runnable run; + Toolbar toolbar; + ProgressDialog loading; + private Retrofit adapter; + private Integer versionCode, mid=0, bid=0, storeId=0; + private double lat = 0.0; + private double lon = 0.0; + private static final int REQUEST_LOCATION = 1; + boolean clickFlag = false, success_geoTag = true; + private FusedLocationProviderClient fusedLocationClient = null; + private LocationCallback locationCallback = null; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_store_image); + db = new Lorealba_Database(this); + db.open(); + SharedPreferences preferences = PrefHelper.getPrefs(this); + fusedLocationClient = LocationServices.getFusedLocationProviderClient(this); + getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); + img_cam = (ImageView) findViewById(R.id.img_selfie); + img_clicked = (ImageView) findViewById(R.id.img_cam_selfie); + btn_save = (Button) findViewById(R.id.btn_save_selfie); + toolbar = findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + if (!CommonFunctions.isTablet(this)) { + toolbar.setTitleTextAppearance(this, R.style.changestext_sizefor_mobile); + } + counter_id = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + username = preferences.getString(CommonString.KEY_USERNAME, ""); + userType = preferences.getString(CommonString.KEY_USER_TYPE, ""); + try { + downloadRequiredData(); + versionCode = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode; + } catch (PackageManager.NameNotFoundException e) { + e.fillInStackTrace(); + } + + Objects.requireNonNull(getSupportActionBar()).setHomeButtonEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + setTitle(getString(R.string.counter_selfie) + " - " + username); + str = CommonString.getImagesFolder(this); + img_cam.setOnClickListener(this); + img_clicked.setOnClickListener(this); + btn_save.setOnClickListener(this); + run = () -> { + if (selfie_imge != null && !selfie_imge.isEmpty()) { + File image1 = new File(str + selfie_imge); + if (image1.exists()) { + image1.delete(); + } + } + }; + ////delete old imge from folder + CommonFunctions.delete_old_imge_from_folder(this, visit_date, db); + try { + checkdates(); + } catch (Exception e) { + e.fillInStackTrace(); + } + + checkAndRequestPermissions(); + getLastLocation(); + } + + private void checkdates() { + try { + db.open(); + ArrayList notiList = db.getNotificationList(); + if (!notiList.isEmpty()) { + for (int k = 0; k < notiList.size(); k++) { + Calendar cal1 = new GregorianCalendar(); + Calendar cal2 = new GregorianCalendar(); + @SuppressLint("SimpleDateFormat") SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy"); + Date date = sdf.parse(visit_date); + assert date != null; + cal1.setTime(date); + date = sdf.parse(notiList.get(k).getVisited_date()); + assert date != null; + cal2.setTime(date); + if (daysBetween(cal1.getTime(), cal2.getTime()) > 7) { + db.open(); + db.deleteNotificationTableafterOneWeek(); + break; + } + } + } + } catch (ParseException e) { + e.fillInStackTrace(); + } + } + + public int daysBetween(Date d1, Date d2) { + return (int) ((d2.getTime() - d1.getTime()) / (1000 * 60 * 60 * 24)); + } + + @SuppressLint("NonConstantResourceId") + @Override + public void onClick(View v) { + int id = v.getId(); + + if (id == R.id.img_cam_selfie) { + clickFlag = true; + _pathforcheck = counter_id + "_Counter_Selfie_img_" + username + "_" + visit_date.replace("/", "") + "_" + getCurrentTime().replace(":", "") + ".jpg"; + _path = CommonString.getImagesFolder(this) + _pathforcheck; + if (CommonFunctions.isTablet(this)) { + CommonFunctions.startAnncaCameraActivity(this, _path, null, false, CommonString.CAMERA_FACE_REAR); + } else { + CommonFunctions.startAnncaCameraActivity(this, _path, null, false, CommonString.CAMERA_FACE_FRONT); + } + + } else if (id == R.id.btn_save_selfie) { + if (img_str != null) { + if (checkNetIsAvailable(this)) { + AlertDialog.Builder builder = new AlertDialog.Builder(this).setTitle(R.string.parinaam); + builder.setMessage("Do you want to save the image ?").setCancelable(false).setPositiveButton(android.R.string.ok, (dialog, id1) -> { + getMid(); + AttempConterCoverage(this); + }).setNegativeButton("Cancel", (dialog, id12) -> dialog.cancel()); + builder.show(); + } else { + AlertandMessages.showToastMsg(this, CommonString.MESSAGE_INTERNET_NOT_AVALABLE); + } + } else { + AlertandMessages.showToastMsg(this, "Please click Counter Selfie Image"); + } + + } + } + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + Log.i("MakeMachine", "resultCode: " + resultCode); + switch (resultCode) { + case 0: + Log.i("MakeMachine", "User cancelled"); + break; + case -1: + if (_pathforcheck != null && !_pathforcheck.isEmpty()) { + if (new File(str + _pathforcheck).exists()) { + try { + Bitmap bmp = convertBitmap(str + _pathforcheck); + img_cam.setImageBitmap(bmp); + } catch (OutOfMemoryError ex) { + CommonFunctions.setScaledImage(img_cam, str + _pathforcheck); + } + img_clicked.setVisibility(View.GONE); + img_cam.setVisibility(View.VISIBLE); + img_str = _pathforcheck; + _pathforcheck = ""; + } + } + + break; + } + super.onActivityResult(requestCode, resultCode, data); + } + + public static Bitmap convertBitmap(String path) { + Bitmap bitmap = null; + BitmapFactory.Options ourOptions = new BitmapFactory.Options(); + ourOptions.inPreferredConfig = Bitmap.Config.RGB_565; + ourOptions.inDither = false; + ourOptions.inPurgeable = true; + ourOptions.inInputShareable = true; + ourOptions.inTempStorage = new byte[32 * 1024]; + File file = new File(path); + FileInputStream fs = null; + try { + fs = new FileInputStream(file); + } catch (FileNotFoundException e) { + e.fillInStackTrace(); + } + try { + if (fs != null) { + bitmap = BitmapFactory.decodeFileDescriptor(fs.getFD(), null, ourOptions); + } + } catch (IOException e) { + e.fillInStackTrace(); + } finally { + if (fs != null) { + try { + fs.close(); + } catch (IOException e) { + e.fillInStackTrace(); + } + } + } + + return bitmap; + } + + @Override + public void onBackPressed() { + if (clickFlag) { + AlertDialog.Builder builder = new AlertDialog.Builder(this).setMessage(CommonString.ONBACK_ALERT_MESSAGE).setCancelable(false).setPositiveButton("Ok", (dialog, id) -> { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + StoreImageActivity.this.finish(); + }).setNegativeButton("Cancel", (dialog, id) -> dialog.cancel()); + AlertDialog alert = builder.create(); + alert.show(); + } else { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + StoreImageActivity.this.finish(); + } + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + if (id == android.R.id.home) { + if (clickFlag) { + AlertDialog.Builder builder = new AlertDialog.Builder(this).setMessage(CommonString.ONBACK_ALERT_MESSAGE).setCancelable(false).setPositiveButton("Ok", (dialog, id1) -> { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + StoreImageActivity.this.finish(); + }).setNegativeButton("Cancel", (dialog, id12) -> dialog.cancel()); + AlertDialog alert = builder.create(); + alert.show(); + } else { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + StoreImageActivity.this.finish(); + } + } + + return super.onOptionsItemSelected(item); + } + + + private void AttempBaCoverage(final ProgressDialog loading, Context context) { + try { + getMid(); + JSONObject jsonObject = new JSONObject(); + jsonObject.put("Mid", mid); + jsonObject.put("Bid", bid); + jsonObject.put("Latitude", lat); + jsonObject.put("Longitude", lon); + jsonObject.put("ImageName", img_str); + jsonObject.put("UserName", username); + String jsonString = jsonObject.toString(); + try { + final OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build(); + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsonString); + adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build(); + PostApi api = adapter.create(PostApi.class); + Call call = api.getBaCoverage(jsonData); + call.enqueue(new Callback() { + @Override + public void onResponse(@NonNull Call call, @NonNull Response response) { + ResponseBody responseBody = response.body(); + String data = null; + if (responseBody != null && response.isSuccessful()) { + try { + assert response.body() != null; + data = response.body().string(); + data = data.substring(1, data.length() - 1).replace("\\", ""); + if (!data.equals(0)) { + db.open(); + db.updateImageLoginData(username, img_str); + db.open(); + if (db.isCheck_Old_Product(visit_date)) { + startActivity(new Intent(context, TimerActivity.class)); + } else { + startActivity(new Intent(context, DealarBoardActivity.class)); + } + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + StoreImageActivity.this.finish(); + } else { + AlertandMessages.showAlertlogin((Activity) context, CommonString.KEY_FAILURE + ". Please try again"); + } + if (loading != null && loading.isShowing()) loading.dismiss(); + } catch (Exception e) { + e.fillInStackTrace(); + if (loading != null && loading.isShowing()) loading.dismiss(); + AlertandMessages.showAlertlogin((Activity) context, CommonString.MESSAGE_SOCKETEXCEPTION + "(" + e + ")"); + } + } else { + if (loading != null && loading.isShowing()) loading.dismiss(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_NO_RESPONSE_SERVER); + } + } + + @Override + public void onFailure(@NonNull Call call, @NonNull Throwable t) { + if (loading != null && loading.isShowing()) loading.dismiss(); + AlertandMessages.showAlertlogin((Activity) context, CommonString.MESSAGE_SOCKETEXCEPTION); + } + }); + } catch (Exception e) { + if (loading != null && loading.isShowing()) loading.dismiss(); + AlertandMessages.showAlertlogin((Activity) context, CommonString.MESSAGE_SOCKETEXCEPTION + "(" + e + ")"); + } + } catch (JSONException e) { + if (loading != null && loading.isShowing()) loading.dismiss(); + AlertandMessages.showAlertlogin((Activity) context, CommonString.MESSAGE_INVALID_JSON); + } + } + + + private void AttempTBajourneyCoverage(final Context context) { + try { + loading = ProgressDialog.show(context, "Processing", "Please wait...", false, false); + JSONObject jsonObject = new JSONObject(); + jsonObject.put("CounterId", counter_id); + jsonObject.put("VisitDate", visit_date); + jsonObject.put("UserName", username); + String jsonString = jsonObject.toString(); + try { + final OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build(); + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsonString); + adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build(); + PostApi api = adapter.create(PostApi.class); + Call call = api.getTabjourneyCoverage(jsonData); + call.enqueue(new Callback() { + @Override + public void onResponse(@NonNull Call call, @NonNull Response response) { + ResponseBody responseBody = response.body(); + String data = null; + if (responseBody != null && response.isSuccessful()) { + try { + assert response.body() != null; + data = response.body().string(); + data = data.substring(1, data.length() - 1).replace("\\", ""); + if (data.equalsIgnoreCase(CommonString.KEY_FAILURE)) { + AlertandMessages.showAlert((Activity) context, CommonString.KEY_FAILURE + " Please try again", true); + } else { + DownloadJCP(context, loading); + } + if (loading != null && loading.isShowing()) loading.dismiss(); + } catch (Exception e) { + e.fillInStackTrace(); + if (loading != null && loading.isShowing()) loading.dismiss(); + AlertandMessages.showAlert((Activity) context, CommonString.MESSAGE_SOCKETEXCEPTION + "(" + e + ")", true); + } + } else { + if (loading != null && loading.isShowing()) loading.dismiss(); + AlertandMessages.showAlert((Activity) context, CommonString.MESSAGE_NO_RESPONSE_SERVER, true); + } + } + + @Override + public void onFailure(@NonNull Call call, @NonNull Throwable t) { + if (loading != null && loading.isShowing()) loading.dismiss(); + AlertandMessages.showAlert((Activity) context, CommonString.MESSAGE_SOCKETEXCEPTION, true); + } + }); + } catch (Exception e) { + e.fillInStackTrace(); + if (loading != null && loading.isShowing()) loading.dismiss(); + AlertandMessages.showAlert((Activity) context, CommonString.MESSAGE_SOCKETEXCEPTION + "(" + e + ")", true); + } + } catch (JSONException e) { + if (loading != null && loading.isShowing()) loading.dismiss(); + AlertandMessages.showAlert((Activity) context, CommonString.MESSAGE_SOCKETEXCEPTION + "(" + e + ")", true); + } + } + + private void AttempConterCoverage(final Context context) { + try { + getMid(); + loading = ProgressDialog.show(context, "Processing", "Please wait...", false, false); + JSONObject jsonObject = new JSONObject(); + jsonObject.put("Mid", mid); + jsonObject.put("CounterId", counter_id); + jsonObject.put("VisitDate", visit_date); + jsonObject.put("Latitude", lat); + jsonObject.put("Longitude", lon); + jsonObject.put("ImageName", ""); + jsonObject.put("Appversion", versionCode); + jsonObject.put("UserName", username); + + String jsonString = jsonObject.toString(); + try { + final OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build(); + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsonString); + adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build(); + PostApi api = adapter.create(PostApi.class); + Call call = api.getCounterCoverage(jsonData); + call.enqueue(new Callback() { + @Override + public void onResponse(@NonNull Call call, @NonNull Response response) { + ResponseBody responseBody = response.body(); + String data = null; + if (responseBody != null && response.isSuccessful()) { + try { + assert response.body() != null; + data = response.body().string(); + data = data.substring(1, data.length() - 1).replace("\\", ""); + if (data.equalsIgnoreCase(CommonString.KEY_FAILURE)) { + AlertandMessages.showAlertlogin((Activity) context, CommonString.KEY_FAILURE + ". Please try again"); + loading.dismiss(); + } else { + AttempBaCoverage(loading, context); + } + if (loading != null && loading.isShowing()) loading.dismiss(); + } catch (Exception e) { + if (loading != null && loading.isShowing()) loading.dismiss(); + AlertandMessages.showAlertlogin((Activity) context, CommonString.MESSAGE_SOCKETEXCEPTION + "(" + e + ")"); + } + } else { + if (loading != null && loading.isShowing()) loading.dismiss(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_NO_RESPONSE_SERVER); + } + } + + @Override + public void onFailure(@NonNull Call call, @NonNull Throwable t) { + if (loading != null && loading.isShowing()) loading.dismiss(); + AlertandMessages.showAlertlogin((Activity) context, CommonString.MESSAGE_SOCKETEXCEPTION); + } + }); + } catch (Exception e) { + if (loading != null && loading.isShowing()) loading.dismiss(); + AlertandMessages.showAlertlogin((Activity) context, CommonString.MESSAGE_SOCKETEXCEPTION + "(" + e.toString() + ")"); + } + } catch (JSONException e) { + if (loading != null && loading.isShowing()) loading.dismiss(); + AlertandMessages.showAlertlogin((Activity) context, CommonString.MESSAGE_INVALID_JSON); + } + } + + private void downloadRequiredData() { + if (userType == null) { + return; + } + Log.d("userType", userType + "--" + username + "---" + counter_id); + if (db.getStoreData(visit_date, username, counter_id).isEmpty()) { + if (CommonFunctions.checkNetIsAvailable(this)) { + if (userType.equalsIgnoreCase(CommonString.TAG_FROM_BA)) { + loading = ProgressDialog.show(this, "Processing", "Please wait...", false, false); + DownloadJCP(this, loading); + } else { + AttempTBajourneyCoverage(this); + } + } else { + AlertandMessages.showAlert(this, getString(R.string.nonetwork), true); + } + } else { + /// checking GeoFencing + getLastLocation(); + checkingGeoFencing(getMid()); + } + } + + @Override + protected void onResume() { + super.onResume(); + if (!db.getinsertGeotaggingData(storeId.toString(), counter_id, username, null).isEmpty()) { + success_geoTag = true; + } + if (!success_geoTag) { + getLastLocation(); + checkingGeoFencing(getMid()); + } + checkgpsEnableDevice(); + getMid(); + } + + private void checkgpsEnableDevice() { + if (!hasGPSDevice(this)) { + Toast.makeText(this, "Gps not Supported", Toast.LENGTH_SHORT).show(); + } + final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); + if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER) && hasGPSDevice(this)) { + enableLocationSettings(); + } else { + if (manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { + hasGPSDevice(this); + } + } + } + + private void enableLocationSettings() { + LocationRequest locationRequest = new LocationRequest.Builder(Priority.PRIORITY_HIGH_ACCURACY, // priority + 5000 // intervalMillis: 5 seconds + ).setMinUpdateIntervalMillis(3000) // fastest interval + .build(); + LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest).setAlwaysShow(true); // show dialog if GPS is off + + SettingsClient settingsClient = LocationServices.getSettingsClient(this); + settingsClient.checkLocationSettings(builder.build()).addOnSuccessListener(locationSettingsResponse -> { + // All location settings are satisfied. You can request location updates here. + }).addOnFailureListener(e -> { + if (e instanceof ResolvableApiException) { + try { + ResolvableApiException resolvable = (ResolvableApiException) e; + resolvable.startResolutionForResult((Activity) this, REQUEST_LOCATION); + } catch (IntentSender.SendIntentException sendEx) { + // Ignore the error. + sendEx.fillInStackTrace(); + } + } + }); + } + + private boolean hasGPSDevice(Context context) { + final LocationManager mgr = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); + if (mgr == null) return false; + final List providers = mgr.getAllProviders(); + if (providers == null) return false; + return providers.contains(LocationManager.GPS_PROVIDER); + } + + private void DownloadJCP(final Context context, final ProgressDialog loading) { + try { + JSONObject jsonObject = new JSONObject(); + jsonObject.put("Downloadtype", "Mapping_JourneyPlan"); + jsonObject.put("Username", username); + jsonObject.put("Param1", counter_id); + jsonObject.put("Param2", ""); + String jsonString = jsonObject.toString(); + + try { + final OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build(); + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsonString); + adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build(); + PostApi api = adapter.create(PostApi.class); + Call call = api.getTabjournePlan(jsonData); + call.enqueue(new Callback() { + @Override + public void onResponse(@NonNull Call call, @NonNull Response response) { + ResponseBody responseBody = response.body(); + String data = null; + if (responseBody != null && response.isSuccessful()) { + try { + assert response.body() != null; + data = response.body().string(); + data = data.substring(1, data.length() - 1).replace("\\", ""); + if (data.equalsIgnoreCase(CommonString.KEY_FAILURE)) { + AlertandMessages.showAlert((Activity) context, CommonString.KEY_FAILURE + " Please try again", true); + } else if (!data.contains("No Data")) { + JCPGetterSetter jcpObject; + jcpObject = new Gson().fromJson(data, JCPGetterSetter.class); + if (jcpObject != null && !db.insertJCPData(jcpObject)) { + AlertandMessages.showAlert((Activity) context, "Mapping_JCP data not saved.", true); + } else { + /// checking GeoFencing + getLastLocation(); + checkingGeoFencing(getMid()); + AlertandMessages.showToastMsg(context, "Journey Plan Download Successfully."); + } + } else { + AlertandMessages.showAlert((Activity) context, "No Journey Plan", true); + } + if (loading != null && loading.isShowing()) loading.dismiss(); + } catch (Exception e) { + e.fillInStackTrace(); + if (loading != null && loading.isShowing()) loading.dismiss(); + AlertandMessages.showAlert((Activity) context, CommonString.MESSAGE_SOCKETEXCEPTION + "(" + e + ")", true); + } + } else { + if (loading != null && loading.isShowing()) loading.dismiss(); + AlertandMessages.showAlert((Activity) context, CommonString.MESSAGE_NO_RESPONSE_SERVER, true); + } + } + + @Override + public void onFailure(@NonNull Call call, @NonNull Throwable t) { + if (loading != null && loading.isShowing()) loading.dismiss(); + AlertandMessages.showAlert((Activity) context, CommonString.MESSAGE_SOCKETEXCEPTION, true); + } + }); + } catch (Exception e) { + e.fillInStackTrace(); + if (loading != null && loading.isShowing()) loading.dismiss(); + AlertandMessages.showAlert((Activity) context, CommonString.MESSAGE_SOCKETEXCEPTION + "(" + e + ")", true); + } + } catch (JSONException e) { + if (loading != null && loading.isShowing()) loading.dismiss(); + AlertandMessages.showAlertlogin((Activity) context, CommonString.MESSAGE_INVALID_JSON); + } + } + + private JourneyPlan getMid() { + db.open(); + JourneyPlan journeyPlan = new JourneyPlan(); + ArrayList jcp = db.getStoreData(visit_date, username, counter_id); + try { + if (!jcp.isEmpty()) { + mid = jcp.get(0).getMID(); + bid = jcp.get(0).getBID(); + storeId = jcp.get(0).getStoreId(); + journeyPlan = jcp.get(0); + Log.d("jcp_data", journeyPlan.toString()); + } + } catch (Exception e) { + e.fillInStackTrace(); + } + + return journeyPlan; + } + + public void showExportDialog() { + AlertDialog.Builder builder1 = new AlertDialog.Builder(this).setTitle(R.string.dialog_title); + builder1.setMessage(R.string.Areyou_sure_take_backup).setCancelable(false).setPositiveButton(R.string.ok, (dialog, id) -> { + try { + File sd = AppUtils.getExterDir(this); + File data = Environment.getDataDirectory(); + assert sd != null; + if (sd.canWrite()) { + long date = System.currentTimeMillis(); + @SuppressLint("SimpleDateFormat") SimpleDateFormat sdf = new SimpleDateFormat("MMM/dd/yy"); + String dateString = sdf.format(date); + String currentDBPath = "//data//" + BuildConfig.APPLICATION_ID + "//databases//" + Lorealba_Database.DATABASE_NAME; + String backupDBPath = username + CommonString.BACKUP_FOLDER_NAME + dateString.replace('/', '_') + CommonFunctions.getCurrentTime_only().replace(":", "") + ".db"; + String path = CommonString.getBackupFolder(this); + File currentDB = new File(data, currentDBPath); + File backupDB = new File(path, backupDBPath); + if (currentDB.exists()) { + @SuppressWarnings("resource") FileChannel src = new FileInputStream(currentDB).getChannel(); + FileChannel dst = new FileOutputStream(backupDB).getChannel(); + dst.transferFrom(src, 0, src.size()); + src.close(); + dst.close(); + } + } + } catch (Exception e) { + e.fillInStackTrace(); + AlertandMessages.showAlert((Activity) this, this.getString(R.string.errordatabase_not_exporting), true); + } + }).setNegativeButton(android.R.string.cancel, (dialog, id) -> dialog.cancel()); + AlertDialog alert1 = builder1.create(); + alert1.show(); + } + + @Override + public boolean onKeyLongPress(int keyCode, KeyEvent event) { + showExportDialog(); + return super.onKeyLongPress(keyCode, event); + } + + private void checkAndRequestPermissions() { + int CAMERA = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA); + int ACCESS_NETWORK_STATE = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_NETWORK_STATE); + int ACCESS_COARSE_LOCATION = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION); + int locationPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION); + int READ_PHONE_STATE = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE); + List listPermissionsNeeded = new ArrayList<>(); + + if (CAMERA != PackageManager.PERMISSION_GRANTED) { + listPermissionsNeeded.add(Manifest.permission.CAMERA); + } + + if (ACCESS_NETWORK_STATE != PackageManager.PERMISSION_GRANTED) { + listPermissionsNeeded.add(Manifest.permission.ACCESS_NETWORK_STATE); + } + if (ACCESS_COARSE_LOCATION != PackageManager.PERMISSION_GRANTED) { + listPermissionsNeeded.add(Manifest.permission.ACCESS_COARSE_LOCATION); + } + if (locationPermission != PackageManager.PERMISSION_GRANTED) { + listPermissionsNeeded.add(Manifest.permission.ACCESS_FINE_LOCATION); + } + + if (READ_PHONE_STATE != PackageManager.PERMISSION_GRANTED) { + listPermissionsNeeded.add(Manifest.permission.READ_PHONE_STATE); + } + + + if (!listPermissionsNeeded.isEmpty()) { + ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), PERMISSION_ALL); + } + } + + private void showDialogOK(DialogInterface.OnClickListener okListener) { + new AlertDialog.Builder(this).setMessage("Location,File,Call and Camera Services Permission required for this app").setPositiveButton("OK", okListener).setNegativeButton("Cancel", okListener).create().show(); + } + + @Override + public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { + super.onRequestPermissionsResult(requestCode, permissions, grantResults); + //test("", "Permission callback called-------"); + if (requestCode == PERMISSION_ALL) { + Map perms = new HashMap<>(); + // Initialize the map with both permissions + perms.put(Manifest.permission.CAMERA, PackageManager.PERMISSION_GRANTED); + perms.put(Manifest.permission.ACCESS_NETWORK_STATE, PackageManager.PERMISSION_GRANTED); + perms.put(Manifest.permission.ACCESS_COARSE_LOCATION, PackageManager.PERMISSION_GRANTED); + perms.put(Manifest.permission.ACCESS_FINE_LOCATION, PackageManager.PERMISSION_GRANTED); + perms.put(Manifest.permission.READ_PHONE_STATE, PackageManager.PERMISSION_GRANTED); + // Fill with actual results from user + if (grantResults.length > 0) { + for (int i = 0; i < permissions.length; i++) + perms.put(permissions[i], grantResults[i]); + // Check for both permissions + boolean allPermissionsGranted = Integer.valueOf(PackageManager.PERMISSION_GRANTED).equals(perms.get(Manifest.permission.CAMERA)) && Integer.valueOf(PackageManager.PERMISSION_GRANTED).equals(perms.get(Manifest.permission.ACCESS_NETWORK_STATE)) && Integer.valueOf(PackageManager.PERMISSION_GRANTED).equals(perms.get(Manifest.permission.ACCESS_COARSE_LOCATION)) && Integer.valueOf(PackageManager.PERMISSION_GRANTED).equals(perms.get(Manifest.permission.ACCESS_FINE_LOCATION)) && Integer.valueOf(PackageManager.PERMISSION_GRANTED).equals(perms.get(Manifest.permission.READ_PHONE_STATE)); + + if (allPermissionsGranted) { + getLastLocation(); + } else { + //test("", "Some permissions are not granted ask again "); + if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA) || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_NETWORK_STATE) || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_COARSE_LOCATION) || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION) || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_PHONE_STATE)) { + showDialogOK((dialog, which) -> { + switch (which) { + case DialogInterface.BUTTON_POSITIVE: + checkAndRequestPermissions(); + break; + case DialogInterface.BUTTON_NEGATIVE: + // proceed with logic by disabling the related features or quit the app. + Intent startMain = new Intent(Intent.ACTION_MAIN); + startMain.addCategory(Intent.CATEGORY_HOME); + startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + startActivity(startMain); + break; + } + }); + } else { + Toast.makeText(this, "Go to settings and enable permissions", Toast.LENGTH_LONG).show(); + } + } + } + } + } + + private void getLastLocation() { + if (fusedLocationClient == null) { + fusedLocationClient = LocationServices.getFusedLocationProviderClient(this); + } + // fastest interval + LocationRequest locationRequest = new LocationRequest.Builder(Priority.PRIORITY_HIGH_ACCURACY, 5000).setMinUpdateIntervalMillis(3000) // fastest interval + .build(); + locationCallback = new LocationCallback() { + @Override + public void onLocationResult(@NonNull LocationResult locationResult) { + for (Location location : locationResult.getLocations()) { + if (location != null) { + lat = location.getLatitude(); + lon = location.getLongitude(); + Log.d("Location", "Lat: " + lat + ", Lng: " + lon); + } + } + } + }; + if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) + != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { + // Request permissions if not granted + return; + } + fusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, Looper.getMainLooper()); + } + + private void stopLocationUpdates() { + if (fusedLocationClient != null && locationCallback != null) { + fusedLocationClient.removeLocationUpdates(locationCallback); + } + } + + @Override + public void onDestroy() { + super.onDestroy(); + stopLocationUpdates(); + if (loading != null && loading.isShowing()) { + loading.dismiss(); + } + } + + private void checkingGeoFencing(JourneyPlan jcp) { + if (jcp != null && jcp.getBID() != null) { + if (jcp.getGeoTag() != null && !jcp.getGeoTag().equalsIgnoreCase(CommonString.KEY_N) && jcp.getGeoFencingAllow() != null && jcp.getGeoFencingAllow() == 1) { + int distance = jcp.getGeoFencingRadius() != null ? jcp.getGeoFencingRadius() : 0; + int current_dist_from_store_using_lat = 0; + if (jcp.getLatitude() != 0.0 && jcp.getLongitude() != 0.0 && jcp.getGeoFencingRadius() != 0 && lat != 0.0 && lon != 0.0) { + current_dist_from_store_using_lat = DistanceUtils.calculateDistanceInMeters(lat, lon, jcp.getLatitude(), jcp.getLongitude()); + Log.d("TagLoc", "Radius " + distance + "\nCurrent dist " + current_dist_from_store_using_lat); + if (current_dist_from_store_using_lat > distance) { + String msg = getString(R.string.you_need_to_be_within) + " " + distance + " metres " + getString(R.string.you_need_to_be_in_the_store) + + "\n\n" + getString(R.string.distance_from_the_store) + " " + current_dist_from_store_using_lat + " " + getString(R.string.meters); + AlertDialog.Builder builder = new AlertDialog.Builder(this); + builder.setTitle(getResources().getString(R.string.alert)); + builder.setMessage(msg).setCancelable(false).setPositiveButton(getResources().getString(R.string.ok), (dialog1, id) -> { + dialog1.cancel(); + finishAffinity(); + }); + AlertDialog alert = builder.create(); + alert.show(); + } + } + } else { + AlertDialog.Builder builder = new AlertDialog.Builder(this); + builder.setTitle(getResources().getString(R.string.dialog_title)); + builder.setMessage(getString(R.string.first_geotag_the_store)).setCancelable(false).setPositiveButton(getResources().getString(R.string.ok), (dialog1, id) -> { + dialog1.cancel(); + success_geoTag = false; + Intent in = new Intent(this, GeoTaggingActivity.class); + startActivity(in); + }); + AlertDialog alert = builder.create(); + alert.show(); + } + } + } +} + diff --git a/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/SuggestedStockActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/SuggestedStockActivity.java new file mode 100644 index 0000000..21c88fa --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/SuggestedStockActivity.java @@ -0,0 +1,653 @@ +package com.cpm.lorealbaautomation.dailyactivity; + +import android.app.AlertDialog; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.SharedPreferences; +import android.os.Bundle; + +import com.google.android.material.floatingactionbutton.FloatingActionButton; + +import androidx.core.content.ContextCompat; +import androidx.appcompat.app.AppCompatActivity; +import androidx.cardview.widget.CardView; +import androidx.appcompat.widget.Toolbar; + +import android.text.Editable; +import android.text.TextWatcher; +import android.util.Log; +import android.view.LayoutInflater; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; +import android.widget.AdapterView; +import android.widget.ArrayAdapter; +import android.widget.BaseExpandableListAdapter; +import android.widget.Button; +import android.widget.EditText; +import android.widget.ExpandableListView; +import android.widget.ImageView; +import android.widget.Spinner; +import android.widget.TextView; + +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.constant.AlertandMessages; +import com.cpm.lorealbaautomation.constant.CommonFunctions; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.gsonGetterSetter.ProductMaster; + +import java.io.File; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +import static com.cpm.lorealbaautomation.constant.CommonFunctions.getCurrentTime; +import static com.cpm.lorealbaautomation.dailyactivity.StoreImageActivity.convertBitmap; + +public class SuggestedStockActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemSelectedListener { + ArrayAdapter axe_name_adapter, sub_axe_name_adapter, brand_name_adapter, product_name_adapter; + Spinner sku_spin, brand_spin, sub_axe_spin, axe_spin; + ArrayList brandList = new ArrayList<>(); + ArrayList subAxeList = new ArrayList<>(); + ArrayList axeList = new ArrayList<>(); + + ExpandableListView lvExp_stock_check; + FloatingActionButton fab_save; + Lorealba_Database db; + Context context; + AlertDialog alert; + private SharedPreferences preferences; + String counter_id, visit_date, username, user_type, _pathforcheck, _path; + ArrayList listDataHeader = new ArrayList<>(); + ArrayList childStockList = new ArrayList<>(); + HashMap> listDataChild; + boolean checkflag = true; + ArrayList checkHeaderArray = new ArrayList<>(); + ExpandableListAdapter listAdapter; + String brandName = ""; + String axeName = ""; + String subAxeName = ""; + + int groupPositionGlobal = -1; + ProductMaster globalHeaderObject = new ProductMaster(); + + EditText et_search; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_suggested_stock); + context = this; + db = new Lorealba_Database(context); + db.open(); + validateUIData(); + prepareListData(); + validate_spin_ui_data(); + listAdapter = new ExpandableListAdapter(context, listDataHeader, listDataChild); + lvExp_stock_check.setAdapter(listAdapter); + } + + private void validateUIData() { + preferences = PrefHelper.getPrefs(context); + counter_id = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + username = preferences.getString(CommonString.KEY_USERNAME, ""); + + Toolbar toolbar = findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + + if (!CommonFunctions.isTablet(context)) { + toolbar.setTitleTextAppearance(context, R.style.changestext_sizefor_mobile); + } + + getSupportActionBar().setHomeButtonEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + setTitle("Report - Suggested Stock"); + sku_spin = (Spinner) findViewById(R.id.sku_spin); + brand_spin = (Spinner) findViewById(R.id.stock_brand_spin); + sub_axe_spin = (Spinner) findViewById(R.id.sub_axe_spin); + axe_spin = (Spinner) findViewById(R.id.axe_spin); + lvExp_stock_check = (ExpandableListView) findViewById(R.id.lvExp_stock_check); + et_search = (EditText) findViewById(R.id.et_search); + fab_save = (FloatingActionButton) findViewById(R.id.save_fab); + fab_save.setOnClickListener(this); + ImageView img_unfilled = (ImageView) findViewById(R.id.img_unfilled); + img_unfilled.setVisibility(View.INVISIBLE); + + db.open(); + brandList = db.getsub_brand_name("1", "BrandName", false); + subAxeList = db.getsub_brand_name("1", "SubAxeName", false); + axeList = db.getsub_brand_name("1", "AxeName", false); + + et_search.addTextChangedListener(new TextWatcher() { + @Override + public void beforeTextChanged(CharSequence s, int start, int count, int after) { + + } + + @Override + public void onTextChanged(CharSequence s, int start, int before, int count) { + + String text = s.toString(); + setSearchFilter(listAdapter.get_listDataHeader(), text, listAdapter.get_listDataChild()); + } + + @Override + public void afterTextChanged(Editable s) { + + String text = s.toString(); + + } + }); + } + + public void setSearchFilter(List originalList, String text, HashMap> listDataChild) { + + HashMap> filterChildHashMap = new HashMap<>(); + + ArrayList filterList = new ArrayList<>(); + for (int i = 0; i < originalList.size(); i++) { + ProductMaster parent = originalList.get(i); + List listChild = listDataChild.get(parent); + List listFilterChild = new ArrayList<>(); + for (int j = 0; j < listChild.size(); j++) { + if (listChild.get(j).getProductName().contains(text)) { + listFilterChild.add(listChild.get(j)); + } else { + continue; + } + } + + if (listFilterChild.size() > 0) { + filterList.add(parent); + filterChildHashMap.put(parent, listFilterChild); + + } + + } + + ExpandableListAdapter listAdapter = new ExpandableListAdapter(context, filterList, filterChildHashMap); + lvExp_stock_check.setAdapter(listAdapter); + listAdapter.notifyDataSetChanged(); + + + } + + private void prepareListData() { + db.open(); + listDataHeader = new ArrayList<>(); + listDataChild = new HashMap<>(); + //inserted data + listDataHeader = db.getSuggestedStockHeaderInsertedData(visit_date); + if (listDataHeader.size() == 0) { + listDataHeader = db.getstock_check_axeandsub_axe("1"); + } + + boolean updateFlag = false; + if (listDataHeader.size() > 0) { + for (int i = 0; i < listDataHeader.size(); i++) { + childStockList = db.getSuggestedInsertedData(listDataHeader.get(i).getAxeName(), listDataHeader.get(i).getSubAxeName(), listDataHeader.get(i).getBrandName()); + if (childStockList.size() > 0) { + updateFlag = true; + + } else { + childStockList = db.getbrand_wise_sku_fromStockData(listDataHeader.get(i).getSubAxeName(), listDataHeader.get(i).getAxeName(), listDataHeader.get(i).getBrandName(), "1"); + } + + listDataChild.put(listDataHeader.get(i), childStockList); // Header, Child data + } + + if (updateFlag) + fab_save.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.edit_txt)); + } + } + + + @Override + public void onClick(View view) { + int id = view.getId(); + + if (id == R.id.save_fab) { + db.open(); + db.insertSuggestedStockCapturedData(visit_date, listDataChild, listDataHeader); + finish(); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + + } + } + + @Override + public void onItemSelected(AdapterView adapterView, View view, int position, long l) { + + if (adapterView.getId() == R.id.stock_brand_spin) { + if (position != 0) { + brandName = adapterView.getSelectedItem().toString(); + setFilter(FILTER_FOR_BRAND); + axeList = db.getAxeNSubAxe("1", "AxeName", brandName, null); + subAxeList = db.getAxeNSubAxe("1", "SubAxeName", brandName, null); + setAxeSpinnerData(axeList); + setSubAxeSpinnerData(subAxeList); + + } else { + brandName = ""; + setFilter(CLEAR_FILTER); + axeList = db.getAxeNSubAxe("1", "AxeName", null, null); + subAxeList = db.getAxeNSubAxe("1", "SubAxeName", null, null); + setAxeSpinnerData(axeList); + setSubAxeSpinnerData(subAxeList); + } + + } + if (adapterView.getId() == R.id.axe_spin) { + + if (position != 0) { + axeName = adapterView.getSelectedItem().toString(); + setFilter(FILTER_FOR_AXE); + subAxeList = db.getAxeNSubAxe("1", "SubAxeName", "", axeName); + setSubAxeSpinnerData(subAxeList); + } else { + axeName = ""; + if (brand_spin.getSelectedItemPosition() == 0) { + subAxeList = db.getAxeNSubAxe("1", "SubAxeName", null, null); + setSubAxeSpinnerData(subAxeList); + setFilter(CLEAR_FILTER); + } else { + subAxeList = db.getAxeNSubAxe("1", "SubAxeName", brandName, null); + setSubAxeSpinnerData(subAxeList); + setFilter(FILTER_FOR_BRAND); + } + } + + } else if (adapterView.getId() == R.id.sub_axe_spin) { + + if (position != 0) { + subAxeName = adapterView.getSelectedItem().toString(); + setFilter(FILTER_FOR_SUBAXE); + } else { + subAxeName = ""; + if (axe_spin.getSelectedItemPosition() == 0) { + if (brand_spin.getSelectedItemPosition() == 0) { + setFilter(CLEAR_FILTER); + } else { + setFilter(FILTER_FOR_BRAND); + } + } else { + setFilter(FILTER_FOR_AXE); + } + } + + } + + } + + @Override + public void onNothingSelected(AdapterView adapterView) { + + } + + public ArrayList filterListForBrand(List originalList, String text) { + ArrayList filterList = new ArrayList<>(); + for (ProductMaster object : originalList) { + if (object.getBrandName().equalsIgnoreCase(text)) { + filterList.add(object); + } else { + continue; + } + } + return filterList; + } + + public ArrayList filterListForAxe(List originalList, String text, String brandName) { + ArrayList filterList = new ArrayList<>(); + for (ProductMaster object : originalList) { + if (object.getAxeName().equalsIgnoreCase(text) && (brandName.equals("") || object.getBrandName().equalsIgnoreCase(brandName))) { + filterList.add(object); + } else { + continue; + } + } + return filterList; + } + + public ArrayList filterListForSubAxe(List originalList, String text, String brandName, String axeName) { + ArrayList filterList = new ArrayList<>(); + for (ProductMaster object : originalList) { + if (object.getSubAxeName().equalsIgnoreCase(text) && (brandName.equals("") || object.getBrandName().equalsIgnoreCase(brandName)) && (axeName.equals("") || object.getAxeName().equalsIgnoreCase(axeName))) { + filterList.add(object); + } else { + continue; + } + } + return filterList; + } + + + public class ExpandableListAdapter extends BaseExpandableListAdapter { + private Context _context; + private List _listDataHeader; + private HashMap> _listDataChild; + + public ExpandableListAdapter(Context context, List listDataHeader, HashMap> listChildData) { + this._context = context; + this._listDataHeader = listDataHeader; + this._listDataChild = listChildData; + } + + @Override + public Object getChild(int groupPosition, int childPosititon) { + return this._listDataChild.get(this._listDataHeader.get(groupPosition)).get(childPosititon); + } + + public HashMap> get_listDataChild() { + return _listDataChild; + } + + public List get_listDataHeader() { + return _listDataHeader; + } + + @Override + public long getChildId(int groupPosition, int childPosition) { + return childPosition; + } + + @Override + public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { + + final ProductMaster childText = (ProductMaster) getChild(groupPosition, childPosition); + ViewHolder holder = null; + if (convertView == null) { + LayoutInflater infalInflater = (LayoutInflater) this._context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); + convertView = infalInflater.inflate(R.layout.list_item_stock_entory, null); + holder = new ViewHolder(); + holder.cardView = convertView.findViewById(R.id.card_view); + holder.ed_Stock = convertView.findViewById(R.id.ed_Stock); + holder.mrp = convertView.findViewById(R.id.mrp); + holder.stock_img_plus = convertView.findViewById(R.id.stock_img_plus); + holder.stock_img_minus = convertView.findViewById(R.id.stock_img_minus); + convertView.setTag(holder); + + + } else { + + holder = (ViewHolder) convertView.getTag(); + } + + TextView txtListChild = convertView.findViewById(R.id.lblListItem); + txtListChild.setText(childText.getProductName() + " (MRP - ₹ " + childText.getMrp() + ")"); + + holder.stock_img_plus.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + listAdapter.notifyDataSetChanged(); + int minteger = childText.getStock(); + ++minteger; + + if (minteger <= 10) { + childText.setStock(minteger); + isDataAdded = true; + } else { + AlertandMessages.showToastMsg(context, "Stock cannot be greater than 10"); + } + } + }); + + holder.stock_img_minus.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + listAdapter.notifyDataSetChanged(); + int minteger = childText.getStock(); + --minteger; + + if (minteger >= 0) { + childText.setStock(minteger); + isDataAdded = true; + } else { + AlertandMessages.showToastMsg(context, "Stock cannot be less than 0"); + } + + } + }); + holder.ed_Stock.setText(childText.getStock() + ""); + holder.ed_Stock.setId(childPosition); + + holder.mrp.setText(" MRP = " + childText.getMrp() + ""); + holder.mrp.setId(childPosition); + + return convertView; + } + + @Override + public int getChildrenCount(int groupPosition) { + return this._listDataChild.get(this._listDataHeader.get(groupPosition)).size(); + } + + @Override + public Object getGroup(int groupPosition) { + return this._listDataHeader.get(groupPosition); + } + + @Override + public int getGroupCount() { + return this._listDataHeader.size(); + } + + @Override + public long getGroupId(int groupPosition) { + return groupPosition; + } + + @Override + public View getGroupView(final int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { + final ProductMaster headerTitle = (ProductMaster) getGroup(groupPosition); + if (convertView == null) { + + LayoutInflater infalInflater = (LayoutInflater) this._context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); + convertView = infalInflater.inflate(R.layout.list_group_stock_entry, null); + } + TextView lblListHeader = (TextView) convertView.findViewById(R.id.lblListHeader); + ImageView stock_cam = (ImageView) convertView.findViewById(R.id.stock_cam); + + stock_cam.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + groupPositionGlobal = groupPosition; + globalHeaderObject = headerTitle; + _pathforcheck = counter_id + "_suggested_stk_img" + visit_date.replace("/", "") + "_" + getCurrentTime().replace(":", "") + ".jpg"; + _path = CommonString.getImagesFolder(context) + _pathforcheck; + CommonFunctions.startAnncaCameraActivity(SuggestedStockActivity.this, _path, null, false, CommonString.CAMERA_FACE_REAR); + } + }); + + if (headerTitle.getImagePath().equals("")) { + stock_cam.setImageDrawable(getResources().getDrawable(R.mipmap.camera)); + } else { + stock_cam.setImageDrawable(getResources().getDrawable(R.mipmap.camera_tick)); + } + + lblListHeader.setText(headerTitle.getAxeName() + " - " + headerTitle.getSubAxeName() + " - " + headerTitle.getBrandName()); + if (!checkflag) { + if (checkHeaderArray.contains(groupPosition)) { + lblListHeader.setBackgroundColor(getResources().getColor(R.color.red)); + } else { + lblListHeader.setBackgroundColor(getResources().getColor(R.color.dashboard_ach)); + } + + } else { + lblListHeader.setBackgroundColor(getResources().getColor(R.color.dashboard_ach)); + } + return convertView; + } + + @Override + public boolean hasStableIds() { + return false; + } + + @Override + public boolean isChildSelectable(int groupPosition, int childPosition) { + return true; + } + } + + public class ViewHolder { + TextView ed_Stock, mrp; + Button stock_img_plus, stock_img_minus; + CardView cardView; + } + + @Override + public void onDestroy() { + super.onDestroy(); + } + + private void validate_spin_ui_data() { + brand_name_adapter = new ArrayAdapter<>(this, R.layout.spinner_custom_item); + brand_name_adapter.add("- Brand -"); + + for (int i = 0; i < brandList.size(); i++) { + brand_name_adapter.add(brandList.get(i).getBrandName()); + } + + brand_spin.setAdapter(brand_name_adapter); + brand_name_adapter.setDropDownViewResource(R.layout.spinner_custom_item); + + setAxeSpinnerData(axeList); + setSubAxeSpinnerData(axeList); + + axe_spin.setOnItemSelectedListener(this); + sub_axe_spin.setOnItemSelectedListener(this); + brand_spin.setOnItemSelectedListener(this); + + } + + private void setAxeSpinnerData(ArrayList axeList) { + axe_name_adapter = new ArrayAdapter<>(this, R.layout.spinner_custom_item); + axe_name_adapter.add("- Axe Name -"); + + for (int i = 0; i < axeList.size(); i++) { + axe_name_adapter.add(axeList.get(i).getBrandName()); + } + + axe_spin.setAdapter(axe_name_adapter); + axe_name_adapter.setDropDownViewResource(R.layout.spinner_custom_item); + + } + + private void setSubAxeSpinnerData(ArrayList subAxeList) { + sub_axe_name_adapter = new ArrayAdapter<>(this, R.layout.spinner_custom_item); + sub_axe_name_adapter.add("- Sub Axe Name -"); + + + for (int i = 0; i < subAxeList.size(); i++) { + sub_axe_name_adapter.add(subAxeList.get(i).getBrandName()); + } + + sub_axe_spin.setAdapter(sub_axe_name_adapter); + sub_axe_name_adapter.setDropDownViewResource(R.layout.spinner_custom_item); + + } + + public void setFilter(int filterType) { + + if (filterType == FILTER_FOR_BRAND) { + listAdapter = new ExpandableListAdapter(context, filterListForBrand(listDataHeader, brandName), listDataChild); + } else if (filterType == FILTER_FOR_AXE) { + listAdapter = new ExpandableListAdapter(context, filterListForAxe(listDataHeader, axeName, brandName), listDataChild); + } else if (filterType == FILTER_FOR_SUBAXE) { + listAdapter = new ExpandableListAdapter(context, filterListForSubAxe(listDataHeader, subAxeName, brandName, axeName), listDataChild); + } else { + listAdapter = new ExpandableListAdapter(context, listDataHeader, listDataChild); + } + + lvExp_stock_check.setAdapter(listAdapter); + listAdapter.notifyDataSetChanged(); + } + + final int FILTER_FOR_BRAND = 1; + final int FILTER_FOR_AXE = 2; + final int FILTER_FOR_SUBAXE = 3; + final int CLEAR_FILTER = 0; + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // Handle action bar item clicks here. The action bar will + // automatically handle clicks on the Home/Up button, so long + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + + if (id == android.R.id.home) { + isChanged(); + } + + + return super.onOptionsItemSelected(item); + } + + boolean isDataAdded = false; + + @Override + public void onBackPressed() { + //super.onBackPressed(); + isChanged(); + } + + void isChanged() { + if (isDataAdded) { + android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(this); + builder.setTitle("Parinaam"); + builder.setMessage(getResources().getString(R.string.data_will_be_lost)).setCancelable(false) + .setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { + + finish(); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + } + }) + .setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + + } + }); + android.app.AlertDialog alert = builder.create(); + alert.show(); + } else { + super.onBackPressed(); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + } + } + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + Log.i("MakeMachine", "resultCode: " + resultCode); + switch (resultCode) { + + case 0: + Log.i("MakeMachine", "User cancelled"); + break; + + case -1: + if (_pathforcheck != null && !_pathforcheck.equals("")) { + if (new File(CommonString.getImagesFolder(context) + _pathforcheck).exists()) { + convertBitmap(CommonString.getImagesFolder(context) + _pathforcheck); + isDataAdded = true; + globalHeaderObject.setImagePath(_pathforcheck); + groupPositionGlobal = -1; + _pathforcheck = ""; + listAdapter.notifyDataSetChanged(); + } + } + + break; + } + + super.onActivityResult(requestCode, resultCode, data); + } + + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/TabLoginActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/TabLoginActivity.java new file mode 100644 index 0000000..6827983 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/TabLoginActivity.java @@ -0,0 +1,719 @@ +package com.cpm.lorealbaautomation.dailyactivity; + +import android.Manifest; +import android.annotation.SuppressLint; +import android.app.Activity; +import android.app.AlertDialog; +import android.app.ProgressDialog; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.IntentSender; +import android.content.SharedPreferences; +import android.content.pm.PackageInfo; +import android.content.pm.PackageManager; +import android.location.LocationManager; +import android.net.ConnectivityManager; +import android.net.NetworkInfo; +import android.os.Build; +import android.os.Bundle; +import android.provider.Settings; +import android.text.InputFilter; +import android.text.Spanned; +import android.view.View; +import android.view.WindowManager; +import android.widget.AdapterView; +import android.widget.ArrayAdapter; +import android.widget.Button; +import android.widget.EditText; +import android.widget.Spinner; +import android.widget.TextView; +import android.widget.Toast; + +import androidx.annotation.NonNull; +import androidx.appcompat.app.AppCompatActivity; +import androidx.core.app.ActivityCompat; +import androidx.core.content.ContextCompat; +import com.google.android.gms.common.api.ResolvableApiException; +import com.google.android.gms.location.FusedLocationProviderClient; +import com.google.android.gms.location.LocationRequest; +import com.google.android.gms.location.LocationServices; +import com.google.android.gms.location.LocationSettingsRequest; +import com.google.android.gms.location.SettingsClient; +import com.google.android.material.snackbar.Snackbar; +import com.google.firebase.analytics.FirebaseAnalytics; +import com.google.firebase.crashlytics.FirebaseCrashlytics; +import com.google.gson.Gson; +import com.cpm.lorealbaautomation.AutoUpdateActivity; +import com.cpm.lorealbaautomation.BuildConfig; +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.Get_IMEI_number.ImeiNumberClass; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.constant.AlertandMessages; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.forgotpassword.ForgotpasswordActity; +import com.cpm.lorealbaautomation.gettersetter.LoginGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.BADeviceLoginGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.BaListGetterSetter; +import com.cpm.lorealbaautomation.password.ChangePasswordActivity; +import com.cpm.lorealbaautomation.pinviewactivity.PinViewActivity; +import com.cpm.lorealbaautomation.retrofit.PostApi; + +import org.json.JSONException; +import org.json.JSONObject; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +import okhttp3.MediaType; +import okhttp3.OkHttpClient; +import okhttp3.RequestBody; +import okhttp3.ResponseBody; +import retrofit2.Call; +import retrofit2.Callback; +import retrofit2.Response; +import retrofit2.Retrofit; +import retrofit2.converter.gson.GsonConverterFactory; + + +public class TabLoginActivity extends AppCompatActivity implements View.OnClickListener { + private String counterId = ""; + private String str_updated_date = "0"; + private String visitdate = ""; + private Spinner sp_sppiner; + private EditText password; + private Button btncontinue; + private String tag_from = ""; + private Context context; + private SharedPreferences preferences; + Lorealba_Database db; + ArrayList bsListData = new ArrayList<>(); + String userId; + String passwordData; + LoginGetterSetter loginGetterSetter; + private int versionCode; + ProgressDialog loading; + private String[] imeiNumbers; + private SharedPreferences.Editor editor = null; + private double lat = 0.0; + private double lon = 0.0; + private static final int REQUEST_LOCATION = 1; + private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 1000; + private LocationRequest mLocationRequest; + private ImeiNumberClass imei; + private String app_ver; + private String manufacturer; + private String model; + private String os_version; + ArrayList allLoginListData = new ArrayList<>(); + TextView forgot_password, versioncode_txt; + private FirebaseAnalytics mFirebaseAnalytics; + private FusedLocationProviderClient fusedLocationClient; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); + setContentView(R.layout.activity_tab_login); + mFirebaseAnalytics = FirebaseAnalytics.getInstance(this); + fusedLocationClient = LocationServices.getFusedLocationProviderClient(this); + FirebaseCrashlytics.getInstance().setCrashlyticsCollectionEnabled(true); + getViewId(); + setSppinerData(); + checkAndRequestPermissions(); + createLocationRequest(); + getLastLocation(); + /* To restrict Space Bar in Keyboard */ + InputFilter filter = new InputFilter() { + public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { + for (int i = start; i < end; i++) { + if (Character.isWhitespace(source.charAt(i))) { + return ""; + } + } + return null; + } + }; + password.setFilters(new InputFilter[]{filter}); + } + + @Override + protected void onResume() { + super.onResume(); + checkgpsEnableDevice(); + createLocationRequest(); + imeiNumbers = imei.getDeviceImei(); + getDeviceName(); + } + + @SuppressLint("VisibleForTests") + protected void createLocationRequest() { + LocationRequest mLocationRequest = new LocationRequest(); + // Location updates intervals in sec + // 5 sec + int UPDATE_INTERVAL = 5000; + mLocationRequest.setInterval(UPDATE_INTERVAL); + // 1 sec + int FATEST_INTERVAL = 1000; + mLocationRequest.setFastestInterval(FATEST_INTERVAL); + mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); + // 10 meters + int DISPLACEMENT = 5; + mLocationRequest.setSmallestDisplacement(DISPLACEMENT); + } + + private void checkgpsEnableDevice() { + if (!hasGPSDevice(context)) { + Toast.makeText(context, "Gps not Supported", Toast.LENGTH_SHORT).show(); + } + + final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); + if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER) && hasGPSDevice(context)) { + enableLocationSettings(); + } else { + if (manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { + hasGPSDevice(context); + } + } + } + + private void enableLocationSettings() { + @SuppressLint("VisibleForTests") LocationRequest locationRequest = LocationRequest.create() + .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY) // new Priority constant + .setInterval(30 * 1000) + .setFastestInterval(5 * 1000); + LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder() + .addLocationRequest(locationRequest) + .setAlwaysShow(true); // show dialog if GPS is off + + SettingsClient settingsClient = LocationServices.getSettingsClient(this); + + settingsClient.checkLocationSettings(builder.build()) + .addOnSuccessListener(locationSettingsResponse -> { + // All location settings are satisfied. You can request location updates here. + }).addOnFailureListener(e -> { + if (e instanceof ResolvableApiException) { + try { + ResolvableApiException resolvable = (ResolvableApiException) e; + resolvable.startResolutionForResult((Activity) context, REQUEST_LOCATION); + } catch (IntentSender.SendIntentException sendEx) { + // Ignore the error. + sendEx.fillInStackTrace(); + } + } + }); + } + + private boolean hasGPSDevice(Context context) { + final LocationManager mgr = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); + if (mgr == null) + return false; + final List providers = mgr.getAllProviders(); + if (providers == null) + return false; + return providers.contains(LocationManager.GPS_PROVIDER); + } + + @SuppressLint("SetTextI18n") + void getViewId() { + context = this; + db = new Lorealba_Database(context); + db.open(); + preferences = PrefHelper.getPrefs(this); + // preferences = PrefHelper.getPrefs(this); + editor = preferences.edit(); + sp_sppiner = (Spinner) findViewById(R.id.sp_sppiner); + password = (EditText) findViewById(R.id.password); + btncontinue = (Button) findViewById(R.id.btncontinue); + TextView user_type_login = (TextView) findViewById(R.id.user_type_login); + TextView counter_name = (TextView) findViewById(R.id.counter_name); + forgot_password = (TextView) findViewById(R.id.forgot_password); + versioncode_txt = (TextView) findViewById(R.id.versioncode_txt); + + String tag_mode = ""; + if (getIntent().getSerializableExtra(CommonString.TAG_FROM) != null && getIntent().getSerializableExtra(CommonString.TAG_MODE) != null) { + tag_from = getIntent().getStringExtra(CommonString.TAG_FROM); + tag_mode = getIntent().getStringExtra(CommonString.TAG_MODE); + } else { + tag_from = preferences.getString(CommonString.TAG_FROM, ""); + tag_mode = preferences.getString(CommonString.TAG_MODE, ""); + } + + imei = new ImeiNumberClass(context); + if (checkAndRequestPermissions()) { + imeiNumbers = imei.getDeviceImei(); + getDeviceName(); + } + + try { + app_ver = String.valueOf(getPackageManager().getPackageInfo(getPackageName(), 0).versionName); + + } catch (PackageManager.NameNotFoundException e) { + // TODO Auto-generated catch block + e.fillInStackTrace(); + } + + user_type_login.setText(tag_mode); + counterId = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + String counterCode = preferences.getString(CommonString.KEY_COUNTER_CODE, ""); + String counterName = preferences.getString(CommonString.KEY_COUNTER_NAME, ""); + visitdate = preferences.getString(CommonString.KEY_DATE, ""); + counter_name.setText("Counter Name : " + counterName + "\n" + "Counter Code : " + counterCode); + db.open(); + bsListData = db.getBAListData(tag_from, counterId); + btncontinue.setOnClickListener(v -> { + if (checkNetIsAvailable()) { + if (validation()) { + attemptLogin(); + } + } else { + AlertandMessages.showAlert((Activity) context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE, false); + } + }); + forgot_password.setOnClickListener(this); + try { + PackageInfo pInfo = context.getPackageManager().getPackageInfo(getPackageName(), 0); + String version = pInfo.versionName; + versioncode_txt.setText("Version : " + version); + } catch (PackageManager.NameNotFoundException e) { + e.fillInStackTrace(); + versioncode_txt.setText("Version : 0.0"); + } + } + + private void setSppinerData() { + ArrayAdapter store_visited_adapter = new ArrayAdapter(context, R.layout.spinner_custom_item); + store_visited_adapter.add("- Select User -"); + for (int i = 0; i < bsListData.size(); i++) { + store_visited_adapter.add(bsListData.get(i).getUserName()); + } + + store_visited_adapter.setDropDownViewResource(R.layout.spinner_custom_item); + sp_sppiner.setAdapter(store_visited_adapter); + sp_sppiner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { + @Override + public void onItemSelected(AdapterView parent, View view, int position, long id) { + if (position != 0) { + userId = bsListData.get(position - 1).getUserName().toLowerCase(); + db.open(); + ArrayList allLoginList = db.getlistAllUserIdData(visitdate, userId, true); + db.open(); + if (!allLoginList.isEmpty()) { + db.open(); + db.updateVisitDateLoginData(userId, visitdate); + str_updated_date = "1"; + } + + db.open(); + allLoginListData = db.getlistAllUserIdData(visitdate, userId, false); + if (!allLoginListData.isEmpty()) { + LoginGetterSetter obj = allLoginListData.get(0); + if (obj != null && obj.getUserId() != null) { + String mpin = preferences.getString(userId, null); + Intent in; + if (mpin != null) { + in = new Intent(context, PinViewActivity.class).putExtra(CommonString.IS_PASSWORD_CHECK, true).putExtra(CommonString.KEY_USERNAME, userId).putExtra(CommonString.KEY_Update_Visit_Date, str_updated_date); + startActivity(in); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + finish(); + } + } + } + } else { + userId = ""; + } + } + + @Override + public void onNothingSelected(AdapterView parent) { + } + }); + } + + private void attemptLogin() { + passwordData = password.getText().toString().trim(); + AttempLogin(); + + } + + + private boolean checkNetIsAvailable() { + ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); + NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); + return activeNetwork != null && activeNetwork.isConnectedOrConnecting(); + } + + + private void AttempLogin() { + try { + loading = ProgressDialog.show(TabLoginActivity.this, "Processing", "Please wait...", false, false); + versionCode = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode; + JSONObject jsonObject = new JSONObject(); + jsonObject.put("UserName", userId); + jsonObject.put("Password", passwordData); + jsonObject.put("CounterId", counterId); + jsonObject.put("Latitude", lat); + jsonObject.put("Longitude", lon); + jsonObject.put("Appversion", app_ver); + jsonObject.put("Attmode", "0"); + jsonObject.put("Networkstatus", "0"); + jsonObject.put("ModelNumber", model); + jsonObject.put("Manufacturer", manufacturer); + jsonObject.put("OSVersion", os_version); + jsonObject.put("AppId", BuildConfig.APPLICATION_ID); + if (Build.VERSION.SDK_INT > Build.VERSION_CODES.P) { + @SuppressLint("HardwareIds") String android_id = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID); + jsonObject.put("IMEINumber1", android_id); + jsonObject.put("IMEINumber2", android_id); + } else { + if (imeiNumbers != null && imeiNumbers.length > 0) { + jsonObject.put("IMEINumber1", imeiNumbers[0]); + if (imeiNumbers != null && imeiNumbers.length > 1) { + jsonObject.put("IMEINumber2", imeiNumbers[1]); + } else { + jsonObject.put("IMEINumber2", "0"); + } + } else { + jsonObject.put("IMEINumber1", "0"); + jsonObject.put("IMEINumber2", "0"); + } + + } + String jsonString = jsonObject.toString(); + + try { + OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, + TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build(); + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsonString); + Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build(); + PostApi api = adapter.create(PostApi.class); + Call call = api.getLoginUserdetail(jsonData); + call.enqueue(new Callback() { + @Override + public void onResponse(@NonNull Call call, @NonNull Response response) { + ResponseBody responseBody = response.body(); + String data = null; + if (responseBody != null && response.isSuccessful()) { + try { + assert response.body() != null; + data = response.body().string(); + data = data.substring(1, data.length() - 1).replace("\\", ""); + if (data != null && data.equalsIgnoreCase(CommonString.KEY_FAILURE)) { + AlertandMessages.showAlertlogin(TabLoginActivity.this, CommonString.KEY_FAILURE + " Please try again"); + loading.dismiss(); + } else if (data != null && data.contains("Changed")) { + loading.dismiss(); + AlertandMessages.showAlertlogin(TabLoginActivity.this, CommonString.MESSAGE_CHANGED); + } else if (data != null && data.contains("No data")) { + loading.dismiss(); + AlertandMessages.showAlertlogin(TabLoginActivity.this, CommonString.MESSAGE_LOGIN_NO_DATA); + } else { + JSONObject obj = new JSONObject(); + obj.put("Downloadtype", "LoginTime"); + obj.put("Username", userId); + obj.put("Param1", counterId); + obj.put("Param2", ""); + + OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, + TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build(); + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), obj.toString()); + Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build(); + PostApi api = adapter.create(PostApi.class); + Call call_login_tym = api.getDownloadAll(jsonData); + final String finalData = data; + call_login_tym.enqueue(new Callback() { + @Override + public void onResponse(@NonNull Call call, @NonNull Response response) { + String responseBody = response.body(); + String data_login_time = null; + if (responseBody != null && response.isSuccessful()) { + try { + data_login_time = response.body(); + assert data_login_time != null; + if (!data_login_time.isEmpty()) { + BADeviceLoginGetterSetter data_login_Tym = null; + if (!data_login_time.contains("No Data")) { + data_login_Tym = new Gson().fromJson(data_login_time, BADeviceLoginGetterSetter.class); + } + Gson gson = new Gson(); + final BADeviceLoginGetterSetter userObject = gson.fromJson(finalData, BADeviceLoginGetterSetter.class); + editor.putString(CommonString.KEY_USERNAME, userId.toLowerCase()); + editor.putString(CommonString.KEY_PASSWORD, passwordData); + editor.putString(CommonString.KEY_DATE, userObject.getLOGIN().get(0).getVisitDate()); + editor.putString(CommonString.KEY_PASSWORD_CHANGE, userObject.getLOGIN().get(0).getPasswordStatus()); + editor.commit(); + + Bundle bundle = new Bundle(); + bundle.putString(FirebaseAnalytics.Param.ITEM_ID, userId.toLowerCase()); + bundle.putString(FirebaseAnalytics.Param.ITEM_NAME, CommonString.KEY_LOGIN_DATA); + bundle.putString(FirebaseAnalytics.Param.CONTENT_TYPE, "Data"); + mFirebaseAnalytics.logEvent(FirebaseAnalytics.Event.SELECT_CONTENT, bundle); + FirebaseCrashlytics.getInstance().setUserId(userId.toLowerCase()); + + if (preferences.getString(CommonString.KEY_VERSION, "").equals(Integer.toString(versionCode))) { + loginGetterSetter = new LoginGetterSetter(); + loginGetterSetter.setUserId(userId.toLowerCase()); + loginGetterSetter.setPassword(passwordData); + loginGetterSetter.setVisitDate(visitdate); + loginGetterSetter.setUserType(tag_from); + loginGetterSetter.setUser_checkout("0"); + if (data_login_Tym != null) { + loginGetterSetter.setUserLoginTym(data_login_Tym.getLoginTime().get(0).getLoginTime()); + } else { + loginGetterSetter.setUserLoginTym("00:00"); + } + + db.open(); + if (!db.ischeck_login_data(userId.toLowerCase())) { + db.open(); + db.insertLoginData(loginGetterSetter); + } + loading.dismiss(); + if (!userObject.getLOGIN().get(0).getPasswordStatus().isEmpty() && userObject.getLOGIN().get(0).getPasswordStatus().equalsIgnoreCase("Change")) { + AlertDialog.Builder builder = new AlertDialog.Builder(context) + .setTitle(R.string.parinaam).setMessage("Your password has been reset. Please change your password"). + setCancelable(false).setPositiveButton(android.R.string.yes, + (dialogInterface, i) -> { + startActivity(new Intent(context, ChangePasswordActivity.class).putExtra(CommonString.KEY_PASSWORD_CHANGE, + userObject.getLOGIN().get(0).getPasswordStatus()).putExtra(CommonString.KEY_ACTIVITY, "Start")); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + dialogInterface.dismiss(); + finish(); + }); + + builder.show(); + } else { + Intent in = new Intent(getApplicationContext(), PinViewActivity.class); + in.putExtra(CommonString.IS_PASSWORD_CHECK, false); + in.putExtra(CommonString.KEY_USERNAME, userId.toLowerCase()); + startActivity(in); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + finish(); + loading.dismiss(); + } + } else { + Intent intent = new Intent(context, AutoUpdateActivity.class); + intent.putExtra(CommonString.KEY_PATH, preferences.getString(CommonString.KEY_PATH, "")); + startActivity(intent); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + finish(); + loading.dismiss(); + } + + } + } catch (Exception e) { + e.fillInStackTrace(); + loading.dismiss(); + AlertandMessages.showAlertlogin((Activity) context, CommonString.MESSAGE_SOCKETEXCEPTION + " - " + e.toString()); + } + } else { + loading.dismiss(); + AlertandMessages.showAlertlogin(TabLoginActivity.this, CommonString.MESSAGE_NO_RESPONSE_SERVER); + } + } + + @Override + public void onFailure(@NonNull Call call, @NonNull Throwable t) { + loading.dismiss(); + AlertandMessages.showAlertlogin((Activity) context, CommonString.MESSAGE_SOCKETEXCEPTION); + } + }); + + } + } catch (Exception e) { + loading.dismiss(); + e.fillInStackTrace(); + AlertandMessages.showAlertlogin(TabLoginActivity.this, CommonString.MESSAGE_SOCKETEXCEPTION + "(" + e.toString() + ")"); + + } + } else { + loading.dismiss(); + AlertandMessages.showAlertlogin(TabLoginActivity.this, CommonString.MESSAGE_NO_RESPONSE_SERVER); + } + } + + @Override + public void onFailure(@NonNull Call call, @NonNull Throwable t) { + loading.dismiss(); + if (t instanceof Exception) { + AlertandMessages.showAlertlogin(TabLoginActivity.this, CommonString.MESSAGE_INTERNET_NOT_AVALABLE + "(" + t.getMessage() + ")"); + } else { + AlertandMessages.showAlertlogin(TabLoginActivity.this, CommonString.MESSAGE_SOCKETEXCEPTION); + } + } + }); + + } catch (Exception e) { + loading.dismiss(); + e.fillInStackTrace(); + AlertandMessages.showAlertlogin(TabLoginActivity.this, CommonString.MESSAGE_SOCKETEXCEPTION + "(" + e + ")"); + } + + } catch (PackageManager.NameNotFoundException | JSONException e) { + loading.dismiss(); + AlertandMessages.showAlertlogin(TabLoginActivity.this, CommonString.MESSAGE_SOCKETEXCEPTION + "(" + e + ")"); + + } + } + + + public void getDeviceName() { + manufacturer = Build.MANUFACTURER; + model = Build.MODEL; + os_version = Build.VERSION.RELEASE; + } + + public boolean validation() { + boolean value = true; + if (sp_sppiner.getSelectedItemPosition() == 0) { + value = false; + showMessage("Please Select User"); + } else if (password.getText().toString().isEmpty()) { + value = false; + showMessage("Please fill Password"); + } + return value; + } + + public void showMessage(String message) { + Snackbar.make(btncontinue, message, Snackbar.LENGTH_SHORT).show(); + } + + @Override + public void onClick(View view) { + if (view.getId() == R.id.forgot_password) { + startActivity(new Intent(context, ForgotpasswordActity.class).putExtra(CommonString.TAG_OBJECT, bsListData)); + } + } + + private boolean checkAndRequestPermissions() { + int CAMERA = ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA); + int ACCESS_NETWORK_STATE = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_NETWORK_STATE); + int ACCESS_COARSE_LOCATION = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION); + int locationPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION); + int READ_PHONE_STATE = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE); + List listPermissionsNeeded = new ArrayList<>(); + + if (CAMERA != PackageManager.PERMISSION_GRANTED) { + listPermissionsNeeded.add(Manifest.permission.CAMERA); + } + + if (ACCESS_NETWORK_STATE != PackageManager.PERMISSION_GRANTED) { + listPermissionsNeeded.add(Manifest.permission.ACCESS_NETWORK_STATE); + } + if (ACCESS_COARSE_LOCATION != PackageManager.PERMISSION_GRANTED) { + listPermissionsNeeded.add(Manifest.permission.ACCESS_COARSE_LOCATION); + } + if (locationPermission != PackageManager.PERMISSION_GRANTED) { + listPermissionsNeeded.add(Manifest.permission.ACCESS_FINE_LOCATION); + } + + if (READ_PHONE_STATE != PackageManager.PERMISSION_GRANTED) { + listPermissionsNeeded.add(Manifest.permission.READ_PHONE_STATE); + } + + + if (!listPermissionsNeeded.isEmpty()) { + ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), CommonString.PERMISSION_ALL); + return false; + } + return true; + } + + private void showDialogOK(String message, DialogInterface.OnClickListener okListener) { + new AlertDialog.Builder(this).setMessage(message).setPositiveButton("OK", okListener).setNegativeButton("Cancel", okListener).create().show(); + } + + @Override + public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { + super.onRequestPermissionsResult(requestCode, permissions, grantResults); + //test("", "Permission callback called-------"); + if (requestCode == CommonString.PERMISSION_ALL) { + Map perms = new HashMap<>(); + // Initialize the map with both permissions + perms.put(Manifest.permission.CAMERA, PackageManager.PERMISSION_GRANTED); + perms.put(Manifest.permission.ACCESS_NETWORK_STATE, PackageManager.PERMISSION_GRANTED); + perms.put(Manifest.permission.ACCESS_COARSE_LOCATION, PackageManager.PERMISSION_GRANTED); + perms.put(Manifest.permission.ACCESS_FINE_LOCATION, PackageManager.PERMISSION_GRANTED); + perms.put(Manifest.permission.READ_PHONE_STATE, PackageManager.PERMISSION_GRANTED); + // Fill with actual results from user + if (grantResults.length > 0) { + for (int i = 0; i < permissions.length; i++) + perms.put(permissions[i], grantResults[i]); + // Check for both permissions + boolean allPermissionsGranted = + Integer.valueOf(PackageManager.PERMISSION_GRANTED).equals(perms.get(Manifest.permission.CAMERA)) && + Integer.valueOf(PackageManager.PERMISSION_GRANTED).equals(perms.get(Manifest.permission.ACCESS_NETWORK_STATE)) && + Integer.valueOf(PackageManager.PERMISSION_GRANTED).equals(perms.get(Manifest.permission.ACCESS_COARSE_LOCATION)) && + Integer.valueOf(PackageManager.PERMISSION_GRANTED).equals(perms.get(Manifest.permission.ACCESS_FINE_LOCATION)) && + Integer.valueOf(PackageManager.PERMISSION_GRANTED).equals(perms.get(Manifest.permission.READ_PHONE_STATE)); + if (allPermissionsGranted) { + //test("Permissions", "All required permissions granted"); + createLocationRequest(); + fusedLocationClient = LocationServices.getFusedLocationProviderClient(this); + getLastLocation(); + getDeviceName(); + imeiNumbers = imei.getDeviceImei(); + } else { + if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA) || + ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_NETWORK_STATE) || + ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_COARSE_LOCATION) || + ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION) || + ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_PHONE_STATE)) { + showDialogOK("Location,Call and Camera Services Permission required for this app", + (dialog, which) -> { + switch (which) { + case DialogInterface.BUTTON_POSITIVE: + checkAndRequestPermissions(); + break; + case DialogInterface.BUTTON_NEGATIVE: + // proceed with logic by disabling the related features or quit the app. + Intent startMain = new Intent(Intent.ACTION_MAIN); + startMain.addCategory(Intent.CATEGORY_HOME); + startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + startActivity(startMain); + break; + } + }); + } else { + Toast.makeText(this, "Go to settings and enable permissions", Toast.LENGTH_LONG).show(); + } + } + } + } + } + @Override + protected void onDestroy () { + super.onDestroy(); + if (loading != null && loading.isShowing()) { + loading.dismiss(); + } + } + private void getLastLocation() { + if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && + ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { + // Request location permissions + return; + } + try { + fusedLocationClient.getLastLocation() + .addOnSuccessListener(this, location -> { + if (location != null) { + lat = location.getLatitude(); + lon = location.getLongitude(); + //test("Location", "Lat: " + lat + ", Lng: " + lon); + } + }); + } catch (Exception e) { + e.fillInStackTrace(); + //test("Location", "Lat: " + lat + ", Lng: " + lon); + } + } + } + + + diff --git a/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/TesterStockActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/TesterStockActivity.java new file mode 100644 index 0000000..859ff05 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/TesterStockActivity.java @@ -0,0 +1,1796 @@ +package com.cpm.lorealbaautomation.dailyactivity; + +import android.annotation.SuppressLint; +import android.app.Activity; +import android.app.AlertDialog; +import android.app.Dialog; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.SharedPreferences; +import android.graphics.drawable.ColorDrawable; +import android.os.AsyncTask; +import android.os.Build; +import android.os.Bundle; + +import androidx.annotation.NonNull; +import androidx.annotation.RequiresApi; + +import com.google.android.material.bottomsheet.BottomSheetDialog; +import com.google.android.material.floatingactionbutton.FloatingActionButton; + +import androidx.appcompat.app.AppCompatActivity; +import androidx.cardview.widget.CardView; +import androidx.recyclerview.widget.GridLayoutManager; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; +import androidx.appcompat.widget.Toolbar; + +import android.text.Editable; +import android.text.TextWatcher; +import android.util.Log; +import android.view.Gravity; +import android.view.LayoutInflater; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; +import android.view.Window; +import android.view.WindowManager; +import android.view.inputmethod.InputMethodManager; +import android.widget.AbsListView; +import android.widget.BaseExpandableListAdapter; +import android.widget.Button; +import android.widget.EditText; +import android.widget.ExpandableListView; +import android.widget.ImageView; +import android.widget.LinearLayout; +import android.widget.ProgressBar; +import android.widget.Spinner; +import android.widget.TextView; + +import com.google.gson.JsonObject; +import com.google.zxing.integration.android.IntentIntegrator; +import com.google.zxing.integration.android.IntentResult; +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.constant.AlertandMessages; +import com.cpm.lorealbaautomation.constant.CommonFunctions; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.gettersetter.SaleableGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.JourneyPlan; +import com.cpm.lorealbaautomation.gsonGetterSetter.ProductMaster; +import com.cpm.lorealbaautomation.retrofit.PostApi; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.File; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.concurrent.TimeUnit; + +import okhttp3.MediaType; +import okhttp3.OkHttpClient; +import okhttp3.RequestBody; +import retrofit2.Call; +import retrofit2.Callback; +import retrofit2.Response; +import retrofit2.Retrofit; +import retrofit2.converter.gson.GsonConverterFactory; + +import static com.cpm.lorealbaautomation.constant.CommonFunctions.getCurrentTime; +import static com.cpm.lorealbaautomation.constant.CommonFunctions.removeFirstChar; +import static com.cpm.lorealbaautomation.dailyactivity.StoreImageActivity.convertBitmap; + +public class TesterStockActivity extends AppCompatActivity implements View.OnClickListener { + Spinner sku_spin, brand_spin, sub_axe_spin, axe_spin; + ArrayList brandList = new ArrayList<>(); + ExpandableListView lvExp_stock_check; + FloatingActionButton fab_save, fab_draft; + Lorealba_Database db; + Context context; + AlertDialog alert; + private SharedPreferences preferences; + String counter_id, visit_date, username, _pathforcheck, _path; + ArrayList listDataHeader = new ArrayList<>(); + ArrayList childStockList = new ArrayList<>(); + HashMap> listDataChild; + boolean checkflag = true; + ArrayList checkHeaderArray = new ArrayList<>(); + ExpandableListAdapter listAdapter; + int groupPositionGlobal = -1; + ProductMaster globalHeaderObject = new ProductMaster(); + EditText et_search; + //filter bottom sheet + ArrayList subBrandList = new ArrayList<>(); + ArrayList referenceList = new ArrayList<>(); + ArrayList signatureList = new ArrayList<>(); + ImageView img_filter; + View sheetView; + ProductMaster selectedSignature, selectedBrand, selectedSubBrand, selectedReference; + final int FILTER_FOR_SIGNATURE = 4; + final int FILTER_FOR_SUB_BRAND = 5; + final int FILTER_FOR_REFERENCE = 6; + final int FILTER_FOR_BRAND = 1; + final int CLEAR_FILTER = 0; + + boolean regularStockFlag = false, check_flag = true; + ImageView img_scan; + + boolean flagScan = true; + private String counterGroupId; + + RecyclerView recSubAxe; + + String selectedSubAxe = ""; + SubAxeValueAdapter subAxeValueAdapter; + ArrayList listSubAxe; + ImageView img_clear_subaxe; + + @SuppressLint("SetTextI18n") + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_tester_stock); + context = this; + ((TesterStockActivity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); + db = new Lorealba_Database(context); + db.open(); + validateUIData(); + String couter_code = preferences.getString(CommonString.KEY_COUNTER_CODE, ""); + TextView txt_counter_code = (TextView) findViewById(R.id.txt_counter_code); + txt_counter_code.setText("Counter Code - " + couter_code + " / Id - " + counter_id); + + new LoadAsync().execute(); + lvExp_stock_check.setOnScrollListener(new AbsListView.OnScrollListener() { + @Override + public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { + lvExp_stock_check.invalidate(); + + int lastItem = firstVisibleItem + visibleItemCount; + if (firstVisibleItem == 0) { + fab_save.show();//.setVisibility(View.VISIBLE); + } else if (lastItem == totalItemCount) { + fab_save.hide();//setVisibility(View.INVISIBLE); + } else { + fab_save.show();//setVisibility(View.VISIBLE); + } + } + + @Override + public void onScrollStateChanged(AbsListView arg0, int arg1) { + InputMethodManager inputManager = (InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE); + if (getCurrentFocus() != null) { + inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0); + getCurrentFocus().clearFocus(); + } + + lvExp_stock_check.invalidateViews(); + } + }); + + } + + JourneyPlan jcp; + + private void validateUIData() { + preferences = PrefHelper.getPrefs(context); + counter_id = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + username = preferences.getString(CommonString.KEY_USERNAME, ""); + + Toolbar toolbar = findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + + if (!CommonFunctions.isTablet(context)) { + toolbar.setTitleTextAppearance(context, R.style.changestext_sizefor_mobile); + } + + getSupportActionBar().setHomeButtonEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + setTitle("Tester Stock - " + visit_date); + sku_spin = (Spinner) findViewById(R.id.sku_spin); + brand_spin = (Spinner) findViewById(R.id.stock_brand_spin); + sub_axe_spin = (Spinner) findViewById(R.id.sub_axe_spin); + axe_spin = (Spinner) findViewById(R.id.axe_spin); + lvExp_stock_check = (ExpandableListView) findViewById(R.id.lvExp_stock_check); + et_search = (EditText) findViewById(R.id.et_search); + fab_save = (FloatingActionButton) findViewById(R.id.save_fab); + fab_draft = (FloatingActionButton) findViewById(R.id.draft_fab); + img_scan = (ImageView) findViewById(R.id.img_scan); + recSubAxe = (RecyclerView) findViewById(R.id.rec_subaxe); + img_clear_subaxe = (ImageView) findViewById(R.id.img_clear_subaxe); + + fab_save.setOnClickListener(this); + fab_draft.setOnClickListener(this); + img_scan.setOnClickListener(this); + img_clear_subaxe.setOnClickListener(this); + ImageView img_unfilled = (ImageView) findViewById(R.id.img_unfilled); + img_unfilled.setVisibility(View.INVISIBLE); + db.open(); + et_search.addTextChangedListener(new TextWatcher() { + @Override + public void beforeTextChanged(CharSequence s, int start, int count, int after) { + + } + + @Override + public void onTextChanged(CharSequence s, int start, int before, int count) { + + String text = s.toString(); + if (text.equals("")) { + lvExp_stock_check.setAdapter(listAdapter); + listAdapter.notifyDataSetChanged(); + } else { + lvExp_stock_check.invalidate(); + setSearchFilter(listAdapter.get_listDataHeader(), text, listAdapter.get_listDataChild()); + } + } + + @Override + public void afterTextChanged(Editable s) { + + String text = s.toString(); + + } + }); + + img_filter = (ImageView) findViewById(R.id.img_filter); + img_filter.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + sheetView = showFilterBottomSheet(); + } + }); + + db.open(); + String status = db.getStatus(CommonString.KEY_TesterStatus, counter_id); + + //if regular stock need to be captured after First stock capture + if (status != null && !status.equals("") && status.equalsIgnoreCase("Complete")) { + regularStockFlag = true; + fab_draft.hide(); + } + } + + public void setSearchFilter(List originalList, String text, HashMap> listDataChild) { + HashMap> filterChildHashMap = new HashMap<>(); + + ArrayList filterList = new ArrayList<>(); + for (int i = 0; i < originalList.size(); i++) { + ProductMaster parent = originalList.get(i); + List listChild = listDataChild.get(parent); + List listFilterChild = new ArrayList<>(); + for (int j = 0; j < listChild.size(); j++) { + if (listChild.get(j).getProductName().toLowerCase().contains(text.toLowerCase()) || (listChild.get(j).getEanCode() != null && listChild.get(j).getEanCode().contains(text))) { + listFilterChild.add(listChild.get(j)); + } else { + continue; + } + } + + if (listFilterChild.size() > 0) { + filterList.add(parent); + filterChildHashMap.put(parent, listFilterChild); + } + } + + ExpandableListAdapter listAdapter = new ExpandableListAdapter(context, filterList, filterChildHashMap); + lvExp_stock_check.setAdapter(listAdapter); + listAdapter.notifyDataSetChanged(); + for (int i = 0; i < listAdapter.getGroupCount(); i++) { + lvExp_stock_check.expandGroup(i); + } + } + + private void prepareListData() { + db.open(); + jcp = db.getJCP(); + if (jcp != null) { + db.open(); + listSubAxe = db.getSubAxe(jcp.getCounterGroupId().toString(), true); + } else { + listSubAxe = db.getSubAxe("1", true); + } + + listDataHeader = new ArrayList<>(); + listDataChild = new HashMap<>(); + + //for filter bottom sheet + jcp = db.getJCP(); + if (jcp != null) { + db.open(); + brandList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "BrandName", false, selectedSubAxe); + db.open(); + subBrandList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "SubBrandName", false, selectedSubAxe); + db.open(); + referenceList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "ReferenceName", false, selectedSubAxe); + db.open(); + signatureList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "SignatureName", false, selectedSubAxe); + } else { + db.open(); + brandList = db.getsub_brand_name("1", "BrandName", false, selectedSubAxe); + subBrandList = db.getsub_brand_name("1", "SubBrandName", false, selectedSubAxe); + referenceList = db.getsub_brand_name("1", "ReferenceName", false, selectedSubAxe); + signatureList = db.getsub_brand_name("1", "SignatureName", false, selectedSubAxe); + } + + //inserted data + db.open(); + listDataHeader = db.getTesterHeaderInsertedData(visit_date, regularStockFlag); + if (listDataHeader.size() == 0) { + if (jcp != null) { + db.open(); + listDataHeader = db.getFunctionName(jcp.getCounterGroupId().toString(), selectedSubAxe, regularStockFlag, "TesterBalance", counter_id, visit_date); + } else { + db.open(); + listDataHeader = db.getStockSignatureBrandSubBrandReference("1", false, regularStockFlag, "TesterBalance"); + } + } + + + if (listDataHeader.size() > 0) { + for (int i = 0; i < listDataHeader.size(); i++) { + db.open(); + childStockList = db.getDefaultStockOnFunctionData(listDataHeader.get(i).getNuanceName(), CommonString.KEY_TesterBalance, counter_id, regularStockFlag, visit_date); + listDataChild.put(listDataHeader.get(i), childStockList); // Header, Child data + } + } + } + + @Override + public void onClick(View view) { + int id = view.getId(); + + if (id == R.id.save_fab) { + db.open(); + lvExp_stock_check.clearFocus(); + lvExp_stock_check.invalidateViews(); + if (regularStockFlag) { + dialogFinalSubmit(listDataChild, listDataHeader); + } else { + dialogFinalSubmit(listDataChild, listDataHeader); + } + + } else if (id == R.id.draft_fab) { + lvExp_stock_check.clearFocus(); + lvExp_stock_check.invalidateViews(); + new InsertAsync().execute(false); + + } else if (id == R.id.card_signature) { + RecyclerView recSignature = sheetView.findViewById(R.id.rec_brand); + recSignature.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, true)); + recSignature.setAdapter(new ValueAdapter(context, signatureList, CommonString.Signature)); + setFilterSelected(sheetView, CommonString.Signature); + + } else if (id == R.id.card_brand) { + + RecyclerView recBrand = sheetView.findViewById(R.id.rec_brand); + recBrand.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, true)); + recBrand.setAdapter(new ValueAdapter(context, brandList, CommonString.Brand)); + setFilterSelected(sheetView, CommonString.Brand); + } else if (id == R.id.card_sub_brand) { + + RecyclerView recSubBrand = sheetView.findViewById(R.id.rec_brand); + recSubBrand.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, true)); + recSubBrand.setAdapter(new ValueAdapter(context, subBrandList, CommonString.SubBrand)); + recSubBrand.getAdapter().notifyDataSetChanged(); + setFilterSelected(sheetView, CommonString.SubBrand); + } else if (id == R.id.card_reference) { + + RecyclerView recReference = sheetView.findViewById(R.id.rec_brand); + recReference.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, true)); + recReference.setAdapter(new ValueAdapter(context, referenceList, CommonString.Reference)); + setFilterSelected(sheetView, CommonString.Reference); + } else if (id == R.id.img_scan) { + if (flagScan) { + openScanner(); + } else { + img_scan.setImageDrawable(getResources().getDrawable(R.mipmap.barcode_icon)); + flagScan = true; + et_search.setText(""); + } + + } else if (id == R.id.img_clear_subaxe) { + et_search.setText(""); + listAdapter = new ExpandableListAdapter(context, listDataHeader, listDataChild); + lvExp_stock_check.setAdapter(listAdapter); + listAdapter.notifyDataSetChanged(); + selectedSubAxe = ""; + subAxeValueAdapter.notifyDataSetChanged(); + + //clear filters also + selectedSignature = null; + selectedBrand = null; + selectedSubBrand = null; + selectedReference = null; + db.open(); + brandList = db.getsub_brand_name(counterGroupId, "BrandName", false, selectedSubAxe); + db.open(); + subBrandList = db.getsub_brand_name(counterGroupId, "SubBrandName", false, selectedSubAxe); + db.open(); + referenceList = db.getsub_brand_name(counterGroupId, "ReferenceName", false, selectedSubAxe); + db.open(); + signatureList = db.getsub_brand_name(counterGroupId, "SignatureName", false, selectedSubAxe); + } + } + + + public ArrayList filterListForBrand(List originalList, String text) { + ArrayList filterList = new ArrayList<>(); + for (ProductMaster object : originalList) { + if (object.getBrandName().equalsIgnoreCase(text)) { + filterList.add(object); + } else { + continue; + } + } + return filterList; + } + + + public class ExpandableListAdapter extends BaseExpandableListAdapter { + private Context _context; + private List _listDataHeader; + private HashMap> _listDataChild; + + public ExpandableListAdapter(Context context, List listDataHeader, HashMap> listChildData) { + this._context = context; + this._listDataHeader = listDataHeader; + this._listDataChild = listChildData; + } + + @Override + public Object getChild(int groupPosition, int childPosititon) { + return this._listDataChild.get(this._listDataHeader.get(groupPosition)).get(childPosititon); + } + + @Override + public long getChildId(int groupPosition, int childPosition) { + return childPosition; + } + + public HashMap> get_listDataChild() { + return _listDataChild; + } + + public List get_listDataHeader() { + return _listDataHeader; + } + + @Override + public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { + + final ProductMaster childText = (ProductMaster) getChild(groupPosition, childPosition); + ViewHolder holder = null; + if (convertView == null) { + LayoutInflater infalInflater = (LayoutInflater) this._context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); + convertView = infalInflater.inflate(R.layout.item_stock_layout, null); + holder = new ViewHolder(); + holder.cardView = convertView.findViewById(R.id.card_view); + holder.ed_Stock = convertView.findViewById(R.id.ed_Stock); + holder.mrp = convertView.findViewById(R.id.mrp); + holder.stock_img_plus = convertView.findViewById(R.id.stock_img_plus); + holder.stock_img_minus = convertView.findViewById(R.id.stock_img_minus); + holder.et_stock = convertView.findViewById(R.id.et_stock); + convertView.setTag(holder); + + + } else { + + holder = (ViewHolder) convertView.getTag(); + } + + TextView txtListChild = convertView.findViewById(R.id.lblListItem); + txtListChild.setText(childText.getProductName() + " (MRP - ₹ " + childText.getMrp() + ")"); + final ViewHolder finalHolder = holder; + holder.stock_img_plus.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + ((ExpandableListAdapter) lvExp_stock_check.getExpandableListAdapter()).notifyDataSetChanged(); + if (!regularStockFlag) { + String stot = finalHolder.et_stock.getText().toString().trim().replaceFirst("^0+(?!$)", ""); + if (!stot.equals("")) { + int st = Integer.parseInt(stot); + childText.setStock(st); + } + } + + + int stock = childText.getStock(); + int receivedStock = childText.getStock_receive(); + ++stock; + + if (stock != 0 && stock > 3) { + AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle(R.string.parinaam); + builder.setMessage("You have entered Tester Stock greater than 3. Please confirm is the value is correct") + .setCancelable(false) + .setPositiveButton("OK", new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { + dialog.dismiss(); + } + }); + AlertDialog alert = builder.create(); + alert.show(); + } + + + if (regularStockFlag) { + if (receivedStock >= stock) { + childText.setStock(stock); + isDataAdded = true; + childText.setSelected(true); + } else { + AlertandMessages.showToastMsg(context, "Stock cannot be greater than Received Stock"); + } + } else { + childText.setStock(stock); + isDataAdded = true; + childText.setSelected(true); + } + } + }); + + holder.stock_img_minus.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + ((ExpandableListAdapter) lvExp_stock_check.getExpandableListAdapter()).notifyDataSetChanged(); + if (!regularStockFlag) { + String stot = finalHolder.et_stock.getText().toString().trim().replaceFirst("^0+(?!$)", ""); + if (!stot.equals("")) { + int st = Integer.parseInt(stot); + childText.setStock(st); + } + } + + + int stock = childText.getStock(); + --stock; + + if (stock >= 0) { + childText.setStock(stock); + isDataAdded = true; + childText.setSelected(true); + } else { + AlertandMessages.showToastMsg(context, "Stock cannot be less than 0"); + } + + } + }); + + holder.et_stock.setOnFocusChangeListener(new View.OnFocusChangeListener() { + @Override + public void onFocusChange(View v, boolean hasFocus) { + // if (!hasFocus) { + final EditText caption = (EditText) v; + String stock = caption.getText().toString().replaceFirst("^0+(?!$)", ""); + if (!stock.equals("")) { + childText.setStock(Integer.parseInt(stock)); + isDataAdded = true; + childText.setSelected(true); + if (childText.getStock() != 0 && childText.getStock() > 3) { + AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle(R.string.parinaam); + builder.setMessage("You have entered Tester Stock greater than 3. Please confirm is the value is correct") + .setCancelable(false) + .setPositiveButton("OK", new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { + dialog.dismiss(); + } + }); + AlertDialog alert = builder.create(); + alert.show(); + } + } else { + childText.setStock(0); + } + + // } + + } + }); + + int stock = childText.getStock(); + if (!childText.isSelected() && childText.getStock() == 0) { + stock = childText.getStock_receive(); + childText.setStock(stock); + } + + if (regularStockFlag) { + holder.ed_Stock.setText(stock + ""); + holder.ed_Stock.setId(childPosition); + + holder.et_stock.setVisibility(View.GONE); + holder.ed_Stock.setVisibility(View.VISIBLE); + } else { + + if (stock == -1) { + holder.et_stock.setText(""); + } else { + holder.et_stock.setText(stock + ""); + } + + holder.et_stock.setId(childPosition); + + holder.ed_Stock.setVisibility(View.GONE); + holder.et_stock.setVisibility(View.VISIBLE); + } + + holder.mrp.setText(" MRP = " + childText.getMrp() + ""); + holder.mrp.setId(childPosition); + + return convertView; + } + + @Override + public int getChildrenCount(int groupPosition) { + return this._listDataChild.get(this._listDataHeader.get(groupPosition)).size(); + } + + @Override + public Object getGroup(int groupPosition) { + return this._listDataHeader.get(groupPosition); + } + + @Override + public int getGroupCount() { + return this._listDataHeader.size(); + } + + @Override + public long getGroupId(int groupPosition) { + return groupPosition; + } + + @Override + public View getGroupView(final int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { + final ProductMaster headerTitle = (ProductMaster) getGroup(groupPosition); + if (convertView == null) { + + LayoutInflater infalInflater = (LayoutInflater) this._context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); + convertView = infalInflater.inflate(R.layout.list_group_stock_entry, null); + } + + TextView lblListHeader = (TextView) convertView.findViewById(R.id.lblListHeader); + ImageView stock_cam = (ImageView) convertView.findViewById(R.id.stock_cam); + + stock_cam.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + groupPositionGlobal = groupPosition; + globalHeaderObject = headerTitle; + _pathforcheck = counter_id + "_tester_stock_img_" + visit_date.replace("/", "") + "_" + getCurrentTime().replace(":", "") + ".jpg"; + _path = CommonString.getImagesFolder(context) + _pathforcheck; + CommonFunctions.startAnncaCameraActivity(TesterStockActivity.this, _path, null, false, CommonString.CAMERA_FACE_REAR); + } + }); + + if (headerTitle.getImagePath().equals("")) { + stock_cam.setImageDrawable(getResources().getDrawable(R.mipmap.camera)); + } else { + stock_cam.setImageDrawable(getResources().getDrawable(R.mipmap.camera_tick)); + } + + + lblListHeader.setText(headerTitle.getNuanceName()); + if (!checkflag) { + if (checkHeaderArray.contains(groupPosition)) { + lblListHeader.setBackgroundColor(getResources().getColor(R.color.red)); + } else { + lblListHeader.setBackgroundColor(getResources().getColor(R.color.bright_red)); + } + + } else { + lblListHeader.setBackgroundColor(getResources().getColor(R.color.bright_red)); + } + + return convertView; + } + + @Override + public boolean hasStableIds() { + return false; + } + + @Override + public boolean isChildSelectable(int groupPosition, int childPosition) { + return true; + } + } + + public class ViewHolder { + TextView ed_Stock, mrp; + Button stock_img_plus, stock_img_minus; + CardView cardView; + EditText et_stock; + } + + + @Override + public void onDestroy() { + if (dialog != null && dialog.isShowing()) { + dialog.dismiss(); + } + super.onDestroy(); + } + + boolean isDataAdded = false; + + @Override + public void onBackPressed() { + //super.onBackPressed(); + isChanged(); + } + + void isChanged() { + if (isDataAdded) { + android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(this); + builder.setTitle("Parinaam"); + builder.setMessage(getResources().getString(R.string.data_will_be_lost)).setCancelable(false) + .setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { + + finish(); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + } + }) + .setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + + } + }); + android.app.AlertDialog alert = builder.create(); + alert.show(); + } else { + super.onBackPressed(); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + } + } + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + Log.i("MakeMachine", "resultCode: " + resultCode); + if (requestCode == 131) { + switch (resultCode) { + + case 0: + Log.i("MakeMachine", "User cancelled"); + break; + + case -1: + if (_pathforcheck != null && !_pathforcheck.equals("")) { + if (new File(CommonString.getImagesFolder(context) + _pathforcheck).exists()) { + convertBitmap(CommonString.getImagesFolder(context) + _pathforcheck); + isDataAdded = true; + globalHeaderObject.setImagePath(_pathforcheck); + groupPositionGlobal = -1; + _pathforcheck = ""; + listAdapter.notifyDataSetChanged(); + } + } + + break; + } + } else { + IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data); + switch (resultCode) { + case 0: + break; + + case -1: + db.open(); + ArrayList productList = db.getsku_fromproductusing_eancode(result.getContents(), false, visit_date, counter_id, null); + if (productList.isEmpty()) { + db.open(); + productList = db.getsku_fromproductusing_eancode(removeFirstChar(result.getContents()), false, visit_date, counter_id, null); + } + + if (!productList.isEmpty()) { + flagScan = false; + img_scan.setImageDrawable(getResources().getDrawable(R.mipmap.ok)); + clearFilters(); + setScanFilter(productList); + } else { + AlertandMessages.showToastMsg(context, "Unable To Scan Correct Data. Please Try Again."); + } + + break; + } + } + super.onActivityResult(requestCode, resultCode, data); + } + + //filter bottom sheet + View showFilterBottomSheet() { + final CardView cardSignature, cardBrand, cardSubBrand, cardReference; + final BottomSheetDialog mBottomSheetDialog = new BottomSheetDialog(this); + final View sheetView = getLayoutInflater().inflate(R.layout.filter_bottom_sheet, null); + mBottomSheetDialog.setContentView(sheetView); + View bottomSheet = mBottomSheetDialog.getWindow().findViewById(com.google.android.material.R.id.design_bottom_sheet); + if (bottomSheet != null) { + bottomSheet.setBackgroundResource(android.R.color.transparent); + } + mBottomSheetDialog.setCancelable(false); + final RecyclerView recBrand = sheetView.findViewById(R.id.rec_brand); + ImageView img_cancel = sheetView.findViewById(R.id.img_cancel); + TextView tv_clear_filter = sheetView.findViewById(R.id.tv_clear_filter); + recBrand.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, true)); + recBrand.setAdapter(new ValueAdapter(context, signatureList, CommonString.Signature)); + + cardSignature = sheetView.findViewById(R.id.card_signature); + cardBrand = sheetView.findViewById(R.id.card_brand); + cardSubBrand = sheetView.findViewById(R.id.card_sub_brand); + cardReference = sheetView.findViewById(R.id.card_reference); + + cardSignature.setOnClickListener(this); + cardBrand.setOnClickListener(this); + cardSubBrand.setOnClickListener(this); + cardReference.setOnClickListener(this); + + cardSignature.setCardBackgroundColor(getResources().getColor(R.color.dashboard_ach)); + + if (selectedSignature != null) { + (sheetView.findViewById(R.id.img_filter_signature)).setVisibility(View.VISIBLE); + } + if (selectedBrand != null) { + (sheetView.findViewById(R.id.img_filter_brand)).setVisibility(View.VISIBLE); + } + if (selectedSubBrand != null) { + (sheetView.findViewById(R.id.img_filter_sub_brand)).setVisibility(View.VISIBLE); + } + if (selectedReference != null) { + (sheetView.findViewById(R.id.img_filter_reference)).setVisibility(View.VISIBLE); + } + + img_cancel.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + mBottomSheetDialog.cancel(); + } + }); + + tv_clear_filter.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + setFilter(CLEAR_FILTER); + selectedSignature = null; + selectedBrand = null; + selectedSubBrand = null; + selectedReference = null; + + cardSignature.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background)); + cardBrand.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background)); + cardSubBrand.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background)); + cardReference.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background)); + + (sheetView.findViewById(R.id.img_filter_signature)).setVisibility(View.GONE); + (sheetView.findViewById(R.id.img_filter_brand)).setVisibility(View.GONE); + (sheetView.findViewById(R.id.img_filter_sub_brand)).setVisibility(View.GONE); + (sheetView.findViewById(R.id.img_filter_reference)).setVisibility(View.GONE); + db.open(); + brandList = db.getsub_brand_name(counterGroupId, "BrandName", false, selectedSubAxe); + db.open(); + subBrandList = db.getsub_brand_name(counterGroupId, "SubBrandName", false, selectedSubAxe); + db.open(); + referenceList = db.getsub_brand_name(counterGroupId, "ReferenceName", false, selectedSubAxe); + db.open(); + signatureList = db.getsub_brand_name(counterGroupId, "SignatureName", false, selectedSubAxe); + + ValueAdapter adapter = (ValueAdapter) recBrand.getAdapter(); + String type = adapter.getType(); + + ArrayList list = new ArrayList<>(); + + switch (type) { + case CommonString.Signature: + list = signatureList; + break; + case CommonString.Brand: + list = brandList; + break; + case CommonString.SubBrand: + list = subBrandList; + break; + case CommonString.Reference: + list = referenceList; + break; + } + recBrand.setLayoutManager(new LinearLayoutManager(TesterStockActivity.this, LinearLayoutManager.VERTICAL, true)); + recBrand.setAdapter(new ValueAdapter(context, list, CommonString.Signature)); + recBrand.getAdapter().notifyDataSetChanged(); + + } + }); + + mBottomSheetDialog.show(); + + return sheetView; + } + + private class ValueAdapter extends RecyclerView.Adapter { + private LayoutInflater inflator; + List data; + ProductMaster productMaster; + String type; + + private ValueAdapter(Context context, List data, String type) { + inflator = LayoutInflater.from(context); + this.data = data; + this.type = type; + } + + public String getType() { + return type; + } + + @NonNull + @Override + public ValueAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) { + View view = inflator.inflate(R.layout.item_filter, parent, false); + return new ValueAdapter.MyViewHolder(view); + } + + @Override + public void onBindViewHolder(@NonNull final ValueAdapter.MyViewHolder holder, final int position) { + final ProductMaster current = data.get(position); + + final boolean[] selected = {false}; + final int[] filterId = {0}; + + switch (type) { + + case CommonString.Signature: + if (selectedSignature != null && selectedSignature == current) { + selected[0] = true; + } + + break; + + case CommonString.Brand: + if (selectedBrand != null && selectedBrand == current) { + selected[0] = true; + } + + break; + + case CommonString.SubBrand: + if (selectedSubBrand != null && selectedSubBrand == current) { + selected[0] = true; + } + + break; + + case CommonString.Reference: + if (selectedReference != null && selectedReference == current) { + selected[0] = true; + } + + break; + } + + holder.tv_item.setText(CommonFunctions.capitalizeFirstLetter(current.getBrandName())); + + holder.tv_item.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + + et_search.setText(""); + + switch (type) { + case CommonString.Signature: + selectedSignature = current; + filterId[0] = R.id.img_filter_signature; + + //clear other sub filters-- + selectedBrand = null; + selectedSubBrand = null; + selectedReference = null; + + (sheetView.findViewById(R.id.img_filter_brand)).setVisibility(View.GONE); + (sheetView.findViewById(R.id.img_filter_sub_brand)).setVisibility(View.GONE); + (sheetView.findViewById(R.id.img_filter_reference)).setVisibility(View.GONE); + //-- + + setBottomFilter(listAdapter.get_listDataHeader(), current.getBrandName(), listAdapter.get_listDataChild(), CommonString.Signature); + db.open(); + brandList = db.getSubBrandOrReference(counterGroupId, "BrandName", current.getBrandName(), null, null, false, selectedSubAxe); + db.open(); + subBrandList = db.getSubBrandOrReference(counterGroupId, "SubBrandName", current.getBrandName(), null, null, false, selectedSubAxe); + db.open(); + referenceList = db.getSubBrandOrReference(counterGroupId, "ReferenceName", current.getBrandName(), null, null, false, selectedSubAxe); + + + break; + case CommonString.Brand: + selectedBrand = current; + filterId[0] = R.id.img_filter_brand; + + //clear other sub filters-- + selectedSubBrand = null; + selectedReference = null; + + (sheetView.findViewById(R.id.img_filter_sub_brand)).setVisibility(View.GONE); + (sheetView.findViewById(R.id.img_filter_reference)).setVisibility(View.GONE); + //-- + + setBottomFilter(listAdapter.get_listDataHeader(), current.getBrandName(), listAdapter.get_listDataChild(), CommonString.Brand); + //setFilter(FILTER_FOR_BRAND); + db.open(); + subBrandList = db.getSubBrandOrReference(counterGroupId, "SubBrandName", "", current.getBrandName(), null, false, selectedSubAxe); + db.open(); + referenceList = db.getSubBrandOrReference(counterGroupId, "ReferenceName", "", current.getBrandName(), null, false, selectedSubAxe); + break; + case CommonString.SubBrand: + selectedSubBrand = current; + filterId[0] = R.id.img_filter_sub_brand; + + //clear other sub filters-- + selectedReference = null; + + (sheetView.findViewById(R.id.img_filter_reference)).setVisibility(View.GONE); + //-- + + setBottomFilter(listAdapter.get_listDataHeader(), current.getBrandName(), listAdapter.get_listDataChild(), CommonString.SubBrand); + //setFilter(FILTER_FOR_SUB_BRAND); + db.open(); + referenceList = db.getSubBrandOrReference(counterGroupId, "ReferenceName", "", null, current.getBrandName(), false, selectedSubAxe); + break; + case CommonString.Reference: + selectedReference = current; + filterId[0] = R.id.img_filter_reference; + + setBottomFilter(listAdapter.get_listDataHeader(), current.getBrandName(), listAdapter.get_listDataChild(), CommonString.Reference); + //setFilter(FILTER_FOR_REFERENCE); + break; + } + + RecyclerView recSubBrand = sheetView.findViewById(R.id.rec_brand); + recSubBrand.getAdapter().notifyDataSetChanged(); + //show filter icon on filter selected + (sheetView.findViewById(filterId[0])).setVisibility(View.VISIBLE); + } + }); + + if (selected[0]) { + holder.card.setCardBackgroundColor(getResources().getColor(R.color.dashboard_ach)); + } else { + holder.card.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background)); + } + } + + @Override + public int getItemCount() { + + return data.size(); + } + + class MyViewHolder extends RecyclerView.ViewHolder { + TextView tv_item; + CardView card; + + public MyViewHolder(View itemView) { + super(itemView); + tv_item = (TextView) itemView.findViewById(R.id.tv_item); + card = (CardView) itemView.findViewById(R.id.item_card); + + } + } + } + + void setFilterSelected(View sheetView, String type) { + CardView cardSignature, cardBrand, cardSubBrand, cardReference; + cardSignature = sheetView.findViewById(R.id.card_signature); + cardBrand = sheetView.findViewById(R.id.card_brand); + cardSubBrand = sheetView.findViewById(R.id.card_sub_brand); + cardReference = sheetView.findViewById(R.id.card_reference); + + cardSignature.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background)); + cardBrand.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background)); + cardSubBrand.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background)); + cardReference.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background)); + + switch (type) { + case CommonString.Signature: + cardSignature.setCardBackgroundColor(getResources().getColor(R.color.dashboard_ach)); + break; + case CommonString.Brand: + cardBrand.setCardBackgroundColor(getResources().getColor(R.color.dashboard_ach)); + break; + case CommonString.SubBrand: + cardSubBrand.setCardBackgroundColor(getResources().getColor(R.color.dashboard_ach)); + break; + case CommonString.Reference: + cardReference.setCardBackgroundColor(getResources().getColor(R.color.dashboard_ach)); + break; + } + } + + public ArrayList filterListForSignature(List originalList, String text) { + ArrayList filterList = new ArrayList<>(); + for (ProductMaster object : originalList) { + if (object.getSignatureName().equalsIgnoreCase(text)) { + filterList.add(object); + } else { + continue; + } + } + return filterList; + } + + public ArrayList filterListForSubBrand(List originalList, String text) { + ArrayList filterList = new ArrayList<>(); + for (ProductMaster object : originalList) { + if (object.getSubBrandName().equalsIgnoreCase(text) && (selectedSignature == null || object.getSignatureName().equalsIgnoreCase(selectedSignature.getBrandName())) && (selectedBrand == null || object.getBrandName().equalsIgnoreCase(selectedBrand.getBrandName()))) { + filterList.add(object); + } else { + continue; + } + } + return filterList; + } + + public ArrayList filterListForReference(List originalList, String text) { + ArrayList filterList = new ArrayList<>(); + for (ProductMaster object : originalList) { + if (object.getReferenceName().equalsIgnoreCase(text) && (selectedSignature == null || object.getSignatureName().equalsIgnoreCase(selectedSignature.getBrandName())) + && (selectedBrand == null || object.getBrandName().equalsIgnoreCase(selectedBrand.getBrandName())) && (selectedSubBrand == null || object.getSubBrandName().equalsIgnoreCase(selectedSubBrand.getBrandName()))) { + filterList.add(object); + } else { + continue; + } + } + return filterList; + } + + public void setFilter(int filterType) { + if (filterType == FILTER_FOR_SIGNATURE) { + listAdapter = new ExpandableListAdapter(context, filterListForSignature(listDataHeader, selectedSignature.getBrandName()), listDataChild); + } else if (filterType == FILTER_FOR_BRAND) { + listAdapter = new ExpandableListAdapter(context, filterListForBrand(listDataHeader, selectedBrand.getBrandName()), listDataChild); + } else if (filterType == FILTER_FOR_SUB_BRAND) { + listAdapter = new ExpandableListAdapter(context, filterListForSubBrand(listDataHeader, selectedSubBrand.getBrandName()), listDataChild); + } else if (filterType == FILTER_FOR_REFERENCE) { + listAdapter = new ExpandableListAdapter(context, filterListForReference(listDataHeader, selectedReference.getBrandName()), listDataChild); + } else { + listAdapter = new ExpandableListAdapter(context, filterListForSubAxe(listDataHeader, selectedSubAxe), listDataChild); + } + + lvExp_stock_check.setAdapter(listAdapter); + listAdapter.notifyDataSetChanged(); + } + + + public void uploadData(boolean finalFlag) { + //download service + // Intent intent = new Intent(context, Downloader.class); + SaleableGetterSetter stock = new SaleableGetterSetter(); + ArrayList data = new ArrayList<>(); + for (int i = 0; i < listDataHeader.size(); i++) { + List list = listDataChild.get(listDataHeader.get(i)); + for (int j = 0; j < list.size(); j++) { + //for final - complete data upload + if (finalFlag) { + list.get(j).setImagePath(listDataHeader.get(i).getImagePath()); + data.add(list.get(j)); + } else { + if (list.get(j).isSelected()) { + list.get(j).setImagePath(listDataHeader.get(i).getImagePath()); + data.add(list.get(j)); + } + } + } + } + + if (data.size() > 0) { + stock.setProductList(data); + String uuid = CommonFunctions.getUUID(context); + stock.setTransactionId(uuid); + ////changes by jeevan insert transaction for future use and handle master traction + if (regularStockFlag) { + db.open(); + db.insertStockTransactionMasterData(counter_id, visit_date, username, CommonString.TESTER, stock, "Regular_Stock"); + } else { + if (finalFlag) { + db.open(); + db.insertStockTransactionMasterData(counter_id, visit_date, username, CommonString.TESTER, stock, "FirstTime_Stock_Comp"); + } else { + db.open(); + db.insertStockTransactionMasterData(counter_id, visit_date, username, CommonString.TESTER, stock, "FirstTime_Stock_Draft"); + } + } + + dialog.cancel(); + CommonFunctions.call_upload(context); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + TesterStockActivity.this.finish(); + + + /*//for complete upload + if (finalFlag) { + if (CommonFunctions.checkNetIsAvailable(context)) { + int endIndex = 0; + int startIndex = endIndex; + if (startIndex + 200 < stock.getProductList().size()) { + endIndex = startIndex + 200; + } else { + endIndex = stock.getProductList().size(); + } + + UploadStockRecursive(CommonString.KEY_COMPLETE, 0, endIndex, stock); + } + } else { + intent.putExtra(CommonString.TESTER, stock); + String status; + if (regularStockFlag) { + status = null; + } else { + if (finalFlag) { + status = CommonString.KEY_COMPLETE; + } else { + status = CommonString.KEY_DRAFT; + } + } + intent.putExtra(CommonString.KEY_STATUS, status); + Downloader.enqueueWork(TesterStockActivity.this, intent); + dialog.cancel(); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + TesterStockActivity.this.finish(); + }*/ + } + } + + void dialogFinalSubmit(final HashMap> listDataChild, final ArrayList listDataHeader) { + android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(TesterStockActivity.this); + builder.setTitle("Parinaam"); + builder.setMessage(getResources().getString(R.string.want_to_final_save)).setCancelable(false) + .setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { + show_dialog_for_final_submit(context); + } + }) + .setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + dialog.dismiss(); + + } + }); + android.app.AlertDialog alert = builder.create(); + alert.show(); + } + + + private void show_dialog_for_final_submit(final Context context) { + final MultiPurposeDialog final_save_dialog = new MultiPurposeDialog(context); + final_save_dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); + final_save_dialog.setContentView(R.layout.custom_dialog_final_save); + final WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); + lp.copyFrom(final_save_dialog.getWindow().getAttributes()); + lp.width = WindowManager.LayoutParams.MATCH_PARENT; + lp.height = WindowManager.LayoutParams.WRAP_CONTENT; + lp.gravity = Gravity.CENTER; + final_save_dialog.getWindow().setAttributes(lp); + final_save_dialog.setCancelable(false); + + final EditText txt_hint_yes = (EditText) final_save_dialog.findViewById(R.id.txt_hint_yes); + Button btn_cancel = (Button) final_save_dialog.findViewById(R.id.btn_cancel); + Button btn_okay = (Button) final_save_dialog.findViewById(R.id.btn_okay); + + btn_okay.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + if (txt_hint_yes.getText().toString().equals("")) { + AlertandMessages.showToastMsg(context, "Please Enter Text"); + } else if (!txt_hint_yes.getText().toString().trim().equalsIgnoreCase("yes")) { + AlertandMessages.showToastMsg(context, "Please Enter 'Yes' Text"); + } else { + final_save_dialog.dismiss(); + if (regularStockFlag) { + new InsertAsync().execute(false); + } else { + new InsertAsync().execute(true); + } + } + } + }); + + + btn_cancel.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + final_save_dialog.dismiss(); + } + }); + + final_save_dialog.show(); + } + + public class MultiPurposeDialog extends Dialog { + public MultiPurposeDialog(Context context) { + super(context); + // DIALOG USER_INTERFACE TEMPLATE + WindowManager.LayoutParams wmLayoutParams = getWindow().getAttributes(); + wmLayoutParams.gravity = Gravity.CENTER; + getWindow().setAttributes(wmLayoutParams); + setTitle(null); + setCancelable(false); + setOnCancelListener(null); + LinearLayout layout = new LinearLayout(context); + layout.setOrientation(LinearLayout.VERTICAL); + } + } + + private void openScanner() { + IntentIntegrator intentIntegrator = new IntentIntegrator((Activity) context); + intentIntegrator.setBeepEnabled(true); + intentIntegrator.setOrientationLocked(false); + intentIntegrator.setPrompt("Scan the barcode or QR code to get the data"); + intentIntegrator.initiateScan(); + } + + + public void setScanFilter(List scanList) { + HashMap> filterChildHashMap = new HashMap<>(); + ArrayList filterList = new ArrayList<>(); + for (int i = 0; i < listDataHeader.size(); i++) { + ProductMaster parent = listDataHeader.get(i); + List listChild = listDataChild.get(parent); + List listFilterChild = new ArrayList<>(); + for (int j = 0; j < listChild.size(); j++) { + if (containsProduct(scanList, listChild.get(j))) { + listFilterChild.add(listChild.get(j)); + } else { + continue; + } + } + + if (listFilterChild.size() > 0) { + filterList.add(parent); + filterChildHashMap.put(parent, listFilterChild); + + } + + } + + ExpandableListAdapter listAdapter1 = new ExpandableListAdapter(context, filterList, filterChildHashMap); + lvExp_stock_check.setAdapter(listAdapter1); + for (int i = 0; i < listAdapter1.getGroupCount(); i++) { + lvExp_stock_check.expandGroup(i); + } + listAdapter1.notifyDataSetChanged(); + + } + + boolean containsProduct(List scanList, ProductMaster obj) { + boolean contains = false; + + for (int i = 0; i < scanList.size(); i++) { + if (scanList.get(i).getProductId().equals(obj.getProductId())) { + contains = true; + break; + } + } + + return contains; + } + + void clearFilters() { + et_search.setText(""); + + setFilter(CLEAR_FILTER); + selectedSignature = null; + selectedBrand = null; + selectedSubBrand = null; + selectedReference = null; + + if (sheetView != null) { + (sheetView.findViewById(R.id.img_filter_signature)).setVisibility(View.GONE); + (sheetView.findViewById(R.id.img_filter_brand)).setVisibility(View.GONE); + (sheetView.findViewById(R.id.img_filter_sub_brand)).setVisibility(View.GONE); + (sheetView.findViewById(R.id.img_filter_reference)).setVisibility(View.GONE); + } + + db.open(); + brandList = db.getsub_brand_name(counterGroupId, "BrandName", false, selectedSubAxe); + db.open(); + subBrandList = db.getsub_brand_name(counterGroupId, "SubBrandName", false, selectedSubAxe); + db.open(); + referenceList = db.getsub_brand_name(counterGroupId, "ReferenceName", false, selectedSubAxe); + db.open(); + signatureList = db.getsub_brand_name(counterGroupId, "SignatureName", false, selectedSubAxe); + } + + private Dialog dialog; + ProgressBar pb; + + class LoadAsync extends AsyncTask { + + @Override + protected void onPreExecute() { + + dialog = new Dialog(context); + dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); + dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT)); + dialog.setContentView(R.layout.circular_progress_bar); + pb = (ProgressBar) dialog.findViewById(R.id.progressBar1); + dialog.setCancelable(false); + dialog.show(); + + super.onPreExecute(); + } + + @Override + protected Void doInBackground(Void... voids) { + prepareListData(); + //validate_spin_ui_data(); + + return null; + } + + @Override + protected void onPostExecute(Void aVoid) { + dialog.cancel(); + recSubAxe.setLayoutManager(new GridLayoutManager(TesterStockActivity.this, 3)); + subAxeValueAdapter = new SubAxeValueAdapter(context, listSubAxe, CommonString.Signature); + recSubAxe.setAdapter(subAxeValueAdapter); + recSubAxe.getAdapter().notifyDataSetChanged(); + + //validate_spin_ui_data(); + listAdapter = new ExpandableListAdapter(context, listDataHeader, listDataChild); + lvExp_stock_check.setAdapter(listAdapter); + db.open(); + JourneyPlan jcp = db.getJCP(); + if (jcp != null) { + db.open(); + counterGroupId = jcp.getCounterGroupId().toString(); + } else { + counterGroupId = "1"; + } + + super.onPostExecute(aVoid); + } + } + + public class SubAxeValueAdapter extends RecyclerView.Adapter { + private LayoutInflater inflator; + List data; + String type; + + public String getType() { + return type; + } + + public SubAxeValueAdapter(Context context, List data, String type) { + inflator = LayoutInflater.from(context); + this.data = data; + this.type = type; + } + + @Override + public SubAxeValueAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int i) { + View view = inflator.inflate(R.layout.item_filter, parent, false); + return new SubAxeValueAdapter.MyViewHolder(view); + } + + @RequiresApi(api = Build.VERSION_CODES.M) + @Override + public void onBindViewHolder(final SubAxeValueAdapter.MyViewHolder holder, final int position) { + final ProductMaster current = data.get(position); + holder.tv_item.setText(CommonFunctions.capitalizeFirstLetter(current.getSubAxeName())); + + holder.tv_item.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + et_search.setText(""); + listAdapter = new ExpandableListAdapter(context, filterListForSubAxe(listDataHeader, current.getSubAxeName()), listDataChild); + lvExp_stock_check.setAdapter(listAdapter); + listAdapter.notifyDataSetChanged(); + //setExpandableDataForSubAxe(current.getSubAxeName()); + current.setSelected(true); + selectedSubAxe = current.getSubAxeName(); + subAxeValueAdapter.notifyDataSetChanged(); + + jcp = db.getJCP(); + if (jcp != null) { + db.open(); + brandList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "BrandName", false, selectedSubAxe); + db.open(); + subBrandList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "SubBrandName", false, selectedSubAxe); + db.open(); + referenceList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "ReferenceName", false, selectedSubAxe); + db.open(); + signatureList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "SignatureName", false, selectedSubAxe); + } else { + db.open(); + brandList = db.getsub_brand_name("1", "BrandName", false, selectedSubAxe); + subBrandList = db.getsub_brand_name("1", "SubBrandName", false, selectedSubAxe); + referenceList = db.getsub_brand_name("1", "ReferenceName", false, selectedSubAxe); + signatureList = db.getsub_brand_name("1", "SignatureName", false, selectedSubAxe); + } + } + }); + + if (current.getSubAxeName().equalsIgnoreCase(selectedSubAxe)) { + holder.card.setCardBackgroundColor(getColor(R.color.dashboard_ach)); + } else { + holder.card.setCardBackgroundColor(getColor(R.color.grey_dark_background)); + } + } + + @Override + public int getItemCount() { + return data.size(); + } + + class MyViewHolder extends RecyclerView.ViewHolder { + TextView tv_item; + CardView card; + + public MyViewHolder(View itemView) { + super(itemView); + tv_item = (TextView) itemView.findViewById(R.id.tv_item); + card = (CardView) itemView.findViewById(R.id.item_card); + + } + } + } + + public ArrayList filterListForSubAxe(List originalList, String text) { + ArrayList filterList = new ArrayList<>(); + for (ProductMaster object : originalList) { + if (object.getSubAxeName().equalsIgnoreCase(text)) { + filterList.add(object); + } else { + continue; + } + } + return filterList; + } + + public void setBottomFilter(List originalList, String text, HashMap> listDataChild, String type) { + + HashMap> filterChildHashMap = new HashMap<>(); + + ArrayList filterList = new ArrayList<>(); + for (int i = 0; i < originalList.size(); i++) { + ProductMaster parent = originalList.get(i); + List listChild = listDataChild.get(parent); + List listFilterChild = new ArrayList<>(); + for (int j = 0; j < listChild.size(); j++) { + + switch (type) { + case CommonString.Signature: + if (listChild.get(j).getSignatureName().equalsIgnoreCase(text)) { + listFilterChild.add(listChild.get(j)); + } + break; + case CommonString.Brand: + if (listChild.get(j).getBrandName().equalsIgnoreCase(text)) { + listFilterChild.add(listChild.get(j)); + } + break; + case CommonString.SubBrand: + if (listChild.get(j).getSubBrandName().equalsIgnoreCase(text)) { + listFilterChild.add(listChild.get(j)); + } + break; + case CommonString.Reference: + if (listChild.get(j).getReferenceName().equalsIgnoreCase(text)) { + listFilterChild.add(listChild.get(j)); + } + break; + } + + } + + if (listFilterChild.size() > 0) { + filterList.add(parent); + filterChildHashMap.put(parent, listFilterChild); + + } + + } + + ExpandableListAdapter listAdapter1 = new ExpandableListAdapter(context, filterList, filterChildHashMap); + lvExp_stock_check.setAdapter(listAdapter1); + + listAdapter1.notifyDataSetChanged(); + + + } + + private void UploadStockRecursive(final String status, final int startIndex, final int endIndex, final SaleableGetterSetter stock) { + try { + + JSONArray topUpArray = new JSONArray(); + String key = "TesterData"; + int mid = 0; + if (stock != null) { + + if (jcp != null) { + mid = jcp.getMID(); + } + for (int j = startIndex; j < endIndex; j++) { + JSONObject obj = new JSONObject(); + obj.put("ProductId", stock.getProductList().get(j).getProductId()); + obj.put("MID", mid); + obj.put("TranId", stock.getTransactionId()); + obj.put("UserId", username); + obj.put("CounterId", counter_id); + + if (status != null) { + int stk = stock.getProductList().get(j).getStock(); + if (stk == -1) { + stk = 0; + } + + obj.put("STOCK", stk); + obj.put("Status", status); + //different key for first time data + key = "TesterFData"; + } else { + obj.put("STOCK", stock.getProductList().get(j).getStock_receive() - stock.getProductList().get(j).getStock()); + } + + topUpArray.put(obj); + } + } + + JSONObject jsonObject = new JSONObject(); + jsonObject.put("MID", mid); + jsonObject.put("Keys", key); + jsonObject.put("JsonData", topUpArray.toString()); + jsonObject.put("UserId", username); + + String jsonString = jsonObject.toString(); + + OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(20, TimeUnit.SECONDS).writeTimeout(20, TimeUnit.SECONDS).connectTimeout(20, TimeUnit.SECONDS).build(); + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsonString); + Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build(); + PostApi api = adapter.create(PostApi.class); + Call call = api.getGeotag(jsonData); + call.enqueue(new Callback() { + @Override + public void onResponse(Call call, Response response) { + String responseBody = response.body().get("UploadJsonResult").toString(); + String data = null; + if (responseBody != null && response.isSuccessful()) { + try { + data = response.body().get("UploadJsonResult").toString(); + if (data.equals("")) { + } else { + data = data.substring(1, data.length() - 1).replace("\\", ""); + if (data.equalsIgnoreCase(CommonString.KEY_SUCCESS)) { + if (endIndex < stock.getProductList().size()) { + int startIndex1 = endIndex; + int endIndex1 = 0; + if (startIndex1 + 200 < stock.getProductList().size()) { + endIndex1 = startIndex1 + 200; + } else { + endIndex1 = stock.getProductList().size(); + } + UploadStockRecursive(status, startIndex1, endIndex1, stock); + } else { + db.open(); + db.updateStockTransactionDataStatus(stock.getTransactionId()); + dialog.cancel(); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + TesterStockActivity.this.finish(); + } + } + } + } catch (Exception e) { + db.open(); + dialog.cancel(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE + " - " + e.toString() + " - Please Try Again"); + } + } else { + dialog.cancel(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_NO_RESPONSE_SERVER + " - Please Try Again"); + } + } + + @Override + public void onFailure(Call call, Throwable t) { + dialog.cancel(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE + " - Please Try Again"); + } + }); + + + } catch (JSONException e) { + e.fillInStackTrace(); + dialog.cancel(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INVALID_JSON + " - Please Try Again"); + } + } + + class InsertAsync extends AsyncTask { + boolean flag = false; + + @Override + protected void onPreExecute() { + super.onPreExecute(); + dialog = new Dialog(context); + dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); + dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT)); + dialog.setContentView(R.layout.circular_progress_bar); + pb = (ProgressBar) dialog.findViewById(R.id.progressBar1); + dialog.setCancelable(false); + dialog.show(); + } + + @Override + protected Void doInBackground(Boolean... bool) { + flag = bool[0]; + db.open(); + db.insertTesterCapturedData(visit_date, listDataChild, listDataHeader, bool[0], counter_id); + uploadData(bool[0]); + return null; + } + + @Override + protected void onPostExecute(Void aVoid) { + super.onPostExecute(aVoid); + dialog.cancel(); + finish(); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + } + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + getMenuInflater().inflate(R.menu.filter_menu_stock, menu); + return super.onCreateOptionsMenu(menu); + } + + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // Handle action bar item clicks here. The action bar will + // automatically handle clicks on the Home/Up button, so long + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + if (id == android.R.id.home) { + isChanged(); + } else if (id == R.id.filter_data) { + sheetView = showFilterBottomSheet(); + } else if (id == R.id.filled_history) { + startActivity(new Intent(context, FilledRegularStockDataActivity.class).putExtra(CommonString.KEY_ACTIVITY, "Tester")); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + } + + return super.onOptionsItemSelected(item); + } + + private boolean validate_regular_stock() { + check_flag = true; + if (listDataHeader.size() > 0) { + for (int k = 0; k < listDataHeader.size(); k++) { + List child_list = listDataChild.get(listDataHeader.get(k)); + for (int i = 0; i < child_list.size(); i++) { + if (child_list.get(i).isSelected() && child_list.get(i).getStock_receive() != child_list.get(i).getStock()) { + if (child_list.get(i).getReasonId() == 0) { + check_flag = false; + AlertandMessages.showToastMsg(context, "Please Select Reason"); + break; + } + } + + } + if (!check_flag) { + break; + } + } + } + + return check_flag; + + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/VisibilityElimentsActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/VisibilityElimentsActivity.java new file mode 100644 index 0000000..dc9af4d --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/dailyactivity/VisibilityElimentsActivity.java @@ -0,0 +1,556 @@ +package com.cpm.lorealbaautomation.dailyactivity; + +import android.annotation.SuppressLint; +import android.app.AlertDialog; +import android.app.Dialog; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.SharedPreferences; +import android.graphics.Bitmap; +import android.graphics.Typeface; +import android.os.Bundle; + +import com.google.android.material.floatingactionbutton.FloatingActionButton; + +import androidx.appcompat.app.AppCompatActivity; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; +import androidx.appcompat.widget.Toolbar; +import android.util.Log; +import android.view.Gravity; +import android.view.LayoutInflater; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; +import android.view.Window; +import android.view.WindowManager; +import android.webkit.WebView; +import android.webkit.WebViewClient; +import android.widget.AdapterView; +import android.widget.ArrayAdapter; +import android.widget.Button; +import android.widget.ImageView; +import android.widget.LinearLayout; +import android.widget.Spinner; +import android.widget.TextView; + +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.constant.AlertandMessages; +import com.cpm.lorealbaautomation.constant.CommonFunctions; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.download.Downloader; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterNonVisibility; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterPosm; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import static com.cpm.lorealbaautomation.constant.CommonFunctions.getCurrentTime; +import static com.cpm.lorealbaautomation.dailyactivity.StoreImageActivity.convertBitmap; + +public class VisibilityElimentsActivity extends AppCompatActivity implements View.OnClickListener { + String visit_date, username, str_promotion_img = "", _pathforcheck, _path, counterId; + private SharedPreferences preferences; + private SharedPreferences.Editor editor = null; + ArrayList visibilityElementList = new ArrayList<>(); + RecyclerView drawer_layout_recycle_store; + ValueAdapter adapter; + FloatingActionButton fab; + int _currectposition = -1; + Lorealba_Database db; + Context context; + Dialog dialog1; + WebView webview; + ImageView img_main; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_visibility_eliments); + context = this; + db = new Lorealba_Database(context); + db.open(); + uivalidate(); + validateAdapterData(); + } + + + void validateAdapterData() { + db.open(); + visibilityElementList = db.getVisibility_inserted_data(counterId, visit_date,null,false); + if (visibilityElementList.size() == 0) { + db.open(); + visibilityElementList = db.getVisibility_master_data(counterId); + } else { + fab.hide(); + } + + if (visibilityElementList.size() > 0) { + adapter = new ValueAdapter(context, visibilityElementList); + drawer_layout_recycle_store.setAdapter(adapter); + drawer_layout_recycle_store.setLayoutManager(new LinearLayoutManager(context)); + } + + } + + private void uivalidate() { + Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); + preferences = PrefHelper.getPrefs(context); + editor = preferences.edit(); + counterId = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + username = preferences.getString(CommonString.KEY_USERNAME, ""); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + drawer_layout_recycle_store = (RecyclerView) findViewById(R.id.drawer_layout_recycle_store); + fab = (FloatingActionButton) findViewById(R.id.fab); + setSupportActionBar(toolbar); + + if (!CommonFunctions.isTablet(context)) { + toolbar.setTitleTextAppearance(context, R.style.changestext_sizefor_mobile); + } + + getSupportActionBar().setHomeButtonEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + getSupportActionBar().setTitle(getString(R.string.visibility) + " - " + visit_date); + fab.setOnClickListener(this); + + drawer_layout_recycle_store.addOnScrollListener(new RecyclerView.OnScrollListener() { + @Override + public void onScrolled(RecyclerView recyclerView, int dx, int dy) { + if (dy > 0) + fab.hide(); + else if (dy < 0) + fab.show(); + } + }); + } + + + @Override + public void onClick(final View v) { + if (v.getId() == R.id.fab) { + if (validate_condition(visibilityElementList)) { + AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle(R.string.parinaam).setMessage(R.string.alertsaveData); + builder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialogInterface, int i) { + db.open(); + db.insertVisibility_data(username, counterId, visit_date, visibilityElementList, CommonFunctions.getUUID(context)); + dialogInterface.dismiss(); + + //upload service + Intent intent = new Intent(context, Downloader.class); + db.open(); + ArrayList arrayList = db.getVisibility_inserted_data(counterId, visit_date, null, false); + if (arrayList.size() > 0) { + intent.putExtra(CommonString.KEY_VisibilityEliment, arrayList); + Downloader.enqueueWork(context, intent); + } + + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + finish(); + + + } + }); + builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialogInterface, int i) { + dialogInterface.cancel(); + } + }); + builder.show(); + } + } + + } + + public class ValueAdapter extends RecyclerView.Adapter { + private LayoutInflater inflator; + List data; + + public ValueAdapter(Context context, List data) { + inflator = LayoutInflater.from(context); + this.data = data; + } + + @Override + public MyViewHolder onCreateViewHolder(ViewGroup parent, int i) { + View view = inflator.inflate(R.layout.report_posm_tracking, parent, false); + return new MyViewHolder(view); + } + + @Override + public void onBindViewHolder(final MyViewHolder holder, @SuppressLint("RecyclerView") final int position) { + final MasterPosm current = data.get(position); + holder.promotion_name.setText(current.getPosm()); + holder.promotion_name.setTypeface(Typeface.create("sans-serif-thin", Typeface.BOLD)); + holder.promotion_name.setId(position); + + if (!current.getPromotion_exists_state().equals("") && current.getPromotion_exists_state().equalsIgnoreCase("Yes")) { + current.setPromotion_exists_state("Yes"); + holder.rl_child_promotion.setVisibility(View.VISIBLE); + holder.rl_child_promotion.setId(position); + holder.promotion_rl_non.setVisibility(View.GONE); + holder.promotion_rl_non.setId(position); + holder.promotion_btn_first.setBackgroundColor(getResources().getColor(R.color.green)); + holder.promotion_btn_first.setTextColor(getResources().getColor(R.color.white)); + holder.promotion_btn_second.setBackgroundDrawable(getResources().getDrawable(R.drawable.rouded_corner_pinki)); + holder.promotion_btn_second.setTextColor(getResources().getColor(R.color.grayfor_login)); + current.setPromotion_currect_ans_Id("0"); + current.setPromotion_currect_ans(""); + holder.promotion_spin.setSelection(0); + } else if (!current.getPromotion_exists_state().equals("") && current.getPromotion_exists_state().equalsIgnoreCase("No")) { + current.setPromotion_exists_state("No"); + holder.rl_child_promotion.setVisibility(View.GONE); + holder.rl_child_promotion.setId(position); + holder.promotion_rl_non.setVisibility(View.VISIBLE); + holder.promotion_rl_non.setId(position); + holder.promotion_btn_second.setBackgroundColor(getResources().getColor(R.color.red)); + holder.promotion_btn_second.setTextColor(getResources().getColor(R.color.white)); + holder.promotion_btn_first.setBackgroundDrawable(getResources().getDrawable(R.drawable.rouded_corner_pinki)); + holder.promotion_btn_first.setTextColor(getResources().getColor(R.color.grayfor_login)); + + holder.img_promotion.setImageResource(R.mipmap.camera_bs); + holder.img_promotion.setId(position); + current.setPromotion_img(""); + } + + + holder.promotion_btn_first.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + current.setPromotion_exists_state("Yes"); + holder.rl_child_promotion.setVisibility(View.VISIBLE); + holder.rl_child_promotion.setId(position); + holder.promotion_rl_non.setVisibility(View.GONE); + holder.promotion_rl_non.setId(position); + holder.promotion_btn_first.setBackgroundColor(getResources().getColor(R.color.green)); + holder.promotion_btn_first.setTextColor(getResources().getColor(R.color.white)); + holder.promotion_btn_second.setBackgroundDrawable(getResources().getDrawable(R.drawable.rouded_corner_pinki)); + holder.promotion_btn_second.setTextColor(getResources().getColor(R.color.grayfor_login)); + current.setPromotion_currect_ans_Id("0"); + current.setPromotion_currect_ans(""); + holder.promotion_spin.setSelection(0); + } + }); + + holder.promotion_btn_second.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + current.setPromotion_exists_state("No"); + holder.rl_child_promotion.setVisibility(View.GONE); + holder.rl_child_promotion.setId(position); + holder.promotion_rl_non.setVisibility(View.VISIBLE); + holder.promotion_rl_non.setId(position); + + holder.promotion_btn_second.setBackgroundColor(getResources().getColor(R.color.red)); + holder.promotion_btn_second.setTextColor(getResources().getColor(R.color.white)); + holder.promotion_btn_first.setBackgroundDrawable(getResources().getDrawable(R.drawable.rouded_corner_pinki)); + holder.promotion_btn_first.setTextColor(getResources().getColor(R.color.grayfor_login)); + + holder.img_promotion.setImageResource(R.mipmap.camera_bs); + holder.img_promotion.setId(position); + current.setPromotion_img(""); + + } + }); + + holder.img_promotion.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + _currectposition = position; + _pathforcheck = counterId + "_" + current.getPosmId().toString() + "_visibility_img_" + getCurrentTime().replace(":", "") + ".jpg"; + _path = CommonString.getImagesFolder(context) + _pathforcheck; + CommonFunctions.startAnncaCameraActivity(context, _path, null, false, CommonString.CAMERA_FACE_REAR); + } + }); + + if (!str_promotion_img.equals("")) { + if (_currectposition == position) { + current.setPromotion_img(str_promotion_img); + str_promotion_img = ""; + } + } + + if (!current.getPromotion_img().equals("")) { + holder.img_promotion.setImageResource(R.mipmap.camera_bsd); + holder.img_promotion.setId(position); + } else { + holder.img_promotion.setImageResource(R.mipmap.camera_bs); + holder.img_promotion.setId(position); + } + + + //for reason spinner + final ArrayList reason_list = db.getnon_promotion_reasonList(); + MasterNonVisibility non = new MasterNonVisibility(); + non.setReason("- Select -"); + non.setReasonId(0); + reason_list.add(0, non); + + holder.promotion_spin.setAdapter(new ReasonSpinnerAdapter(context, R.layout.spinner_text_view, reason_list)); + + for (int i = 0; i < reason_list.size(); i++) { + if (reason_list.get(i).getReasonId().toString().equals(current.getPromotion_currect_ans_Id())) { + holder.promotion_spin.setSelection(i); + break; + } + } + + holder.promotion_spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { + @Override + public void onItemSelected(AdapterView parent, View view, int pos, long id) { + if (pos != 0) { + MasterNonVisibility ans = reason_list.get(pos); + current.setPromotion_currect_ans(ans.getReason()); + current.setPromotion_currect_ans_Id(ans.getReasonId().toString()); + } else { + current.setPromotion_currect_ans(""); + current.setPromotion_currect_ans_Id("0"); + } + } + + @Override + public void onNothingSelected(AdapterView parent) { + } + }); + + holder.reference_img.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + if (current.getRefImage() != null && !current.getRefImage().equals("")) { + popup(current.getRefImage()); + } else { + AlertandMessages.showToastMsg(context, "Promo Reference image not found"); + } + } + }); + } + + + @Override + public int getItemCount() { + return data.size(); + } + + class MyViewHolder extends RecyclerView.ViewHolder { + ImageView img_promotion; + // TextView promotion_name, start_date, end_date, reference_img; + TextView promotion_name, reference_img; + LinearLayout promotion_rl_non, rl_child_promotion; + Button promotion_btn_first, promotion_btn_second; + Spinner promotion_spin; + + public MyViewHolder(View itemView) { + super(itemView); + promotion_rl_non = (LinearLayout) itemView.findViewById(R.id.promotion_rl_non); + rl_child_promotion = (LinearLayout) itemView.findViewById(R.id.rl_child_promotion); + promotion_spin = (Spinner) itemView.findViewById(R.id.promotion_spin); + promotion_btn_first = (Button) itemView.findViewById(R.id.posm_btn_first); + promotion_btn_second = (Button) itemView.findViewById(R.id.posm_btn_second); + img_promotion = (ImageView) itemView.findViewById(R.id.img_promotion); + promotion_name = (TextView) itemView.findViewById(R.id.posm_name); + reference_img = (TextView) itemView.findViewById(R.id.reference_img); + + } + } + } + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + switch (resultCode) { + case 0: + Log.i("MakeMachine", "User cancelled"); + break; + case -1: + if (_pathforcheck != null && !_pathforcheck.equals("")) { + try { + if (new File(CommonString.getImagesFolder(context) + _pathforcheck).exists()) { + convertBitmap(CommonString.getImagesFolder(context) + _pathforcheck); + str_promotion_img = _pathforcheck; + adapter.notifyDataSetChanged(); + _pathforcheck = ""; + } + + } catch (Exception e) { + e.fillInStackTrace(); + } + } + break; + } + + super.onActivityResult(requestCode, resultCode, data); + } + + public class ReasonSpinnerAdapter extends ArrayAdapter { + List list; + Context context; + int resourceId; + + public ReasonSpinnerAdapter(Context context, int resourceId, ArrayList list) { + super(context, resourceId, list); + this.context = context; + this.list = list; + this.resourceId = resourceId; + } + + @Override + public View getView(int position, View convertView, ViewGroup parent) { + View view = convertView; + LayoutInflater inflater = getLayoutInflater(); + view = inflater.inflate(resourceId, parent, false); + MasterNonVisibility cm = list.get(position); + TextView txt_spinner = (TextView) view.findViewById(R.id.txt_sp_text); + txt_spinner.setText(list.get(position).getReason()); + + return view; + } + + @Override + public View getDropDownView(int position, View convertView, ViewGroup parent) { + View view = convertView; + LayoutInflater inflater = getLayoutInflater(); + view = inflater.inflate(resourceId, parent, false); + MasterNonVisibility cm = list.get(position); + TextView txt_spinner = (TextView) view.findViewById(R.id.txt_sp_text); + txt_spinner.setText(cm.getReason()); + + return view; + } + + } + + @Override + public void onBackPressed() { + AlertDialog.Builder builder = new AlertDialog.Builder(context); + builder.setMessage(CommonString.ONBACK_ALERT_MESSAGE) + .setCancelable(false) + .setPositiveButton("OK", new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + finish(); + } + }) + .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { + dialog.cancel(); + } + }); + AlertDialog alert = builder.create(); + alert.show(); + } + + + private boolean validate_condition(ArrayList promotionList) { + boolean status = true; + for (int k = 0; k < promotionList.size(); k++) { + MasterPosm object = promotionList.get(k); + if (!object.getPromotion_exists_state().equals("")) { + if (object.getPromotion_exists_state().equalsIgnoreCase("Yes")) { + if (object.getPromotion_img().equals("")) { + showTost("Please capture " + object.getPosm() + " image_icon."); + status = false; + break; + } + } else { + if (object.getPromotion_currect_ans_Id().equals("0")) { + showTost("Please Select reason of " + object.getPosm() + "."); + status = false; + break; + } + } + } else { + // showTost("Please Click Exists of " + object.getPromotionName() + "."); + showTost("Please Click Exists of " + object.getPosm() + "."); + status = false; + } + } + return status; + } + + void showTost(String msg) { + AlertandMessages.showToastMsg(context, msg); + } + + public class MultiPurposeDialog extends Dialog { + public MultiPurposeDialog(Context context) { + super(context); + // DIALOG USER_INTERFACE TEMPLATE + WindowManager.LayoutParams wmLayoutParams = getWindow().getAttributes(); + wmLayoutParams.gravity = Gravity.CENTER; + getWindow().setAttributes(wmLayoutParams); + setTitle(null); + setCancelable(false); + setOnCancelListener(null); + LinearLayout layout = new LinearLayout(context); + layout.setOrientation(LinearLayout.VERTICAL); + } + } + + private void popup(final String window_image) { + dialog1 = new Dialog(VisibilityElimentsActivity.this); + dialog1.requestWindowFeature(Window.FEATURE_NO_TITLE); + dialog1.setContentView(R.layout.dialog_refrence_image); + webview = (WebView) dialog1.findViewById(R.id.webview); + img_main = (ImageView) dialog1.findViewById(R.id.img_main); + // dialog1.setCancelable(false); + dialog1.setCanceledOnTouchOutside(true); + db.open(); + + webview.setWebViewClient(new MyWebViewClient()); + + + webview.getSettings().setJavaScriptEnabled(true); + if (window_image != null) { + webview.loadUrl(window_image); + } + + dialog1.show(); + } + + private class MyWebViewClient extends WebViewClient { + @Override + public boolean shouldOverrideUrlLoading(WebView view, String url) { + view.loadUrl(url); + return true; + } + + @Override + public void onPageFinished(WebView view, String url) { + + // img_main.setVisibility(View.VISIBLE); + webview.setVisibility(View.VISIBLE); + super.onPageFinished(view, url); + view.clearCache(true); + } + + @Override + public void onPageStarted(WebView view, String url, Bitmap favicon) { + + super.onPageStarted(view, url, favicon); + } + + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // Handle action bar item clicks here. The action bar will + // automatically handle clicks on the Home/Up button, so long + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + + if (id == android.R.id.home) { + super.onBackPressed(); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + } + + + return super.onOptionsItemSelected(item); + } + + +} \ No newline at end of file diff --git a/app/src/main/java/com/cpm/lorealbaautomation/delegates/CoverageBean.java b/app/src/main/java/com/cpm/lorealbaautomation/delegates/CoverageBean.java new file mode 100644 index 0000000..e116247 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/delegates/CoverageBean.java @@ -0,0 +1,119 @@ +package com.cpm.lorealbaautomation.delegates; + +public class CoverageBean +{ + protected int MID; + protected String storeId; + protected String Remark; + public String getRemark() { + return Remark; + } + public void setRemark(String remark) { + Remark = remark; + } + protected String userId; + protected String visitDate; + private String latitude; + private String longitude; + private String reasonid=""; + private String reason=""; + private String image=""; + String counter_name="",counter_Id=""; + + public String getCounter_name() { + return counter_name; + } + + public void setCounter_name(String counter_name) { + this.counter_name = counter_name; + } + + public String getCounter_Id() { + return counter_Id; + } + + public void setCounter_Id(String counter_Id) { + this.counter_Id = counter_Id; + } + + public String getCkeckout_image() { + return ckeckout_image; + } + + public void setCkeckout_image(String ckeckout_image) { + this.ckeckout_image = ckeckout_image; + } + + private String ckeckout_image=""; + + public String getImage() { + return image; + } + public void setImage(String image) { + this.image = image; + } + public int getMID() { + return MID; + } + + public void setMID(int mID) { + MID = mID; + } + + public String getStoreId() { + return storeId; + } + + public void setStoreId(String storeId) { + this.storeId = storeId; + } + + public String getUserId() { + return userId; + } + + public void setUserId(String userId) { + this.userId = userId; + } + public String getVisitDate() { + return visitDate; + } + + public void setVisitDate(String visitDate) { + this.visitDate = visitDate; + } + public String getLatitude() { + return latitude; + } + + public void setLatitude(String latitude) { + this.latitude = latitude; + } + + public String getLongitude() { + return longitude; + } + + public void setLongitude(String longitude) { + this.longitude = longitude; + } + + public String getReasonid() { + return reasonid; + } + + public void setReasonid(String reasonid) { + this.reasonid = reasonid; + } + + public String getReason() { + return reason; + } + + public void setReason(String reason) { + this.reason = reason; + } + + + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/delegates/NavMenuItemGetterSetter.java b/app/src/main/java/com/cpm/lorealbaautomation/delegates/NavMenuItemGetterSetter.java new file mode 100644 index 0000000..54c3fe9 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/delegates/NavMenuItemGetterSetter.java @@ -0,0 +1,18 @@ +package com.cpm.lorealbaautomation.delegates; + +public class NavMenuItemGetterSetter { + String iconName = ""; + int iconImg = -1; // menu icon resource id + public String getIconName() { + return iconName; + } + public void setIconName(String iconName) { + this.iconName = iconName; + } + public int getIconImg() { + return iconImg; + } + public void setIconImg(int iconImg) { + this.iconImg = iconImg; + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/delegates/PrefHelper.java b/app/src/main/java/com/cpm/lorealbaautomation/delegates/PrefHelper.java new file mode 100644 index 0000000..ddc9b26 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/delegates/PrefHelper.java @@ -0,0 +1,12 @@ +package com.cpm.lorealbaautomation.delegates; + +import android.content.Context; +import android.content.SharedPreferences; + +public class PrefHelper { + private static final String PREF_NAME = "loreal_ba_prefs"; + public static SharedPreferences getPrefs(Context context) { + return context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE); + } +} + diff --git a/app/src/main/java/com/cpm/lorealbaautomation/download/DownloadActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/download/DownloadActivity.java new file mode 100644 index 0000000..e5d182c --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/download/DownloadActivity.java @@ -0,0 +1,247 @@ +package com.cpm.lorealbaautomation.download; + +import android.annotation.SuppressLint; +import android.app.ProgressDialog; +import android.content.Context; +import android.content.SharedPreferences; +import android.net.Uri; +import android.os.Bundle; + +import androidx.annotation.NonNull; +import androidx.appcompat.app.AppCompatActivity; +import androidx.appcompat.widget.Toolbar; + +import android.widget.TextView; +import android.widget.VideoView; + +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.retrofit.DownloadAllDatawithRetro; + +import org.json.JSONException; +import org.json.JSONObject; + +import java.util.ArrayList; + + +public class DownloadActivity extends AppCompatActivity { + Lorealba_Database db; + String userId, date, counter_id = ""; + private SharedPreferences preferences = null; + SharedPreferences.Editor editor; + Toolbar toolbar; + Context context; + int downloadindex = 0, tagfor_downloadalldata = 0; + VideoView vedio_view, vedio_view_2; + ProgressDialog pd; + + @SuppressLint("SetTextI18n") + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_download); + toolbar = (Toolbar) findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + context = this; + db = new Lorealba_Database(context); + preferences = PrefHelper.getPrefs(context); + editor = preferences.edit(); + + userId = preferences.getString(CommonString.KEY_USERNAME, ""); + date = preferences.getString(CommonString.KEY_DATE, ""); + counter_id = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + downloadindex = preferences.getInt(CommonString.KEY_DOWNLOAD_INDEX, 0); + tagfor_downloadalldata = getIntent().getIntExtra(CommonString.TAG_FROM, 0); + vedio_view = (VideoView) findViewById(R.id.vedio_view); + vedio_view_2 = (VideoView) findViewById(R.id.vedio_view_2); + String path = "android.resource://" + getPackageName() + "/" + R.raw.giffy; + vedio_view.setVideoURI(Uri.parse(path)); + vedio_view.start(); + vedio_view_2.setVideoURI(Uri.parse(path)); + vedio_view_2.start(); + vedio_view.resume(); + vedio_view_2.resume(); + setTitle("Downloading Data - " + date); + String couter_code = preferences.getString(CommonString.KEY_COUNTER_CODE, ""); + TextView txt_counter_code = (TextView) findViewById(R.id.txt_counter_code); + txt_counter_code.setText("Counter Code - " + couter_code + " / Id - " + counter_id); + UploadDataTask(); + } + + public void UploadDataTask() { + try { + ArrayList keysList = new ArrayList<>(); + ArrayList jsonList = new ArrayList<>(); + ArrayList KeyNames = new ArrayList<>(); + keysList.add("Table_Structure"); + if (tagfor_downloadalldata == 1) { + keysList.add("StockSummary_Check"); + keysList.add("T_StockSummary"); + editor = preferences.edit(); + editor.putInt(CommonString.KEY_FIRST_DOWNLOAD_TsTOCK + date, 1); + editor.commit(); + } else { + keysList.add("Mapping_JourneyPlan"); + keysList.add("BA_List"); + keysList.add("ServerTime"); + keysList.add("Mapping_CounterGroup_Brand"); + keysList.add("Mapping_Visibility"); + keysList.add("Master_Posm"); + keysList.add("T_CounterInvoice"); + keysList.add("Master_NonVisibility"); + keysList.add("Master_SkinType"); + keysList.add("Master_AgeLimit"); + keysList.add("Master_Profile"); + keysList.add("Master_ProfileQuestion"); + keysList.add("Master_SkinType"); + keysList.add("Master_AgeLimit"); + keysList.add("Master_NonStockReason"); + keysList.add("Master_ReturnReason"); + keysList.add("Master_TermsCondition"); + keysList.add("T_LeaveRequest"); + //keysList.add("T_LeaveLedger"); + keysList.add("Master_Break"); + keysList.add("Master_InvoiceType"); + /////Checking T_StockSummery and StockSummeryCheck size is not from current date + db.open(); + if (!db.isTStockSummaryFilled(date)) { + keysList.add("StockSummary_Check"); + keysList.add("T_StockSummary"); + editor = preferences.edit(); + editor.putInt(CommonString.KEY_FIRST_DOWNLOAD_TsTOCK + date, 1); + editor.commit(); + } + + ///download_report by JP + keysList.add("Report_SalesValue"); + keysList.add("Report_Sales_Detail"); + keysList.add("Report_AvgTransactionPerDay"); + keysList.add("Report_AvgUnitsPerBill"); + keysList.add("Report_AvgBillValue"); + keysList.add("Report_AvgLinPerBill"); + keysList.add("Report_SellingPrice"); + keysList.add("Report_Top10Volume"); + keysList.add("Report_Top10Value"); + keysList.add("Master_BAProfile"); + keysList.add("Master_PromoOffers"); + keysList.add("Report_AttendanceDetail"); + keysList.add("Report_AttendanceSummary"); + keysList.add("Report_InwardStockSummary"); + keysList.add("Report_BA_Availability"); + keysList.add("Master_Looks"); + keysList.add("ME_MEAuditQuestion"); + //promotion related + keysList.add("Master_Promotion"); + keysList.add("Master_PromotionSetEntityItem"); + keysList.add("Master_PromotionGetEntityItem"); + keysList.add("Master_PromotionSetProductGroup"); + keysList.add("Master_PromotionGetProductGroup"); + keysList.add("Master_Survey"); + keysList.add("Master_LeaveType"); + keysList.add("Damage_ReturnToDistributor"); + keysList.add("Master_Survey_UploadStatus"); + keysList.add("ME_MEAuditQuestion_UploadStatus"); + keysList.add("Master_PromotionSetProductCatalog"); + keysList.add("Master_PromotionGetProductCatalog"); + keysList.add("Report_ProductGroupWiseSalesValue"); + keysList.add("Report_SalesDateWise"); + keysList.add("Damage_PreviousPending"); + keysList.add("SkinGeniusUrl"); + keysList.add("Report_SalesL3MValue"); + keysList.add("Master_PromotionSetExclusionList"); + keysList.add("Master_PromotionGetExclusionList"); + keysList.add("Master_SourcesOfSales"); + keysList.add("Report_DamageStockHistory"); + keysList.add("Master_CompetitonBrandWiseNuance"); + keysList.add("Master_CompetitionOfferSet"); + keysList.add("Master_CompetitionOfferGet"); + keysList.add("Master_CompetitionPromoType"); + keysList.add("Master_CompetitionProductType"); + //////// + keysList.add("Master_CompetitionOffer"); + keysList.add("Master_CompetitionOfferSaleRange"); + keysList.add("Master_RetailExcellence_Item"); + keysList.add("D2D_ARS"); + ///new report for me + keysList.add("Report_Sales_DetailME"); + keysList.add("Report_SalesDateWiseME"); + keysList.add("Report_SalesL3MValueME"); + keysList.add("Report_MTD_WorkingCounterME"); + //keysList.add("Report_ME_Sale"); + ///new reports added 25/5/024 + keysList.add("AppDashboard_TVA"); + keysList.add("AppDashboard_TVADrillDown"); + keysList.add("AppDashboard_LeaderBoard"); + keysList.add("AppDashboard_Incentive"); + /* All reports replaced by new reports + keysList.add("AppDashboard_L3MOffTake_Counter"); + keysList.add("AppDashboard_L3MOffTake_Nuance"); + keysList.add("AppDashboard_L3MOffTake_SubAxe");*/ + keysList.add("ReportDaily_TVA"); + keysList.add("Report_SalesGrowth_Counter"); + keysList.add("Report_SalesGrowth_CounterDetail"); + keysList.add("Report_TesterCounterDetail"); + keysList.add("Report_TesterCounter"); + keysList.add("Report_CounterVolume"); + keysList.add("Report_CounterVolumeDetail"); + keysList.add("Report_ConterValue"); + keysList.add("Report_ConterValueDetail"); + keysList.add("Report_CounterInwardStock"); + keysList.add("Report_CounterInwardStockDetail"); + keysList.add("Report_CounterStockLedger"); + keysList.add("Report_CounterStockLedgerDetail"); + keysList.add("Report_BA_TBAPromoSale"); + keysList.add("Report_BA_TBASale"); + keysList.add("T_LeaveRequestDetail"); + keysList.add("Master_HolidayList"); + keysList.add("T_LeaveLedgerSummary"); + keysList.add("Mapping_AppRestrictedKPI"); + keysList.add("Product_Master"); + } + + if (!keysList.isEmpty()) { + for (int i = 0; i < keysList.size(); i++) { + JSONObject jsonObject1 = getJsonObject(keysList, i); + jsonList.add(jsonObject1.toString()); + KeyNames.add(keysList.get(i)); + } + + if (!jsonList.isEmpty()) { + pd = new ProgressDialog(context); + pd.setCancelable(false); + pd.setMessage("Downloading Data" + "(" + "/" + ")"); + pd.show(); + DownloadAllDatawithRetro downloadData = new DownloadAllDatawithRetro(context, db, pd, CommonString.TAG_FROM_CURRENT); + downloadData.listSize = jsonList.size(); + downloadData.downloadDataUniversalWithoutWait(jsonList, KeyNames, downloadindex, CommonString.DOWNLOAD_ALL_SERVICE); + } + } + } catch (Exception e) { + e.fillInStackTrace(); + } + } + + private @NonNull JSONObject getJsonObject(ArrayList keysList, int i) throws JSONException { + JSONObject jsonObject1 = new JSONObject(); + jsonObject1.put("Downloadtype", keysList.get(i)); + jsonObject1.put("Username", userId); + jsonObject1.put("Param1", counter_id); + jsonObject1.put("Param2", keysList.get(i).equals("Report_TesterCounterDetail") + || keysList.get(i).equals("Report_CounterVolumeDetail") + || keysList.get(i).equals("Report_ConterValueDetail") + || keysList.get(i).equals("Report_CounterInwardStockDetail") + || keysList.get(i).equals("Report_CounterStockLedgerDetail") + || keysList.get(i).equals("Report_SalesGrowth_CounterDetail") ? "AxeName" : ""); + return jsonObject1; + } + + @Override + public void onDestroy() { + super.onDestroy(); + if (pd != null && pd.isShowing()) { + pd.cancel(); + } + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/download/Downloader.java b/app/src/main/java/com/cpm/lorealbaautomation/download/Downloader.java new file mode 100644 index 0000000..cde3ed5 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/download/Downloader.java @@ -0,0 +1,1214 @@ +package com.cpm.lorealbaautomation.download; + +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; + +import androidx.core.app.JobIntentService; + +import com.google.gson.JsonObject; +import com.google.gson.JsonSyntaxException; +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.gettersetter.BaProfileGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.GroomingGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.InvoiceGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.JourneyPlan; +import com.cpm.lorealbaautomation.gsonGetterSetter.MEMEAuditQuestion; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterBreak; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterPosm; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterProfile; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterRetailExcellence; +import com.cpm.lorealbaautomation.gsonGetterSetter.ProductMaster; +import com.cpm.lorealbaautomation.gsonGetterSetter.TStockSummaryGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.T_LeaveRequest; +import com.cpm.lorealbaautomation.retrofit.PostApi; +import com.cpm.lorealbaautomation.retrofit.PostApiForUpload; +import com.cpm.lorealbaautomation.retrofit.StringConverterFactory; +import com.squareup.okhttp.MultipartBuilder; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.File; +import java.io.IOException; +import java.net.SocketException; +import java.net.SocketTimeoutException; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.concurrent.TimeUnit; + +import okhttp3.MediaType; +import okhttp3.OkHttpClient; +import okhttp3.RequestBody; +import retrofit2.Call; +import retrofit2.Callback; +import retrofit2.Response; +import retrofit2.Retrofit; +import retrofit2.converter.gson.GsonConverterFactory; + +import static com.cpm.lorealbaautomation.constant.CommonFunctions.saveBitmapToFile; + +public class Downloader extends JobIntentService { + private static final int UNIQUE_JOB_ID = 1337; + Context context; + Lorealba_Database db; + SharedPreferences preferences; + SharedPreferences.Editor editor; + String uploadimg_str; + protected TStockSummaryGetterSetter tStockSummaryObj; + private String counter_id; + private String visit_date; + private String username; + int mid = 0; + BaProfileGetterSetter baProfile; + JourneyPlan counterimg_object; + MasterProfile baProfileImage; + ArrayList visibilityEliment = new ArrayList<>(); + T_LeaveRequest leaveRequestObject; + MasterBreak breakManagementObject; + InvoiceGetterSetter me_makeover_captueObject; + ArrayList me_makeoverList = new ArrayList<>(); + ArrayList quizList = new ArrayList<>(); + ArrayList productMasterArrayList = new ArrayList<>(); + ArrayList masterRetailExcellenceArrayList = new ArrayList<>(); + JourneyPlan ba_counter_imges_dataObject, me_counter_imges_dataObject; + GroomingGetterSetter groomedImagGetterSetter; + + public static void enqueueWork(Context ctxt, Intent i) { + enqueueWork(ctxt, Downloader.class, UNIQUE_JOB_ID, i); + } + + @Override + public void onHandleWork(Intent intent) { + context = getApplicationContext(); + preferences = PrefHelper.getPrefs(context); + editor = preferences.edit(); + counter_id = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + username = preferences.getString(CommonString.KEY_USERNAME, ""); + db = new Lorealba_Database(context); + db.open(); + counterimg_object = (JourneyPlan) intent.getSerializableExtra(CommonString.KEY_CounterProfile); + baProfile = (BaProfileGetterSetter) intent.getSerializableExtra(CommonString.KEY_BaProfile_list); + baProfileImage = (MasterProfile) intent.getSerializableExtra(CommonString.KEY_BaProfile); + visibilityEliment = (ArrayList) intent.getSerializableExtra(CommonString.KEY_VisibilityEliment); + leaveRequestObject = (T_LeaveRequest) intent.getSerializableExtra(CommonString.KEY_LEAVE_Mangemennt); + breakManagementObject = (MasterBreak) intent.getSerializableExtra(CommonString.KEY_Break_Mangemennt); + ba_counter_imges_dataObject = (JourneyPlan) intent.getSerializableExtra(CommonString.KEY_BA_Counter_Image); + me_counter_imges_dataObject = (JourneyPlan) intent.getSerializableExtra(CommonString.KEY_Me_Counter_Image); + ///change jp + groomedImagGetterSetter = (GroomingGetterSetter) intent.getSerializableExtra(CommonString.KEY_Groomed_Image); + uploadimg_str = intent.getStringExtra(CommonString.KEY_UPLOADIMAGE); + ArrayList jcp = db.getStoreData(visit_date, null,counter_id); + quizList = (ArrayList) intent.getSerializableExtra(CommonString.KEY_ME_QUIZ); + masterRetailExcellenceArrayList = (ArrayList) intent.getSerializableExtra(CommonString.KEY_RETAIL_EXCELLENCE); + productMasterArrayList = (ArrayList) intent.getSerializableExtra(CommonString.ME_SALE); + + me_makeover_captueObject = (InvoiceGetterSetter) intent.getSerializableExtra(CommonString.KEY_Me_MakeOver_Capture); + if (jcp.size() > 0) { + mid = jcp.get(0).getMID(); + } + + //Corrected 01-12-20 + if (quizList != null) { + ////for upload quiz data me + quizList = db.getme_quiz_from_database(null, null, visit_date, counter_id, null); + calculate_me_quiz_data(db.getBIDfromJCP(username, counter_id), quizList); + } + else if(masterRetailExcellenceArrayList!=null){ + masterRetailExcellenceArrayList = db.getRetailExcellencedata(null, null, visit_date, counter_id); + calculate_retail_excellence_data(db.getBIDfromJCP(username, counter_id), masterRetailExcellenceArrayList); + } + else if(productMasterArrayList!=null){ + productMasterArrayList = db.getMeSaledata(null, null, visit_date, counter_id); + calculate_me_sale_data(db.getBIDfromJCP(username, counter_id), productMasterArrayList); + } + else if (counterimg_object != null) { + UploadCounterProfile(); + } else if (baProfileImage != null) { + UploadBaProfile(); + } else if (visibilityEliment != null) { + UploadVisibilityElement(); + } else if (leaveRequestObject != null) { + String TransId = leaveRequestObject.getTransId(); + db.open(); + leaveRequestObject = db.getinserted_leave_request_data(counter_id, username, visit_date, TransId, false); + if (leaveRequestObject.getTransId() != null && !leaveRequestObject.getTransId().equals("")) { + calculate_leave_data(leaveRequestObject); + } + } else if (me_makeover_captueObject != null) { + db.open(); + me_makeoverList = db.getMakeoverCapture(visit_date, counter_id); + calculate_me_makeoverdata(me_makeoverList, 0); + + } else if (breakManagementObject != null) { + String TransId = breakManagementObject.getTransId(); + db.open(); + breakManagementObject = db.getBreakManagementforuploadList(counter_id, visit_date, username, TransId, false); + if (breakManagementObject.getBreakId() != null && !breakManagementObject.getEndTym().equals("")) { + calculate_break_data(breakManagementObject); + } + } else if (ba_counter_imges_dataObject != null) { + String TransId = ba_counter_imges_dataObject.getTransId(); + db.open(); + ba_counter_imges_dataObject = db.getba_counter_img(counter_id, visit_date, username, TransId); + calculate_ba_counter_imgage_data(ba_counter_imges_dataObject); + } else if (me_counter_imges_dataObject != null) { + String TransId = me_counter_imges_dataObject.getTransId(); + db.open(); + me_counter_imges_dataObject = db.getba_counter_img(counter_id, visit_date, username, TransId); + calculate_me_counter_imgage_data(me_counter_imges_dataObject); + } else if (groomedImagGetterSetter != null) { + db.open(); + groomedImagGetterSetter = db.getinserted_groomingdata(counter_id, username, visit_date); + calculate_Groomed_Image_Data(groomedImagGetterSetter); + } + if (uploadimg_str != null && !getFileNames(new File(CommonString.getImagesFolder(context)).listFiles()).isEmpty()) { + UploadImageRecursive(); + } + } + + private void UploadVisibilityElement() { + try { + JSONArray topUpArray = new JSONArray(); + if (visibilityEliment != null) { + for (int j = 0; j < visibilityEliment.size(); j++) { + JSONObject obj = new JSONObject(); + obj.put("MID", mid); + obj.put("UserId", username); + obj.put("PosmId", visibilityEliment.get(j).getPosmId()); + obj.put("PosmTypeId", visibilityEliment.get(j).getPosmTypeId()); + obj.put("Counter_id", counter_id); + + if (visibilityEliment.get(j).getPromotion_exists_state().equalsIgnoreCase("Yes")) { + obj.put("Promotion_Exists", "1"); + obj.put("Promo_Img", visibilityEliment.get(j).getPromotion_img()); + obj.put("PReason_Id", "0"); + } else { + obj.put("Promotion_Exists", "0"); + obj.put("Promo_Img", ""); + obj.put("PReason_Id", visibilityEliment.get(j).getPromotion_currect_ans_Id()); + } + topUpArray.put(obj); + } + } + + JSONObject jsonObject = new JSONObject(); + jsonObject.put("MID", mid); + jsonObject.put("Keys", "VisibiliElementData"); + jsonObject.put("JsonData", topUpArray.toString()); + jsonObject.put("UserId", username); + + String jsonString = jsonObject.toString(); + + OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build(); + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsonString); + Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build(); + PostApi api = adapter.create(PostApi.class); + Call call = api.getGeotag(jsonData); + call.enqueue(new Callback() { + @Override + public void onResponse(Call call, Response response) { + String responseBody = response.body().get("UploadJsonResult").toString(); + String data = null; + if (responseBody != null && response.isSuccessful()) { + try { + data = response.body().get("UploadJsonResult").toString(); + if (data.equals("")) { + } else { + data = data.substring(1, data.length() - 1).replace("\\", ""); + if (data.equalsIgnoreCase(CommonString.KEY_SUCCESS)) { + db.open(); + if (visibilityEliment.size() > 0) { + db.updateVisibilityStatus(visibilityEliment.get(0).getTransId()); + db.open(); + db.updateMasterTransactionDataStatus(visibilityEliment.get(0).getTransId()); + } + } + } + } catch (Exception e) { + e.fillInStackTrace(); + } + } + } + @Override + public void onFailure(Call call, Throwable t) { + + } + }); + + + } catch (JSONException e) { + e.fillInStackTrace(); + } + } + + private void UploadBaProfile() { + try { + JSONArray topUpArray = new JSONArray(); + JSONArray storeDetail = new JSONArray(); + if (baProfileImage != null) { + if (baProfile != null && baProfile.getBaProfileList().size() > 0) { + for (int j = 0; j < baProfile.getBaProfileList().size(); j++) { + JSONObject obj = new JSONObject(); + obj.put("Category_Id", baProfile.getBaProfileList().get(j).getCATEGORY_ID()); + obj.put("Question_Id", baProfile.getBaProfileList().get(j).getQUESTION_ID()); + obj.put("Question", baProfile.getBaProfileList().get(j).getQUESTION()); + obj.put("Answer_type", baProfile.getBaProfileList().get(j).getANSWER_TYPE()); + obj.put("Answer_Id", baProfile.getBaProfileList().get(j).getANSWER_ID()); + obj.put("Answer", baProfile.getBaProfileList().get(j).getANSWER()); + obj.put("OthersTextValue", baProfile.getBaProfileList().get(j).getSpin_others_for_edt()); + obj.put("Visit_Date", visit_date); + obj.put("MID", mid); + obj.put("UserId", username); + obj.put("Counter_id", counter_id); + topUpArray.put(obj); + } + } + + if (baProfileImage.getProfilePic() != null && !baProfileImage.getProfilePic().equals("")) { + + JSONObject jsonObject = new JSONObject(); + jsonObject.put("Address", baProfileImage.getAddress()); + jsonObject.put("Dob", baProfileImage.getDob()); + jsonObject.put("Mobile_no", baProfileImage.getMobile()); + jsonObject.put("Email_Address", baProfileImage.getEmail()); + jsonObject.put("Instagram_Address", baProfileImage.getInstragramAddress()); + jsonObject.put("Profile_pic", baProfileImage.getProfilePic()); + jsonObject.put("Location", baProfileImage.getLocation()); + jsonObject.put("Landmark", baProfileImage.getLandmark()); + jsonObject.put("MID", mid); + jsonObject.put("UserId", username); + jsonObject.put("Counter_id", counter_id); + if (baProfile != null && baProfile.getBaProfileList().size() > 0) { + jsonObject.put("BA_PROFILE_DATA", topUpArray); + } else { + jsonObject.put("BA_PROFILE_DATA", ""); + } + + storeDetail.put(jsonObject); + } + + JSONObject jsonFinalObject = new JSONObject(); + jsonFinalObject.put("MID", mid); + jsonFinalObject.put("Keys", "BaProfileData"); + jsonFinalObject.put("JsonData", storeDetail.toString()); + jsonFinalObject.put("UserId", username); + upload_BaProfilewithaudit(jsonFinalObject.toString()); + } + } catch (JSONException e) { + e.fillInStackTrace(); + } + } + + private void UploadCounterProfile() { + try { + JSONArray storeDetail = new JSONArray(); + JSONObject jsonObject; + db.open(); + counterimg_object = db.getCounterProfileData(username, visit_date, counter_id, false); + if (counterimg_object.getUserId() != null && !counterimg_object.getUserId().equals("")) { + jsonObject = new JSONObject(); + jsonObject.put("MID", mid); + jsonObject.put("UserId", username); + jsonObject.put("ProfileImage1", counterimg_object.getProfileImage1()); + jsonObject.put("ProfileImage2", counterimg_object.getProfileImage2()); + jsonObject.put("Counterlength", counterimg_object.getCounterlength()); + jsonObject.put("Counterwidth", counterimg_object.getCounterwidth()); + jsonObject.put("SetupDate", counterimg_object.getSetupDate()); + jsonObject.put("Visit_Date", visit_date); + jsonObject.put("Counter_id", counter_id); + storeDetail.put(jsonObject); + + jsonObject = new JSONObject(); + jsonObject.put("MID", mid); + jsonObject.put("Keys", "ConterProfileData"); + jsonObject.put("JsonData", storeDetail.toString()); + jsonObject.put("UserId", username); + upload_CounterProfile(jsonObject.toString(), counterimg_object); + } + } catch (JSONException e) { + e.fillInStackTrace(); + } + } + + private void calculate_leave_data(T_LeaveRequest leaveRequestObject) { + try { + JourneyPlan jcpfor_bid = db.getBIDfromJCP(username, counter_id); + JSONArray promoArray = new JSONArray(); + JSONObject obj = new JSONObject(); + obj.put("MID", jcpfor_bid.getMID()); + obj.put("BID", jcpfor_bid.getBID()); + obj.put("UserId", username); + + obj.put("TranId", leaveRequestObject.getTransId()); + obj.put("Applied_Date", leaveRequestObject.getUpload_request_date()); + obj.put("From_Date", leaveRequestObject.getUpload_start_date_str()); + obj.put("End_Date", leaveRequestObject.getUpload_end_date_str()); + obj.put("Leave_Type", leaveRequestObject.getOne_day_leave_str()); + obj.put("Leave_TypeId", leaveRequestObject.getStr_leaveTypeId()); + obj.put("Reason", leaveRequestObject.getLeave_reason()); + promoArray.put(obj); + + JSONObject jsonObject = new JSONObject(); + jsonObject.put("MID", jcpfor_bid.getMID()); + jsonObject.put("Keys", "RequestFor_Leave_Approval"); + jsonObject.put("JsonData", promoArray.toString()); + jsonObject.put("UserId", username); + upload_Request_ApprovalLeave(jsonObject.toString(), leaveRequestObject); + } catch (JSONException e) { + e.fillInStackTrace(); + } + } + + public void upload_Request_ApprovalLeave(String jsondata, final T_LeaveRequest leaveRequestObject) { + try { + OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, + TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build(); + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsondata); + Retrofit adapter; + adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build(); + PostApi api = adapter.create(PostApi.class); + Call call = api.getGeotag(jsonData); + call.enqueue(new Callback() { + @Override + public void onResponse(Call call, Response response) { + String responseBody = response.body().get("UploadJsonResult").toString(); + String data = null; + if (responseBody != null && response.isSuccessful()) { + try { + data = response.body().get("UploadJsonResult").toString(); + if (data.equals("")) { + } else { + data = data.substring(1, data.length() - 1).replace("\\", ""); + if (data.equalsIgnoreCase(CommonString.KEY_SUCCESS)) { + db.open(); + db.updateMasterTransactionDataStatus(leaveRequestObject.getTransId()); + db.open(); + db.update_leave_management_status(counter_id, visit_date, username, leaveRequestObject.getTransId(), false); + } + } + } catch (Exception e) { + e.fillInStackTrace(); + } + } + } + + @Override + public void onFailure(Call call, Throwable t) { + + } + }); + + } catch (Exception e) { + e.fillInStackTrace(); + } + } + + public static String convertTym(String str) { + SimpleDateFormat displayFormat = null; + SimpleDateFormat parseFormat = null; + Date date = null; + try { + displayFormat = new SimpleDateFormat("HH:mm"); + parseFormat = new SimpleDateFormat("hh:mm a"); + date = parseFormat.parse(str); + //test(parseFormat.format(date) + " = " + displayFormat.format(date)); + } catch (ParseException e) { + e.fillInStackTrace(); + } + return displayFormat.format(date) + ":00"; + } + + private void calculate_break_data(MasterBreak breakManagementObject) { + try { + db.open(); + JourneyPlan jcpfor_bid = db.getBIDfromJCP(username, counter_id); + JSONArray promoArray = new JSONArray(); + JSONObject obj = new JSONObject(); + obj.put("MID", jcpfor_bid.getMID()); + obj.put("BID", jcpfor_bid.getBID()); + obj.put("UserId", username); + obj.put("VisitDate", visit_date); + + obj.put("TranId", breakManagementObject.getTransId()); + obj.put("BreakId", breakManagementObject.getBreakId().toString()); + obj.put("StartTym", convertTym(breakManagementObject.getStartTym())); + obj.put("EndTym", convertTym(breakManagementObject.getEndTym())); + obj.put("TotalDuration", breakManagementObject.getTotalDuration().toString()); + + promoArray.put(obj); + + JSONObject jsonObject = new JSONObject(); + jsonObject.put("MID", jcpfor_bid.getMID()); + jsonObject.put("Keys", "Break_Management_Data"); + jsonObject.put("JsonData", promoArray.toString()); + jsonObject.put("UserId", username); + upload_break_M(jsonObject.toString(), breakManagementObject); + } catch (JSONException e) { + e.fillInStackTrace(); + } + } + + public void upload_break_M(String jsondata, final MasterBreak breakManagementObject) { + try { + OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, + TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build(); + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsondata); + Retrofit adapter; + adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build(); + PostApi api = adapter.create(PostApi.class); + Call call = api.getGeotag(jsonData); + call.enqueue(new Callback() { + @Override + public void onResponse(Call call, Response response) { + String responseBody = response.body().get("UploadJsonResult").toString(); + String data = null; + if (responseBody != null && response.isSuccessful()) { + try { + data = response.body().get("UploadJsonResult").toString(); + if (data.equals("")) { + } else { + data = data.substring(1, data.length() - 1).replace("\\", ""); + if (data.equalsIgnoreCase(CommonString.KEY_SUCCESS)) { + db.open(); + db.updateMasterTransactionDataStatus(breakManagementObject.getTransId()); + db.open(); + db.update_break_management_status(counter_id, visit_date, username, breakManagementObject.getTransId(), false); + } + } + } catch (Exception e) { + e.fillInStackTrace(); + } + } + } + + @Override + public void onFailure(Call call, Throwable t) { + + } + }); + + } catch (Exception e) { + e.fillInStackTrace(); + } + } + + private void calculate_ba_counter_imgage_data(JourneyPlan ba_counter_imgObject) { + try { + JourneyPlan jcpfor_bid = db.getBIDfromJCP(username, counter_id); + JSONArray promoArray = new JSONArray(); + JSONObject obj = new JSONObject(); + obj.put("MID", jcpfor_bid.getMID()); + obj.put("UserId", username); + obj.put("VisitDate", visit_date); + obj.put("Counter_Img_One", ba_counter_imgObject.getCounter_img_onefor_ba()); + obj.put("Counter_Img_Two", ba_counter_imgObject.getCounter_img_two_for_ba()); + promoArray.put(obj); + + JSONObject jsonObject = new JSONObject(); + jsonObject.put("MID", jcpfor_bid.getMID()); + jsonObject.put("Keys", "Counter_Image_Data"); + jsonObject.put("JsonData", promoArray.toString()); + jsonObject.put("UserId", username); + upload_ba_counter_img(jsonObject.toString(), ba_counter_imgObject); + } catch (JSONException e) { + e.fillInStackTrace(); + } + } + + public void upload_ba_counter_img(String jsondata, final JourneyPlan breakManagementObject) { + try { + final OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, + TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build(); + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsondata); + Retrofit adapter; + adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build(); + PostApi api = adapter.create(PostApi.class); + Call call = api.getGeotag(jsonData); + call.enqueue(new Callback() { + @Override + public void onResponse(Call call, Response response) { + String responseBody = response.body().get("UploadJsonResult").toString(); + String data = null; + if (responseBody != null && response.isSuccessful()) { + try { + data = response.body().get("UploadJsonResult").toString(); + if (data.equals("")) { + } else { + data = data.substring(1, data.length() - 1).replace("\\", ""); + if (data.equalsIgnoreCase(CommonString.KEY_SUCCESS)) { + db.open(); + db.update_ba_counter_img(counter_id, visit_date, username, breakManagementObject.getTransId()); + } + } + } catch (Exception e) { + e.fillInStackTrace(); + } + } + } + + @Override + public void onFailure(Call call, Throwable t) { + + } + }); + + } catch (Exception e) { + e.fillInStackTrace(); + } + } + + private void calculate_Groomed_Image_Data(GroomingGetterSetter groomedObject) { + try { + JourneyPlan jcpfor_bid = db.getBIDfromJCP(username, counter_id); + JSONArray promoArray = new JSONArray(); + JSONObject obj = new JSONObject(); + obj.put("MID", jcpfor_bid.getMID()); + obj.put("BID", jcpfor_bid.getBID()); + obj.put("UserId", username); + obj.put("VisitDate", visit_date); + obj.put("Groomed_Morng_Img", groomedObject.getMorning_groom_img_str()); + obj.put("Groomed_Morng_Time_Str", groomedObject.getMorning_groom_time_str()); + obj.put("Groomed_Noon_Img", groomedObject.getNoon_groom_img_str()); + obj.put("Groomed_Noon_Time_Str", groomedObject.getNoon_groom_time_str()); + obj.put("Groomed_Eveng_Img", groomedObject.getEvenning_groom_img_str()); + obj.put("Groomed_Eveng_Time_Str", groomedObject.getEvenning_groom_time_str()); + + promoArray.put(obj); + JSONObject jsonObject = new JSONObject(); + jsonObject.put("MID", jcpfor_bid.getMID()); + jsonObject.put("Keys", "Groomed_Data"); + jsonObject.put("JsonData", promoArray.toString()); + jsonObject.put("UserId", username); + upload_Groomrd_img_data(jsonObject.toString(), groomedObject); + } catch (JSONException e) { + e.fillInStackTrace(); + } + } + + public void upload_Groomrd_img_data(String jsondata, final GroomingGetterSetter groomedObject) { + try { + OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, + TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build(); + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsondata); + Retrofit adapter; + adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build(); + PostApi api = adapter.create(PostApi.class); + Call call = api.getGeotag(jsonData); + call.enqueue(new Callback() { + @Override + public void onResponse(Call call, Response response) { + String responseBody = response.body().get("UploadJsonResult").toString(); + String data = null; + if (responseBody != null && response.isSuccessful()) { + try { + data = response.body().get("UploadJsonResult").toString(); + if (data.equals("")) { + } else { + data = data.substring(1, data.length() - 1).replace("\\", ""); + if (data.equalsIgnoreCase(CommonString.KEY_SUCCESS)) { + db.open(); + if (!groomedObject.getMorning_groom_img_str().equals("") && !groomedObject.getNoon_groom_img_str().equals("") && !groomedObject.getNoon_groom_img_str().equals("")) { + db.update_groomed_img(counter_id, visit_date, username); + } + + + } + } + } catch (Exception e) { + e.fillInStackTrace(); + } + } + } + + @Override + public void onFailure(Call call, Throwable t) { + + } + }); + + } catch (Exception e) { + e.fillInStackTrace(); + } + } + + public static ArrayList getFileNames(File[] file) { + ArrayList arrayFiles = new ArrayList(); + if (file != null && file.length > 0) { + for (int i = 0; i < file.length; i++) + arrayFiles.add(file[i].getName()); + } + return arrayFiles; + } + + public void UploadImageRecursive() { + try { + final int[] uploadedFiles = {0}; + final int[] statusforimage = {0}; + statusforimage[0] = 0; + String filename = null, foldername = null; + File f = new File(CommonString.getImagesFolder(context)); + ArrayList finalList = new ArrayList<>(); + if (!getFileNames(f.listFiles()).isEmpty()) { + for (int k = 0; k < getFileNames(f.listFiles()).size(); k++) { + if (!db.ischeck_uploaded_image(visit_date, getFileNames(f.listFiles()).get(k))) { + finalList.add(getFileNames(f.listFiles()).get(k)); + } + } + } + + if (!finalList.isEmpty()) { + filename = ""; + for (int i = 0; i < finalList.size(); i++) { + if (new File(CommonString.getImagesFolder(context) + finalList.get(i)).exists()) { + if (finalList.get(i).contains("_Counter_Selfie_img_")) { + foldername = "BACoverageImages"; + } else if (finalList.get(i).contains("_cp_img_one_") || finalList.get(i).contains("_cp_img_two_")) { + foldername = "CounterProfileImages"; + } else if (finalList.get(i).contains("_counter_img_one_") || finalList.get(i).contains("_counter_img_two_")) { + foldername = "CounterImages"; + } else if (finalList.get(i).contains("_ba_AuditPic_") || finalList.get(i).contains("_ba_profile_img_")) { + foldername = "BAProfileImages"; + } else if (finalList.get(i).contains("_Damaged_stock_img_") || finalList.get(i).contains("_Damage_header_img_")) { + foldername = "DamageStockImages"; + } else if (finalList.get(i).contains("_groomed_img_mrng_") || finalList.get(i).contains("_groomed_img_noon_") || finalList.get(i).contains("_groomed_img_evning_")) { + foldername = "GroomingImages"; + } else if (finalList.get(i).contains("_stock_check_img_") || finalList.get(i).contains("_tester_stock_img_") || finalList.get(i).contains("_suggested_stk_img") || finalList.get(i).contains("_Sample_stock_img")) { + foldername = "SaleableStockImages"; + } else if (finalList.get(i).contains("_visibility_img_")) { + foldername = "VisibilityImages"; + } else if (finalList.get(i).contains("_ConsumerSimg_")) { + foldername = "ConsumerInteractionImages"; + } else if (finalList.get(i).contains("_QuizPic-")) { + foldername = "MEAuditImages"; + } else if (finalList.get(i).contains("_before_makeo_img_") || finalList.get(i).contains("_after_makeo_img_")) { + foldername = "MeMakeoverImages"; + } else if (finalList.get(i).contains("SurveyPic-")) { + foldername = "SurveyImages"; + } else if (finalList.get(i).contains("_invoiceimg_")) { + foldername = "ConsumerReturnImages"; + } else if (finalList.get(i).contains("_minwordsimg_")) { + foldername = "InwardImages"; + } else if (finalList.get(i).contains("-SkinGenius-")) { + foldername = "SkinGeniusImages"; + } else if (finalList.get(i).contains("-CompOfferImg-") || finalList.get(i).contains("-Gwp_CompOfferImg-")) { + foldername = "CompetitionOffersImages"; + } else if (finalList.get(i).contains("_GeoTag-")) { + foldername = "GeoTagImages"; + } else { + foldername = "BulkUpload"; + } + + filename = finalList.get(i); + } + + break; + } + + + File originalFile = new File(CommonString.getImagesFolder(context) + filename); + File finalFile = saveBitmapToFile(originalFile); + if (finalFile == null) { + finalFile = originalFile; + } + + + String date = visit_date.replace("/", ""); + com.squareup.okhttp.OkHttpClient okHttpClient = new com.squareup.okhttp.OkHttpClient(); + okHttpClient.setConnectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS); + okHttpClient.setWriteTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS); + okHttpClient.setReadTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS); + com.squareup.okhttp.RequestBody photo = com.squareup.okhttp.RequestBody.create(com.squareup.okhttp.MediaType.parse("application/octet-stream"), finalFile); + com.squareup.okhttp.RequestBody body1 = new MultipartBuilder().type(MultipartBuilder.FORM) + .addFormDataPart("file", finalFile.getName(), photo).addFormDataPart("FolderName", foldername) + .addFormDataPart("Path", date).build(); + retrofit.Retrofit adapter = new retrofit.Retrofit.Builder().baseUrl(CommonString.URLGORIMAG).client(okHttpClient) + .addConverterFactory(new StringConverterFactory()).build(); + PostApiForUpload api = adapter.create(PostApiForUpload.class); + retrofit.Call call = api.getUploadImageRetrofitOne(body1); + final File finalFile1 = finalFile; + final String finalFilename = filename; + call.enqueue(new retrofit.Callback() { + @Override + public void onResponse(retrofit.Response response) { + try { + if (response.code() == 200 && response.message().equalsIgnoreCase("OK") && response.isSuccess() && response.body().contains("Success")) { + if (finalFilename.contains("_counter_img_two_") || finalFilename.contains("_counter_img_one_") || finalFilename.contains("_cp_img_one_") || finalFilename.contains("_cp_img_two_") || finalFilename.contains("_groomed_img_mrng_") || finalFilename.contains("_groomed_img_noon_") || finalFilename.contains("_groomed_img_evning_")) { + db.open(); + db.insert_temp_image(finalFilename, visit_date); + + } else { + finalFile1.delete(); + } + statusforimage[0] = 1; + uploadedFiles[0]++; + } else { + statusforimage[0] = 0; + } + if (statusforimage[0] == 0) { + } else { + UploadImageRecursive(); + } + } catch (Exception e) { + e.fillInStackTrace(); + } catch (OutOfMemoryError error) { + statusforimage[0] = -1; + error.fillInStackTrace(); + } + } + + @Override + public void onFailure(Throwable t) { + if (t instanceof IOException || t instanceof SocketTimeoutException || t instanceof SocketException) { + statusforimage[0] = -1; + } + } + }); + } + } catch (JsonSyntaxException e) { + e.fillInStackTrace(); + } catch (Exception e) { + e.fillInStackTrace(); + } + } + + public void upload_BaProfilewithaudit(String jsondata) { + try { + OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, + TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build(); + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsondata); + Retrofit adapter; + adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build(); + PostApi api = adapter.create(PostApi.class); + Call call = api.getGeotag(jsonData); + call.enqueue(new Callback() { + @Override + public void onResponse(Call call, Response response) { + String responseBody = response.body().get("UploadJsonResult").toString(); + String data = null; + if (responseBody != null && response.isSuccessful()) { + try { + data = response.body().get("UploadJsonResult").toString(); + if (data.equals("")) { + } else { + data = data.substring(1, data.length() - 1).replace("\\", ""); + if (data.equalsIgnoreCase(CommonString.KEY_SUCCESS)) { + db.open(); + db.updateBaProfileStatus(username, visit_date, CommonString.KEY_Y); + } + } + } catch (Exception e) { + e.fillInStackTrace(); + } + } + } + + @Override + public void onFailure(Call call, Throwable t) { + + } + }); + + } catch (Exception e) { + e.fillInStackTrace(); + } + } + + public void upload_CounterProfile(String jsondata, final JourneyPlan object) { + try { + OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, + TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build(); + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsondata); + Retrofit adapter; + adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build(); + PostApi api = adapter.create(PostApi.class); + Call call = api.getGeotag(jsonData); + call.enqueue(new Callback() { + @Override + public void onResponse(Call call, Response response) { + String responseBody = response.body().get("UploadJsonResult").toString(); + String data = null; + if (responseBody != null && response.isSuccessful()) { + try { + data = response.body().get("UploadJsonResult").toString(); + if (data.equals("")) { + } else { + data = data.substring(1, data.length() - 1).replace("\\", ""); + if (data.equalsIgnoreCase(CommonString.KEY_SUCCESS)) { + db.open(); + db.updateCounterProfileStatus(username, visit_date, CommonString.KEY_Y); + } + } + } catch (Exception e) { + e.fillInStackTrace(); + } + } + } + + @Override + public void onFailure(Call call, Throwable t) { + + } + }); + + } catch (Exception e) { + e.fillInStackTrace(); + } + } + + private void calculate_me_quiz_data(JourneyPlan jcp_Object, ArrayList me_quizList) { + try { + if (me_quizList.size() > 0) { + JSONArray consumerUserInfoArray = new JSONArray(); + for (int k = 0; k < me_quizList.size(); k++) { + JSONObject obj = new JSONObject(); + obj.put("MID", jcp_Object.getMID()); + obj.put("BID", jcp_Object.getBID()); + obj.put("VisiteDate", visit_date); + obj.put("QuizId", me_quizList.get(k).getQuizId()); + obj.put("UserId", me_quizList.get(k).getUser_Id()); + obj.put("Question_Id", me_quizList.get(k).getQuestionId()); + obj.put("Question_Type", me_quizList.get(k).getQuestionType()); + JSONArray compArraymult = new JSONArray(); + JSONObject objmultians = new JSONObject(); + if (me_quizList.get(k).getQuestionType().equalsIgnoreCase("List Single Choice")) { + objmultians.put("Answer", me_quizList.get(k).getAnswer()); + objmultians.put("Answer_Id", me_quizList.get(k).getAnswerId()); + objmultians.put("Answer_Image", me_quizList.get(k).getStr_audit_img()); + compArraymult.put(objmultians); + } else if (!me_quizList.get(k).getQuestionType().equalsIgnoreCase("List Multiple Choice")) { + objmultians.put("Answer", me_quizList.get(k).getAnswer()); + objmultians.put("Answer_Id", 0); + objmultians.put("Answer_Image", ""); + compArraymult.put(objmultians); + } else { + db.open(); + ArrayList multiansList = db.getquiz_answer(me_quizList.get(k).getKeyId()); + if (multiansList.size() > 0) { + for (int j2 = 0; j2 < multiansList.size(); j2++) { + objmultians = new JSONObject(); + objmultians.put("Answer", multiansList.get(j2).getAnswer()); + objmultians.put("Answer_Id", multiansList.get(j2).getAnswerId()); + objmultians.put("Answer_Image", ""); + compArraymult.put(objmultians); + } + } + } + obj.put("AnsList", compArraymult); + consumerUserInfoArray.put(obj); + } + JSONObject jsonObject = new JSONObject(); + jsonObject.put("MID", jcp_Object.getMID()); + jsonObject.put("Keys", "ME_Quiz_Data"); + jsonObject.put("JsonData", consumerUserInfoArray.toString()); + jsonObject.put("UserId", username.toLowerCase()); + upload_ME_Quiz_Data(jsonObject.toString(), quizList); + } + } catch (Exception e) { + e.fillInStackTrace(); + } + } + public void upload_ME_Quiz_Data(String jsondata, final ArrayList me_quizList) { + try { + OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, + TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build(); + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsondata); + Retrofit adapter; + adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build(); + PostApi api = adapter.create(PostApi.class); + Call call = api.getGeotag(jsonData); + call.enqueue(new Callback() { + @Override + public void onResponse(Call call, Response response) { + String responseBody = response.body().get("UploadJsonResult").toString(); + String data = null; + if (responseBody != null && response.isSuccessful()) { + try { + data = response.body().get("UploadJsonResult").toString(); + if (data.equals("")) { + } else { + data = data.substring(1, data.length() - 1).replace("\\", ""); + if (data.equalsIgnoreCase(CommonString.KEY_SUCCESS)) { + db.open(); + // db.update_groomed_img(counter_id, visit_date, username); + db.update_Me_Quiz(counter_id, username); + } + } + } catch (Exception e) { + e.fillInStackTrace(); + } + } + } + + @Override + public void onFailure(Call call, Throwable t) { + } + }); + + } catch (Exception e) { + e.fillInStackTrace(); + } + } + + private void calculate_retail_excellence_data(JourneyPlan jcp_Object, ArrayList masterRetailExcellenceArrayList) { + try { + if (masterRetailExcellenceArrayList.size() > 0) { + JSONArray consumerUserInfoArray = new JSONArray(); + for (int k = 0; k < masterRetailExcellenceArrayList.size(); k++) { + JSONObject obj = new JSONObject(); + obj.put("MID", jcp_Object.getMID()); + obj.put("BID", jcp_Object.getBID()); + obj.put("UserId", username.toLowerCase()); + obj.put("VisiteDate", visit_date); + obj.put("ItemCategoryId", masterRetailExcellenceArrayList.get(k).getItemCatId()); + obj.put("ItemId", masterRetailExcellenceArrayList.get(k).getItemId()); + if(masterRetailExcellenceArrayList.get(k).getAnswer().equalsIgnoreCase("Yes")){ + obj.put("Available", 1); + } + else{ + obj.put("Available", 0); + } + consumerUserInfoArray.put(obj); + } + JSONObject jsonObject = new JSONObject(); + jsonObject.put("MID", jcp_Object.getMID()); + jsonObject.put("Keys", "Retail_Excellence_Data"); + jsonObject.put("JsonData", consumerUserInfoArray.toString()); + jsonObject.put("UserId", username.toLowerCase()); + //test("retailjson",jsonObject.toString()); + upload_Retail_Excellence_Data(jsonObject.toString(), masterRetailExcellenceArrayList); + } + } catch (Exception e) { + e.fillInStackTrace(); + } + } + + public void upload_Retail_Excellence_Data(String jsondata, final ArrayList masterRetailExcellenceArrayList) { + try { + OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, + TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build(); + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsondata); + Retrofit adapter; + adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build(); + PostApi api = adapter.create(PostApi.class); + Call call = api.getGeotag(jsonData); + call.enqueue(new Callback() { + @Override + public void onResponse(Call call, Response response) { + String responseBody = response.body().get("UploadJsonResult").toString(); + String data = null; + if (responseBody != null && response.isSuccessful()) { + try { + data = response.body().get("UploadJsonResult").toString(); + if (data.equals("")) { + } else { + data = data.substring(1, data.length() - 1).replace("\\", ""); + if (data.equalsIgnoreCase(CommonString.KEY_SUCCESS)) { + db.open(); + db.update_retail_excellence(counter_id, username); + } + } + } catch (Exception e) { + e.fillInStackTrace(); + } + } + } + + @Override + public void onFailure(Call call, Throwable t) { + } + }); + + } catch (Exception e) { + e.fillInStackTrace(); + } + } + + private void calculate_me_sale_data(JourneyPlan jcp_Object, ArrayList productMasterArrayList) { + try { + if (productMasterArrayList.size() > 0) { + JSONArray consumerUserInfoArray = new JSONArray(); + for (int k = 0; k < productMasterArrayList.size(); k++) { + if(productMasterArrayList.get(k).getStock()>0){ + JSONObject obj = new JSONObject(); + obj.put("MID", jcp_Object.getMID()); + obj.put("BID", jcp_Object.getBID()); + obj.put("UserId", username.toLowerCase()); + obj.put("VisiteDate", visit_date); + obj.put("ProductId", productMasterArrayList.get(k).getProductId()); + obj.put("Sale", productMasterArrayList.get(k).getStock()); + consumerUserInfoArray.put(obj); + } + } + JSONObject jsonObject = new JSONObject(); + jsonObject.put("MID", jcp_Object.getMID()); + jsonObject.put("Keys", "ME_Sale_Data"); + jsonObject.put("JsonData", consumerUserInfoArray.toString()); + jsonObject.put("UserId", username.toLowerCase()); + // //test("salejson",jsonObject.toString()); + upload_ME_Sale_Data(jsonObject.toString(), productMasterArrayList); + } + } catch (Exception e) { + e.fillInStackTrace(); + } + } + + public void upload_ME_Sale_Data(String jsondata, final ArrayList productMasterArrayList) { + try { + OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, + TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build(); + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsondata); + Retrofit adapter; + adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build(); + PostApi api = adapter.create(PostApi.class); + Call call = api.getGeotag(jsonData); + call.enqueue(new Callback() { + @Override + public void onResponse(Call call, Response response) { + String responseBody = response.body().get("UploadJsonResult").toString(); + String data = null; + if (responseBody != null && response.isSuccessful()) { + try { + data = response.body().get("UploadJsonResult").toString(); + if (data.equals("")) { + } else { + data = data.substring(1, data.length() - 1).replace("\\", ""); + if (data.equalsIgnoreCase(CommonString.KEY_SUCCESS)) { + db.open(); + db.update_me_sale(counter_id, username); + // db.update_groomed_img(counter_id, visit_date, username); + } + } + } catch (Exception e) { + e.fillInStackTrace(); + } + } + } + + @Override + public void onFailure(Call call, Throwable t) { + } + }); + + } catch (Exception e) { + e.fillInStackTrace(); + } + } + + + private void calculate_me_makeoverdata(ArrayList memakeoverList, int consumerIndex) { + try { + + if (memakeoverList.size() > 0) { + db.open(); + JourneyPlan jcp_Object = db.getBIDfromJCP(memakeoverList.get(consumerIndex).getStrUserId(), counter_id); + JSONArray consumerUserInfoArray = new JSONArray(); + JSONObject obj = new JSONObject(); + obj.put("MID", jcp_Object.getMID()); + obj.put("BID", jcp_Object.getBID()); + obj.put("VisiteDate", visit_date); + obj.put("UserId", memakeoverList.get(consumerIndex).getStrUserId()); + obj.put("TranId", memakeoverList.get(consumerIndex).getUnique_code()); + obj.put("ConsumerName", memakeoverList.get(consumerIndex).getCustomer_name()); + obj.put("MobileNumber", memakeoverList.get(consumerIndex).getMobile_no()); + obj.put("EmailId", memakeoverList.get(consumerIndex).getConsumer_email_Id()); + obj.put("Age", memakeoverList.get(consumerIndex).getConsumer_age()); + obj.put("SkinType", memakeoverList.get(consumerIndex).getConsumer_skinType()); + obj.put("Look", memakeoverList.get(consumerIndex).getLook_creater_str()); + obj.put("Gender", memakeoverList.get(consumerIndex).getCustomer_gender()); + obj.put("BeforeMakeoverImg", memakeoverList.get(consumerIndex).getBefore_makeover_img()); + obj.put("AfterMakeoverImg", memakeoverList.get(consumerIndex).getAfter_makeover_img()); + obj.put("Feedback", memakeoverList.get(consumerIndex).getCst_feed_back_value()); + obj.put("TermConditions", memakeoverList.get(consumerIndex).getStr_termcondition()); + consumerUserInfoArray.put(obj); + + JSONObject jsonObject = new JSONObject(); + jsonObject.put("MID", jcp_Object.getMID()); + jsonObject.put("Keys", "ME_Makeover_Capture"); + jsonObject.put("JsonData", consumerUserInfoArray.toString()); + jsonObject.put("UserId", memakeoverList.get(consumerIndex).getStrUserId()); + upload_Me_Makeover_Data(jsonObject.toString(), memakeoverList.get(consumerIndex),consumerIndex); + } + } catch (Exception e) { + e.fillInStackTrace(); + } + } + + public void upload_Me_Makeover_Data(String jsondata, final InvoiceGetterSetter object, final int index) { + try { + final int[] finalJsonIndex = {index}; + OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, + TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build(); + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsondata); + Retrofit adapter; + adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build(); + PostApi api = adapter.create(PostApi.class); + Call call = api.getGeotag(jsonData); + call.enqueue(new Callback() { + @Override + public void onResponse(Call call, Response response) { + String responseBody = response.body().get("UploadJsonResult").toString(); + String data = null; + if (responseBody != null && response.isSuccessful()) { + try { + data = response.body().get("UploadJsonResult").toString(); + if (data.equals("")) { + } else { + data = data.substring(1, data.length() - 1).replace("\\", ""); + if (data.equalsIgnoreCase(CommonString.KEY_SUCCESS)) { + db.open(); + db.update_makeover(counter_id, object.getStrUserId(), object.getKeyId(), false); + db.updateMasterTransactionDataStatus(object.getUnique_code()); + finalJsonIndex[0]++; + if (finalJsonIndex[0] != me_makeoverList.size()) { + calculate_me_makeoverdata(me_makeoverList, finalJsonIndex[0]); + } + } + } + } catch (Exception e) { + e.fillInStackTrace(); + } + } + } + + @Override + public void onFailure(Call call, Throwable t) { + } + }); + + } catch (Exception e) { + e.fillInStackTrace(); + } + } + + private void calculate_me_counter_imgage_data(JourneyPlan ba_counter_imgObject) { + try { + JourneyPlan jcpfor_bid = db.getBIDfromJCP(username, counter_id); + JSONArray promoArray = new JSONArray(); + JSONObject obj = new JSONObject(); + obj.put("MID", jcpfor_bid.getMID()); + obj.put("UserId", username); + obj.put("VisitDate", visit_date); + obj.put("PreSetUpImgOne", ba_counter_imgObject.getPresetup_img_one_str()); + obj.put("PreSetUpImgTwo", ba_counter_imgObject.getPresetup_img_two_str()); + obj.put("PostSetUpImgOne", ba_counter_imgObject.getPostsetup_img_one_str()); + obj.put("PostSetUpImgTwo", ba_counter_imgObject.getPostsetup_img_two_str()); + promoArray.put(obj); + + JSONObject jsonObject = new JSONObject(); + jsonObject.put("MID", jcpfor_bid.getMID()); + jsonObject.put("Keys", "ME_Counter_Image_Data"); + jsonObject.put("JsonData", promoArray.toString()); + jsonObject.put("UserId", username); + upload_ba_counter_img(jsonObject.toString(), ba_counter_imgObject); + } catch (JSONException e) { + e.fillInStackTrace(); + } + } +} \ No newline at end of file diff --git a/app/src/main/java/com/cpm/lorealbaautomation/downloadService/DownloadResultReceiver.java b/app/src/main/java/com/cpm/lorealbaautomation/downloadService/DownloadResultReceiver.java new file mode 100644 index 0000000..a0e9117 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/downloadService/DownloadResultReceiver.java @@ -0,0 +1,29 @@ +package com.cpm.lorealbaautomation.downloadService; + +import android.os.Bundle; +import android.os.Handler; +import android.os.ResultReceiver; + +public class DownloadResultReceiver extends ResultReceiver { + private Receiver mReceiver; + + public DownloadResultReceiver(Handler handler) { + super(handler); + } + + public void setReceiver(Receiver receiver) { + mReceiver = receiver; + } + + public interface Receiver { + public void onReceiveResult(int resultCode, Bundle resultData); + } + + @Override + protected void onReceiveResult(int resultCode, Bundle resultData) { + if (mReceiver != null) { + mReceiver.onReceiveResult(resultCode, resultData); + } + } +} + diff --git a/app/src/main/java/com/cpm/lorealbaautomation/downloadService/DownloadService.java b/app/src/main/java/com/cpm/lorealbaautomation/downloadService/DownloadService.java new file mode 100644 index 0000000..349921a --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/downloadService/DownloadService.java @@ -0,0 +1,132 @@ +package com.cpm.lorealbaautomation.downloadService; + +import android.app.IntentService; +import android.content.Intent; +import android.os.Bundle; +import android.os.ResultReceiver; +import android.text.TextUtils; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.BufferedInputStream; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.URL; + +public class DownloadService extends IntentService { + private static final String TAG = "DownloadService"; + public static final int STATUS_RUNNING = 0; + public static final int STATUS_FINISHED = 1; + public static final int STATUS_ERROR = 2; + + + public DownloadService() { + super(DownloadService.class.getName()); + } + + @Override + protected void onHandleIntent(Intent intent) { + //test(TAG, "Service Started!"); + final ResultReceiver receiver = intent.getParcelableExtra("receiver"); + String url = intent.getStringExtra("Username"); + String user_name = intent.getStringExtra("Username"); + String param_1 = intent.getStringExtra("Param1"); + Bundle bundle = new Bundle(); + if (!TextUtils.isEmpty(url)) { + /* Update UI: Download Service is Running */ + receiver.send(STATUS_RUNNING, Bundle.EMPTY); + try { + + String[] results = downloadData(url); + /* Sending result back to activity */ + if (null != results && results.length > 0) { + bundle.putStringArray("result", results); + receiver.send(STATUS_FINISHED, bundle); + } + + } catch (Exception e) { + /* Sending error message back to activity */ + bundle.putString(Intent.EXTRA_TEXT, e.toString()); + receiver.send(STATUS_ERROR, bundle); + } + } + //test(TAG, "Service Stopping!"); + this.stopSelf(); + } + + private String[] downloadData(String requestUrl) throws IOException, DownloadException { + InputStream inputStream = null; + HttpURLConnection urlConnection = null; + /* forming th java.net.URL object */ + URL url = new URL(requestUrl); + urlConnection = (HttpURLConnection) url.openConnection(); + /* optional request header */ + urlConnection.setRequestProperty("Content-Type", "application/json"); + + /* optional request header */ + urlConnection.setRequestProperty("Accept", "application/json"); + + /* for Get request */ + urlConnection.setRequestMethod("GET"); + + int statusCode = urlConnection.getResponseCode(); + + /* 200 represents HTTP OK */ + if (statusCode == 200) { + inputStream = new BufferedInputStream(urlConnection.getInputStream()); + String response = convertInputStreamToString(inputStream); + String[] results = parseResult(response); + return results; + } else { + throw new DownloadException("Failed to fetch data!!"); + } + } + + private String convertInputStreamToString(InputStream inputStream) throws IOException { + BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); + String line = ""; + String result = ""; + while ((line = bufferedReader.readLine()) != null) { + result += line; + } + + /* Close Stream */ + if (null != inputStream) { + inputStream.close(); + } + + return result; + } + + private String[] parseResult(String result) { + String[] blogTitles = null; + try { + + JSONObject response = new JSONObject(result); + JSONArray posts = response.optJSONArray("posts"); + blogTitles = new String[posts.length()]; + for (int i = 0; i < posts.length(); i++) { + JSONObject post = posts.optJSONObject(i); + String title = post.optString("title"); + blogTitles[i] = title; + } + + } catch (JSONException e) { + e.fillInStackTrace(); + } + + return blogTitles; + } + + public class DownloadException extends Exception { + + public DownloadException(String message) { + super(message); + } + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/forgotpassword/ForgotpasswordActity.java b/app/src/main/java/com/cpm/lorealbaautomation/forgotpassword/ForgotpasswordActity.java new file mode 100644 index 0000000..75a81bd --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/forgotpassword/ForgotpasswordActity.java @@ -0,0 +1,560 @@ +package com.cpm.lorealbaautomation.forgotpassword; + +import android.app.Activity; +import android.app.AlertDialog; +import android.app.Dialog; +import android.app.ProgressDialog; +import android.content.Context; +import android.content.DialogInterface; +import android.content.SharedPreferences; +import android.graphics.Bitmap; +import android.graphics.BitmapFactory; +import android.graphics.drawable.ColorDrawable; +import android.os.AsyncTask; + +import com.google.android.material.floatingactionbutton.FloatingActionButton; + +import androidx.appcompat.app.AppCompatActivity; + +import android.os.Bundle; + +import androidx.cardview.widget.CardView; +import androidx.appcompat.widget.Toolbar; + +import android.text.InputFilter; +import android.text.Spanned; +import android.view.MenuItem; +import android.view.View; +import android.view.Window; +import android.view.WindowManager; +import android.widget.AdapterView; +import android.widget.ArrayAdapter; +import android.widget.EditText; +import android.widget.ImageView; +import android.widget.LinearLayout; +import android.widget.Spinner; +import android.widget.TextView; +import android.widget.Toast; + +import com.goodiebag.pinview.Pinview; +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.constant.AlertandMessages; +import com.cpm.lorealbaautomation.constant.CommonFunctions; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.constant.RoundedImageView; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.gsonGetterSetter.BaListGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterProfile; +import com.cpm.lorealbaautomation.retrofit.DownloadAllDatawithRetro; +import com.cpm.lorealbaautomation.retrofit.PostApi; +import com.squareup.picasso.NetworkPolicy; +import com.squareup.picasso.Picasso; + +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.File; +import java.util.ArrayList; +import java.util.concurrent.TimeUnit; +import java.util.regex.Pattern; + +import okhttp3.MediaType; +import okhttp3.OkHttpClient; +import okhttp3.RequestBody; +import okhttp3.ResponseBody; +import retrofit2.Retrofit; +import retrofit2.converter.gson.GsonConverterFactory; + +import static com.cpm.lorealbaautomation.dailyactivity.StoreImageActivity.convertBitmap; + +public class ForgotpasswordActity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemSelectedListener { + private String visit_date, counterId, user_type, otp_code = "", str_user_name = "", user_id; + ArrayList bsListData = new ArrayList<>(); + private SharedPreferences.Editor editor = null; + SharedPreferences preferences; + private Lorealba_Database db; + ProgressDialog loading; + Toolbar toolbar; + Context context; + + EditText edt_password, edt_confirm_password; + CardView card_forgot_password_layout, card_view_forgot_password_top; + FloatingActionButton btn_save_forgot; + RoundedImageView round_img_pic; + LinearLayout rl_otp_pinview; + TextView forgot_user_name, profile_user, profile_user_type, txt_confirm_pin; + ImageView img_invisible, img_info; + ArrayAdapter user_adapter; + Spinner user_spin; + boolean clicked_flag = false; + Pinview pinview_otp; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_forgotpassword_actity); + context = this; + getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); + db = new Lorealba_Database(context); + db.open(); + getId(); + set_user_icon(); + setpin_view(); + } + + private void getId() { + preferences = PrefHelper.getPrefs(context); + editor = preferences.edit(); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + counterId = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + user_type = preferences.getString(CommonString.KEY_USER_TYPE, ""); + user_id = preferences.getString(CommonString.KEY_USERNAME, ""); + toolbar = findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + getSupportActionBar().setHomeButtonEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + if (!CommonFunctions.isTablet(context)) { + toolbar.setTitleTextAppearance(context, R.style.changestext_sizefor_mobile); + } + + pinview_otp = (Pinview) findViewById(R.id.pinview_otp); + img_invisible = (ImageView) findViewById(R.id.img_invisible); + img_info = (ImageView) findViewById(R.id.img_info); + forgot_user_name = (TextView) findViewById(R.id.forgot_user_name); + profile_user = (TextView) findViewById(R.id.profile_user); + profile_user_type = (TextView) findViewById(R.id.profile_user_type); + txt_confirm_pin = (TextView) findViewById(R.id.txt_confirm_pin); + round_img_pic = (RoundedImageView) findViewById(R.id.round_img_pic); + btn_save_forgot = (FloatingActionButton) findViewById(R.id.btn_save_forgot); + rl_otp_pinview = (LinearLayout) findViewById(R.id.rl_otp_pinview); + + card_forgot_password_layout = (CardView) findViewById(R.id.card_forgot_password_layout); + card_view_forgot_password_top = (CardView) findViewById(R.id.card_view_forgot_password_top); + + user_spin = (Spinner) findViewById(R.id.user_spin); + edt_password = (EditText) findViewById(R.id.edt_password); + edt_confirm_password = (EditText) findViewById(R.id.edt_confirm_password); + + img_invisible.setOnClickListener(this); + btn_save_forgot.setOnClickListener(this); + img_info.setOnClickListener(this); + bsListData = (ArrayList) getIntent().getSerializableExtra(CommonString.TAG_OBJECT); + if (bsListData != null && bsListData.size() > 0) { + setBrandSpinnerData(bsListData, user_spin); + } + if (!CommonFunctions.isTablet(context)) { + toolbar.setTitleTextAppearance(context, R.style.changestext_sizefor_mobile); + } + + + setTitle("Forgot Password " + visit_date); + user_spin.setOnItemSelectedListener(this); + + /* To restrict Space Bar in Keyboard */ + InputFilter filter = new InputFilter() { + public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { + for (int i = start; i < end; i++) { + if (Character.isWhitespace(source.charAt(i))) { + return ""; + } + } + return null; + } + + }; + edt_password.setFilters(new InputFilter[]{filter}); + + /* To restrict Space Bar in Keyboard */ + InputFilter filteredt_confirm = new InputFilter() { + public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { + for (int i = start; i < end; i++) { + if (Character.isWhitespace(source.charAt(i))) { + return ""; + } + } + return null; + } + + }; + + edt_confirm_password.setFilters(new InputFilter[]{filteredt_confirm}); + } + + + private void setBrandSpinnerData(ArrayList userList, Spinner user_spin) { + user_adapter = new ArrayAdapter<>(this, R.layout.spinner_custom_item); + user_adapter.add("- Select User -"); + + for (int i = 0; i < userList.size(); i++) { + user_adapter.add(userList.get(i).getUserName()); + } + + user_spin.setAdapter(user_adapter); + user_adapter.setDropDownViewResource(R.layout.spinner_custom_item); + + } + + @Override + public void onClick(View view) { + if (view.getId() == R.id.img_invisible) { + if (!otp_code.equals("") && card_view_forgot_password_top.getVisibility() == View.GONE) { + // Its visible + card_view_forgot_password_top.setVisibility(View.VISIBLE); + img_invisible.setImageResource(R.mipmap.invisible); + } else { + // Either gone or invisible + card_view_forgot_password_top.setVisibility(View.GONE); + card_forgot_password_layout.setVisibility(View.VISIBLE); + img_invisible.setImageResource(R.mipmap.visible); + } + + } else if (view.getId() == R.id.btn_save_forgot) { + submit(); + + } else if (view.getId() == R.id.img_info) { + Dialog dialog = new Dialog(context); + dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); + dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT)); + dialog.setContentView(R.layout.password_rule_dialog); + dialog.show(); + + } + + } + + private void setpin_view() { + pinview_otp.setPinViewEventListener(new Pinview.PinViewEventListener() { + @Override + public void onDataEntered(Pinview pinview, boolean fromUser) { + if (!pinview.getValue().equals("") && otp_code != null && !otp_code.equals("")) + if (pinview.getValue().equals(otp_code)) { + card_view_forgot_password_top.setVisibility(View.GONE); + card_forgot_password_layout.setVisibility(View.VISIBLE); + } + } + }); + + } + + private void set_user_icon() { + Bitmap bitmp = null; + if (user_type != null && !user_type.equals("") && user_type.equalsIgnoreCase(CommonString.TAG_FROM_BA)) { + profile_user_type.setText("Beauty Advisor"); + } else if (user_type != null && !user_type.equals("") && user_type.equalsIgnoreCase(CommonString.TAG_FROM_TBA)) { + profile_user_type.setText("Temp Beauty Advisor"); + } else if (user_type != null && !user_type.equals("") && user_type.equalsIgnoreCase(CommonString.TAG_FROM_ME)) { + profile_user_type.setText("Makeup Expert"); + } + + db.open(); + MasterProfile baProfileGetterSetter = db.getBaProfileData(str_user_name, visit_date, false); + db.open(); + ArrayList baProfileListData = db.getBAProfileListAllData(str_user_name, visit_date); + if (!baProfileListData.isEmpty()) { + profile_user.setText(baProfileListData.get(0).getFullName()); + } else { + profile_user.setText("User Id - " + str_user_name); + } + + if (baProfileGetterSetter.getProfilePic() != null && !baProfileGetterSetter.getProfilePic().equals("")) { + if (new File(CommonString.getProfileFolder(context) + baProfileGetterSetter.getProfilePic()).exists()) { + bitmp = convertBitmap(CommonString.getProfileFolder(context) + baProfileGetterSetter.getProfilePic()); + round_img_pic.setImageBitmap(bitmp); + } else { + bitmp = BitmapFactory.decodeResource(getResources(), R.mipmap.profile_image); + round_img_pic.setImageBitmap(bitmp); + } + } else if (baProfileListData.size() > 0 && baProfileListData.get(0).getProfilePic() != null && !baProfileListData.get(0).getProfilePic().equals("")) { + if (CommonFunctions.checkNetIsAvailable(context)) + Picasso.with(context).load(baProfileListData.get(0).getProfilePic()).networkPolicy(NetworkPolicy.NO_CACHE).into(round_img_pic); + } else { + bitmp = BitmapFactory.decodeResource(getResources(), R.mipmap.profile_image); + round_img_pic.setImageBitmap(bitmp); + } + } + + public void showAlert(String str, final boolean flag_finish) { + AlertDialog.Builder builder = new AlertDialog.Builder(context); + builder.setTitle(R.string.dialog_title); + builder.setMessage(str).setCancelable(false) + .setPositiveButton("OK", new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { + if (flag_finish) { + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + finish(); + } + } + }); + AlertDialog alert = builder.create(); + alert.show(); + } + + public void getotp_from_mobile_no(String jsondata) { + try { + loading = ProgressDialog.show(context, "Processing", "Please wait...", false, false); + final OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(20, TimeUnit.SECONDS).writeTimeout(20, TimeUnit.SECONDS).connectTimeout(20, TimeUnit.SECONDS).build(); + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsondata); + Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build(); + PostApi api = adapter.create(PostApi.class); + retrofit2.Call call = api.getOTPMethodForForgotpass(jsonData); + call.enqueue(new retrofit2.Callback() { + @Override + public void onResponse(retrofit2.Call call, retrofit2.Response response) { + ResponseBody responseBody = response.body(); + String data = null; + if (responseBody != null && response.isSuccessful()) { + try { + data = response.body().string(); + data = data.substring(1, data.length() - 1).replace("\\", ""); + if (!data.equals("") && !data.contains("Failure")) { + if (!data.isEmpty()) { + String s[] = data.split(","); + otp_code = s[0]; + String mobile_no = s[1].substring(6, 10); + txt_confirm_pin.setText(getString(R.string.verification_code) + mobile_no); + rl_otp_pinview.setVisibility(View.VISIBLE); + user_spin.setEnabled(false); + loading.dismiss(); + } + } else { + loading.dismiss(); + showAlert("Mobile Number Does Not Exist In Database. So Can Not Able to Reset Password", true); + } + + } catch (Exception e) { + Toast.makeText(context, "Server Not Responding . Please Try Again.", Toast.LENGTH_SHORT).show(); + e.fillInStackTrace(); + loading.dismiss(); + } + } else { + loading.dismiss(); + Toast.makeText(context, "Server Not Responding . Please Try Again.", Toast.LENGTH_SHORT).show(); + } + } + + @Override + public void onFailure(retrofit2.Call call, Throwable t) { + loading.dismiss(); + AlertandMessages.showAlertlogin((Activity) context, t.toString()); + } + }); + } catch (Exception e) { + Toast.makeText(context, "Server Not Responding . Please Try Again.", Toast.LENGTH_SHORT).show(); + e.fillInStackTrace(); + loading.dismiss(); + } + } + + void submit() { + boolean cancel = false; + View focusView = null; + //New Password + Pattern textPattern = Pattern.compile("^(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%])(?=.*\\d).+$"); + if (user_spin.getSelectedItemId() == 0) { + AlertandMessages.showToastMsg(context, "Please Select User"); + focusView = user_spin; + cancel = true; + } else if (pinview_otp.getValue().equals("")) { + AlertandMessages.showToastMsg(context, "Please Enter OTP"); + focusView = pinview_otp; + cancel = true; + } else if (pinview_otp.getValue().length() != 4) { + AlertandMessages.showToastMsg(context, "Please Enter Four Digit OTP"); + focusView = pinview_otp; + cancel = true; + } else if (!pinview_otp.getValue().equals(otp_code)) { + AlertandMessages.showToastMsg(context, "Please Enter Correct OTP"); + focusView = pinview_otp; + cancel = true; + } else if (edt_password.getText().toString().equals("")) { + AlertandMessages.showToastMsg(context, getString(R.string.error_field_required)); + focusView = edt_password; + cancel = true; + } else if (edt_password.getText().toString().length() >= 8 && textPattern.matcher(edt_password.getText().toString()).matches()) { + String confirm_pw = edt_confirm_password.getText().toString(); + if (confirm_pw.equals("")) { + AlertandMessages.showToastMsg(context, getString(R.string.error_field_required)); + focusView = edt_confirm_password; + cancel = true; + } else if (!confirm_pw.equals(edt_password.getText().toString())) { + AlertandMessages.showToastMsg(context, getString(R.string.password_and_confirm_password_not_match)); + focusView = edt_confirm_password; + cancel = true; + } else { + AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle(R.string.parinaam).setMessage(R.string.alertsaveData); + builder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialogInterface, int i) { + new AuthenticateTask().execute(); + + } + }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialogInterface, int i) { + dialogInterface.cancel(); + } + }); + builder.show(); + } + } else { + AlertandMessages.showToastMsg(context, getString(R.string.invalid_password)); + focusView = edt_password; + cancel = true; + } + + if (cancel) { + // There was an error; don't attempt login and focus the first + // form field with an error. + focusView.requestFocus(); + + } else { + + } + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + if (id == android.R.id.home) { + if (clicked_flag) { + AlertDialog.Builder builder = new AlertDialog.Builder(context).setMessage(CommonString.ONBACK_ALERT_MESSAGE).setCancelable(false).setPositiveButton("Ok", + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + ForgotpasswordActity.this.finish(); + } + }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { + dialog.cancel(); + } + }); + AlertDialog alert = builder.create(); + alert.show(); + } else { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + ForgotpasswordActity.this.finish(); + } + } + + return super.onOptionsItemSelected(item); + } + + @Override + public void onBackPressed() { + if (clicked_flag) { + AlertDialog.Builder builder = new AlertDialog.Builder(context).setMessage(CommonString.ONBACK_ALERT_MESSAGE).setCancelable(false).setPositiveButton("Ok", + new DialogInterface.OnClickListener() { + public void onClick( + DialogInterface dialog, int id) { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + ForgotpasswordActity.this.finish(); + } + }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { + dialog.cancel(); + } + }); + AlertDialog alert = builder.create(); + alert.show(); + } else { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + ForgotpasswordActity.this.finish(); + } + } + + @Override + public void onItemSelected(AdapterView adapterView, View view, int pos, long l) { + if (pos != 0) { + str_user_name = bsListData.get(pos - 1).getUserName().toLowerCase(); + clicked_flag = true; + try { + JSONObject jsonObject = new JSONObject(); + jsonObject.put("UserId", str_user_name); + jsonObject.put("MobileNo", ""); + getotp_from_mobile_no(jsonObject.toString()); + } catch (JSONException e) { + e.fillInStackTrace(); + } + } else { + str_user_name = ""; + + } + + } + + @Override + public void onNothingSelected(AdapterView adapterView) { + + } + + private class AuthenticateTask extends AsyncTask { + private ProgressDialog dialog = null; + + @Override + protected void onPreExecute() { + super.onPreExecute(); + dialog = new ProgressDialog(context); + dialog.setTitle("Updating Password"); + dialog.setMessage("Updating...."); + dialog.setCancelable(false); + if (!dialog.isShowing()) { + dialog.show(); + } + } + + @Override + protected String doInBackground(Void... params) { + try { + + JSONObject jsonObject = new JSONObject(); + jsonObject.put("UserId", str_user_name); + jsonObject.put("NewPassword", edt_confirm_password.getText().toString()); + + String jsonString2 = jsonObject.toString(); + DownloadAllDatawithRetro upload = new DownloadAllDatawithRetro(getApplicationContext()); + String result_str = upload.downloadDataUniversal(jsonString2, CommonString.FORGOT_PASSWORD_SERVICE); + if (result_str.contains(CommonString.KEY_SUCCESS)) { + return CommonString.KEY_SUCCESS; + } else { + return result_str; + } + + } catch (Exception e) { + dialog.dismiss(); + runOnUiThread(new Runnable() { + @Override + public void run() { + AlertandMessages.showAlert((Activity) context, CommonString.MESSAGE_EXCEPTION, false); + } + }); + } + + return ""; + + } + + @Override + protected void onPostExecute(String result) { + super.onPostExecute(result); + dialog.dismiss(); + if (result.equals(CommonString.KEY_SUCCESS)) { + db.open(); + if (db.ischeck_login_data(str_user_name.toLowerCase())) { + db.open(); + db.deleteTableWithLogin(str_user_name.toLowerCase()); + } + if (user_id.toLowerCase().equals(str_user_name.toLowerCase())) { + editor.putString(CommonString.KEY_PASSWORD, ""); + editor.putString(CommonString.MPIN, null); + editor.putString(CommonString.KEY_USERNAME, ""); + editor.commit(); + } + showAlert(getString(R.string.password_reset_successfully), true); + } else { + showAlert(result, false); + } + } + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/fragements/BAdvisorMenuFragment.java b/app/src/main/java/com/cpm/lorealbaautomation/fragements/BAdvisorMenuFragment.java new file mode 100644 index 0000000..d1c351a --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/fragements/BAdvisorMenuFragment.java @@ -0,0 +1,192 @@ +package com.cpm.lorealbaautomation.fragements; + +import android.content.Context; +import android.content.SharedPreferences; +import android.os.Bundle; + +import androidx.fragment.app.Fragment; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; + +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; + +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.DealarBoardActivity; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.delegates.NavMenuItemGetterSetter; +import com.cpm.lorealbaautomation.delegates.PrefHelper; + +import java.util.ArrayList; +import java.util.List; + +/** + * A fragment representing a list of Items. + *

+ * interface. + */ +public class BAdvisorMenuFragment extends Fragment { + // TODO: Customize parameter argument names + private static final String ARG_COLUMN_COUNT = "column-count"; + Lorealba_Database db; + String counterId, visit_date = "", username, user_type; + + /** + * Mandatory empty constructor for the fragment manager to instantiate the + * fragment (e.g. upon screen orientation changes). + */ + public BAdvisorMenuFragment() { + } + + // TODO: Customize parameter initialization + @SuppressWarnings("unused") + public static BAdvisorMenuFragment newInstance(int columnCount) { + BAdvisorMenuFragment fragment = new BAdvisorMenuFragment(); + Bundle args = new Bundle(); + args.putInt(ARG_COLUMN_COUNT, columnCount); + fragment.setArguments(args); + return fragment; + } + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + if (getArguments() != null) { + // TODO: Customize parameters + int mColumnCount = getArguments().getInt(ARG_COLUMN_COUNT); + } + } + + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { + final View view = inflater.inflate(R.layout.fragment_item_list4, container, false); + db = new Lorealba_Database(getActivity()); + db.open(); + SharedPreferences preferences = PrefHelper.getPrefs(getActivity()); + counterId = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + username = preferences.getString(CommonString.KEY_USERNAME, null); + user_type = preferences.getString(CommonString.KEY_USER_TYPE, ""); + ((DealarBoardActivity) requireActivity()).setBaMenuRefreshListener(value -> { + // Set the adapter + if (view instanceof RecyclerView) { + Context context = view.getContext(); + RecyclerView recyclerView = (RecyclerView) view; + recyclerView.setAdapter(new MyAdaperForIcon(context, getdata(value), value)); + recyclerView.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)); + } + }); + + return view; + } + + public List getdata(String value) { + List data = new ArrayList<>(); + int groomed_img = 0, consumer_interaction = 0, consumer_return = 0, break_mangment = 0, ba_training = 0, leave_mangment = 0, ba_survey = 0, ba_skin_genius = 0; + db.open(); + String saleable_status = db.getStatus(CommonString.KEY_SaleableStatus, counterId); + if (value.equals("1")) { + groomed_img = R.mipmap.groomed_grey; + consumer_interaction = R.mipmap.consumer_intraction_grey; + consumer_return = R.mipmap.consumer_return_grey; + break_mangment = R.mipmap.break_m_grey; + ba_training = R.mipmap.training; + if (user_type != null && user_type.equalsIgnoreCase(CommonString.TAG_FROM_BA)) { + leave_mangment = R.mipmap.leave_m_grey; + } + ba_survey = R.mipmap.ba_survey; + ba_skin_genius = R.mipmap.vto_grey; + + } else if (value.equals("2")) { + groomed_img = R.mipmap.groomed_grey; + consumer_interaction = R.mipmap.consumer_intraction_grey; + consumer_return = R.mipmap.consumer_return_grey; + break_mangment = R.mipmap.b_mangement; + if (user_type != null && user_type.equalsIgnoreCase(CommonString.TAG_FROM_BA)) { + leave_mangment = R.mipmap.leave_m_grey; + } + ba_training = R.mipmap.training; + ba_survey = R.mipmap.ba_survey; + ba_skin_genius = R.mipmap.vto_grey; + } else { + db.open(); + boolean complete = saleable_status != null && saleable_status.equalsIgnoreCase("Complete"); + if (db.isGroomedChecked(counterId, username, visit_date).equalsIgnoreCase("Green")) { + if (complete) { + consumer_return = R.mipmap.consumer_return; + consumer_interaction = R.mipmap.consumer_interaction; + ba_skin_genius = R.mipmap.vto; + } else { + consumer_return = R.mipmap.consumer_return_grey; + consumer_interaction = R.mipmap.consumer_intraction_grey; + ba_skin_genius = R.mipmap.vto_grey; + } + groomed_img = R.mipmap.groomed_green; + break_mangment = R.mipmap.b_mangement; + ba_training = R.mipmap.training; + if (user_type != null && user_type.equalsIgnoreCase(CommonString.TAG_FROM_BA)) { + leave_mangment = R.mipmap.leave_management; + } + ba_survey = R.mipmap.ba_survey; + + + } else if (db.isGroomedChecked(counterId, username, visit_date).equalsIgnoreCase("Amber")) { + if (complete) { + consumer_return = R.mipmap.consumer_return; + consumer_interaction = R.mipmap.consumer_interaction; + ba_skin_genius = R.mipmap.vto; + } else { + consumer_return = R.mipmap.consumer_return_grey; + consumer_interaction = R.mipmap.consumer_intraction_grey; + ba_skin_genius = R.mipmap.vto_grey; + } + groomed_img = R.mipmap.groomed_amber; + break_mangment = R.mipmap.b_mangement; + ba_training = R.mipmap.training; + if (user_type != null && user_type.equalsIgnoreCase(CommonString.TAG_FROM_BA)) { + leave_mangment = R.mipmap.leave_management; + } + ba_survey = R.mipmap.ba_survey; + + } else { + if (complete) { + consumer_return = R.mipmap.consumer_return; + consumer_interaction = R.mipmap.consumer_interaction; + ba_skin_genius = R.mipmap.vto; + } else { + consumer_return = R.mipmap.consumer_return_grey; + consumer_interaction = R.mipmap.consumer_intraction_grey; + ba_skin_genius = R.mipmap.vto_grey; + } + + groomed_img = R.mipmap.grooming; + break_mangment = R.mipmap.b_mangement; + ba_training = R.mipmap.training; + if (user_type != null && user_type.equalsIgnoreCase(CommonString.TAG_FROM_BA)) { + leave_mangment = R.mipmap.leave_management; + } + ba_survey = R.mipmap.ba_survey; + } + } + + int[] img = {groomed_img, consumer_interaction, consumer_return, break_mangment, ba_training, ba_survey, ba_skin_genius}; + String[] name = {"Grooming Image", "Consumer Interaction", "Consumer Return", "Break Management", "Training", "BA Survey", "VTO"}; + + if (user_type != null && user_type.equalsIgnoreCase(CommonString.TAG_FROM_BA)) { + name = new String[]{"Grooming Image", "Consumer Interaction", "Consumer Return", "Break Management", "Leave Management", "Training", "BA Survey", "VTO"}; + img = new int[]{groomed_img, consumer_interaction, consumer_return, break_mangment, leave_mangment, ba_training, ba_survey, ba_skin_genius}; + } + for (int i = 0; i < img.length; i++) { + NavMenuItemGetterSetter recData = new NavMenuItemGetterSetter(); + recData.setIconImg(img[i]); + recData.setIconName(name[i]); + data.add(recData); + } + + return data; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/fragements/CounterMenuFragment.java b/app/src/main/java/com/cpm/lorealbaautomation/fragements/CounterMenuFragment.java new file mode 100644 index 0000000..82a2285 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/fragements/CounterMenuFragment.java @@ -0,0 +1,181 @@ +package com.cpm.lorealbaautomation.fragements; + +import android.content.Context; +import android.content.SharedPreferences; +import android.os.Bundle; + +import androidx.fragment.app.Fragment; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; + +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.DealarBoardActivity; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.delegates.NavMenuItemGetterSetter; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.gsonGetterSetter.JourneyPlan; + + +import java.util.ArrayList; +import java.util.List; + +/** + * A fragment representing a list of Items. + *

+ *

+ * interface. + */ +public class CounterMenuFragment extends Fragment { + // TODO: Customize parameter argument names + private static final String ARG_COLUMN_COUNT = "column-count"; + JourneyPlan counterimg_object = new JourneyPlan(); + Lorealba_Database db; + String counterId, visit_date = "", username; + /** + * Mandatory empty constructor for the fragment manager to instantiate the + * fragment (e.g. upon screen orientation changes). + */ + public CounterMenuFragment() { + + } + + // TODO: Customize parameter initialization + @SuppressWarnings("unused") + public static CounterMenuFragment newInstance(int columnCount) { + CounterMenuFragment fragment = new CounterMenuFragment(); + Bundle args = new Bundle(); + args.putInt(ARG_COLUMN_COUNT, columnCount); + fragment.setArguments(args); + + + return fragment; + + } + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + if (getArguments() != null) { + // TODO: Customize parameters + int mColumnCount = getArguments().getInt(ARG_COLUMN_COUNT); + } + + + } + + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { + final View view = inflater.inflate(R.layout.fragment_item_list2, container, false); + db = new Lorealba_Database(getActivity()); + db.open(); + SharedPreferences preferences = PrefHelper.getPrefs(getActivity()); + counterId = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + username = preferences.getString(CommonString.KEY_USERNAME, null); + counterimg_object = db.getCounterProfileData(username, visit_date,counterId,false); + // Set the adapter + ((DealarBoardActivity) requireActivity()).setCounterMenuRefreshListener(value -> { + // Set the adapter + if (view instanceof RecyclerView) { + Context context = view.getContext(); + RecyclerView recyclerView = (RecyclerView) view; + recyclerView.setAdapter(new MyAdaperForIcon(context, getdata(value), value)); + recyclerView.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)); + } + }); + + return view; + } + + public List getdata(String value) { + List data = new ArrayList<>(); + int counter_img = 0, stock_check = 0, tester_stock, pwp_gwp_stock = 0, sample_stock, damaged_stock, counter_survey = 0, + visibility, inward_stock, counter_profile,competition_offers,retail_excellence,geoTag; + db.open(); + String saleable_status = db.getStatus(CommonString.KEY_SaleableStatus,counterId); + if (value.equals("1")) { + db.open(); + if (db.isCounterChecked(visit_date, counterId)) { + counter_img = R.mipmap.counter_img_tick; + } else { + counter_img = R.mipmap.counter_image; + } + stock_check = R.mipmap.stock_check_grey; + tester_stock = R.mipmap.tester_stock_grey; + pwp_gwp_stock = R.mipmap.pwp_gwp_grey; + sample_stock = R.mipmap.sample_stock_grey; + damaged_stock = R.mipmap.damage_stock_grey; + visibility = R.mipmap.visibility_grey; + competition_offers = R.mipmap.competition_offers_gray; + retail_excellence = R.mipmap.retail_excellence_grey; + inward_stock = R.mipmap.inward_stock_grey; + counter_profile = R.mipmap.counterprofile_grey; + counter_survey = R.mipmap.survey; + geoTag = R.mipmap.geotag; + } else if (value.equals("2")) { + db.open(); + if (db.isCounterChecked(visit_date, counterId)) { + counter_img = R.mipmap.counter_img_tick; + } else { + counter_img = R.mipmap.counter_image; + } + + stock_check = R.mipmap.stock_check_grey; + tester_stock = R.mipmap.tester_stock_grey; + pwp_gwp_stock = R.mipmap.pwp_gwp_grey; + sample_stock = R.mipmap.sample_stock_grey; + damaged_stock = R.mipmap.damage_stock_grey; + visibility = R.mipmap.visibility_grey; + competition_offers = R.mipmap.competition_offers_gray; + retail_excellence = R.mipmap.retail_excellence_grey; + inward_stock = R.mipmap.inward_stock_grey; + counter_profile = R.mipmap.counterprofile_grey; + counter_survey = R.mipmap.survey; + geoTag = R.mipmap.geotag; + } else { + db.open(); + if (db.isCounterChecked(visit_date, counterId)) { + counter_img = R.mipmap.counter_img_tick; + } else { + counter_img = R.mipmap.counter_image; + } + if (saleable_status != null && saleable_status.equalsIgnoreCase("Complete")) { + inward_stock = R.mipmap.inward_stock; + damaged_stock = R.mipmap.damage_stock; + } else { + inward_stock = R.mipmap.inward_stock_grey; + damaged_stock = R.mipmap.damage_stock_grey; + } + + stock_check = R.mipmap.stock_check; + tester_stock = R.mipmap.tester_stock; + pwp_gwp_stock = R.mipmap.pwp_gwp; + sample_stock = R.mipmap.sample_stock; + visibility = R.mipmap.visibility; + competition_offers = R.mipmap.competition_offers; + retail_excellence = R.mipmap.retail_excellence; + counter_profile = R.mipmap.counterprofile; + counter_survey = R.mipmap.survey; + + geoTag = R.mipmap.geotag; + } + + + int[] img = {counter_img, stock_check, tester_stock, pwp_gwp_stock, sample_stock, damaged_stock, counter_survey,visibility, inward_stock, counter_profile,competition_offers,retail_excellence,geoTag}; + String[] name = {"Counter Image", "Stock Check", "Tester", "GWP", "Sample", "Damaged", "Counter Survey","Visibility", + "InWard Stock", "Counter Profile","Competition Intelligence","Retail Excellence","Counter GeoTag"}; + + for (int i = 0; i < img.length; i++) { + NavMenuItemGetterSetter recData = new NavMenuItemGetterSetter(); + recData.setIconImg(img[i]); + recData.setIconName(name[i]); + data.add(recData); + } + return data; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/fragements/DashboardFragment.java b/app/src/main/java/com/cpm/lorealbaautomation/fragements/DashboardFragment.java new file mode 100644 index 0000000..ff13e37 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/fragements/DashboardFragment.java @@ -0,0 +1,246 @@ +package com.cpm.lorealbaautomation.fragements; + +import android.annotation.SuppressLint; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.os.Bundle; + +import androidx.annotation.NonNull; +import androidx.fragment.app.Fragment; +import androidx.cardview.widget.CardView; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; + +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.ImageView; +import android.widget.LinearLayout; +import android.widget.TextView; + +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.DealarBoardActivity; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.constant.CommonFunctions; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.reportGetterSetter.ReportAvgUnitsPerBill; +import com.cpm.lorealbaautomation.reports.TargetAchievementActivity; + +import java.util.ArrayList; +import java.util.List; + +import lecho.lib.hellocharts.model.PieChartData; +import lecho.lib.hellocharts.model.SliceValue; +import lecho.lib.hellocharts.view.PieChartView; + +/** + * A fragment representing a list of Items. + *

+ *

+ * interface. + */ +public class DashboardFragment extends Fragment { + // TODO: Customize parameter argument names + private static final String ARG_COLUMN_COUNT = "column-count"; + // TODO: Customize parameters + ArrayList dashReportList = new ArrayList<>(); + String CounterId, username, visit_date; + Lorealba_Database db; + Context context; + + /** + * Mandatory empty constructor for the fragment manager to instantiate the + * fragment (e.g. upon screen orientation changes). + */ + + public DashboardFragment() { + } + + // TODO: Customize parameter initialization + @SuppressWarnings("unused") + public static DashboardFragment newInstance(int columnCount) { + DashboardFragment fragment = new DashboardFragment(); + Bundle args = new Bundle(); + args.putInt(ARG_COLUMN_COUNT, columnCount); + fragment.setArguments(args); + return fragment; + } + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + context = (getContext()); + db = new Lorealba_Database(context); + db.open(); + SharedPreferences preferences = PrefHelper.getPrefs(context); + CounterId = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + username = preferences.getString(CommonString.KEY_USERNAME, ""); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + db.open(); + dashReportList = db.getDashboardReport(CounterId); + } + + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { + final View view = inflater.inflate(R.layout.fragment_item_list, container, false); + // Set the adapter + ((DealarBoardActivity) requireActivity()).setDashboardRefreshListener(value -> { + context = (getContext()); + db = new Lorealba_Database(context); + db.open(); + dashReportList = db.getDashboardReport(CounterId); + if (view instanceof RecyclerView) { + Context context = view.getContext(); + RecyclerView recyclerView = (RecyclerView) view; + ///add data for temp + if (dashReportList.size() == 0) { + ReportAvgUnitsPerBill sb = new ReportAvgUnitsPerBill(); + sb.setKPI("No Data"); + sb.setMTDTg(0.0); + sb.setMTDAch(0.0); + sb.setAchPer(0.0); + sb.setPending(0.0); + sb.setRunRate(0); + dashReportList.add(sb); + } + recyclerView.setAdapter(new DashboardAdapter(context, dashReportList)); + recyclerView.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)); + } + }); + + return view; + } + + private class DashboardAdapter extends RecyclerView.Adapter { + ArrayList dashboardList; + Context context; + + DashboardAdapter(Context context, ArrayList dashboardList) { + this.dashboardList = dashboardList; + this.context = context; + } + + + @NonNull + @Override + public Viewholder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { + View view = LayoutInflater.from(context).inflate(R.layout.dashboard_item_adapter, viewGroup, false); + return new Viewholder(view); + } + + @SuppressLint("SetTextI18n") + @Override + public void onBindViewHolder(@NonNull Viewholder viewholder, int position) { + final ReportAvgUnitsPerBill current = dashboardList.get(position); + if (current.getKPI().equalsIgnoreCase("No Data")) { + LinearLayout.LayoutParams layout_description = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, + LinearLayout.LayoutParams.WRAP_CONTENT); + viewholder.parent_layout.setLayoutParams(layout_description); + + viewholder.no_data_card.setVisibility(View.VISIBLE); + viewholder.no_data_card.setId(position); + + viewholder.no_dash_img.setImageResource(R.mipmap.no_dashboard); + viewholder.no_dash_img.setId(position); + + viewholder.dash_card.setVisibility(View.GONE); + viewholder.dash_card.setId(position); + + } else { + viewholder.no_dash_img.setVisibility(View.GONE); + viewholder.no_dash_img.setId(position); + + viewholder.no_data_card.setVisibility(View.GONE); + viewholder.no_data_card.setId(position); + + viewholder.dash_card.setVisibility(View.VISIBLE); + viewholder.dash_card.setId(position); + + List pieData = new ArrayList<>(); + pieData.add(new SliceValue(Float.parseFloat(current.getAchPer().toString()), + getResources().getColor(R.color.dashboard_ach))); + if (current.getAchPer() > 100.0) { + pieData.add(new SliceValue(0, getResources().getColor(R.color.dashboard_less_ach))); + } else { + pieData.add(new SliceValue(Float.parseFloat(current.getPending().toString()), + getResources().getColor(R.color.dashboard_less_ach))); + + } + if (CommonFunctions.isTablet(context)) { + PieChartData pieChartData = new PieChartData(pieData); + pieChartData.setHasLabels(false).setValueLabelTextSize(14); + pieChartData.setHasCenterCircle(true).setCenterText1(current.getAchPer().toString() + + "%").setCenterText1FontSize(10).setCenterText1Color(getResources().getColor(R.color.black)); + viewholder.pieChartView.setPieChartData(pieChartData); + + } else { + viewholder.pieChartView.setCircleFillRatio(0.7f); + PieChartData pieChartData = new PieChartData(pieData); + pieChartData.setHasLabels(false).setValueLabelTextSize(12); + pieChartData.setHasCenterCircle(true).setCenterText1(current.getAchPer().toString() + + "%").setCenterText1FontSize(8).setCenterText1Color(getResources().getColor(R.color.black)); + viewholder.pieChartView.setPieChartData(pieChartData); + } + + viewholder.target_text.setText("MTD TGT : " + current.getMTDTg().toString()); + viewholder.target_text.setId(position); + viewholder.mtd_acheivement_text.setText("MTD ACH : " + current.getMTDAch().toString()); + viewholder.mtd_acheivement_text.setId(position); + + viewholder.txt_nameof_sale.setText(current.getKPI()); + viewholder.txt_nameof_sale.setId(position); + + if (current.getRunRate() != 0) { + viewholder.run_rate_value.setVisibility(View.VISIBLE); + viewholder.run_rate_value.setText("Run Rate : " + current.getRunRate()); + viewholder.run_rate_value.setId(position); + } else { + viewholder.run_rate_value.setVisibility(View.INVISIBLE); + viewholder.run_rate_value.setText(""); + viewholder.run_rate_value.setId(position); + } + + viewholder.dash_card.setOnClickListener(view -> { + if (current.getRunRate() != 0) { + context.startActivity(new Intent(context, TargetAchievementActivity.class)); + } + }); + + viewholder.pieChartView.setOnClickListener(view -> { + if (current.getRunRate() != 0) { + context.startActivity(new Intent(context, TargetAchievementActivity.class)); + } + }); + + } + } + + @Override + public int getItemCount() { + return dashboardList.size(); + } + + class Viewholder extends RecyclerView.ViewHolder { + TextView target_text, mtd_acheivement_text, txt_nameof_sale, run_rate_value; + PieChartView pieChartView; + CardView dash_card, no_data_card; + LinearLayout parent_layout; + ImageView no_dash_img; + + public Viewholder(@NonNull View itemView) { + super(itemView); + pieChartView = itemView.findViewById(R.id.chart); + target_text = (TextView) itemView.findViewById(R.id.target_text); + mtd_acheivement_text = (TextView) itemView.findViewById(R.id.mtd_acheivement_text); + txt_nameof_sale = (TextView) itemView.findViewById(R.id.txt_nameof_sale); + run_rate_value = (TextView) itemView.findViewById(R.id.run_rate_value); + dash_card = (CardView) itemView.findViewById(R.id.dash_card); + no_data_card = (CardView) itemView.findViewById(R.id.no_data_card); + parent_layout = (LinearLayout) itemView.findViewById(R.id.parent_layout); + no_dash_img = (ImageView) itemView.findViewById(R.id.no_dash_img); + } + } + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/fragements/DashboardsFragment.java b/app/src/main/java/com/cpm/lorealbaautomation/fragements/DashboardsFragment.java new file mode 100644 index 0000000..b5e029e --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/fragements/DashboardsFragment.java @@ -0,0 +1,325 @@ +package com.cpm.lorealbaautomation.fragements; + +import android.annotation.SuppressLint; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.graphics.Color; +import android.os.Bundle; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.ImageView; +import android.widget.LinearLayout; +import android.widget.TextView; + +import androidx.annotation.NonNull; +import androidx.cardview.widget.CardView; +import androidx.fragment.app.Fragment; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; + +import com.bikomobile.donutprogress.DonutProgress; +import com.ekn.gruzer.gaugelibrary.HalfGauge; +import com.ekn.gruzer.gaugelibrary.Range; +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.DealarBoardActivity; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.constant.CommonFunctions; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.gsonGetterSetter.AppDashboardTVA; +import com.cpm.lorealbaautomation.reports.TargetAchievementActivity; + +import java.util.ArrayList; + +/** + * A fragment representing a list of Items. + *

+ *

+ * interface. + */ +public class DashboardsFragment extends Fragment { + // TODO: Customize parameter argument names + private static final String ARG_COLUMN_COUNT = "column-count"; + // TODO: Customize parameters + ArrayList dashReportList = new ArrayList<>(); + String CounterId, username, visit_date; + Lorealba_Database db; + Context context; + + /** + * Mandatory empty constructor for the fragment manager to instantiate the + * fragment (e.g. upon screen orientation changes). + */ + public DashboardsFragment() { + } + + // TODO: Customize parameter initialization + @SuppressWarnings("unused") + public static DashboardsFragment newInstance(int columnCount) { + DashboardsFragment fragment = new DashboardsFragment(); + Bundle args = new Bundle(); + args.putInt(ARG_COLUMN_COUNT, columnCount); + fragment.setArguments(args); + return fragment; + } + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + context = (getContext()); + db = new Lorealba_Database(context); + db.open(); + SharedPreferences preferences = PrefHelper.getPrefs(context); + CounterId = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + username = preferences.getString(CommonString.KEY_USERNAME, ""); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + db.open(); + dashReportList = db.getDashboardInfo(CounterId, username); + } + + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { + final View view = inflater.inflate(R.layout.fragment_item_list, container, false); + // Set the adapter + ((DealarBoardActivity) requireActivity()).setDashboardRefreshListener(value -> { + context = (getContext()); + db = new Lorealba_Database(context); + db.open(); + dashReportList = db.getDashboardInfo(CounterId, username); + if (view instanceof RecyclerView) { + Context context = view.getContext(); + RecyclerView recyclerView = (RecyclerView) view; + ///add data for temp + if (dashReportList.isEmpty()) { + AppDashboardTVA sb = new AppDashboardTVA(); + sb.setkPI("No Data"); + sb.setTotalSale(0); + sb.setTarget(0.0); + sb.setPer(0.0); + sb.setGraph(""); + dashReportList.add(sb); + } + recyclerView.setAdapter(new DashboardAdapter(context, dashReportList)); + recyclerView.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)); + } + }); + + return view; + } + + private class DashboardAdapter extends RecyclerView.Adapter { + ArrayList dashboardList; + Context context; + + DashboardAdapter(Context context, ArrayList dashboardList) { + this.dashboardList = dashboardList; + this.context = context; + } + + @NonNull + @Override + public Viewholder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { + View view = LayoutInflater.from(context).inflate(R.layout.dashboard_item_adapter, viewGroup, false); + return new Viewholder(view); + } + + @SuppressLint("SetTextI18n") + @Override + public void onBindViewHolder(@NonNull Viewholder viewholder, int position) { + final AppDashboardTVA current = dashboardList.get(position); + if (current.getkPI().equalsIgnoreCase("No Data")) { + LinearLayout.LayoutParams layout_description = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, + LinearLayout.LayoutParams.WRAP_CONTENT); + viewholder.parent_layout.setLayoutParams(layout_description); + viewholder.no_data_card.setVisibility(View.VISIBLE); + viewholder.no_data_card.setId(position); + viewholder.no_dash_img.setImageResource(R.mipmap.no_dashboard); + viewholder.no_dash_img.setId(position); + viewholder.rlDashInfo.setVisibility(View.GONE); + viewholder.rlDashInfo.setId(position); + } else { + switch (current.getkPI()) { + case "TVA": + if (current.getGraph().equals("HalfGauge")) { + viewholder.cardDonutProgress.setVisibility(View.GONE); + viewholder.cardLeaderBoard.setVisibility(View.GONE); + viewholder.dash_card.setVisibility(View.VISIBLE); + viewholder.rlDashInfo.setVisibility(View.VISIBLE); + viewholder.no_data_card.setVisibility(View.GONE); + viewholder.no_dash_img.setVisibility(View.GONE); + + viewholder.cardDonutProgress.setId(position); + viewholder.cardLeaderBoard.setId(position); + viewholder.no_data_card.setId(position); + viewholder.rlDashInfo.setId(position); + viewholder.no_dash_img.setId(position); + viewholder.dash_card.setId(position); + + Range range = new Range(); + range.setColor(Color.parseColor("#e21c22")); + range.setFrom(0); + range.setTo(30); + + Range range2 = new Range(); + range2.setColor(Color.parseColor("#ffdd76")); + range2.setFrom(31); + range2.setTo(70); + + Range range3 = new Range(); + range3.setColor(Color.parseColor("#2bbf7d")); + range3.setFrom(71); + range3.setTo(100); + //add color ranges to gauge + viewholder.pieChartView.addRange(range); + viewholder.pieChartView.addRange(range2); + viewholder.pieChartView.addRange(range3); + //set min max and current value + viewholder.pieChartView.setMinValue(0); + viewholder.pieChartView.setMaxValue(100); + viewholder.pieChartView.setValue(current.getPer()); + viewholder.pieChartView.setEnableNeedleShadow(true); + viewholder.tvAchievmentHalf.setText(getString(R.string.Rs) + " " + current.getTarget().intValue()); + viewholder.tvAchievmentHalf.setId(position); + viewholder.tvTargetsHalf.setText(getString(R.string.Rs) + " " + (current.getTotalSale())); + viewholder.tvTargetsHalf.setId(position); + viewholder.dash_card.setBackgroundResource(R.drawable.round_corner_parent); + viewholder.dash_card.setId(position); + } else { + viewholder.cardDonutProgress.setBackgroundResource(R.drawable.round_corner_parent); + viewholder.cardDonutProgress.setVisibility(View.VISIBLE); + viewholder.cardLeaderBoard.setVisibility(View.GONE); + viewholder.dash_card.setVisibility(View.GONE); + viewholder.rlDashInfo.setVisibility(View.VISIBLE); + viewholder.no_data_card.setVisibility(View.GONE); + viewholder.no_dash_img.setVisibility(View.GONE); + + viewholder.cardDonutProgress.setId(position); + viewholder.cardLeaderBoard.setId(position); + viewholder.no_data_card.setId(position); + viewholder.rlDashInfo.setId(position); + viewholder.no_dash_img.setId(position); + viewholder.dash_card.setId(position); + + viewholder.tvTargets.setText(getString(R.string.Rs) + " " + (current.getTotalSale())); + viewholder.tvTargets.setId(position); + viewholder.tvAchievment.setText("of " + getString(R.string.Rs) + " " + current.getTarget().intValue()); + viewholder.donutProgress.setProgress(current.getPer() != null ? current.getPer().intValue() : 0); + // or if you want animation progress + viewholder.donutProgress.setProgressWithAnimation(current.getPer() != null ? current.getPer().intValue() : 0, 20); + viewholder.donutProgress.setTextColor(getResources().getColor(R.color.black)); + viewholder.donutProgress.setFinishedStrokeColor(getResources().getColor(R.color.achievement)); + viewholder.donutProgress.setUnfinishedStrokeColor(getResources().getColor(R.color.target_color)); + viewholder.donutProgress.setUnfinishedStrokeWidth(30f); + viewholder.donutProgress.setFinishedStrokeWidth(30f); + viewholder.donutProgress.setSuffix("%"); + } + break; + case "LeaderBoard": + ///for Leader Board + viewholder.tvLeaderbKPI.setText("Leader Board"); + viewholder.tvLeaderbKPI.setId(position); + viewholder.tvLeaderbAchPer.setText(current.getPer().toString() + "%"); + viewholder.tvLeaderbAchPer.setId(position); + viewholder.tvLeaderbaName.setText(current.getGraph()); + viewholder.tvLeaderbaName.setId(position); + viewholder.tvCounterName.setText(CommonFunctions.capitalizeFirstLetter(current.getCounter_name())); + viewholder.tvCounterName.setId(position); + viewholder.tvCounterId.setText(current.getCounter_code()); + viewholder.tvCounterId.setId(position); + viewholder.rlDashInfo.setVisibility(View.VISIBLE); + viewholder.dash_card.setVisibility(View.GONE); + viewholder.dash_card.setId(position); + viewholder.rlDashInfo.setId(position); + viewholder.cardLeaderBoard.setVisibility(View.VISIBLE); + viewholder.cardDonutProgress.setVisibility(View.GONE); + viewholder.cardLeaderBoard.setBackgroundResource(R.drawable.round_corner_parent); + viewholder.cardDonutProgress.setId(position); + viewholder.cardLeaderBoard.setId(position); + break; + case "Incentive": + viewholder.cardDonutIncentive.setBackgroundResource(R.drawable.round_corner_parent); + viewholder.cardDonutIncentive.setVisibility(View.VISIBLE); + viewholder.cardDonutProgress.setVisibility(View.GONE); + viewholder.cardLeaderBoard.setVisibility(View.GONE); + viewholder.rlDashInfo.setVisibility(View.VISIBLE); + viewholder.no_data_card.setVisibility(View.GONE); + viewholder.no_dash_img.setVisibility(View.GONE); + viewholder.dash_card.setVisibility(View.GONE); + + viewholder.cardDonutIncentive.setId(position); + viewholder.cardDonutProgress.setId(position); + viewholder.cardLeaderBoard.setId(position); + viewholder.no_data_card.setId(position); + viewholder.no_dash_img.setId(position); + viewholder.rlDashInfo.setId(position); + viewholder.dash_card.setId(position); + + viewholder.tvMaximumIncentive.setText(getString(R.string.Rs) + " " + (current.getTarget().intValue())); + viewholder.tvMaximumIncentive.setId(position); + viewholder.tvAchIncentive.setText(getString(R.string.Rs) + " " + current.getTotalSale()); + viewholder.tvAchIncentive.setId(position); + viewholder.donut_progress_incentive.setProgress(current.getPer() != null ? current.getPer().intValue() : 0); + // or if you want animation progress + viewholder.donut_progress_incentive.setProgressWithAnimation(current.getPer() != null ? current.getPer().intValue() : 0, 20); + viewholder.donut_progress_incentive.setTextColor(getResources().getColor(R.color.black)); + viewholder.donut_progress_incentive.setFinishedStrokeColor(getResources().getColor(R.color.incentive_max)); + viewholder.donut_progress_incentive.setUnfinishedStrokeColor(getResources().getColor(R.color.incentive_min)); + viewholder.donut_progress_incentive.setUnfinishedStrokeWidth(30f); + viewholder.donut_progress_incentive.setFinishedStrokeWidth(30f); + viewholder.donut_progress_incentive.setSuffix("%"); + break; + } + + viewholder.rlDashInfo.setOnClickListener(view -> context.startActivity(new Intent(context, TargetAchievementActivity.class).putExtra("kpi", current.getkPI()))); + } + } + + @Override + public int getItemCount() { + return dashboardList.size(); + } + + class Viewholder extends RecyclerView.ViewHolder { + TextView tvTargetsHalf, tvAchievmentHalf, + tvLeaderbAchPer, tvLeaderbaName, tvCounterName, tvCounterId, tvLeaderbKPI, tvTargets, + tvAchievment, tvAchIncentive, tvMaximumIncentive; + HalfGauge pieChartView; + DonutProgress donutProgress, donut_progress_incentive; + CardView dash_card, no_data_card, cardLeaderBoard, cardDonutProgress, cardDonutIncentive; + LinearLayout parent_layout, rlDashInfo, rlViewReport; + ImageView no_dash_img; + + public Viewholder(@NonNull View it) { + super(it); + pieChartView = it.findViewById(R.id.chart); + dash_card = it.findViewById(R.id.dash_card); + tvAchievmentHalf = it.findViewById(R.id.tvAchievmentHalf); + tvTargetsHalf = it.findViewById(R.id.tvTargetsHalf); + parent_layout = it.findViewById(R.id.parent_layout); + no_data_card = it.findViewById(R.id.no_data_card); + no_dash_img = it.findViewById(R.id.no_dash_img); + rlDashInfo = it.findViewById(R.id.rlDashInfo); + ////for leaderBoard + cardLeaderBoard = it.findViewById(R.id.cardLeaderBoard); + tvLeaderbAchPer = it.findViewById(R.id.tvLeaderbAchPer); + tvLeaderbaName = it.findViewById(R.id.tvLeaderbaName); + tvCounterName = it.findViewById(R.id.tvCounterName); + tvLeaderbKPI = it.findViewById(R.id.tvLeaderbKPI); + tvCounterId = it.findViewById(R.id.tvCounterId); + /////for Dognut graph + cardDonutProgress = it.findViewById(R.id.cardDonutProgress); + donutProgress = it.findViewById(R.id.donut_progress); + rlViewReport = it.findViewById(R.id.rlViewReport); + tvAchievment = it.findViewById(R.id.tvAchievment); + tvTargets = it.findViewById(R.id.tvTargets); + ///for Incentive + cardDonutIncentive = it.findViewById(R.id.cardDonutIncentive); + donut_progress_incentive = it.findViewById(R.id.donut_progress_incentive); + tvMaximumIncentive = it.findViewById(R.id.tvMaximumIncentive); + tvAchIncentive = it.findViewById(R.id.tvAchIncentive); + } + } + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/fragements/MakeupExpertMenuFragment.java b/app/src/main/java/com/cpm/lorealbaautomation/fragements/MakeupExpertMenuFragment.java new file mode 100644 index 0000000..50ccbc6 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/fragements/MakeupExpertMenuFragment.java @@ -0,0 +1,95 @@ +package com.cpm.lorealbaautomation.fragements; + +import android.content.Context; +import android.content.SharedPreferences; +import android.os.Bundle; + +import androidx.fragment.app.Fragment; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; + +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; + +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.delegates.NavMenuItemGetterSetter; +import com.cpm.lorealbaautomation.delegates.PrefHelper; + +import java.util.ArrayList; +import java.util.List; + +public class MakeupExpertMenuFragment extends Fragment { + // TODO: Customize parameter argument names + private static final String ARG_COLUMN_COUNT = "column-count"; + Lorealba_Database db; + String counterId, visit_date = "", username; + + /** + * Mandatory empty constructor for the fragment manager to instantiate the + * fragment (e.g. upon screen orientation changes). + */ + public MakeupExpertMenuFragment() { + } + + // TODO: Customize parameter initialization + @SuppressWarnings("unused") + public static MakeupExpertMenuFragment newInstance(int columnCount) { + MakeupExpertMenuFragment fragment = new MakeupExpertMenuFragment(); + Bundle args = new Bundle(); + args.putInt(ARG_COLUMN_COUNT, columnCount); + fragment.setArguments(args); + return fragment; + } + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + if (getArguments() != null) { + // TODO: Customize parameters + int mColumnCount = getArguments().getInt(ARG_COLUMN_COUNT); + } + } + + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { + final View view = inflater.inflate(R.layout.fragment_item_me, container, false); + db = new Lorealba_Database(getActivity()); + db.open(); + SharedPreferences preferences = PrefHelper.getPrefs(getActivity()); + counterId = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + username = preferences.getString(CommonString.KEY_USERNAME, null); + + if (view instanceof RecyclerView) { + Context context = view.getContext(); + RecyclerView recyclerView = (RecyclerView) view; + recyclerView.setAdapter(new MyAdaperForIcon(context, getdata(), "3")); + recyclerView.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)); + } + return view; + } + + public List getdata() { + List data = new ArrayList<>(); + int counter_image = 0, makeover_capturing = 0, sales = 0, quiz = 0; + db.open(); + String saleable_status = db.getStatus(CommonString.KEY_SaleableStatus, counterId); + counter_image = R.mipmap.counter_image; + makeover_capturing = R.mipmap.makeover; + quiz = R.mipmap.quiz; + sales = (saleable_status != null && saleable_status.equalsIgnoreCase("Complete")) ? R.mipmap.me_sale : R.mipmap.me_sales_grey; + db.open(); + int[] img = {counter_image, makeover_capturing, sales, quiz}; + String[] name = {"Counter Image", "Makeover Capturing", "ME_Sales", "Quiz"}; + for (int i = 0; i < img.length; i++) { + NavMenuItemGetterSetter recData = new NavMenuItemGetterSetter(); + recData.setIconImg(img[i]); + recData.setIconName(name[i]); + data.add(recData); + } + return data; + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/fragements/MonthlyOfferFragment.java b/app/src/main/java/com/cpm/lorealbaautomation/fragements/MonthlyOfferFragment.java new file mode 100644 index 0000000..b33753a --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/fragements/MonthlyOfferFragment.java @@ -0,0 +1,190 @@ +package com.cpm.lorealbaautomation.fragements; + +import android.os.Bundle; + +import androidx.fragment.app.Fragment; +import androidx.viewpager.widget.ViewPager; + +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; + +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.DealarBoardActivity; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.adapter.MyPager; +import com.cpm.lorealbaautomation.constant.CommonFunctions; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterPromoOffer; + +import java.io.File; +import java.util.ArrayList; +import java.util.Timer; +import java.util.TimerTask; + +import me.relex.circleindicator.CircleIndicator; + + +/** + * A simple {@link Fragment} subclass. + * Activities that contain this fragment must implement the + * to handle interaction events. + * Use the {@link MonthlyOfferFragment#newInstance} factory method to + * create an instance of this fragment. + */ +public class MonthlyOfferFragment extends Fragment { + // TODO: Rename parameter arguments, choose names that match + // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER + private static final String ARG_PARAM1 = "param1"; + private static final String ARG_PARAM2 = "param2"; + // TODO: Rename and change types of parameters + private ViewPager viewPager; + private CircleIndicator circleIndicator; + private MyPager myPager; + Lorealba_Database db; + Timer timer; + + public MonthlyOfferFragment() { + // Required empty public constructor + } + + /** + * Use this factory method to create a new instance of + * this fragment using the provided parameters. + * + * @param param1 Parameter 1. + * @param param2 Parameter 2. + * @return A new instance of fragment MonthlyOfferFragment. + */ + // TODO: Rename and change types and number of parameters + public static MonthlyOfferFragment newInstance(String param1, String param2) { + MonthlyOfferFragment fragment = new MonthlyOfferFragment(); + Bundle args = new Bundle(); + args.putString(ARG_PARAM1, param1); + args.putString(ARG_PARAM2, param2); + fragment.setArguments(args); + return fragment; + } + + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { + // Inflate the layout for this fragment + final View view = inflater.inflate(R.layout.fragment_monthly_offer, container, false); + viewPager = view.findViewById(R.id.view_pager); + db = new Lorealba_Database(getContext()); + final ArrayList[] masterPromoOffers = new ArrayList[]{new ArrayList<>()}; + final ArrayList[] finalPromoOffers = new ArrayList[]{new ArrayList<>()}; + ((DealarBoardActivity) requireActivity()).setOfferMenuRefreshListener(() -> { + db.open(); + masterPromoOffers[0] = db.getmaterPromoOffers(); + if (!masterPromoOffers[0].isEmpty()) { + finalPromoOffers[0] = new ArrayList<>(); + for (int k = 0; k < masterPromoOffers[0].size(); k++) { + if (CommonFunctions.isTablet(requireActivity())) { + String path = CommonString.getPromosFolder(getContext()) + masterPromoOffers[0].get(k).getPromoOfferTab(); + File dir = new File(path); + if (dir.exists()) { + finalPromoOffers[0].add(masterPromoOffers[0].get(k)); + } + } else { + String path = CommonString.getPromosFolder(getContext()) + masterPromoOffers[0].get(k).getPromoOfferMobile(); + File dir = new File(path); + if (dir.exists()) { + finalPromoOffers[0].add(masterPromoOffers[0].get(k)); + } + } + } + } + + + ///add data for temp + if (finalPromoOffers[0].isEmpty()) { + MasterPromoOffer sb = new MasterPromoOffer(); + sb.setPromoId("No Data"); + sb.setPromoPath(""); + sb.setPromoOfferTab(""); + sb.setPromoOfferMobile(""); + sb.setDescription(""); + sb.setStartDate(""); + sb.setEndDate(""); + finalPromoOffers[0].add(sb); + + } + + + if (finalPromoOffers[0].size() > 0) { + myPager = new MyPager(view.getContext(), finalPromoOffers[0]); + viewPager.setAdapter(myPager); + circleIndicator = view.findViewById(R.id.circle); + circleIndicator.setViewPager(viewPager); + } + }); + + db.open(); + masterPromoOffers[0] = db.getmaterPromoOffers(); + if (!masterPromoOffers[0].isEmpty()) { + finalPromoOffers[0] = new ArrayList<>(); + for (int k = 0; k < masterPromoOffers[0].size(); k++) { + if (CommonFunctions.isTablet(requireContext())) { + String path = CommonString.getPromosFolder(getContext()) + masterPromoOffers[0].get(k).getPromoOfferTab(); + File dir = new File(path); + if (dir.exists()) { + finalPromoOffers[0].add(masterPromoOffers[0].get(k)); + } + } else { + String path = CommonString.getPromosFolder(getContext()) + masterPromoOffers[0].get(k).getPromoOfferMobile(); + File dir = new File(path); + if (dir.exists()) { + finalPromoOffers[0].add(masterPromoOffers[0].get(k)); + } + } + } + } + + + ///add data for temp + if (finalPromoOffers[0].isEmpty()) { + MasterPromoOffer sb = new MasterPromoOffer(); + sb.setPromoId("No Data"); + sb.setPromoPath(""); + sb.setPromoOfferTab(""); + sb.setPromoOfferMobile(""); + sb.setDescription(""); + sb.setStartDate(""); + sb.setEndDate(""); + finalPromoOffers[0].add(sb); + + } + + + if (finalPromoOffers[0].size() > 0) { + myPager = new MyPager(view.getContext(), finalPromoOffers[0]); + viewPager.setAdapter(myPager); + circleIndicator = view.findViewById(R.id.circle); + circleIndicator.setViewPager(viewPager); + } + + TimerTask timerTask = new TimerTask() { + @Override + public void run() { + if (viewPager != null) { + viewPager.post(() -> { + if (!finalPromoOffers[0].isEmpty()) + viewPager.setCurrentItem((viewPager.getCurrentItem() + 1) % finalPromoOffers[0].size()); + }); + + } + } + }; + + timer = new Timer(); + timer.schedule(timerTask, 3000, 3000); + return view; + } + + @Override + public void onDestroy() { + timer.cancel(); + super.onDestroy(); + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/fragements/MyAdaperForIcon.java b/app/src/main/java/com/cpm/lorealbaautomation/fragements/MyAdaperForIcon.java new file mode 100644 index 0000000..16b0e08 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/fragements/MyAdaperForIcon.java @@ -0,0 +1,244 @@ +package com.cpm.lorealbaautomation.fragements; + +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.ImageView; +import android.widget.TextView; + +import androidx.annotation.NonNull; +import androidx.cardview.widget.CardView; +import androidx.recyclerview.widget.RecyclerView; + +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.breakmanagement.BreakManagementActivity; +import com.cpm.lorealbaautomation.competitionoffer.CompetitionOfferActivity; +import com.cpm.lorealbaautomation.constant.AlertandMessages; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.consumeractivity.ConsumerIntractionDetailActivity; +import com.cpm.lorealbaautomation.dailyactivity.BASurveyListActivity; +import com.cpm.lorealbaautomation.dailyactivity.ConsumerReturnActivity; +import com.cpm.lorealbaautomation.dailyactivity.CounterImageActivity; +import com.cpm.lorealbaautomation.dailyactivity.CounterProfileActivity; +import com.cpm.lorealbaautomation.dailyactivity.DamagedCategoryActivity; +import com.cpm.lorealbaautomation.dailyactivity.GWPActivity; +import com.cpm.lorealbaautomation.dailyactivity.GroomedActivity; +import com.cpm.lorealbaautomation.dailyactivity.InWardStockActivity; +import com.cpm.lorealbaautomation.dailyactivity.MeQuizListActivity; +import com.cpm.lorealbaautomation.dailyactivity.RetailExcellenceActivity; +import com.cpm.lorealbaautomation.dailyactivity.SampleStockActivity; +import com.cpm.lorealbaautomation.dailyactivity.SkinGeniusCategoryActivity; +import com.cpm.lorealbaautomation.dailyactivity.StockCheckActivity; +import com.cpm.lorealbaautomation.dailyactivity.SuggestedStockActivity; +import com.cpm.lorealbaautomation.dailyactivity.TesterStockActivity; +import com.cpm.lorealbaautomation.dailyactivity.VisibilityElimentsActivity; +import com.cpm.lorealbaautomation.delegates.NavMenuItemGetterSetter; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.geotag.GeoTaggingActivity; +import com.cpm.lorealbaautomation.gsonGetterSetter.JourneyPlan; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterPosm; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterSurvey; +import com.cpm.lorealbaautomation.gsonGetterSetter.ProductMaster; +import com.cpm.lorealbaautomation.gsonGetterSetter.TCounterInvoice; +import com.cpm.lorealbaautomation.leavemanagement.LeaveManagemntActivity; +import com.cpm.lorealbaautomation.makeupexpert.MakeoverActivity; +import com.cpm.lorealbaautomation.reports.MyLibraryActivity; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class MyAdaperForIcon extends RecyclerView.Adapter { + List data = Collections.emptyList(); + final LayoutInflater inflator; + Context context; + Lorealba_Database db; + String counter_id, visit_date = "", userId, username, user_type, storeGeoTag = "N"; + SharedPreferences preferences; + ArrayList promotionList = new ArrayList<>(); + String value; + + public MyAdaperForIcon(Context context, List data, String value) { + inflator = LayoutInflater.from(context); + this.context = context; + this.data = data; + this.value = value; + db = new Lorealba_Database(context); + db.open(); + preferences = PrefHelper.getPrefs(context); + counter_id = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + userId = preferences.getString(CommonString.KEY_USER_ID, ""); + username = preferences.getString(CommonString.KEY_USERNAME, ""); + user_type = preferences.getString(CommonString.KEY_USER_TYPE, ""); + } + + @NonNull + @Override + public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { + View view = null; + if (user_type.equalsIgnoreCase("ME")) { + view = inflator.inflate(R.layout.custom_row_me, parent, false); + } else { + view = inflator.inflate(R.layout.custom_row, parent, false); + } + + return new ViewHolder(view); + } + + @Override + public void onBindViewHolder(final ViewHolder holder, int position) { + final NavMenuItemGetterSetter current = data.get(position); + holder.list_icon.setImageResource(current.getIconImg()); + holder.list_icon.setId(position); + holder.icon_txtname.setText(current.getIconName()); + holder.icon_txtname.setId(position); + + if (value.equals("1")) { + if (current.getIconImg() == R.mipmap.counter_image || current.getIconImg() == R.mipmap.training || current.getIconImg() == R.mipmap.counter_img_tick) { + holder.icon_txtname.setTextColor(context.getResources().getColor(R.color.black)); + holder.icon_txtname.setId(position); + } else { + holder.icon_txtname.setTextColor(context.getResources().getColor(R.color.background_color)); + holder.icon_txtname.setId(position); + } + } else if (value.equals("2")) { + if (current.getIconImg() == R.mipmap.counter_image || current.getIconImg() == R.mipmap.b_mangement || current.getIconImg() == R.mipmap.training || current.getIconImg() == R.mipmap.counter_img_tick || current.getIconImg() == R.mipmap.geotag) { + holder.icon_txtname.setTextColor(context.getResources().getColor(R.color.black)); + holder.icon_txtname.setId(position); + } else { + holder.icon_txtname.setTextColor(context.getResources().getColor(R.color.background_color)); + holder.icon_txtname.setId(position); + } + } else { + holder.icon_txtname.setTextColor(context.getResources().getColor(R.color.black)); + holder.icon_txtname.setId(position); + } + + String saleable_status = db.getStatus(CommonString.KEY_SaleableStatus, counter_id); + String gwp_status = db.getStatus(CommonString.KEY_GwpStatus, counter_id); + + if (saleable_status != null && saleable_status.equalsIgnoreCase("Complete") && gwp_status != null && gwp_status.equalsIgnoreCase("Complete")) { + if (current.getIconImg() == R.mipmap.damage_stock || current.getIconImg() == R.mipmap.inward_stock || current.getIconImg() == R.mipmap.consumer_interaction || current.getIconImg() == R.mipmap.consumer_return || current.getIconImg() == R.mipmap.competition_offers || current.getIconImg() == R.mipmap.retail_excellence || current.getIconImg() == R.mipmap.me_sale) { + holder.icon_txtname.setTextColor(context.getResources().getColor(R.color.black)); + holder.icon_txtname.setId(position); + } + } else { + if (current.getIconImg() == R.mipmap.damage_stock_grey || current.getIconImg() == R.mipmap.inward_stock_grey || current.getIconImg() == R.mipmap.consumer_intraction_grey || current.getIconImg() == R.mipmap.consumer_return_grey || current.getIconImg() == R.mipmap.competition_offers_gray || current.getIconImg() == R.mipmap.retail_excellence_grey || current.getIconImg() == R.mipmap.me_sales_grey) { + holder.icon_txtname.setTextColor(context.getResources().getColor(R.color.background_color)); + holder.icon_txtname.setId(position); + } + } + + holder.dashbrd_card_view.setOnClickListener(v -> { + if (current.getIconImg() == R.mipmap.counter_image || current.getIconImg() == R.mipmap.counter_img_tick) { + context.startActivity(new Intent(context, CounterImageActivity.class)); + } else if (current.getIconImg() == R.mipmap.grooming || current.getIconImg() == R.mipmap.groomed_amber || current.getIconImg() == R.mipmap.groomed_green) { + context.startActivity(new Intent(context, GroomedActivity.class)); + } else if (current.getIconImg() == R.mipmap.consumer_return) { + context.startActivity(new Intent(context, ConsumerReturnActivity.class)); + } else if (current.getIconImg() == R.mipmap.stock_check) { + context.startActivity(new Intent(context, StockCheckActivity.class)); + } else if (current.getIconImg() == R.mipmap.damage_stock) { + context.startActivity(new Intent(context, DamagedCategoryActivity.class)); + } else if (current.getIconImg() == R.mipmap.sample_stock) { + context.startActivity(new Intent(context, SampleStockActivity.class)); + } else if (current.getIconImg() == R.mipmap.suggested_stock) { + context.startActivity(new Intent(context, SuggestedStockActivity.class)); + } else if (current.getIconImg() == R.mipmap.tester_stock) { + context.startActivity(new Intent(context, TesterStockActivity.class)); + } else if (current.getIconImg() == R.mipmap.visibility) { + promotionList = db.getVisibility_master_data(counter_id); + if (!promotionList.isEmpty()) { + context.startActivity(new Intent(context, VisibilityElimentsActivity.class)); + } else { + AlertandMessages.showToastMsg(context, "Visibility Data Not Found"); + } + } else if (current.getIconImg() == R.mipmap.inward_stock) { + db.open(); + ArrayList stockList = db.getinwardStockTransactionList(counter_id, visit_date); + ArrayList manualInwardStockList = db.getManualInwardStockList(counter_id, visit_date); + if (!stockList.isEmpty()) { + db.deleteInwardStockData(counter_id, visit_date); + } + if (!manualInwardStockList.isEmpty()) { + db.deleteManualStockData(counter_id, visit_date); + } + + context.startActivity(new Intent(context, InWardStockActivity.class)); + } else if (current.getIconImg() == R.mipmap.ba_survey) { + db.open(); + JourneyPlan jcp_Object = db.getBIDfromJCP(username, counter_id); + ArrayList listDataHeader = db.getBASurveySavedData1("BA", jcp_Object, visit_date); + if (!listDataHeader.isEmpty()) { + db.deleteBASurveyData(counter_id, visit_date); + } + context.startActivity(new Intent(context, BASurveyListActivity.class).putExtra("SurveyType", "BA")); + } else if (current.getIconImg() == R.mipmap.survey) { + db.open(); + JourneyPlan jcp_Object = db.getBIDfromJCP(username, counter_id); + ArrayList listDataHeader = db.getBASurveySavedData1("Counter", jcp_Object, visit_date); + if (!listDataHeader.isEmpty()) { + db.deleteCounterSurveyData(counter_id, visit_date); + } + context.startActivity(new Intent(context, BASurveyListActivity.class).putExtra("SurveyType", "Counter")); + } else if (current.getIconImg() == R.mipmap.consumer_interaction) { + context.startActivity(new Intent(context, + ConsumerIntractionDetailActivity.class).putExtra("from", CommonString.TAG_FROM_BA)); + } else if (current.getIconImg() == R.mipmap.leave_management) { + context.startActivity(new Intent(context, LeaveManagemntActivity.class)); + } else if (current.getIconImg() == R.mipmap.b_mangement) { + context.startActivity(new Intent(context, BreakManagementActivity.class)); + } else if (current.getIconImg() == R.mipmap.pwp_gwp) { + context.startActivity(new Intent(context, GWPActivity.class)); + } else if (current.getIconImg() == R.mipmap.counterprofile) { + context.startActivity(new Intent(context, CounterProfileActivity.class)); + } else if (current.getIconImg() == R.mipmap.training) { + context.startActivity(new Intent(context, MyLibraryActivity.class).putExtra(CommonString.KEY_BODY, "1")); + } else if (current.getIconImg() == R.mipmap.makeover) { + context.startActivity(new Intent(context, MakeoverActivity.class)); + } else if (current.getIconImg() == R.mipmap.quiz) { + context.startActivity(new Intent(context, MeQuizListActivity.class)); + } else if (current.getIconImg() == R.mipmap.me_sale) { + // context.startActivity(new Intent(context, SalesActivity.class)); + context.startActivity(new Intent(context, + ConsumerIntractionDetailActivity.class).putExtra("from", CommonString.TAG_FROM_ME)); + } + ///for Skin Genius + else if (current.getIconImg() == R.mipmap.vto) { + context.startActivity(new Intent(context, SkinGeniusCategoryActivity.class)); + } else if (current.getIconImg() == R.mipmap.competition_offers) { + context.startActivity(new Intent(context, CompetitionOfferActivity.class)); + } else if (current.getIconImg() == R.mipmap.retail_excellence) { + context.startActivity(new Intent(context, RetailExcellenceActivity.class)); + } else if (storeGeoTag.equals("N") && (current.getIconImg() == R.mipmap.geotag || current.getIconImg() == R.mipmap.geotag_done)) { + context.startActivity(new Intent(context, GeoTaggingActivity.class)); + } + }); + + holder.dashbrd_card_view.setBackgroundResource(R.drawable.round_corner_parent); + holder.dashbrd_card_view.setId(position); + } + + @Override + public int getItemCount() { + return data.size(); + } + + class ViewHolder extends RecyclerView.ViewHolder { + CardView dashbrd_card_view; + ImageView list_icon; + TextView icon_txtname; + + public ViewHolder(View view) { + super(view); + list_icon = (ImageView) view.findViewById(R.id.list_icon); + icon_txtname = (TextView) view.findViewById(R.id.icon_txtname); + dashbrd_card_view = (CardView) view.findViewById(R.id.dashbrd_card_view); + } + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/fragements/OffersFragment.java b/app/src/main/java/com/cpm/lorealbaautomation/fragements/OffersFragment.java new file mode 100644 index 0000000..b2be773 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/fragements/OffersFragment.java @@ -0,0 +1,64 @@ +package com.cpm.lorealbaautomation.fragements; + +import android.os.Bundle; +import androidx.fragment.app.Fragment; +import androidx.viewpager.widget.ViewPager; + +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; + +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.adapter.MyPager; + + +import me.relex.circleindicator.CircleIndicator; + +/** + * A fragment representing a list of Items. + *

+ * interface. + */ +public class OffersFragment extends Fragment { + // TODO: Customize parameter argument names + private static final String ARG_COLUMN_COUNT = "column-count"; + private MyPager myPager; + + /** + * Mandatory empty constructor for the fragment manager to instantiate the + * fragment (e.g. upon screen orientation changes). + */ + public OffersFragment() { + } + + // TODO: Customize parameter initialization + @SuppressWarnings("unused") + public static OffersFragment newInstance(int columnCount) { + OffersFragment fragment = new OffersFragment(); + Bundle args = new Bundle(); + args.putInt(ARG_COLUMN_COUNT, columnCount); + fragment.setArguments(args); + return fragment; + } + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + if (getArguments() != null) { + // TODO: Customize parameters + int mColumnCount = getArguments().getInt(ARG_COLUMN_COUNT); + } + } + + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { + View view = inflater.inflate(R.layout.fragment_item_list3, container, false); + ViewPager viewPager = view.findViewById(R.id.view_pager); + viewPager.setAdapter(myPager); + CircleIndicator circleIndicator = view.findViewById(R.id.circle); + circleIndicator.setViewPager(viewPager); + // Set the adapter + return view; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/fragements/ServiceActivityFragment.java b/app/src/main/java/com/cpm/lorealbaautomation/fragements/ServiceActivityFragment.java new file mode 100644 index 0000000..b7d1674 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/fragements/ServiceActivityFragment.java @@ -0,0 +1,130 @@ +package com.cpm.lorealbaautomation.fragements; + +import android.content.Context; +import android.content.SharedPreferences; +import android.os.Bundle; + +import androidx.annotation.NonNull; +import androidx.fragment.app.Fragment; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; + +import android.view.LayoutInflater; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; +import android.widget.ImageView; + +import com.cpm.lorealbaautomation.BuildConfig; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.delegates.PrefHelper; + +import java.util.ArrayList; + + +/** + * A placeholder fragment containing a simple view. + */ +public class ServiceActivityFragment extends Fragment { + public ServiceActivityFragment() { + } + ArrayList serviceList; + Context context; + SharedPreferences preferences; + String user_name; + RecyclerView rec; + + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { + View view = inflater.inflate(R.layout.fragment_service, container, false); + rec = (RecyclerView) view.findViewById(R.id.rec_daily_entry_menu); + context = view.getContext(); + preferences = PrefHelper.getPrefs(context); + user_name = preferences.getString(CommonString.KEY_USERNAME, null); + ServiceGetterSetter service = new ServiceGetterSetter(); + service.setName(getString(R.string.export_database)); + service.setIcon(R.mipmap.entry_grey); + service.setFragment(null); + serviceList = new ArrayList<>(); + serviceList.add(service); + + rec.setLayoutManager(new LinearLayoutManager(getActivity())); + ServiceAdapter serviceAdapter = new ServiceAdapter(); + rec.setAdapter(serviceAdapter); + return view; + } + + class ServiceAdapter extends RecyclerView.Adapter { + + @NonNull + @Override + public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { + View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.settings_item_layout, parent, false); + return new ViewHolder(view); + } + + @Override + public void onBindViewHolder(@NonNull ViewHolder holder, int position) { + final ServiceGetterSetter mItem = serviceList.get(position); + } + + @Override + public int getItemCount() { + return serviceList.size(); + } + + class ViewHolder extends RecyclerView.ViewHolder { + public ImageView btn_is_present; + + public ViewHolder(View itemView) { + super(itemView); + btn_is_present = (ImageView) itemView.findViewById(R.id.btn_is_present); + } + } + } + + class ServiceGetterSetter { + String name; + int icon; + Fragment fragment; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getIcon() { + return icon; + } + + public void setIcon(int icon) { + this.icon = icon; + } + + + public Fragment getFragment() { + return fragment; + } + + public void setFragment(Fragment fragment) { + this.fragment = fragment; + } + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // Handle action bar item clicks here. The action bar will + // automatically handle clicks on the Home/Up button, so long + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + if (id == android.R.id.home) { + requireActivity().finish(); + } + return super.onOptionsItemSelected(item); + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/geotag/GeoTaggingActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/geotag/GeoTaggingActivity.java new file mode 100644 index 0000000..aaeaf20 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/geotag/GeoTaggingActivity.java @@ -0,0 +1,502 @@ +package com.cpm.lorealbaautomation.geotag; + +import static com.cpm.lorealbaautomation.constant.CommonFunctions.checkNetIsAvailable; + +import android.Manifest; +import android.annotation.SuppressLint; +import android.app.Activity; +import android.app.Dialog; +import android.content.Context; +import android.content.Intent; +import android.content.IntentSender; +import android.content.SharedPreferences; +import android.content.pm.PackageManager; +import android.content.res.ColorStateList; +import android.graphics.Color; +import android.location.Address; +import android.location.Geocoder; +import android.location.Location; +import android.location.LocationManager; +import android.os.AsyncTask; +import android.os.Bundle; +import android.os.Looper; +import android.util.Log; +import android.view.View; +import android.widget.ProgressBar; +import android.widget.Toast; + +import androidx.annotation.NonNull; +import androidx.appcompat.app.AppCompatActivity; +import androidx.appcompat.widget.Toolbar; +import androidx.core.app.ActivityCompat; +import androidx.core.content.ContextCompat; + +import com.google.android.gms.common.api.ResolvableApiException; +import com.google.android.gms.location.FusedLocationProviderClient; +import com.google.android.gms.location.LocationCallback; +import com.google.android.gms.location.LocationRequest; +import com.google.android.gms.location.LocationResult; +import com.google.android.gms.location.LocationServices; +import com.google.android.gms.location.LocationSettingsRequest; +import com.google.android.gms.location.Priority; +import com.google.android.gms.location.SettingsClient; +import com.google.android.gms.maps.CameraUpdateFactory; +import com.google.android.gms.maps.GoogleMap; +import com.google.android.gms.maps.OnMapReadyCallback; +import com.google.android.gms.maps.SupportMapFragment; +import com.google.android.gms.maps.model.BitmapDescriptorFactory; +import com.google.android.gms.maps.model.LatLng; +import com.google.android.gms.maps.model.Marker; +import com.google.android.gms.maps.model.MarkerOptions; +import com.google.android.material.floatingactionbutton.FloatingActionButton; +import com.google.gson.JsonSyntaxException; +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.constant.AlertandMessages; +import com.cpm.lorealbaautomation.constant.CommonFunctions; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.gettersetter.GeotaggingBeans; +import com.cpm.lorealbaautomation.gsonGetterSetter.JourneyPlan; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.File; +import java.io.IOException; +import java.net.SocketTimeoutException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.List; + +public class GeoTaggingActivity extends AppCompatActivity implements OnMapReadyCallback { + double latitude = 0.0; + double longitude = 0.0; + FloatingActionButton fab, camera_fab; + SharedPreferences preferences; + private static final int REQUEST_LOCATION = 1; + String username, str, counter_id, userType, visit_date, _path, _pathforcheck, img_str = "", app_ver = "0"; + Lorealba_Database db; + ArrayList geotaglist = new ArrayList<>(); + Context context; + private GoogleMap mMap; + JourneyPlan jcpGetset; + private FusedLocationProviderClient fusedLocationClient; + private LocationCallback locationCallback; + private Marker currLocationMarker; + private Geocoder geocoder; + private double previousLatitude = 0.0, previousLongitude = 0.0; + private static final int LOCATION_PERMISSION_REQUEST_CODE = 1001; + private boolean cameraMovedOnce = false; + UploadImageWithRetrofit upload; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_geo_tagging); + Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + upload = new UploadImageWithRetrofit(this); + if (!CommonFunctions.isTablet(this)) { + toolbar.setTitleTextAppearance(this, R.style.changestext_sizefor_mobile); + } + setTitle("GeoTag"); + fusedLocationClient = LocationServices.getFusedLocationProviderClient(this); + geocoder = new Geocoder(this); + declaration(); + fab.setOnClickListener(view -> { + try { + startLocationUpdates(); + if (!img_str.isEmpty()) { + if (db.InsertSTOREgeotag(jcpGetset.getStoreId().toString(), counter_id, jcpGetset.getBID().toString(), username, latitude, longitude, img_str) > 0) { + img_str = ""; + db.updateStatus(jcpGetset.getStoreId().toString(), jcpGetset.getCounterId().toString(), + jcpGetset.getBID().toString(), CommonString.KEY_Y, latitude, longitude); + new GeoTagUpload().execute(); + } else { + AlertandMessages.showToastMsg(context, "Error in saving Geotag"); + } + } else { + AlertandMessages.showToastMsg(view.getContext(), getResources().getString(R.string.takeimage)); + } + } catch (Exception e) { + e.fillInStackTrace(); + } + }); + camera_fab.setOnClickListener(view -> { + try { + if (checkNetIsAvailable(view.getContext())) { + if (latitude != 0.0 && longitude != 0.0) { + _pathforcheck = jcpGetset.getStoreId().toString() + "-" + jcpGetset.getCounterId().toString() + + "-" + jcpGetset.getBID().toString() + "_GeoTag-" + jcpGetset.getVisitDate().replace("/", "") + + "_" + getCurrentTime().replace(":", "") + ".jpg"; + _path = CommonString.getImagesFolder(context) + _pathforcheck; + CommonFunctions.startAnncaCameraActivity(context, _path, null, false, CommonString.CAMERA_FACE_REAR); + } else { + AlertandMessages.showToastMsg(context, "Please wait for location"); + } + } else { + AlertandMessages.showToastMsg(context, getResources().getString(R.string.nonetwork)); + } + } catch (Exception e) { + e.fillInStackTrace(); + } + }); + + if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) + != PackageManager.PERMISSION_GRANTED) { + ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION); + } + locationCallback = new LocationCallback() { + @Override + public void onLocationResult(@NonNull LocationResult locationResult) { + for (Location location : locationResult.getLocations()) { + if (location != null) { + Log.e("jeevanp", location.toString()); + latitude = location.getLatitude(); + longitude = location.getLongitude(); + // Handle the location update (e.g., update map, store location, etc.) + // Avoid 0.0 updates + if (latitude != 0.0 && longitude != 0.0) { + float[] results = new float[1]; + Location.distanceBetween(previousLatitude, previousLongitude, latitude, longitude, results); + float distance = results[0]; + // Update only if moved more than 10 meters + if (distance > 10) { + previousLatitude = latitude; + previousLongitude = longitude; + + updateMapWithLocation(latitude, longitude); + } + } + } + } + } + }; + } + + private void startLocationUpdates() { + @SuppressLint("VisibleForTests") LocationRequest locationRequest = new LocationRequest.Builder(Priority.PRIORITY_HIGH_ACCURACY, 5000) + .setMinUpdateIntervalMillis(1000) + .build(); + if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { + fusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, Looper.getMainLooper()); + } else { + ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1001); + } + } + + private void updateMapWithLocation(double lat, double lon) { + if (geocoder != null && mMap != null) { + Log.e("jeevanp", "" + lat); + String address = ""; + try { + + List

addressList = geocoder.getFromLocation(lat, lon, 1); + if (addressList != null && !addressList.isEmpty()) { + address = addressList.get(0).getAddressLine(0); + } + } catch (IOException e) { + Log.e("MapError", "Geocoder error", e); + } + LatLng latLng = new LatLng(lat, lon); + // Remove old marker + if (currLocationMarker != null) { + currLocationMarker.remove(); + } + // Add new marker + MarkerOptions markerOptions = new MarkerOptions() + .position(latLng) + .title(address) + .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA)); + + currLocationMarker = mMap.addMarker(markerOptions); + + // Move camera only once + if (!cameraMovedOnce) { + mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15)); + cameraMovedOnce = true; + } else { + mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng)); + } + } + } + + @Override + protected void onStop() { + super.onStop(); + fusedLocationClient.removeLocationUpdates(locationCallback); + } + + @Override + public void onMapReady(@NonNull GoogleMap googleMap) { + mMap = googleMap; + mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL); + mMap.getUiSettings().setZoomControlsEnabled(true); + mMap.getUiSettings().setCompassEnabled(true); + mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(22.5726, 88.3639), 15)); + // Enable My Location layer + if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED || + ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) { + mMap.setMyLocationEnabled(true); // ✅ this shows blue dot + mMap.getUiSettings().setMyLocationButtonEnabled(true); // ✅ this shows the GPS icon + startLocationUpdates(); + } else { + // request permission + ActivityCompat.requestPermissions(this, + new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, + LOCATION_PERMISSION_REQUEST_CODE); + } + } + + @Override + public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { + super.onRequestPermissionsResult(requestCode, permissions, grantResults); + if (requestCode == LOCATION_PERMISSION_REQUEST_CODE) { + if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { + if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { + mMap.setMyLocationEnabled(true); + mMap.getUiSettings().setMyLocationButtonEnabled(true); + } + } + } + } + + @Override + protected void onResume() { + super.onResume(); + checkgpsEnableDevice(); + } + + @Override + protected void onStart() { + super.onStart(); + startLocationUpdates(); + + } + + public String getCurrentTime() { + Calendar m_cal = Calendar.getInstance(); + @SuppressLint("SimpleDateFormat") SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss"); + return formatter.format(m_cal.getTime()); + } + + + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + switch (resultCode) { + case 0: + Log.i("MakeMachine", "User cancelled"); + break; + case -1: + if (_pathforcheck != null && !_pathforcheck.isEmpty()) { + try { + if (new File(CommonString.getImagesFolder(this) + _pathforcheck).exists()) { + camera_fab.setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.mipmap.camera_tick)); + camera_fab.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#888888"))); + img_str = _pathforcheck; + _pathforcheck = ""; + } + } catch (Exception e) { + e.fillInStackTrace(); + } + } + + break; + } + + super.onActivityResult(requestCode, resultCode, data); + } + + @SuppressLint("CutPasteId") + void declaration() { + context = this; + preferences = PrefHelper.getPrefs(context); + counter_id = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + username = preferences.getString(CommonString.KEY_USERNAME, ""); + userType = preferences.getString(CommonString.KEY_USER_TYPE, ""); + camera_fab = (FloatingActionButton) findViewById(R.id.camrabtn); + fab = (FloatingActionButton) findViewById(R.id.fab); + db = new Lorealba_Database(context); + db.open(); + str = CommonString.getImagesFolder(this); + SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() + .findFragmentById(R.id.map); + if (mapFragment != null) { + mapFragment.getMapAsync(this); + } + if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { + return; + } + try { + app_ver = String.valueOf(getPackageManager().getPackageInfo(getPackageName(), 0).versionName); + } catch (PackageManager.NameNotFoundException ignored) { + } + db.open(); + if (!db.getStoreData(visit_date, username, counter_id).isEmpty()) { + jcpGetset = db.getStoreData(visit_date, username, counter_id).get(0); + fab.setVisibility(!jcpGetset.getGeoTag().equals("N") ? View.GONE : View.VISIBLE); + camera_fab.setVisibility(!jcpGetset.getGeoTag().equals("N") ? View.GONE : View.VISIBLE); + } + } + + @SuppressLint("StaticFieldLeak") + private class GeoTagUpload extends AsyncTask { + boolean uploadflag; + String errormsg = ""; + Dialog dialog; + ProgressBar pb; + + @Override + protected void onPreExecute() { + super.onPreExecute(); + dialog = new Dialog(context); + dialog.setContentView(R.layout.custom); + dialog.setTitle(getResources().getString(R.string.dialog_title)); + dialog.setCancelable(false); + dialog.show(); + pb = (ProgressBar) dialog.findViewById(R.id.progressBar1); + } + + @Override + protected String doInBackground(Void... params) { + try { + // uploading Geotag + uploadflag = false; + geotaglist = db.getinsertGeotaggingData(jcpGetset.getStoreId().toString(), counter_id, username, CommonString.KEY_N); + if (!geotaglist.isEmpty()) { + String jsonString2 = getString(); + Log.e("jsonString2", jsonString2); + String result = upload.downloadDataUniversal(jsonString2); + Log.e("jsonString2", result); + if (result.equalsIgnoreCase(CommonString.MESSAGE_NO_RESPONSE_SERVER)) { + uploadflag = false; + throw new SocketTimeoutException(); + } else if (result.equalsIgnoreCase(CommonString.MESSAGE_SOCKETEXCEPTION)) { + uploadflag = false; + throw new IOException(); + } else if (result.equalsIgnoreCase(CommonString.KEY_FAILURE)) { + uploadflag = false; + throw new Exception(); + } else { + uploadflag = true; + } + } + } catch (IOException ex) { + uploadflag = false; + ex.fillInStackTrace(); + errormsg = CommonString.MESSAGE_INTERNET_NOT_AVALABLE; + } catch (JsonSyntaxException ex) { + uploadflag = false; + ex.fillInStackTrace(); + errormsg = CommonString.MESSAGE_INVALID_JSON; + } catch (Exception ex) { + uploadflag = false; + errormsg = CommonString.MESSAGE_EXCEPTION; + } + + if (uploadflag) { + return CommonString.KEY_SUCCESS; + } else { + return errormsg; + } + + } + + private @NonNull String getString() throws JSONException { + JSONArray topUpArray = new JSONArray(); + for (int j = 0; j < geotaglist.size(); j++) { + JSONObject obj = getJsonObject(j); + topUpArray.put(obj); + } + + JSONObject jsonObject = new JSONObject(); + jsonObject.put("MID", jcpGetset.getMID() != null ? jcpGetset.getMID() : 0); + jsonObject.put("Keys", "GeoTag"); + jsonObject.put("JsonData", topUpArray.toString()); + jsonObject.put("UserId", username); + return jsonObject.toString(); + } + + @NonNull + private JSONObject getJsonObject(int j) throws JSONException { + JSONObject obj = new JSONObject(); + obj.put("UserId",username); + obj.put("StoreId", geotaglist.get(j).getStoreid()); + obj.put("CounterId", geotaglist.get(j).getCounterId()); + obj.put("bID", geotaglist.get(j).getBid()); + obj.put("VisitDate", jcpGetset.getVisitDate()); + obj.put("Latitude", geotaglist.get(j).getLatitude()); + obj.put("Longitude", geotaglist.get(j).getLongitude()); + obj.put("GeoImg", geotaglist.get(j).getImage()); + return obj; + } + + @Override + protected void onPostExecute(String result) { + super.onPostExecute(result); + dialog.dismiss(); + if (result != null && result.equalsIgnoreCase(CommonString.KEY_SUCCESS)) { + db.open(); + if (db.updateInsertedGeoTagStatus(jcpGetset.getStoreId().toString(), counter_id, username, CommonString.KEY_Y) > 0) { + img_str = ""; + AlertandMessages.showToastMsg(context, "Geotag Saved Successfully"); + finish(); + } else { + AlertandMessages.showAlert((Activity) context, "Error in updating Geotag status", true); + } + } else { + AlertandMessages.showToastMsg((Activity) context, getResources().getString(R.string.failure) + " : " + errormsg); + GeoTaggingActivity.this.finish(); + } + } + } + + private void checkgpsEnableDevice() { + if (!hasGPSDevice(this)) { + Toast.makeText(this, "Gps not Supported", Toast.LENGTH_SHORT).show(); + } + final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); + if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER) && hasGPSDevice(this)) { + enableLocationSettings(); + } else { + if (manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { + hasGPSDevice(this); + } + } + } + + private void enableLocationSettings() { + LocationRequest locationRequest = new LocationRequest.Builder(Priority.PRIORITY_HIGH_ACCURACY, // priority + 5000 // intervalMillis: 5 seconds + ).setMinUpdateIntervalMillis(3000) // fastest interval + .build(); + LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest).setAlwaysShow(true); // show dialog if GPS is off + + SettingsClient settingsClient = LocationServices.getSettingsClient(this); + settingsClient.checkLocationSettings(builder.build()).addOnSuccessListener(locationSettingsResponse -> { + // All location settings are satisfied. You can request location updates here. + }).addOnFailureListener(e -> { + if (e instanceof ResolvableApiException) { + try { + ResolvableApiException resolvable = (ResolvableApiException) e; + resolvable.startResolutionForResult((Activity) this, REQUEST_LOCATION); + } catch (IntentSender.SendIntentException sendEx) { + // Ignore the error. + sendEx.fillInStackTrace(); + } + } + }); + } + + private boolean hasGPSDevice(Context context) { + final LocationManager mgr = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); + if (mgr == null) return false; + final List providers = mgr.getAllProviders(); + if (providers == null) return false; + return providers.contains(LocationManager.GPS_PROVIDER); + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/geotag/UploadImageWithRetrofit.java b/app/src/main/java/com/cpm/lorealbaautomation/geotag/UploadImageWithRetrofit.java new file mode 100644 index 0000000..e384fb6 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/geotag/UploadImageWithRetrofit.java @@ -0,0 +1,132 @@ +package com.cpm.lorealbaautomation.geotag; +import android.app.ProgressDialog; +import android.content.Context; +import android.content.SharedPreferences; +import android.content.pm.PackageManager; +import androidx.annotation.NonNull; +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.gettersetter.ReferenceVariablesForDownloadActivity; +import com.cpm.lorealbaautomation.retrofit.PostApi; +import java.io.IOException; +import java.net.SocketTimeoutException; +import java.util.concurrent.TimeUnit; +import okhttp3.MediaType; +import okhttp3.OkHttpClient; +import okhttp3.RequestBody; +import okhttp3.ResponseBody; +import retrofit2.Call; +import retrofit2.Callback; +import retrofit2.Response; +import retrofit2.Retrofit; +import retrofit2.converter.gson.GsonConverterFactory; + +public class UploadImageWithRetrofit extends ReferenceVariablesForDownloadActivity { + boolean isvalid; + int status = 0; + Context context; + Lorealba_Database db; + ProgressDialog pd; + SharedPreferences preferences; + SharedPreferences.Editor editor; + String _UserId, date, app_ver; + + public UploadImageWithRetrofit(Context context) { + this.context = context; + } + public UploadImageWithRetrofit(Context context, Lorealba_Database db, ProgressDialog pd) { + this.context = context; + this.db = db; + this.pd = pd; + preferences = PrefHelper.getPrefs(context); + editor = preferences.edit(); + _UserId = preferences.getString(CommonString.KEY_USERNAME, ""); + date = preferences.getString(CommonString.KEY_DATE, null); + try { + app_ver = String.valueOf(context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName); + } catch (PackageManager.NameNotFoundException e) { + // TODO Auto-generated catch block + e.fillInStackTrace(); + } + db.open(); + } + public String downloadDataUniversal(final String jsonString) { + try { + status = 0; + isvalid = false; + final String[] data_global = {""}; + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsonString); + OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build(); + Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).addConverterFactory(GsonConverterFactory.create()).client(okHttpClient).build(); + PostApi api = adapter.create(PostApi.class); + Call call = api.getUploadJsonDetail(jsonData); + call.enqueue(new Callback() { + @Override + public void onResponse(@NonNull Call call, @NonNull Response response) { + ResponseBody responseBody = response.body(); + String data = null; + if (responseBody != null && response.isSuccessful()) { + try { + assert response.body() != null; + data = response.body().string(); + if (data.isEmpty()) { + data_global[0] = ""; + } else { + data = data.substring(1, data.length() - 1).replace("\\", ""); + data_global[0] = data; + } + isvalid = true; + status = 1; + } catch (Exception e) { + e.fillInStackTrace(); + isvalid = true; + status = -2; + } + } else { + isvalid = true; + status = -1; + } + } + + @Override + public void onFailure(@NonNull Call call, @NonNull Throwable t) { + isvalid = true; + if (t instanceof SocketTimeoutException) { + status = 3; + } else if (t instanceof IOException) { + status = 3; + } else { + status = 3; + } + } + }); + + while (!isvalid) { + synchronized (this) { + this.wait(25); + } + } + if (isvalid) { + synchronized (this) { + this.notify(); + } + } + if (status == 1) { + return data_global[0]; + } else if (status == 2) { + return CommonString.MESSAGE_NO_RESPONSE_SERVER; + } else if (status == 3) { + return CommonString.MESSAGE_SOCKETEXCEPTION; + } else if (status == -2) { + return CommonString.MESSAGE_INVALID_JSON; + } else { + return CommonString.KEY_FAILURE; + } + } catch (Exception e) { + e.fillInStackTrace(); + return CommonString.KEY_FAILURE; + } + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gettersetter/AttendanceStatus.java b/app/src/main/java/com/cpm/lorealbaautomation/gettersetter/AttendanceStatus.java new file mode 100644 index 0000000..eeb6989 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gettersetter/AttendanceStatus.java @@ -0,0 +1,19 @@ +package com.cpm.lorealbaautomation.gettersetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class AttendanceStatus { + @SerializedName("Status") + @Expose + private String status; + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gettersetter/AuditDataGetterSetter.java b/app/src/main/java/com/cpm/lorealbaautomation/gettersetter/AuditDataGetterSetter.java new file mode 100644 index 0000000..3c51fcb --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gettersetter/AuditDataGetterSetter.java @@ -0,0 +1,192 @@ +package com.cpm.lorealbaautomation.gettersetter; + +import com.androidbuts.multispinnerfilter.KeyPairBoolData; + +import java.io.Serializable; +import java.util.ArrayList; + +/** + * Created by yadavendras on 3/22/2018. + */ + +public class AuditDataGetterSetter implements Serializable { + + String QUESTION_ID; + String MENU_ID; + + public String getMENU_ID() { + return MENU_ID; + } + + public void setMENU_ID(String MENU_ID) { + this.MENU_ID = MENU_ID; + } + + String MERCHANDISER_ID; + + public String getMERCHANDISER_ID() { + return MERCHANDISER_ID; + } + + public void setMERCHANDISER_ID(String MERCHANDISER_ID) { + this.MERCHANDISER_ID = MERCHANDISER_ID; + } + + String CULTURE_ID; + String CATEGORY_ID; + String QUESTION; + String ANSWER_TYPE; + String ANSWER_ID="0"; + String ANSWER; + String CAM_IMAGE=""; + String CAMERA_ALLOW="0"; + String KEYACCOUNT_ID="0"; + String NO_OF_CAMERA ="1"; + String CAM_IMAGE2=""; + + public String getSpin_others_for_edt() { + return spin_others_for_edt; + } + + public void setSpin_others_for_edt(String spin_others_for_edt) { + this.spin_others_for_edt = spin_others_for_edt; + } + + String spin_others_for_edt=""; + + public String getQUESTION_CATEGORY_ID() { + return QUESTION_CATEGORY_ID; + } + + public void setQUESTION_CATEGORY_ID(String QUESTION_CATEGORY_ID) { + this.QUESTION_CATEGORY_ID = QUESTION_CATEGORY_ID; + } + + public String getQUESTION_CATEGORY() { + return QUESTION_CATEGORY; + } + + public void setQUESTION_CATEGORY(String QUESTION_CATEGORY) { + this.QUESTION_CATEGORY = QUESTION_CATEGORY; + } + + String QUESTION_CATEGORY_ID; + String QUESTION_CATEGORY; + + public String getRIGHT_ANSWER() { + return RIGHT_ANSWER; + } + + public void setRIGHT_ANSWER(String RIGHT_ANSWER) { + this.RIGHT_ANSWER = RIGHT_ANSWER; + } + + String RIGHT_ANSWER = ""; + + + public String getQUESTION_ID() { + return QUESTION_ID; + } + + public void setQUESTION_ID(String QUESTION_ID) { + this.QUESTION_ID = QUESTION_ID; + } + + public String getCULTURE_ID() { + return CULTURE_ID; + } + + public void setCULTURE_ID(String CULTURE_ID) { + this.CULTURE_ID = CULTURE_ID; + } + + public String getCATEGORY_ID() { + return CATEGORY_ID; + } + + public void setCATEGORY_ID(String CATEGORY_ID) { + this.CATEGORY_ID = CATEGORY_ID; + } + + public String getQUESTION() { + return QUESTION; + } + + public void setQUESTION(String QUESTION) { + this.QUESTION = QUESTION; + } + + public String getANSWER_TYPE() { + return ANSWER_TYPE; + } + + public void setANSWER_TYPE(String ANSWER_TYPE) { + this.ANSWER_TYPE = ANSWER_TYPE; + } + + public String getANSWER_ID() { + return ANSWER_ID; + } + + public void setANSWER_ID(String ANSWER_ID) { + this.ANSWER_ID = ANSWER_ID; + } + + public String getANSWER() { + return ANSWER; + } + + public void setANSWER(String ANSWER) { + this.ANSWER = ANSWER; + } + + public String getCAM_IMAGE() { + return CAM_IMAGE; + } + + public void setCAM_IMAGE(String CAM_IMAGE) { + this.CAM_IMAGE = CAM_IMAGE; + } + + public String getCAMERA_ALLOW() { + return CAMERA_ALLOW; + } + + public void setCAMERA_ALLOW(String CAMERA_ALLOW) { + this.CAMERA_ALLOW = CAMERA_ALLOW; + } + + public String getKEYACCOUNT_ID() { + return KEYACCOUNT_ID; + } + + public void setKEYACCOUNT_ID(String KEYACCOUNT_ID) { + this.KEYACCOUNT_ID = KEYACCOUNT_ID; + } + + public String getNO_OF_CAMERA() { + return NO_OF_CAMERA; + } + + public void setNO_OF_CAMERA(String NO_OF_CAMERA) { + this.NO_OF_CAMERA = NO_OF_CAMERA; + } + + public String getCAM_IMAGE2() { + return CAM_IMAGE2; + } + + public void setCAM_IMAGE2(String CAM_IMAGE2) { + this.CAM_IMAGE2 = CAM_IMAGE2; + } + + private ArrayList selectedSamplingData = new ArrayList<>(); + + public ArrayList getSelectedSamplingData() { + return selectedSamplingData; + } + + public void setSelectedSamplingData(ArrayList selectedSamplingData) { + this.selectedSamplingData = selectedSamplingData; + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gettersetter/BaProfileGetterSetter.java b/app/src/main/java/com/cpm/lorealbaautomation/gettersetter/BaProfileGetterSetter.java new file mode 100644 index 0000000..86a2e22 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gettersetter/BaProfileGetterSetter.java @@ -0,0 +1,139 @@ +package com.cpm.lorealbaautomation.gettersetter; + + +import java.io.Serializable; +import java.util.ArrayList; + +public class BaProfileGetterSetter implements Serializable { + + + String userId; + String profileImage=""; + String dob; + String visitDate; + String address; + String mobile; + String email_address; + String instagram_address; + String counterId; + String answer_type; + String answer; + String answer_id; + String question_id; + + public String getQuestion_id() { + return question_id; + } + + public void setQuestion_id(String question_id) { + this.question_id = question_id; + } + + public String getAnswer_id() { + return answer_id; + } + + public void setAnswer_id(String answer_id) { + this.answer_id = answer_id; + } + + public String getAnswer() { + return answer; + } + + public void setAnswer(String answer) { + this.answer = answer; + } + + public String getAnswer_type() { + return answer_type; + } + + public void setAnswer_type(String answer_type) { + this.answer_type = answer_type; + } + + public String getCounterId() { + return counterId; + } + + public void setCounterId(String counterId) { + this.counterId = counterId; + } + + public String getDob() { + return dob; + } + + public void setDob(String dob) { + this.dob = dob; + } + + + + public String getUserId() { + return userId; + } + + public void setUserId(String userId) { + this.userId = userId; + } + + public String getProfileImage() { + return profileImage; + } + + public void setProfileImage(String profileImage) { + this.profileImage = profileImage; + } + + public String getVisitDate() { + return visitDate; + } + + public void setVisitDate(String visitDate) { + this.visitDate = visitDate; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } + + public String getMobile() { + return mobile; + } + + public void setMobile(String mobile) { + this.mobile = mobile; + } + + public String getEmail_address() { + return email_address; + } + + public void setEmail_address(String email_address) { + this.email_address = email_address; + } + + public String getInstagram_address() { + return instagram_address; + } + + public void setInstagram_address(String instagram_address) { + this.instagram_address = instagram_address; + } + + ArrayList BaProfileList = new ArrayList<>(); + + public ArrayList getBaProfileList() { + return BaProfileList; + } + + public void setBaProfileList(ArrayList baProfileList) { + BaProfileList = baProfileList; + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gettersetter/BaTenureDetail.java b/app/src/main/java/com/cpm/lorealbaautomation/gettersetter/BaTenureDetail.java new file mode 100644 index 0000000..9bbd06e --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gettersetter/BaTenureDetail.java @@ -0,0 +1,53 @@ +package com.cpm.lorealbaautomation.gettersetter; + +import java.io.Serializable; + +public class BaTenureDetail implements Serializable { + String tenure; + String experience; + String ctc; + String regularIncentive; + String topUpIncentive; + + public String getTenure() { + return tenure; + } + + public void setTenure(String tenure) { + this.tenure = tenure; + } + + public String getExperience() { + return experience; + } + + public void setExperience(String experience) { + this.experience = experience; + } + + public String getCtc() { + return ctc; + } + + public void setCtc(String ctc) { + this.ctc = ctc; + } + + public String getRegularIncentive() { + return regularIncentive; + } + + public void setRegularIncentive(String regularIncentive) { + this.regularIncentive = regularIncentive; + } + + public String getTopUpIncentive() { + return topUpIncentive; + } + + public void setTopUpIncentive(String topUpIncentive) { + this.topUpIncentive = topUpIncentive; + } + + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gettersetter/CounterProfileGetterSetter.java b/app/src/main/java/com/cpm/lorealbaautomation/gettersetter/CounterProfileGetterSetter.java new file mode 100644 index 0000000..d7c14bc --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gettersetter/CounterProfileGetterSetter.java @@ -0,0 +1,83 @@ +package com.cpm.lorealbaautomation.gettersetter; + + + +public class CounterProfileGetterSetter { + + String userId; + String visitDate; + String img1=""; + String img2=""; + String counterDimensionsHight; + String counterDimensionsWidth; + String setupDate; + String counterAgeing; + + public String getCounterAgeing() { + return counterAgeing; + } + + public void setCounterAgeing(String counterAgeing) { + this.counterAgeing = counterAgeing; + } + + public String getSetupDate() { + return setupDate; + } + + public void setSetupDate(String setupDate) { + this.setupDate = setupDate; + } + + + public String getCounterDimensionsHight() { + return counterDimensionsHight; + } + + public void setCounterDimensionsHight(String counterDimensionsHight) { + this.counterDimensionsHight = counterDimensionsHight; + } + + public String getCounterDimensionsWidth() { + return counterDimensionsWidth; + } + + public void setCounterDimensionsWidth(String counterDimensionsWidth) { + this.counterDimensionsWidth = counterDimensionsWidth; + } + + public String getUserId() { + return userId; + } + + public void setUserId(String userId) { + this.userId = userId; + } + + + public String getVisitDate() { + return visitDate; + } + + public void setVisitDate(String visitDate) { + this.visitDate = visitDate; + } + + public String getImg1() { + return img1; + } + + public void setImg1(String img1) { + this.img1 = img1; + } + + public String getImg2() { + return img2; + } + + public void setImg2(String img2) { + this.img2 = img2; + } + + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gettersetter/FocusProductGetterSetter.java b/app/src/main/java/com/cpm/lorealbaautomation/gettersetter/FocusProductGetterSetter.java new file mode 100644 index 0000000..66b88f8 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gettersetter/FocusProductGetterSetter.java @@ -0,0 +1,139 @@ +package com.cpm.lorealbaautomation.gettersetter; + +public class FocusProductGetterSetter { + private String brand_id,brand,category_id,category,region_id,distributor_id,sku,sku_id,visit_date; + private String stock=""; + private String customer_id; + private String customer_name; + private String mobile_no; + private String card_no; + private String BrandName,BrandId; + + public String getBrandName() { + return BrandName; + } + + public void setBrandName(String brandName) { + BrandName = brandName; + } + + public String getBrandId() { + return BrandId; + } + + public void setBrandId(String brandId) { + BrandId = brandId; + } + + public String getCustomer_name() { + return customer_name; + } + + public void setCustomer_name(String customer_name) { + this.customer_name = customer_name; + } + + public String getMobile_no() { + return mobile_no; + } + + public void setMobile_no(String mobile_no) { + this.mobile_no = mobile_no; + } + + public String getCard_no() { + return card_no; + } + + public void setCard_no(String card_no) { + this.card_no = card_no; + } + + public String getCustomer_id() { + return customer_id; + } + + public void setCustomer_id(String customer_id) { + this.customer_id = customer_id; + } + + public String getBrand_id() { + return brand_id; + } + + public void setBrand_id(String brand_id) { + this.brand_id = brand_id; + } + + public String getBrand() { + return brand; + } + + public void setBrand(String brand) { + this.brand = brand; + } + + public String getCategory_id() { + return category_id; + } + + public void setCategory_id(String category_id) { + this.category_id = category_id; + } + + public String getCategory() { + return category; + } + + public void setCategory(String category) { + this.category = category; + } + + public String getRegion_id() { + return region_id; + } + + public void setRegion_id(String region_id) { + this.region_id = region_id; + } + + public String getDistributor_id() { + return distributor_id; + } + + public void setDistributor_id(String distributor_id) { + this.distributor_id = distributor_id; + } + + public String getSku() { + return sku; + } + + public void setSku(String sku) { + this.sku = sku; + } + + public String getSku_id() { + return sku_id; + } + + public void setSku_id(String sku_id) { + this.sku_id = sku_id; + } + + public String getVisit_date() { + return visit_date; + } + + public void setVisit_date(String visit_date) { + this.visit_date = visit_date; + } + + public String getStock() { + return stock; + } + + public void setStock(String stock) { + this.stock = stock; + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gettersetter/GeotaggingBeans.java b/app/src/main/java/com/cpm/lorealbaautomation/gettersetter/GeotaggingBeans.java new file mode 100644 index 0000000..49122ca --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gettersetter/GeotaggingBeans.java @@ -0,0 +1,61 @@ +package com.cpm.lorealbaautomation.gettersetter; + +public class GeotaggingBeans { + public String storeid; + public String status; + + public String getImage() { + return image; + } + public void setImage(String image) { + this.image = image; + } + public String image; + public String getStatus() { + return status; + } + public void setStatus(String status) { + this.status = status; + } + public double Latitude ; + public double Longitude; + + public String getStoreid() { + return storeid; + } + public void setStoreid(String storeid) { + this.storeid = storeid; + } + public double getLatitude() { + return Latitude; + } + public void setLatitude(double d) { + Latitude = d; + } + public double getLongitude() { + return Longitude; + } + public void setLongitude(double d) { + Longitude = d; + } + String counterId; + + public String getBid() { + return bid; + } + + public void setBid(String bid) { + this.bid = bid; + } + + public String getCounterId() { + return counterId; + } + + public void setCounterId(String counterId) { + this.counterId = counterId; + } + + String bid; + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gettersetter/GroomingGetterSetter.java b/app/src/main/java/com/cpm/lorealbaautomation/gettersetter/GroomingGetterSetter.java new file mode 100644 index 0000000..1156b91 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gettersetter/GroomingGetterSetter.java @@ -0,0 +1,79 @@ +package com.cpm.lorealbaautomation.gettersetter; + + + +public class GroomingGetterSetter { + + String StoreCd; + String image1=""; + String image2=""; + String image3=""; + String image4=""; + String visitDate; + String sigature_id; + String category_id; + + public String getSigature_id() { + return sigature_id; + } + + public void setSigature_id(String sigature_id) { + this.sigature_id = sigature_id; + } + + public String getCategory_id() { + return category_id; + } + + public void setCategory_id(String category_id) { + this.category_id = category_id; + } + + public String getVisitDate() { + return visitDate; + } + + public void setVisitDate(String visitDate) { + this.visitDate = visitDate; + } + + public String getStoreCd() { + return StoreCd; + } + + public void setStoreCd(String storeCd) { + StoreCd = storeCd; + } + + public String getImage1() { + return image1; + } + + public void setImage1(String image1) { + this.image1 = image1; + } + + public String getImage2() { + return image2; + } + + public void setImage2(String image2) { + this.image2 = image2; + } + + public String getImage3() { + return image3; + } + + public void setImage3(String image3) { + this.image3 = image3; + } + + public String getImage4() { + return image4; + } + + public void setImage4(String image4) { + this.image4 = image4; + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gettersetter/HeaderGetterSetter.java b/app/src/main/java/com/cpm/lorealbaautomation/gettersetter/HeaderGetterSetter.java new file mode 100644 index 0000000..75b62c3 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gettersetter/HeaderGetterSetter.java @@ -0,0 +1,15 @@ +package com.cpm.lorealbaautomation.gettersetter; + +public class HeaderGetterSetter { + + public String getKeyId() { + return keyId; + } + + public void setKeyId(String keyId) { + this.keyId = keyId; + } + + String keyId; + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gettersetter/LoginGetterSetter.java b/app/src/main/java/com/cpm/lorealbaautomation/gettersetter/LoginGetterSetter.java new file mode 100644 index 0000000..13b45a8 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gettersetter/LoginGetterSetter.java @@ -0,0 +1,102 @@ +package com.cpm.lorealbaautomation.gettersetter; + + + +public class LoginGetterSetter { + + String userId; + String password; + String mpin; + String visitDate; + String img=""; + + public String getUserLoginTym() { + return userLoginTym; + } + + public void setUserLoginTym(String userLoginTym) { + this.userLoginTym = userLoginTym; + } + + String userLoginTym=""; + + public String getImg() { + return img; + } + + public void setImg(String img) { + this.img = img; + } + + public String getUserId() { + return userId; + } + + public void setUserId(String userId) { + this.userId = userId; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public String getMpin() { + return mpin; + } + + public void setMpin(String mpin) { + this.mpin = mpin; + } + + public String getVisitDate() { + return visitDate; + } + + public void setVisitDate(String visitDate) { + this.visitDate = visitDate; + } + String userType=""; + + public String getUserType() { + return userType; + } + + public void setUserType(String userType) { + this.userType = userType; + } + + public String getUser_checkout() { + return user_checkout; + } + + public void setUser_checkout(String user_checkout) { + this.user_checkout = user_checkout; + } + + String user_checkout="0"; + String ProfilePath=""; + + public String getProfilePath() { + return ProfilePath; + } + + public void setProfilePath(String profilePath) { + ProfilePath = profilePath; + } + + public String getProfile_Pic() { + return Profile_Pic; + } + + public void setProfile_Pic(String profile_Pic) { + Profile_Pic = profile_Pic; + } + + String Profile_Pic=""; + + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gettersetter/LoginGsonGetterSetter.java b/app/src/main/java/com/cpm/lorealbaautomation/gettersetter/LoginGsonGetterSetter.java new file mode 100644 index 0000000..a7f4a45 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gettersetter/LoginGsonGetterSetter.java @@ -0,0 +1,47 @@ +package com.cpm.lorealbaautomation.gettersetter; + + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +import java.util.List; + +/** + * Created by jeevanp on 14-12-2017. + */ + +public class LoginGsonGetterSetter { + @SerializedName("Result") + @Expose + private List result = null; + + public List getResult() { + return result; + } + public void setResult(List result) { + this.result = result; + } + + //today question + @SerializedName("Today_Question") + @Expose + private List todayQuestion = null; + + public List getTodayQuestion() { + return todayQuestion; + } + + public void setTodayQuestion(List todayQuestion) { + this.todayQuestion = todayQuestion; + } + + @SerializedName("Attendance_Status") + @Expose + private List attendanceStatus = null; + + public List getAttendanceStatus() { + return attendanceStatus; + } + + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gettersetter/MasterCompetitionOffer.java b/app/src/main/java/com/cpm/lorealbaautomation/gettersetter/MasterCompetitionOffer.java new file mode 100644 index 0000000..4f2a25e --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gettersetter/MasterCompetitionOffer.java @@ -0,0 +1,98 @@ +package com.cpm.lorealbaautomation.gettersetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class MasterCompetitionOffer { + @SerializedName("CompOfferId") + @Expose + private Integer compOfferId; + @SerializedName("CompOffer") + @Expose + private String compOffer; + @SerializedName("CompBuyTypeId") + @Expose + private Integer compBuyTypeId; + @SerializedName("CompBuyType") + @Expose + private String compBuyType; + @SerializedName("CompSetId") + @Expose + private Integer compSetId; + @SerializedName("CompSetName") + @Expose + private String compSetName; + + @SerializedName("CompGetId") + @Expose + private Integer compGetId; + @SerializedName("CompGetName") + @Expose + private String compGetName; + + + public Integer getCompOfferId() { + return compOfferId; + } + + public void setCompOfferId(Integer compOfferId) { + this.compOfferId = compOfferId; + } + + public String getCompOffer() { + return compOffer; + } + + public void setCompOffer(String compOffer) { + this.compOffer = compOffer; + } + + public Integer getCompBuyTypeId() { + return compBuyTypeId; + } + + public void setCompBuyTypeId(Integer compBuyTypeId) { + this.compBuyTypeId = compBuyTypeId; + } + + public String getCompBuyType() { + return compBuyType; + } + + public void setCompBuyType(String compBuyType) { + this.compBuyType = compBuyType; + } + + public Integer getCompSetId() { + return compSetId; + } + + public void setCompSetId(Integer compSetId) { + this.compSetId = compSetId; + } + + public String getCompSetName() { + return compSetName; + } + + public void setCompSetName(String compSetName) { + this.compSetName = compSetName; + } + + public Integer getCompGetId() { + return compGetId; + } + + public void setCompGetId(Integer compGetId) { + this.compGetId = compGetId; + } + + public String getCompGetName() { + return compGetName; + } + + public void setCompGetName(String compGetName) { + this.compGetName = compGetName; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gettersetter/MasterCompetitionOfferSaleRange.java b/app/src/main/java/com/cpm/lorealbaautomation/gettersetter/MasterCompetitionOfferSaleRange.java new file mode 100644 index 0000000..add00fe --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gettersetter/MasterCompetitionOfferSaleRange.java @@ -0,0 +1,19 @@ +package com.cpm.lorealbaautomation.gettersetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class MasterCompetitionOfferSaleRange { + @SerializedName("SaleRange") + @Expose + private String saleRange; + + public String getSaleRange() { + return saleRange; + } + + public void setSaleRange(String saleRange) { + this.saleRange = saleRange; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gettersetter/ReferenceVariablesForDownloadActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/gettersetter/ReferenceVariablesForDownloadActivity.java new file mode 100644 index 0000000..1928dcd --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gettersetter/ReferenceVariablesForDownloadActivity.java @@ -0,0 +1,48 @@ +package com.cpm.lorealbaautomation.gettersetter; + + +import com.cpm.lorealbaautomation.gsonGetterSetter.JCPGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterBAProfileGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterInvoiceTypeGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterNonStockReasonGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterNonVisibilityGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterProfileGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterProfileQuestionGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.ResponseResult; +import com.cpm.lorealbaautomation.gsonGetterSetter.ServerTimeGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.TCounterInvoiceGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.TStockSummaryGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.TableStructureGetterSetter; + +/** + * Created by jeevanp on 15-12-2017. + */ + +public class ReferenceVariablesForDownloadActivity { + protected TableStructureGetterSetter tableStructureObj,product_masterObject,inwardSales_POObject, mapping_visibilityObject, + posmmasterObject,masterSkinTypeObject,masterAgeLimitObject,SkinGeniusUrlObject; + protected JCPGetterSetter jcpObject,baListObject,mappingCounterGroupBrandObject,d2DARSGetterSetter; + protected ServerTimeGetterSetter serverTimeObj,tStockSummaryCheckObj; + protected TCounterInvoiceGetterSetter tCounterInvoiceObj; + protected TStockSummaryGetterSetter tStockSummaryObj; + protected MasterNonStockReasonGetterSetter masterNonStockReasonObj; + protected MasterProfileGetterSetter masterProfileGetterSetter; + protected MasterInvoiceTypeGetterSetter masterInvoiceTypeObj; + protected MasterProfileQuestionGetterSetter masterProfileQuestionGetterSetter,return_ReasonObject,termConditionObject,LeaveRequestObject, + leaveStatusObject,masterBreakObject; + protected MasterProfileQuestionGetterSetter reportSaleValueObject,reportSaleDetailsObject,reportavGTransationValueObject,reportAvgUnitPerBillObject,reportAvgBillUnitObject + ,reportAvgLinPerBillObject,reportSalingPrizeObject,reportTop10VolumeObject,reportTop10ValueObject,reportMeSale; + protected MasterNonVisibilityGetterSetter masterNonVisibilityGetterSetter; + protected MasterBAProfileGetterSetter masterBAProfileGetterSetter,masterPromoOfferObject; + protected MasterBAProfileGetterSetter reportAttendenceDetailGetterSetter,reportAttendenceSummeryGetterSetter,reportInwordStockSummeryGetterSetter, + reportbaAvailabilityGetterSetter,masterLookObject,meAuditMasterObject,meAuditMasterUploadStatusObject; + protected ResponseResult responseResult, resultPromotionSetEntityItem, resultPromotionGetEntityItem, resultPromotionSetProductGroup, + resultPromotionGetProductGroup,masterSurvey,masterLeaveType,damagedReturnToDistributorObject,baorcounterUploadStatusObject,promosetproductCatologObject, + promogetproductCatologObject; + protected ResponseResult productGroupwiseSaleObject,reportsaleDatewiseObject,damagedpendingObject, + reportlastmonth,promogetexclusionlistob,promosetexclusionlistob,mastersourceofsales, + reportdamagehistory,masterCompetitionOfferSet,masterCompetitionOffer,masterCompetitionOfferSaleRange, + masterCompetitonBrandWiseNuance,masterCompetitionProductType,masterCompetitionPromoType, + masterCompetitionOfferGet,masterRetailExcellence; + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gettersetter/Result.java b/app/src/main/java/com/cpm/lorealbaautomation/gettersetter/Result.java new file mode 100644 index 0000000..860bf75 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gettersetter/Result.java @@ -0,0 +1,87 @@ + +package com.cpm.lorealbaautomation.gettersetter; +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class Result { + @SerializedName("Rightname") + @Expose + private String rightname; + @SerializedName("App_Version") + @Expose + private Integer appVersion; + @SerializedName("App_Path") + @Expose + private String appPath; + @SerializedName("Status") + @Expose + private String status; + @SerializedName("Currentdate") + @Expose + private String currentdate; + @SerializedName("Geo_Fencing") + @Expose + private Integer geoFencing; + + public String getNotice_board() { + return notice_board; + } + + public void setNotice_board(String notice_board) { + this.notice_board = notice_board; + } + + //for notice board url + @SerializedName("Notice_Url") + @Expose + private String notice_board; + + public String getRightname() { + return rightname; + } + + public void setRightname(String rightname) { + this.rightname = rightname; + } + + public Integer getAppVersion() { + return appVersion; + } + + public void setAppVersion(Integer appVersion) { + this.appVersion = appVersion; + } + + public String getAppPath() { + return appPath; + } + + public void setAppPath(String appPath) { + this.appPath = appPath; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getCurrentdate() { + return currentdate; + } + + public void setCurrentdate(String currentdate) { + this.currentdate = currentdate; + } + + public Integer getGeoFencing() { + return geoFencing; + } + + public void setGeoFencing(Integer geoFencing) { + this.geoFencing = geoFencing; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gettersetter/SaleableGetterSetter.java b/app/src/main/java/com/cpm/lorealbaautomation/gettersetter/SaleableGetterSetter.java new file mode 100644 index 0000000..14f876d --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gettersetter/SaleableGetterSetter.java @@ -0,0 +1,39 @@ +package com.cpm.lorealbaautomation.gettersetter; + +import com.cpm.lorealbaautomation.gsonGetterSetter.ProductMaster; + +import java.io.Serializable; +import java.util.ArrayList; + +public class SaleableGetterSetter implements Serializable { + + public ArrayList getProductList() { + return productList; + } + + public void setProductList(ArrayList productList) { + this.productList = productList; + } + + ArrayList productList = new ArrayList<>(); + + public String getTransactionId() { + return transactionId; + } + + public void setTransactionId(String transactionId) { + this.transactionId = transactionId; + } + + String transactionId = ""; + ArrayList BaProfileList = new ArrayList<>(); + + public ArrayList getBaProfileList() { + return BaProfileList; + } + + public void setBaProfileList(ArrayList baProfileList) { + BaProfileList = baProfileList; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gettersetter/TodayQuestion.java b/app/src/main/java/com/cpm/lorealbaautomation/gettersetter/TodayQuestion.java new file mode 100644 index 0000000..e58f737 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gettersetter/TodayQuestion.java @@ -0,0 +1,76 @@ + +package com.cpm.lorealbaautomation.gettersetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class TodayQuestion { + + @SerializedName("Question_Id") + @Expose + private Integer questionId; + @SerializedName("Question") + @Expose + private String question; + @SerializedName("Answer_Id") + @Expose + private Integer answerId; + @SerializedName("Answer") + @Expose + private String answer; + @SerializedName("Right_Answer") + @Expose + private Boolean rightAnswer; + @SerializedName("Status") + @Expose + private String status; + + public Integer getQuestionId() { + return questionId; + } + + public void setQuestionId(Integer questionId) { + this.questionId = questionId; + } + + public String getQuestion() { + return question; + } + + public void setQuestion(String question) { + this.question = question; + } + + public Integer getAnswerId() { + return answerId; + } + + public void setAnswerId(Integer answerId) { + this.answerId = answerId; + } + + public String getAnswer() { + return answer; + } + + public void setAnswer(String answer) { + this.answer = answer; + } + + public Boolean getRightAnswer() { + return rightAnswer; + } + + public void setRightAnswer(Boolean rightAnswer) { + this.rightAnswer = rightAnswer; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gettersetter/TrainingGetterSetter.java b/app/src/main/java/com/cpm/lorealbaautomation/gettersetter/TrainingGetterSetter.java new file mode 100644 index 0000000..e73aef8 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gettersetter/TrainingGetterSetter.java @@ -0,0 +1,128 @@ +package com.cpm.lorealbaautomation.gettersetter; + +import java.io.Serializable; + +/** + * Created by upendrak on 19-12-2017. + */ + +public class TrainingGetterSetter implements Serializable { + + private String rspname; + private String trainingtype; + private String topic; + String key_id; + private String photo; + private String topic_cd; + private String trainingtype_cd; + private String rspname_cd; + + public boolean isFilter() { + return filter; + } + + public void setFilter(boolean filter) { + this.filter = filter; + } + + boolean filter=true; + + public String getUnoque_RSPID() { + return unoque_RSPID; + } + + public void setUnoque_RSPID(String unoque_RSPID) { + this.unoque_RSPID = unoque_RSPID; + } + + private String unoque_RSPID; + + + public String getKey_id() { + return key_id; + } + + public void setKey_id(String key_id) { + this.key_id = key_id; + } + + public String getPhoto() { + return photo; + } + + public void setPhoto(String photo) { + this.photo = photo; + } + + + public String getTopic_cd() { + return topic_cd; + } + + public void setTopic_cd(String topic_cd) { + this.topic_cd = topic_cd; + } + + public String getTrainingtype_cd() { + return trainingtype_cd; + } + + public void setTrainingtype_cd(String trainingtype_cd) { + this.trainingtype_cd = trainingtype_cd; + } + + public String getRspname_cd() { + return rspname_cd; + } + + public void setRspname_cd(String rspname_cd) { + this.rspname_cd = rspname_cd; + } + + public String getRspname() { + return rspname; + } + + public void setRspname(String rspname) { + this.rspname = rspname; + } + + public String getTrainingtype() { + return trainingtype; + } + + public void setTrainingtype(String trainingtype) { + this.trainingtype = trainingtype; + } + + public String getTopic() { + return topic; + } + + public void setTopic(String topic) { + this.topic = topic; + } + @Override + public boolean equals(Object obj) { + if (obj == this) { + return true; + } + if (!(obj instanceof TrainingGetterSetter)) { + return false; + } + + TrainingGetterSetter other = (TrainingGetterSetter) obj; + return this.getTopic_cd().equals(other.getTopic_cd()); + } + @Override + public int hashCode() { + // return super.hashCode(); + return getTopic_cd().hashCode(); + } + + +} + + + + diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/AppDashboardTVA.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/AppDashboardTVA.java new file mode 100644 index 0000000..4ec5ce4 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/AppDashboardTVA.java @@ -0,0 +1,87 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.SerializedName; + +public class AppDashboardTVA { + @SerializedName("KPI") + private String kPI; + @SerializedName("Graph") + private String graph; + @SerializedName("CounterId") + private Integer counterId; + @SerializedName("Target") + private Double target; + @SerializedName("TotalSale") + private Integer totalSale; + @SerializedName("Per") + private Double per; + + public String getkPI() { + return kPI; + } + + public void setkPI(String kPI) { + this.kPI = kPI; + } + + public String getGraph() { + return graph; + } + + public void setGraph(String graph) { + this.graph = graph; + } + + public Integer getCounterId() { + return counterId; + } + + public void setCounterId(Integer counterId) { + this.counterId = counterId; + } + + public Double getTarget() { + return target; + } + + public void setTarget(Double target) { + this.target = target; + } + + public Integer getTotalSale() { + return totalSale; + } + + public void setTotalSale(Integer totalSale) { + this.totalSale = totalSale; + } + + public Double getPer() { + return per; + } + + public void setPer(Double per) { + this.per = per; + } + + public String getCounter_name() { + return counter_name; + } + + public void setCounter_name(String counter_name) { + this.counter_name = counter_name; + } + + String counter_name=""; + + public String getCounter_code() { + return counter_code; + } + + public void setCounter_code(String counter_code) { + this.counter_code = counter_code; + } + + String counter_code; + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/AppDashboardTVADrillDown.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/AppDashboardTVADrillDown.java new file mode 100644 index 0000000..3fe52ba --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/AppDashboardTVADrillDown.java @@ -0,0 +1,86 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.SerializedName; + +public class AppDashboardTVADrillDown { + @SerializedName("KPI") + private String kPI; + @SerializedName("Graph") + private String graph; + @SerializedName("CounterId") + private Integer counterId; + @SerializedName("ProductGroupId") + private Integer productGroupId; + @SerializedName("ProductGroupName") + private String productGroupName; + @SerializedName("Target") + private Double target; + @SerializedName("TotalSale") + private Double totalSale; + @SerializedName("Per") + private Double per; + + public String getGraph() { + return graph; + } + + public void setGraph(String graph) { + this.graph = graph; + } + + public Integer getCounterId() { + return counterId; + } + + public void setCounterId(Integer counterId) { + this.counterId = counterId; + } + + public Integer getProductGroupId() { + return productGroupId; + } + + public void setProductGroupId(Integer productGroupId) { + this.productGroupId = productGroupId; + } + + public String getProductGroupName() { + return productGroupName; + } + + public void setProductGroupName(String productGroupName) { + this.productGroupName = productGroupName; + } + + public Double getTarget() { + return target; + } + + public void setTarget(Double target) { + this.target = target; + } + + public Double getTotalSale() { + return totalSale; + } + + public void setTotalSale(Double totalSale) { + this.totalSale = totalSale; + } + + public Double getPer() { + return per; + } + + public void setPer(Double per) { + this.per = per; + } + public String getkPI() { + return kPI; + } + + public void setkPI(String kPI) { + this.kPI = kPI; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/AppDatabaseName.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/AppDatabaseName.java new file mode 100644 index 0000000..aa48283 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/AppDatabaseName.java @@ -0,0 +1,54 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; +public class AppDatabaseName { + @SerializedName("AppVersion") + @Expose + private Integer appVersion; + @SerializedName("DatabaseName") + @Expose + private String databaseName; + @SerializedName("DBUpdateStatus") + @Expose + private Boolean dBUpdateStatus; + + public Integer getAppVersion() { + return appVersion; + } + + public void setAppVersion(Integer appVersion) { + this.appVersion = appVersion; + } + + public AppDatabaseName withAppVersion(Integer appVersion) { + this.appVersion = appVersion; + return this; + } + + public String getDatabaseName() { + return databaseName; + } + + public void setDatabaseName(String databaseName) { + this.databaseName = databaseName; + } + + public AppDatabaseName withDatabaseName(String databaseName) { + this.databaseName = databaseName; + return this; + } + + public Boolean getDBUpdateStatus() { + return dBUpdateStatus; + } + + public void setDBUpdateStatus(Boolean dBUpdateStatus) { + this.dBUpdateStatus = dBUpdateStatus; + } + + public AppDatabaseName withDBUpdateStatus(Boolean dBUpdateStatus) { + this.dBUpdateStatus = dBUpdateStatus; + return this; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/AttendanceHistory.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/AttendanceHistory.java new file mode 100644 index 0000000..6d6ddc4 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/AttendanceHistory.java @@ -0,0 +1,56 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; + +public class AttendanceHistory { + @Expose + private Integer empId; + @Expose + private String reason; + @Expose + private String checkinTime; + @Expose + private String checkoutTime; + @Expose + private String date; + + public Integer getEmpId() { + return empId; + } + + public void setEmpId(Integer empId) { + this.empId = empId; + } + + public String getReason() { + return reason; + } + + public void setReason(String reason) { + this.reason = reason; + } + + public String getCheckinTime() { + return checkinTime; + } + + public void setCheckinTime(String checkinTime) { + this.checkinTime = checkinTime; + } + + public String getCheckoutTime() { + return checkoutTime; + } + + public void setCheckoutTime(String checkoutTime) { + this.checkoutTime = checkoutTime; + } + + public String getDate() { + return date; + } + + public void setDate(String date) { + this.date = date; + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/AuditQuestion.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/AuditQuestion.java new file mode 100644 index 0000000..8809dfc --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/AuditQuestion.java @@ -0,0 +1,135 @@ + +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class AuditQuestion { + + @Expose + private Integer questionId; + @SerializedName("Question") + @Expose + private String question; + @Expose + private Integer answerId; + @Expose + private String answer; + @Expose + private Integer questionCategoryId; + @Expose + private String questionCategory; + + public Integer getQuestionId() { + return questionId; + } + + public void setQuestionId(Integer questionId) { + this.questionId = questionId; + } + + public String getQuestion() { + return question; + } + + public void setQuestion(String question) { + this.question = question; + } + + public Integer getAnswerId() { + return answerId; + } + + public void setAnswerId(Integer answerId) { + this.answerId = answerId; + } + + public String getAnswer() { + return answer; + } + + public void setAnswer(String answer) { + this.answer = answer; + } + + public Integer getQuestionCategoryId() { + return questionCategoryId; + } + + public void setQuestionCategoryId(Integer questionCategoryId) { + this.questionCategoryId = questionCategoryId; + } + + public String getQuestionCategory() { + return questionCategory; + } + + public void setQuestionCategory(String questionCategory) { + this.questionCategory = questionCategory; + } + + + + public String getCurrectanswerCd() { + return currectanswerCd; + } + + public String getCameraFLAG() { + return cameraFLAG; + } + + public void setCameraFLAG(String cameraFLAG) { + this.cameraFLAG = cameraFLAG; + } + + public String cameraFLAG; + + public void setCurrectanswerCd(String currectanswerCd) { + this.currectanswerCd = currectanswerCd; + } + + + public String getCurrectanswer() { + return currectanswer; + } + + public void setCurrectanswer(String currectanswer) { + this.currectanswer = currectanswer; + } + public String currectanswerCd; + public String currectanswer; + + public String getAudit_cam() { + return audit_cam; + } + @SerializedName("Image_Allow") + @Expose + private String imageAllow; + + public String getImageAllowforanswer() { + return imageAllowforanswer; + } + + public void setImageAllowforanswer(String imageAllowforanswer) { + this.imageAllowforanswer = imageAllowforanswer; + } + + @Expose + private String imageAllowforanswer; + + + public void setAudit_cam(String audit_cam) { + this.audit_cam = audit_cam; + } + + public String audit_cam; + + public String getImageAllow() { + return imageAllow; + } + + public void setImageAllow(String imageAllow) { + this.imageAllow = imageAllow; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/AuditQuestionGetterSetter.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/AuditQuestionGetterSetter.java new file mode 100644 index 0000000..320517c --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/AuditQuestionGetterSetter.java @@ -0,0 +1,21 @@ + +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; + +import java.util.List; + +public class AuditQuestionGetterSetter { + + @Expose + private List auditQuestion = null; + + public List getAuditQuestion() { + return auditQuestion; + } + + public void setAuditQuestion(List auditQuestion) { + this.auditQuestion = auditQuestion; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/BADeviceLoginGetterSetter.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/BADeviceLoginGetterSetter.java new file mode 100644 index 0000000..fb9032b --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/BADeviceLoginGetterSetter.java @@ -0,0 +1,42 @@ + +package com.cpm.lorealbaautomation.gsonGetterSetter; +import com.google.gson.annotations.SerializedName; +import java.util.List; + +public class BADeviceLoginGetterSetter { + @SerializedName("APPLOGIN") + private List lOGIN = null; + public List getLOGIN() { + return lOGIN; + } + @SerializedName("LoginTime") + private List loginTime = null; + public List getLoginTime() { + return loginTime; + } + + @SerializedName("Report_SalesConsumerWise") + private List reportSalesConsumerWise = null; + public List getReportSalesConsumerWise() { + return reportSalesConsumerWise; + } + @SerializedName("Report_SalesConsumerWiseME") + private List reportSalesConsumerWiseMe = null; + public List getReportSalesConsumerWiseMe() { + return reportSalesConsumerWiseMe; + } + + @SerializedName("Report_SalesConsumerProductwise") + private List reportSalesConsumerProductwise = null; + public List getReportSalesConsumerProductwise() { + return reportSalesConsumerProductwise; + } + @SerializedName("Report_SalesConsumerProductwiseME") + private List reportSalesConsumerProductwiseMe = null; + + public List getReportSalesConsumerProductwiseMe() { + return reportSalesConsumerProductwiseMe; + } + + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/BASurveyGetterSetter.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/BASurveyGetterSetter.java new file mode 100644 index 0000000..36079e5 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/BASurveyGetterSetter.java @@ -0,0 +1,139 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import java.util.ArrayList; + +/** + * Created by yadavendras on 3/22/2018. + */ + +public class BASurveyGetterSetter { + + String SurveyId; + String SurveyName; + String SurveyType; + String SurveyQuestionId; + String SurveyQuestion; + String SurveyQuestionType; + String SurveyAnswerId; + String SurveyAnswer=""; + String ImageAllow="0"; + String visit_date=""; + String correct_answer_id = ""; + String cam_image=""; + String upload_status = ""; + + public String getUpload_status() { + return upload_status; + } + + public void setUpload_status(String upload_status) { + this.upload_status = upload_status; + } + + public String getCam_image() { + return cam_image; + } + + public void setCam_image(String cam_image) { + this.cam_image = cam_image; + } + + public String getSurveyId() { + return SurveyId; + } + + public void setSurveyId(String surveyId) { + SurveyId = surveyId; + } + + public String getSurveyName() { + return SurveyName; + } + + public void setSurveyName(String surveyName) { + SurveyName = surveyName; + } + + public String getSurveyType() { + return SurveyType; + } + + public void setSurveyType(String surveyType) { + SurveyType = surveyType; + } + + public String getSurveyQuestionId() { + return SurveyQuestionId; + } + + public void setSurveyQuestionId(String surveyQuestionId) { + SurveyQuestionId = surveyQuestionId; + } + + public String getSurveyQuestion() { + return SurveyQuestion; + } + + public void setSurveyQuestion(String surveyQuestion) { + SurveyQuestion = surveyQuestion; + } + + public String getSurveyQuestionType() { + return SurveyQuestionType; + } + + public void setSurveyQuestionType(String surveyQuestionType) { + SurveyQuestionType = surveyQuestionType; + } + + public String getSurveyAnswerId() { + return SurveyAnswerId; + } + + public void setSurveyAnswerId(String surveyAnswerId) { + SurveyAnswerId = surveyAnswerId; + } + + public String getSurveyAnswer() { + return SurveyAnswer; + } + + public void setSurveyAnswer(String surveyAnswer) { + SurveyAnswer = surveyAnswer; + } + + public String getImageAllow() { + return ImageAllow; + } + + public void setImageAllow(String imageAllow) { + ImageAllow = imageAllow; + } + + public String getVisit_date() { + return visit_date; + } + + public void setVisit_date(String visit_date) { + this.visit_date = visit_date; + } + + ArrayList answerList = new ArrayList<>(); + + public String getCorrect_answer_id() { + return correct_answer_id; + } + + public void setCorrect_answer_id(String correct_answer_id) { + this.correct_answer_id = correct_answer_id; + } + + public ArrayList getAnswerList() { + return answerList; + } + + public void setAnswerList(ArrayList answerList) { + this.answerList = answerList; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/BaListGetterSetter.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/BaListGetterSetter.java new file mode 100644 index 0000000..1857840 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/BaListGetterSetter.java @@ -0,0 +1,101 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +import java.io.Serializable; + +public class BaListGetterSetter implements Serializable { + @SerializedName("EmpId") + @Expose + private Integer empId; + @SerializedName("UserName") + @Expose + private String userName; + + @SerializedName("DesignationId") + @Expose + private Integer designationId; + + public Integer getCounterId() { + return CounterId; + } + + public void setCounterId(Integer counterId) { + CounterId = counterId; + } + + @SerializedName("CounterId") + @Expose + private Integer CounterId; + + @SerializedName("DesignationName") + @Expose + private String designationName; + @SerializedName("VisitDate") + @Expose + private String visitDate; + @SerializedName("ProfilePath") + @Expose + private String profilePath; + @SerializedName("Profile_Pic") + @Expose + private String profilePic; + + public Integer getEmpId() { + return empId; + } + + public void setEmpId(Integer empId) { + this.empId = empId; + } + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } + + public Integer getDesignationId() { + return designationId; + } + + public void setDesignationId(Integer designationId) { + this.designationId = designationId; + } + + public String getDesignationName() { + return designationName; + } + + public void setDesignationName(String designationName) { + this.designationName = designationName; + } + + public String getVisitDate() { + return visitDate; + } + + public void setVisitDate(String visitDate) { + this.visitDate = visitDate; + } + + public String getProfilePath() { + return profilePath; + } + + public void setProfilePath(String profilePath) { + this.profilePath = profilePath; + } + + public String getProfilePic() { + return profilePic; + } + + public void setProfilePic(String profilePic) { + this.profilePic = profilePic; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/ConsumerSalesHistory.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/ConsumerSalesHistory.java new file mode 100644 index 0000000..a4c95dd --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/ConsumerSalesHistory.java @@ -0,0 +1,170 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class ConsumerSalesHistory { + + @SerializedName("VisitDate") + @Expose + private String visitDate; + @SerializedName("ConsumerName") + @Expose + private String consumerName; + @SerializedName("ProductId") + @Expose + private Integer productId; + @SerializedName("ProductName") + @Expose + private String productName; + @SerializedName("Mrp") + @Expose + private Integer mrp; + @SerializedName("QtySold") + @Expose + private Integer qtySold; + @SerializedName("TotalAmount") + @Expose + private Double totalAmount; + + @SerializedName("AgeGroup") + @Expose + private String ageGroup; + @SerializedName("SkinType") + @Expose + private String skinType; + @SerializedName("Gender") + @Expose + private String gender; + @SerializedName("EanCode") + @Expose + private String eanCode; + + + public String getVisitDate() { + return visitDate; + } + + public void setVisitDate(String visitDate) { + this.visitDate = visitDate; + } + + public String getConsumerName() { + return consumerName; + } + + public void setConsumerName(String consumerName) { + this.consumerName = consumerName; + } + + public Integer getProductId() { + return productId; + } + + public void setProductId(Integer productId) { + this.productId = productId; + } + + public String getProductName() { + return productName; + } + + public void setProductName(String productName) { + this.productName = productName; + } + + public Integer getMrp() { + return mrp; + } + + public void setMrp(Integer mrp) { + this.mrp = mrp; + } + + public Integer getQtySold() { + return qtySold; + } + + public void setQtySold(Integer qtySold) { + this.qtySold = qtySold; + } + + public Double getTotalAmount() { + return totalAmount; + } + + public void setTotalAmount(Double totalAmount) { + this.totalAmount = totalAmount; + } + + public boolean isChecked_flag() { + return checked_flag; + } + + public void setChecked_flag(boolean checked_flag) { + this.checked_flag = checked_flag; + } + + boolean checked_flag=false; + + public String getSelected_reason_Id() { + return selected_reason_Id; + } + + public void setSelected_reason_Id(String selected_reason_Id) { + this.selected_reason_Id = selected_reason_Id; + } + + String selected_reason_Id="0"; + + public String getSelected_reason() { + return selected_reason; + } + + public void setSelected_reason(String selected_reason) { + this.selected_reason = selected_reason; + } + + String selected_reason=""; + public int getSelected_product_qty() { + return selected_product_qty; + } + + public void setSelected_product_qty(int selected_product_qty) { + this.selected_product_qty = selected_product_qty; + } + + int selected_product_qty=0; + public String getAgeGroup() { + return ageGroup; + } + + public void setAgeGroup(String ageGroup) { + this.ageGroup = ageGroup; + } + + public String getSkinType() { + return skinType; + } + + public void setSkinType(String skinType) { + this.skinType = skinType; + } + + public String getGender() { + return gender; + } + + public void setGender(String gender) { + this.gender = gender; + } + + public String getEanCode() { + return eanCode; + } + + public void setEanCode(String eanCode) { + this.eanCode = eanCode; + } +} + diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/ConsumerTermsConditionAccept.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/ConsumerTermsConditionAccept.java new file mode 100644 index 0000000..37bc8b9 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/ConsumerTermsConditionAccept.java @@ -0,0 +1,19 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class ConsumerTermsConditionAccept { + @SerializedName("TermsConditionAccept") + @Expose + private Boolean termsConditionAccept; + + public Boolean getTermsConditionAccept() { + return termsConditionAccept; + } + + public void setTermsConditionAccept(Boolean termsConditionAccept) { + this.termsConditionAccept = termsConditionAccept; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/CounterDeviceLogin.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/CounterDeviceLogin.java new file mode 100644 index 0000000..a8798b7 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/CounterDeviceLogin.java @@ -0,0 +1,78 @@ + +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class CounterDeviceLogin { + + @SerializedName("CounterId") + @Expose + private Integer counterId; + @SerializedName("VisitDate") + @Expose + private String visitDate; + @SerializedName("AppVersion") + @Expose + private Integer appVersion; + @SerializedName("AppPath") + @Expose + private String appPath; + + @SerializedName("CounterName") + @Expose + private String counterName; + + public String getCounterCode() { + return CounterCode; + } + + public void setCounterCode(String counterCode) { + CounterCode = counterCode; + } + + @SerializedName("CounterCode") + @Expose + private String CounterCode; + + public String getCounterName() { + return counterName; + } + + public void setCounterName(String counterName) { + this.counterName = counterName; + } + + public Integer getCounterId() { + return counterId; + } + + public void setCounterId(Integer counterId) { + this.counterId = counterId; + } + + public String getVisitDate() { + return visitDate; + } + + public void setVisitDate(String visitDate) { + this.visitDate = visitDate; + } + + public Integer getAppVersion() { + return appVersion; + } + + public void setAppVersion(Integer appVersion) { + this.appVersion = appVersion; + } + + public String getAppPath() { + return appPath; + } + + public void setAppPath(String appPath) { + this.appPath = appPath; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/CounterDeviceLoginGetterSetter.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/CounterDeviceLoginGetterSetter.java new file mode 100644 index 0000000..587e05a --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/CounterDeviceLoginGetterSetter.java @@ -0,0 +1,61 @@ + +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import java.util.List; +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class CounterDeviceLoginGetterSetter { + + public List getCounterInfo() { + return counterInfo; + } + + public void setCounterInfo(List counterInfo) { + this.counterInfo = counterInfo; + } + + @SerializedName("CounterInfo") + @Expose + private List counterInfo = null; + + public List getEmailOtpLogin() { + return emailOtpLogin; + } + + public void setEmailOtpLogin(List emailOtpLogin) { + this.emailOtpLogin = emailOtpLogin; + } + + @SerializedName("GenerateOTP") + @Expose + private List emailOtpLogin = null; + + public List getValidateOtp() { + return validateOtp; + } + + public void setValidateOtp(List validateOtp) { + this.validateOtp = validateOtp; + } + + @SerializedName("CounterAndBALoginWithIMEIset") + @Expose + private List validateOtp = null; + + @SerializedName("CounterDeviceLoginWithCodeApp") + @Expose + private List counterDeviceLogin = null; + + public List getCounterDeviceLogin() { + return counterDeviceLogin; + } + @SerializedName("AppDatabaseName") + @Expose + private List appDatabaseName = null; + + public List getAppDatabaseName() { + return appDatabaseName; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/CustomerVisited.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/CustomerVisited.java new file mode 100644 index 0000000..6351777 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/CustomerVisited.java @@ -0,0 +1,27 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; + +public class CustomerVisited { + + @Expose + private String label; + @Expose + private Integer count; + + public String getLabel() { + return label; + } + + public void setLabel(String label) { + this.label = label; + } + + public Integer getCount() { + return count; + } + + public void setCount(Integer count) { + this.count = count; + } +} \ No newline at end of file diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/CustomerVisitedCurMonth.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/CustomerVisitedCurMonth.java new file mode 100644 index 0000000..ce31ebf --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/CustomerVisitedCurMonth.java @@ -0,0 +1,27 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; +import com.google.gson.annotations.Expose; + +public class CustomerVisitedCurMonth { + + @Expose + private String date; + @Expose + private Integer count; + + public String getDate() { + return date; + } + + public void setDate(String date) { + this.date = date; + } + + public Integer getCount() { + return count; + } + + public void setCount(Integer count) { + this.count = count; + } + +} \ No newline at end of file diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/D2DArs.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/D2DArs.java new file mode 100644 index 0000000..76437b6 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/D2DArs.java @@ -0,0 +1,20 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +import java.io.Serializable; + +public class D2DArs implements Serializable { + @SerializedName("d2d_ars_url") + @Expose + private String d2d_ars_url; + + public String getD2d_ars_url() { + return d2d_ars_url; + } + + public void setD2d_ars_url(String d2d_ars_url) { + this.d2d_ars_url = d2d_ars_url; + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/DamagePreviousPending.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/DamagePreviousPending.java new file mode 100644 index 0000000..43c481a --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/DamagePreviousPending.java @@ -0,0 +1,52 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class DamagePreviousPending { + @SerializedName("CounterId") + @Expose + private Integer counterId; + @SerializedName("ProductId") + @Expose + private Integer productId; + @SerializedName("DamageQty") + @Expose + private Integer damageQty; + @SerializedName("Verify") + @Expose + private String verify; + + public Integer getCounterId() { + return counterId; + } + + public void setCounterId(Integer counterId) { + this.counterId = counterId; + } + + public Integer getProductId() { + return productId; + } + + public void setProductId(Integer productId) { + this.productId = productId; + } + + public Integer getDamageQty() { + return damageQty; + } + + public void setDamageQty(Integer damageQty) { + this.damageQty = damageQty; + } + + public String getVerify() { + return verify; + } + + public void setVerify(String verify) { + this.verify = verify; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/DamageReturnToDistributor.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/DamageReturnToDistributor.java new file mode 100644 index 0000000..12acfba --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/DamageReturnToDistributor.java @@ -0,0 +1,53 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class DamageReturnToDistributor { + + @SerializedName("CounterId") + @Expose + private Integer counterId; + @SerializedName("ProductId") + @Expose + private Integer productId; + @SerializedName("ReturnQty") + @Expose + private Integer returnQty; + @SerializedName("Verify") + @Expose + private String verify; + + public Integer getCounterId() { + return counterId; + } + + public void setCounterId(Integer counterId) { + this.counterId = counterId; + } + + public Integer getProductId() { + return productId; + } + + public void setProductId(Integer productId) { + this.productId = productId; + } + + public Integer getReturnQty() { + return returnQty; + } + + public void setReturnQty(Integer returnQty) { + this.returnQty = returnQty; + } + + public String getVerify() { + return verify; + } + + public void setVerify(String verify) { + this.verify = verify; + } + +} \ No newline at end of file diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/DashboardAchivementDetail.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/DashboardAchivementDetail.java new file mode 100644 index 0000000..6593cac --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/DashboardAchivementDetail.java @@ -0,0 +1,90 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class DashboardAchivementDetail { + + @Expose + private String visitDate; + @Expose + private Integer productId; + @Expose + private String productName; + @Expose + private Double mrp; + @Expose + private Integer qtySold; + @Expose + private Double discountPer; + @SerializedName("DiscountValue") + @Expose + private Double discountValue; + @Expose + private Double totalAmount; + + public String getVisitDate() { + return visitDate; + } + + public void setVisitDate(String visitDate) { + this.visitDate = visitDate; + } + + public Integer getProductId() { + return productId; + } + + public void setProductId(Integer productId) { + this.productId = productId; + } + + public String getProductName() { + return productName; + } + + public void setProductName(String productName) { + this.productName = productName; + } + + public Double getMrp() { + return mrp; + } + + public void setMrp(Double mrp) { + this.mrp = mrp; + } + + public Integer getQtySold() { + return qtySold; + } + + public void setQtySold(Integer qtySold) { + this.qtySold = qtySold; + } + + public Double getDiscountPer() { + return discountPer; + } + + public void setDiscountPer(Double discountPer) { + this.discountPer = discountPer; + } + + public Double getDiscountValue() { + return discountValue; + } + + public void setDiscountValue(Double discountValue) { + this.discountValue = discountValue; + } + + public Double getTotalAmount() { + return totalAmount; + } + + public void setTotalAmount(Double totalAmount) { + this.totalAmount = totalAmount; + } + +} \ No newline at end of file diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/DashboardDataGetter.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/DashboardDataGetter.java new file mode 100644 index 0000000..6129a64 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/DashboardDataGetter.java @@ -0,0 +1,77 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; + +public class DashboardDataGetter { + @Expose + private Integer id; + @Expose + private String label; + @Expose + private Double value; + @Expose + private Double percentage; + @Expose + private String url; + @Expose + private String imageName; + @Expose + private Integer detailShow; + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getLabel() { + return label; + } + + public void setLabel(String label) { + this.label = label; + } + + public Double getValue() { + return value; + } + + public void setValue(Double value) { + this.value = value; + } + + public Double getPercentage() { + return percentage; + } + + public void setPercentage(Double percentage) { + this.percentage = percentage; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getImageName() { + return imageName; + } + + public void setImageName(String imageName) { + this.imageName = imageName; + } + + public Integer getDetailShow() { + return detailShow; + } + + public void setDetailShow(Integer detailShow) { + this.detailShow = detailShow; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/DownloadStatus.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/DownloadStatus.java new file mode 100644 index 0000000..e3707ee --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/DownloadStatus.java @@ -0,0 +1,15 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class DownloadStatus { + + @SerializedName("DownloadStatus") + @Expose + private String downloadStatus; + + public String getDownloadStatus() { + return downloadStatus; + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/EmailOtpLoginGetterSetter.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/EmailOtpLoginGetterSetter.java new file mode 100644 index 0000000..4341abf --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/EmailOtpLoginGetterSetter.java @@ -0,0 +1,104 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class EmailOtpLoginGetterSetter { + @SerializedName("OTP") + @Expose + private String otp; + + @SerializedName("Email") + @Expose + private String email; + + @SerializedName("Status") + @Expose + private Integer status; + + @SerializedName("VisitDate") + @Expose + private String visitDate; + + @SerializedName("PasswordStatus") + @Expose + private String passwordStatus; + + @SerializedName("AppVersion") + @Expose + private String appversion; + + @SerializedName("AppPath") + @Expose + private String apppath; + + @SerializedName("Msg") + @Expose + private String message; + + public String getOtp() { + return otp; + } + + public void setOtp(String otp) { + this.otp = otp; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public Integer getStatus() { + return status; + } + + public void setStatus(Integer status) { + this.status = status; + } + + public String getVisitDate() { + return visitDate; + } + + public void setVisitDate(String visitDate) { + this.visitDate = visitDate; + } + + public String getPasswordStatus() { + return passwordStatus; + } + + public void setPasswordStatus(String passwordStatus) { + this.passwordStatus = passwordStatus; + } + + public String getAppversion() { + return appversion; + } + + public void setAppversion(String appversion) { + this.appversion = appversion; + } + + public String getApppath() { + return apppath; + } + + public void setApppath(String apppath) { + this.apppath = apppath; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/GroomingGetterSetter.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/GroomingGetterSetter.java new file mode 100644 index 0000000..7f1644b --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/GroomingGetterSetter.java @@ -0,0 +1,102 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.cpm.lorealbaautomation.constant.CommonString; + +import java.io.Serializable; + +public class GroomingGetterSetter implements Serializable { + String morning_groom_img_str=""; + String morning_groom_time_str=""; + String noon_groom_img_str=""; + String noon_groom_time_str=""; + + public String getVisit_date() { + return visit_date; + } + + public void setVisit_date(String visit_date) { + this.visit_date = visit_date; + } + + String visit_date=""; + + public String getMorning_groom_img_str() { + return morning_groom_img_str; + } + + public void setMorning_groom_img_str(String morning_groom_img_str) { + this.morning_groom_img_str = morning_groom_img_str; + } + + public String getMorning_groom_time_str() { + return morning_groom_time_str; + } + + public void setMorning_groom_time_str(String morning_groom_time_str) { + this.morning_groom_time_str = morning_groom_time_str; + } + + public String getNoon_groom_img_str() { + return noon_groom_img_str; + } + + public void setNoon_groom_img_str(String noon_groom_img_str) { + this.noon_groom_img_str = noon_groom_img_str; + } + + public String getNoon_groom_time_str() { + return noon_groom_time_str; + } + + public void setNoon_groom_time_str(String noon_groom_time_str) { + this.noon_groom_time_str = noon_groom_time_str; + } + + public String getEvenning_groom_img_str() { + return evenning_groom_img_str; + } + + public void setEvenning_groom_img_str(String evenning_groom_img_str) { + this.evenning_groom_img_str = evenning_groom_img_str; + } + + public String getEvenning_groom_time_str() { + return evenning_groom_time_str; + } + + public void setEvenning_groom_time_str(String evenning_groom_time_str) { + this.evenning_groom_time_str = evenning_groom_time_str; + } + + String evenning_groom_img_str=""; + String evenning_groom_time_str=""; + + public String getTransId() { + return TransId; + } + + public void setTransId(String transId) { + TransId = transId; + } + + String TransId=""; + + public String getUpload_status() { + return upload_status; + } + + public void setUpload_status(String upload_status) { + this.upload_status = upload_status; + } + + public String getUser_Id() { + return user_Id; + } + + public void setUser_Id(String user_Id) { + this.user_Id = user_Id; + } + + String upload_status= CommonString.KEY_N; + String user_Id=""; +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/ImageNMResponseGetterSetter.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/ImageNMResponseGetterSetter.java new file mode 100644 index 0000000..af15669 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/ImageNMResponseGetterSetter.java @@ -0,0 +1,27 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +/** + * Created by jeevanp on 5/30/2018. + */ + +public class ImageNMResponseGetterSetter { + String imgNAME; + + public String getImgNAME() { + return imgNAME; + } + + public void setImgNAME(String imgNAME) { + this.imgNAME = imgNAME; + } + + public String getIMGRESPONSE() { + return IMGRESPONSE; + } + + public void setIMGRESPONSE(String IMGRESPONSE) { + this.IMGRESPONSE = IMGRESPONSE; + } + + String IMGRESPONSE; +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/InvoiceGetterSetter.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/InvoiceGetterSetter.java new file mode 100644 index 0000000..da7f0fc --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/InvoiceGetterSetter.java @@ -0,0 +1,729 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.cpm.lorealbaautomation.constant.CommonString; + +import java.io.Serializable; +import java.util.ArrayList; + +public class InvoiceGetterSetter implements Serializable { + String product; + private String actualQty = ""; + private int reasonId = 0; + private String brandName=""; + private String subBrandName = ""; + private String referenceName = ""; + private String viewMode = "-1"; + boolean confirmChecked = false; + private String userName = ""; + + public String getUserType() { + return userType; + } + + public void setUserType(String userType) { + this.userType = userType; + } + + private String userType=""; + private String before_makeover_img=""; + + public String getDiscounted_value_productwise() { + return discounted_value_productwise; + } + + public void setDiscounted_value_productwise(String discounted_value_productwise) { + this.discounted_value_productwise = discounted_value_productwise; + } + + private String discounted_value_productwise =""; + int maybellineorskingenius_count=0; + + public int getMaybellineorskingenius_count() { + return maybellineorskingenius_count; + } + + public void setMaybellineorskingenius_count(int maybellineorskingenius_count) { + this.maybellineorskingenius_count = maybellineorskingenius_count; + } + + public String getBefore_makeover_img() { + return before_makeover_img; + } + + public void setBefore_makeover_img(String before_makeover_img) { + this.before_makeover_img = before_makeover_img; + } + + public String getAfter_makeover_img() { + return after_makeover_img; + } + + public void setAfter_makeover_img(String after_makeover_img) { + this.after_makeover_img = after_makeover_img; + } + + private String after_makeover_img=""; + + public String getStrUserId() { + return strUserId; + } + + public void setStrUserId(String strUserId) { + this.strUserId = strUserId; + } + + private String strUserId=""; + private String draft_status = "",invoice_status = "" ; + + public String getInvoice_status() { + return invoice_status; + } + + public void setInvoice_status(String invoice_status) { + this.invoice_status = invoice_status; + } + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } + + public boolean isConfirmChecked() { + return confirmChecked; + } + + public void setConfirmChecked(boolean confirmChecked) { + this.confirmChecked = confirmChecked; + } + + public String getViewMode() { + return viewMode; + } + + public void setViewMode(String viewMode) { + this.viewMode = viewMode; + } + + public String getBrandName() { + return brandName; + } + + public void setBrandName(String brandName) { + this.brandName = brandName; + } + + public String getSubBrandName() { + return subBrandName; + } + + public void setSubBrandName(String subBrandName) { + this.subBrandName = subBrandName; + } + + public String getReferenceName() { + return referenceName; + } + + public void setReferenceName(String referenceName) { + this.referenceName = referenceName; + } + + public String getActualQty() { + return actualQty; + } + + public void setActualQty(String actualQty) { + this.actualQty = actualQty; + } + + public int getReasonId() { + return reasonId; + } + + public void setReasonId(int reasonId) { + this.reasonId = reasonId; + } + + public boolean isPos_sale_flag() { + return pos_sale_flag; + } + + public void setPos_sale_flag(boolean pos_sale_flag) { + this.pos_sale_flag = pos_sale_flag; + } + + boolean pos_sale_flag = false; + + public String getScan_ean_code_or_enterd_ean_code() { + return scan_ean_code_or_enterd_ean_code; + } + + public void setScan_ean_code_or_enterd_ean_code(String scan_ean_code_or_enterd_ean_code) { + this.scan_ean_code_or_enterd_ean_code = scan_ean_code_or_enterd_ean_code; + } + + String scan_ean_code_or_enterd_ean_code; + + public String getStr_termcondition() { + return str_termcondition; + } + + public void setStr_termcondition(String str_termcondition) { + this.str_termcondition = str_termcondition; + } + + String str_termcondition=""; + + public String getProduct() { + return product; + } + + public void setProduct(String product) { + this.product = product; + } + + public String getProduct_Id() { + return product_Id; + } + + public void setProduct_Id(String product_Id) { + this.product_Id = product_Id; + } + + public String getQuantity() { + return quantity; + } + + public void setQuantity(String quantity) { + this.quantity = quantity; + } + + public String getProduct_rate() { + return product_rate; + } + + public void setProduct_rate(String product_rate) { + this.product_rate = product_rate; + } + + public String getTotal_amount() { + return total_amount; + } + + public void setTotal_amount(String total_amount) { + this.total_amount = total_amount; + } + + public String getCustomer_name() { + return customer_name; + } + + public void setCustomer_name(String customer_name) { + this.customer_name = customer_name; + } + + public String getMobile_no() { + return mobile_no; + } + + public void setMobile_no(String mobile_no) { + this.mobile_no = mobile_no; + } + + String product_Id; + String quantity=""; + String product_rate; + String total_amount; + String customer_name; + String mobile_no; + String store_name; + String percheasing_tym; + public String getConsumer_return_bill_no() { + return consumer_return_bill_no; + } + + public void setConsumer_return_bill_no(String consumer_return_bill_no) { + this.consumer_return_bill_no = consumer_return_bill_no; + } + + String consumer_return_bill_no=""; + + public String getConsumer_email_Id() { + return consumer_email_Id; + } + + public void setConsumer_email_Id(String consumer_email_Id) { + this.consumer_email_Id = consumer_email_Id; + } + + public String getConsumer_age() { + return consumer_age; + } + + public void setConsumer_age(String consumer_age) { + this.consumer_age = consumer_age; + } + + public String getConsumer_skinType() { + return consumer_skinType; + } + + public void setConsumer_skinType(String consumer_skinType) { + this.consumer_skinType = consumer_skinType; + } + String consumer_email_Id=""; + String consumer_age=""; + String consumer_skinType=""; + String demo_given_str=""; + + public String getLook_creater_str() { + return look_creater_str; + } + + public void setLook_creater_str(String look_creater_str) { + this.look_creater_str = look_creater_str; + } + + String look_creater_str=""; + + public String getDemo_given_str() { + return demo_given_str; + } + + public void setDemo_given_str(String demo_given_str) { + this.demo_given_str = demo_given_str; + } + + public String getProduct_sold_str() { + return product_sold_str; + } + + public void setProduct_sold_str(String product_sold_str) { + this.product_sold_str = product_sold_str; + } + + String product_sold_str=""; + + public String getSourceofSales() { + return sourceofSales; + } + + public void setSourceofSales(String sourceofSales) { + this.sourceofSales = sourceofSales; + } + + String sourceofSales=""; + + public String getSkin_genius_str() { + return skin_genius_str; + } + + public void setSkin_genius_str(String skin_genius_str) { + this.skin_genius_str = skin_genius_str; + } + + String skin_genius_str = ""; + + public String getMaybelline_vto_str() { + return maybelline_vto_str; + } + + public void setMaybelline_vto_str(String maybelline_vto_str) { + this.maybelline_vto_str = maybelline_vto_str; + } + + String maybelline_vto_str=""; + + public String getSkuType() { + return skuType; + } + + public void setSkuType(String skuType) { + this.skuType = skuType; + } + + String skuType=""; + + public String getPercheasing_tym() { + return percheasing_tym; + } + + public void setPercheasing_tym(String percheasing_tym) { + this.percheasing_tym = percheasing_tym; + } + + + public int getReccept_count() { + return reccept_count; + } + + public void setReccept_count(int reccept_count) { + this.reccept_count = reccept_count; + } + + int reccept_count=0; + + public String getCst_count() { + return cst_count; + } + + public void setCst_count(String cst_count) { + this.cst_count = cst_count; + } + + String cst_count = "0"; + + public String getStr_invoiceType() { + return str_invoiceType; + } + + public void setStr_invoiceType(String str_invoiceType) { + this.str_invoiceType = str_invoiceType; + } + + String str_invoiceType=""; + + public String getCustomer_gender() { + return customer_gender; + } + + public void setCustomer_gender(String customer_gender) { + this.customer_gender = customer_gender; + } + + String customer_gender; + + public String getStore_name() { + return store_name; + } + + public void setStore_name(String store_name) { + this.store_name = store_name; + } + + public String getStore_address() { + return store_address; + } + + public void setStore_address(String store_address) { + this.store_address = store_address; + } + + String store_address; + + public String getVisit_date() { + return visit_date; + } + + public void setVisit_date(String visit_date) { + this.visit_date = visit_date; + } + + String visit_date; + String cst_feed_back_value = ""; + + public String getCst_feed_back_value() { + return cst_feed_back_value; + } + + public void setCst_feed_back_value(String cst_feed_back_value) { + this.cst_feed_back_value = cst_feed_back_value; + } + + public String getFeed_back_type() { + return feed_back_type; + } + + public void setFeed_back_type(String feed_back_type) { + this.feed_back_type = feed_back_type; + } + + String feed_back_type = ""; + + private Integer mtdSales; + + private String counterName; + private Double target; + + public Double getDiscount() { + return discount; + } + + public void setDiscount(Double discount) { + this.discount = discount; + } + + private Double discount=0.0; + + public String getCounterName() { + return counterName; + } + + public void setCounterName(String counterName) { + this.counterName = counterName; + } + + public Double getTarget() { + return target; + } + + public void setTarget(Double target) { + this.target = target; + } + + public Integer getMtdSales() { + return mtdSales; + } + + public void setMtdSales(Integer mtdSales) { + this.mtdSales = mtdSales; + } + + public Double getActual_price_per_product() { + return actual_price_per_product; + } + + public void setActual_price_per_product(Double actual_price_per_product) { + this.actual_price_per_product = actual_price_per_product; + } + + Double actual_price_per_product=0.0; + String con_return_reason_Id="0"; + + public String getCon_return_reason_Id() { + return con_return_reason_Id; + } + + public void setCon_return_reason_Id(String con_return_reason_Id) { + this.con_return_reason_Id = con_return_reason_Id; + } + + public String getCon_return_reason() { + return con_return_reason; + } + + public void setCon_return_reason(String con_return_reason) { + this.con_return_reason = con_return_reason; + } + + String con_return_reason=""; + + public Double getDiscounted_value() { + return discounted_value; + } + + public void setDiscounted_value(Double discounted_value) { + this.discounted_value = discounted_value; + } + + Double discounted_value=0.0; + + public String getUnique_code() { + return unique_code; + } + + public void setUnique_code(String unique_code) { + this.unique_code = unique_code; + } + + String unique_code=""; + + public String getStr_upload_status() { + return str_upload_status; + } + + public void setStr_upload_status(String str_upload_status) { + this.str_upload_status = str_upload_status; + } + + String str_upload_status= CommonString.KEY_N; + private Double mrp; + public Double getMrp() { + return mrp; + } + + public void setMrp(Double mrp) { + this.mrp = mrp; + } + + public Double getDiscountValue() { + return discountValue; + } + + public void setDiscountValue(Double discountValue) { + this.discountValue = discountValue; + } + + public Double getTotalAmount() { + return totalAmount; + } + + public void setTotalAmount(Double totalAmount) { + this.totalAmount = totalAmount; + } + + private Double discountValue; + + private Double totalAmount; + + + public String getDraft_status() { + return draft_status; + } + + public void setDraft_status(String draft_status) { + this.draft_status = draft_status; + } + + public String getKeyId() { + return keyId; + } + + public void setKeyId(String keyId) { + this.keyId = keyId; + } + + String keyId; + + public String getConsumer_no_saleImg() { + return consumer_no_saleImg; + } + + public void setConsumer_no_saleImg(String consumer_no_saleImg) { + this.consumer_no_saleImg = consumer_no_saleImg; + } + + public String getInvoice_img() { + return invoice_img; + } + + public void setInvoice_img(String invoice_img) { + this.invoice_img = invoice_img; + } + + private String invoice_img=""; + + String consumer_no_saleImg=""; + ////for promo + public boolean isPromotionactive() { + return promotionactive; + } + + public void setPromotionactive(boolean promotionactive) { + this.promotionactive = promotionactive; + } + + public boolean promotionactive=false; + + public String getSelected_promo_productId() { + return selected_promo_productId; + } + + public void setSelected_promo_productId(String selected_promo_productId) { + this.selected_promo_productId = selected_promo_productId; + } + + String selected_promo_productId ="0"; + + public String getSelected_promoproduct() { + return selected_promoproduct; + } + + public void setSelected_promoproduct(String selected_promoproduct) { + this.selected_promoproduct = selected_promoproduct; + } + + String selected_promoproduct=""; + + String promotion_name=""; + + public String getPromotion_name() { + return promotion_name; + } + + public void setPromotion_name(String promotion_name) { + this.promotion_name = promotion_name; + } + + public String getPromotion_Id() { + return promotion_Id; + } + + public void setPromotion_Id(String promotion_Id) { + this.promotion_Id = promotion_Id; + } + + String promotion_Id="0"; + + public boolean isPromo_flag() { + return promo_flag; + } + + public void setPromo_flag(boolean promo_flag) { + this.promo_flag = promo_flag; + } + + boolean promo_flag=false; + + public String getPromo_type() { + return promo_type; + } + + public void setPromo_type(String promo_type) { + this.promo_type = promo_type; + } + + String promo_type=""; + + public String getReturn_bill_img() { + return return_bill_img; + } + + public void setReturn_bill_img(String return_bill_img) { + this.return_bill_img = return_bill_img; + } + + String return_bill_img=""; + int aplyieddiscountedprice=0; + + public int getAplyieddiscountedprice() { + return aplyieddiscountedprice; + } + + public void setAplyieddiscountedprice(int aplyieddiscountedprice) { + this.aplyieddiscountedprice = aplyieddiscountedprice; + } + + int total_replace_product_value=0; + + public int getTotal_replace_product_value() { + return total_replace_product_value; + } + + public void setTotal_replace_product_value(int total_replace_product_value) { + this.total_replace_product_value = total_replace_product_value; + } + + public int getTotal_replace_product_qty() { + return total_replace_product_qty; + } + + public void setTotal_replace_product_qty(int total_replace_product_qty) { + this.total_replace_product_qty = total_replace_product_qty; + } + + int total_replace_product_qty=0; + + public ArrayList getApplyiedproductList() { + return applyiedproductList; + } + + public void setApplyiedproductList(ArrayList applyiedproductList) { + this.applyiedproductList = applyiedproductList; + } + + ArrayListapplyiedproductList=new ArrayList<>(); +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/InwardSalesPO.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/InwardSalesPO.java new file mode 100644 index 0000000..8e41cd7 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/InwardSalesPO.java @@ -0,0 +1,195 @@ + +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; + +public class InwardSalesPO { + + @Expose + private Integer storeId; + @Expose + private String storeCode; + @Expose + private Integer counterId; + @Expose + private String counterCode; + @Expose + private Integer productId; + @Expose + private String productCode; + @Expose + private String grnRefNo; + @Expose + private Integer qTY; + @Expose + private Integer mRP; + @Expose + private String uOM; + @Expose + private String grnDate; + @Expose + private String grnType; + @Expose + private String productName; + + public String getProductName() { + return productName; + } + + private int stock=0; + private int reasonId=0; + private String Reason=""; + + public String getReason() { + return Reason; + } + + public void setReason(String reason) { + Reason = reason; + } + + public int getReasonId() { + return reasonId; + } + + public void setReasonId(int reasonId) { + this.reasonId = reasonId; + } + + public int getStock() { + return stock; + } + + public void setStock(int stock) { + this.stock = stock; + } + + public void setProductName(String productName) { + this.productName = productName; + } + + public Integer getStoreId() { + return storeId; + } + + public void setStoreId(Integer storeId) { + this.storeId = storeId; + } + + public String getStoreCode() { + return storeCode; + } + + public void setStoreCode(String storeCode) { + this.storeCode = storeCode; + } + + public Integer getCounterId() { + return counterId; + } + + public void setCounterId(Integer counterId) { + this.counterId = counterId; + } + + public String getCounterCode() { + return counterCode; + } + + public void setCounterCode(String counterCode) { + this.counterCode = counterCode; + } + + public Integer getProductId() { + return productId; + } + + public void setProductId(Integer productId) { + this.productId = productId; + } + + public String getProductCode() { + return productCode; + } + + public void setProductCode(String productCode) { + this.productCode = productCode; + } + + public String getGrnRefNo() { + return grnRefNo; + } + + public void setGrnRefNo(String grnRefNo) { + this.grnRefNo = grnRefNo; + } + + public Integer getQTY() { + return qTY; + } + + public void setQTY(Integer qTY) { + this.qTY = qTY; + } + + public Integer getMRP() { + return mRP; + } + + public void setMRP(Integer mRP) { + this.mRP = mRP; + } + + public String getUOM() { + return uOM; + } + + public void setUOM(String uOM) { + this.uOM = uOM; + } + + public String getGrnDate() { + return grnDate; + } + + public void setGrnDate(String grnDate) { + this.grnDate = grnDate; + } + + public String getGrnType() { + return grnType; + } + + public void setGrnType(String grnType) { + this.grnType = grnType; + } + String accept_flag=""; + + public String getAccept_flag() { + return accept_flag; + } + + public void setAccept_flag(String accept_flag) { + this.accept_flag = accept_flag; + } + + private int resion_id=0; + private String resion=""; + + + public int getResion_id() { + return resion_id; + } + + public void setResion_id(int resion_id) { + this.resion_id = resion_id; + } + + public String getResion() { + return resion; + } + + public void setResion(String resion) { + this.resion = resion; + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/JCPGetterSetter.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/JCPGetterSetter.java new file mode 100644 index 0000000..dcc310e --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/JCPGetterSetter.java @@ -0,0 +1,57 @@ + +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +import java.util.List; + +public class JCPGetterSetter { + @SerializedName("Mapping_JourneyPlan") + @Expose + private List journeyPlan = null; + + + public List getD2DArsList() { + return d2DArsList; + } + + public void setD2DArsList(List d2DArsList) { + this.d2DArsList = d2DArsList; + } + + @SerializedName("SkinGeniusUrl") + @Expose + private List d2DArsList = null; + + + public List getJourneyPlan() { + return journeyPlan; + } + + + @SerializedName("BA_List") + @Expose + private List bAList = null; + + public List getBAList() { + return bAList; + } + + @SerializedName("Mapping_CounterGroup_Brand") + @Expose + private List mappingCounterGroupBrand = null; + + public List getMappingCounterGroupBrand() { + return mappingCounterGroupBrand; + } + + @SerializedName("Download_Status") + @Expose + private List downloadStatus = null; + + public List getDownloadStatus() { + return downloadStatus; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/JourneyPlan.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/JourneyPlan.java new file mode 100644 index 0000000..00439b2 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/JourneyPlan.java @@ -0,0 +1,537 @@ + +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +import java.io.Serializable; + +public class JourneyPlan implements Serializable { + @SerializedName("StoreId") + @Expose + private Integer storeId; + @SerializedName("CounterId") + @Expose + private Integer counterId; + @SerializedName("EmpId") + @Expose + private Integer empId; + @SerializedName("ChainId") + @Expose + private Integer chainId; + @SerializedName("ChainName") + @Expose + private String chainName; + @SerializedName("StoreName") + @Expose + private String storeName; + @SerializedName("Address") + @Expose + private String address; + @SerializedName("Location") + @Expose + private String location; + @SerializedName("Landmark") + @Expose + private String landmark; + @SerializedName("CityId") + @Expose + private Integer cityId; + @SerializedName("CityName") + @Expose + private String cityName; + @SerializedName("CounterName") + @Expose + private String counterName; + @SerializedName("IMEI") + @Expose + private String iMEI; + @SerializedName("ChannelId") + @Expose + private Integer channelId; + @SerializedName("ChannelName") + @Expose + private String channelName; + @SerializedName("StoreTypeId") + @Expose + private Integer storeTypeId; + @SerializedName("StoreTypeName") + @Expose + private String storeTypeName; + @SerializedName("ClassId") + @Expose + private Integer classId; + @SerializedName("ClassName") + @Expose + private String className; + @SerializedName("CounterGroupId") + @Expose + private Integer counterGroupId; + @SerializedName("CounterUploadStatus") + @Expose + private String counterUploadStatus; + @SerializedName("BAUploadStatus") + @Expose + private String bAUploadStatus; + @SerializedName("MID") + @Expose + private Integer mID; + @SerializedName("BID") + @Expose + private Integer bID; + + @SerializedName("RefImage") + @Expose + private String refImage; + + @SerializedName("ProfileImage1") + @Expose + private String profileImage1; + + @SerializedName("ProfileImage2") + @Expose + private String profileImage2; + + @SerializedName("CounterLength") + @Expose + private double counterlength; + + @SerializedName("CounterWidth") + @Expose + private double counterwidth; + + @SerializedName("SetUpDate") + @Expose + private String setupDate; + + @SerializedName("VisitDate") + @Expose + private String visitDate; + + @SerializedName("UserId") + @Expose + private String userId; + @SerializedName("Latitude") + @Expose + private Double latitude; + @SerializedName("Longitude") + @Expose + private Double longitude; + @SerializedName("GeoTag") + @Expose + private String geoTag; + @SerializedName("GeoFencingRadius") + @Expose + private Integer geoFencingRadius; + @SerializedName("GeoFencingAllow") + @Expose + private Integer geoFencingAllow; + + public String getVisitDate() { + return visitDate; + } + + public void setVisitDate(String visitDate) { + this.visitDate = visitDate; + } + + public String getRefImage() { + return refImage; + } + + public void setRefImage(String refImage) { + this.refImage = refImage; + } + + public String getProfileImage1() { + return profileImage1; + } + + public void setProfileImage1(String profileImage1) { + this.profileImage1 = profileImage1; + } + + public String getProfileImage2() { + return profileImage2; + } + + public void setProfileImage2(String profileImage2) { + this.profileImage2 = profileImage2; + } + + public double getCounterlength() { + return counterlength; + } + + public void setCounterlength(double counterlength) { + this.counterlength = counterlength; + } + + public double getCounterwidth() { + return counterwidth; + } + + public void setCounterwidth(double counterwidth) { + this.counterwidth = counterwidth; + } + + public String getSetupDate() { + return setupDate; + } + + public void setSetupDate(String setupDate) { + this.setupDate = setupDate; + } + + public Integer getStoreId() { + return storeId; + } + + public void setStoreId(Integer storeId) { + this.storeId = storeId; + } + + public Integer getCounterId() { + return counterId; + } + + public void setCounterId(Integer counterId) { + this.counterId = counterId; + } + + public Integer getEmpId() { + return empId; + } + + public void setEmpId(Integer empId) { + this.empId = empId; + } + + public Integer getChainId() { + return chainId; + } + + public void setChainId(Integer chainId) { + this.chainId = chainId; + } + + public String getChainName() { + return chainName; + } + + public void setChainName(String chainName) { + this.chainName = chainName; + } + + public String getStoreName() { + return storeName; + } + + public void setStoreName(String storeName) { + this.storeName = storeName; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } + + public String getLocation() { + return location; + } + + public void setLocation(String location) { + this.location = location; + } + + public String getLandmark() { + return landmark; + } + + public void setLandmark(String landmark) { + this.landmark = landmark; + } + + public Integer getCityId() { + return cityId; + } + + public void setCityId(Integer cityId) { + this.cityId = cityId; + } + + public String getCityName() { + return cityName; + } + + public void setCityName(String cityName) { + this.cityName = cityName; + } + + public String getCounterName() { + return counterName; + } + + public void setCounterName(String counterName) { + this.counterName = counterName; + } + + public String getIMEI() { + return iMEI; + } + + public void setIMEI(String iMEI) { + this.iMEI = iMEI; + } + + public Integer getChannelId() { + return channelId; + } + + public void setChannelId(Integer channelId) { + this.channelId = channelId; + } + + public String getChannelName() { + return channelName; + } + + public void setChannelName(String channelName) { + this.channelName = channelName; + } + + public Integer getStoreTypeId() { + return storeTypeId; + } + + public void setStoreTypeId(Integer storeTypeId) { + this.storeTypeId = storeTypeId; + } + + public String getStoreTypeName() { + return storeTypeName; + } + + public void setStoreTypeName(String storeTypeName) { + this.storeTypeName = storeTypeName; + } + + public Integer getClassId() { + return classId; + } + + public void setClassId(Integer classId) { + this.classId = classId; + } + + public String getClassName() { + return className; + } + + public void setClassName(String className) { + this.className = className; + } + + public Integer getCounterGroupId() { + return counterGroupId; + } + + public void setCounterGroupId(Integer counterGroupId) { + this.counterGroupId = counterGroupId; + } + + public String getCounterUploadStatus() { + return counterUploadStatus; + } + + public void setCounterUploadStatus(String counterUploadStatus) { + this.counterUploadStatus = counterUploadStatus; + } + + public String getBAUploadStatus() { + return bAUploadStatus; + } + + public void setBAUploadStatus(String bAUploadStatus) { + this.bAUploadStatus = bAUploadStatus; + } + + public Integer getMID() { + return mID; + } + + public void setMID(Integer mID) { + this.mID = mID; + } + + public Integer getBID() { + return bID; + } + + public void setBID(Integer bID) { + this.bID = bID; + } + public Double getLatitude() { + return latitude; + } + + public void setLatitude(Double latitude) { + this.latitude = latitude; + } + + public Double getLongitude() { + return longitude; + } + + public void setLongitude(Double longitude) { + this.longitude = longitude; + } + + public String getGeoTag() { + return geoTag; + } + + public void setGeoTag(String geoTag) { + this.geoTag = geoTag; + } + + public Integer getGeoFencingRadius() { + return geoFencingRadius; + } + + public void setGeoFencingRadius(Integer geoFencingRadius) { + this.geoFencingRadius = geoFencingRadius; + } + + public Integer getGeoFencingAllow() { + return geoFencingAllow; + } + + public void setGeoFencingAllow(Integer geoFencingAllow) { + this.geoFencingAllow = geoFencingAllow; + } + + + public String getPresetup_img_one_str() { + return presetup_img_one_str; + } + + public void setPresetup_img_one_str(String presetup_img_one_str) { + this.presetup_img_one_str = presetup_img_one_str; + } + + public String getPresetup_img_two_str() { + return presetup_img_two_str; + } + + public void setPresetup_img_two_str(String presetup_img_two_str) { + this.presetup_img_two_str = presetup_img_two_str; + } + + public String getPostsetup_img_one_str() { + return postsetup_img_one_str; + } + + public void setPostsetup_img_one_str(String postsetup_img_one_str) { + this.postsetup_img_one_str = postsetup_img_one_str; + } + + public String getPostsetup_img_two_str() { + return postsetup_img_two_str; + } + + public void setPostsetup_img_two_str(String postsetup_img_two_str) { + this.postsetup_img_two_str = postsetup_img_two_str; + } + + String presetup_img_one_str = "", presetup_img_two_str = "", postsetup_img_one_str = "", postsetup_img_two_str = ""; + String CounterAgeing; + + public String getCounterAgeing() { + return CounterAgeing; + } + + public void setCounterAgeing(String counterAgeing) { + CounterAgeing = counterAgeing; + } + + public String getUserId() { + return userId; + } + + public void setUserId(String userId) { + this.userId = userId; + } + + String counter_img_onefor_ba=""; + + public String getCounter_img_onefor_ba() { + return counter_img_onefor_ba; + } + + public void setCounter_img_onefor_ba(String counter_img_onefor_ba) { + this.counter_img_onefor_ba = counter_img_onefor_ba; + } + + public String getCounter_img_two_for_ba() { + return counter_img_two_for_ba; + } + + public void setCounter_img_two_for_ba(String counter_img_two_for_ba) { + this.counter_img_two_for_ba = counter_img_two_for_ba; + } + + String counter_img_two_for_ba=""; + + public String getTransId() { + return TransId; + } + + public void setTransId(String transId) { + TransId = transId; + } + + String TransId=""; + + public String getUser_type() { + return user_type; + } + + public void setUser_type(String user_type) { + this.user_type = user_type; + } + + String user_type=""; + + public String getUpload_status_ba() { + return upload_status_ba; + } + + public void setUpload_status_ba(String upload_status_ba) { + this.upload_status_ba = upload_status_ba; + } + + String upload_status_ba=""; + String stock_type=""; + + public String getStock_type() { + return stock_type; + } + + public void setStock_type(String stock_type) { + this.stock_type = stock_type; + } + + public String getEntry_type() { + return entry_type; + } + + public void setEntry_type(String entry_type) { + this.entry_type = entry_type; + } + + String entry_type=""; +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/JourneyPlanSearch.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/JourneyPlanSearch.java new file mode 100644 index 0000000..7e8f099 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/JourneyPlanSearch.java @@ -0,0 +1,109 @@ + +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; + +public class JourneyPlanSearch { + + @Expose + private Integer storeId; + @Expose + private String visitDate; + @Expose + private String storeName; + @Expose + private String address1; + @Expose + private String address2; + @Expose + private String landmark; + @Expose + private String pincode; + @Expose + private String city; + @Expose + private String storeType; + @Expose + private String classification; + + public Integer getStoreId() { + return storeId; + } + + public void setStoreId(Integer storeId) { + this.storeId = storeId; + } + + public String getVisitDate() { + return visitDate; + } + + public void setVisitDate(String visitDate) { + this.visitDate = visitDate; + } + + public String getStoreName() { + return storeName; + } + + public void setStoreName(String storeName) { + this.storeName = storeName; + } + + public String getAddress1() { + return address1; + } + + public void setAddress1(String address1) { + this.address1 = address1; + } + + public String getAddress2() { + return address2; + } + + public void setAddress2(String address2) { + this.address2 = address2; + } + + public String getLandmark() { + return landmark; + } + + public void setLandmark(String landmark) { + this.landmark = landmark; + } + + public String getPincode() { + return pincode; + } + + public void setPincode(String pincode) { + this.pincode = pincode; + } + + public String getCity() { + return city; + } + + public void setCity(String city) { + this.city = city; + } + + public String getStoreType() { + return storeType; + } + + public void setStoreType(String storeType) { + this.storeType = storeType; + } + + public String getClassification() { + return classification; + } + + public void setClassification(String classification) { + this.classification = classification; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/LOGIN.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/LOGIN.java new file mode 100644 index 0000000..b841b05 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/LOGIN.java @@ -0,0 +1,42 @@ + +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class LOGIN { + + @SerializedName("Result") + @Expose + private Integer result; + @SerializedName("VisitDate") + @Expose + private String visitDate; + @SerializedName("PasswordStatus") + @Expose + private String passwordStatus; + public String getPasswordStatus() { + return passwordStatus; + } + + public void setPasswordStatus(String passwordStatus) { + this.passwordStatus = passwordStatus; + } + + public Integer getResult() { + return result; + } + + public void setResult(Integer result) { + this.result = result; + } + + public String getVisitDate() { + return visitDate; + } + + public void setVisitDate(String visitDate) { + this.visitDate = visitDate; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/LoginTime.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/LoginTime.java new file mode 100644 index 0000000..6589133 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/LoginTime.java @@ -0,0 +1,20 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class LoginTime { + + @SerializedName("LoginTime") + @Expose + private String loginTime; + + public String getLoginTime() { + return loginTime; + } + + public void setLoginTime(String loginTime) { + this.loginTime = loginTime; + } + +} \ No newline at end of file diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MEMEAuditQuestion.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MEMEAuditQuestion.java new file mode 100644 index 0000000..2cd359f --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MEMEAuditQuestion.java @@ -0,0 +1,194 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +import java.io.Serializable; +import java.util.ArrayList; + +public class MEMEAuditQuestion implements Serializable { + @SerializedName("QuizId") + @Expose + private Integer quizId; + @SerializedName("QuizName") + @Expose + private String quizName; + @SerializedName("CategoryId") + @Expose + private Integer categoryId; + @SerializedName("Category") + @Expose + private String category; + @SerializedName("AuditType") + @Expose + private String auditType; + @SerializedName("QuestionId") + @Expose + private Integer questionId; + @SerializedName("Question") + @Expose + private String question; + @SerializedName("QuestionType") + @Expose + private String questionType; + @SerializedName("AnswerId") + @Expose + private Integer answerId; + @SerializedName("Answer") + @Expose + private String answer; + @SerializedName("ImageAllow") + @Expose + private Boolean imageAllow; + + public Integer getQuizId() { + return quizId; + } + + public void setQuizId(Integer quizId) { + this.quizId = quizId; + } + + public String getQuizName() { + return quizName; + } + + public void setQuizName(String quizName) { + this.quizName = quizName; + } + + public Integer getCategoryId() { + return categoryId; + } + + public void setCategoryId(Integer categoryId) { + this.categoryId = categoryId; + } + + public String getCategory() { + return category; + } + + public void setCategory(String category) { + this.category = category; + } + + public String getAuditType() { + return auditType; + } + + public void setAuditType(String auditType) { + this.auditType = auditType; + } + + public Integer getQuestionId() { + return questionId; + } + + public void setQuestionId(Integer questionId) { + this.questionId = questionId; + } + + public String getQuestion() { + return question; + } + + public void setQuestion(String question) { + this.question = question; + } + + public String getQuestionType() { + return questionType; + } + + public void setQuestionType(String questionType) { + this.questionType = questionType; + } + + public Integer getAnswerId() { + return answerId; + } + + public void setAnswerId(Integer answerId) { + this.answerId = answerId; + } + + public String getAnswer() { + return answer; + } + + public void setAnswer(String answer) { + this.answer = answer; + } + + public Boolean getImageAllow() { + return imageAllow; + } + + public void setImageAllow(Boolean imageAllow) { + this.imageAllow = imageAllow; + } + + ArrayList answerList = new ArrayList<>(); + + public ArrayList getAnswerList() { + return answerList; + } + + public void setAnswerList(ArrayList answerList) { + this.answerList = answerList; + } + public String getStr_audit_img() { + return str_audit_img; + } + + public void setStr_audit_img(String str_audit_img) { + this.str_audit_img = str_audit_img; + } + + String str_audit_img=""; + boolean isSelected; + /** + * @return the isSelected + */ + public boolean isSelected() { + return isSelected; + } + + /** + * @param isSelected the isSelected to set + */ + public void setSelected(boolean isSelected) { + this.isSelected = isSelected; + } + + public String getKeyId() { + return keyId; + } + + public void setKeyId(String keyId) { + this.keyId = keyId; + } + + String keyId=""; + + public String getUser_Id() { + return user_Id; + } + + public void setUser_Id(String user_Id) { + this.user_Id = user_Id; + } + + String user_Id=""; + + public String getVisit_date() { + return visit_date; + } + + public void setVisit_date(String visit_date) { + this.visit_date = visit_date; + } + + String visit_date=""; +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MEMEAuditQuestionUploadstatus.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MEMEAuditQuestionUploadstatus.java new file mode 100644 index 0000000..dc3f29c --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MEMEAuditQuestionUploadstatus.java @@ -0,0 +1,42 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class MEMEAuditQuestionUploadstatus { + + @SerializedName("QuizId") + @Expose + private Integer quizId; + @SerializedName("EmpId") + @Expose + private Integer empId; + @SerializedName("UploadStatus") + @Expose + private String uploadStatus; + + public Integer getQuizId() { + return quizId; + } + + public void setQuizId(Integer quizId) { + this.quizId = quizId; + } + + public Integer getEmpId() { + return empId; + } + + public void setEmpId(Integer empId) { + this.empId = empId; + } + + public String getUploadStatus() { + return uploadStatus; + } + + public void setUploadStatus(String uploadStatus) { + this.uploadStatus = uploadStatus; + } + +} \ No newline at end of file diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MappingAppRestrictedKPI.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MappingAppRestrictedKPI.java new file mode 100644 index 0000000..7846802 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MappingAppRestrictedKPI.java @@ -0,0 +1,51 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class MappingAppRestrictedKPI { + @SerializedName("KPIName") + @Expose + private String kPIName; + @SerializedName("FieldValueType") + @Expose + private String fieldValueType; + @SerializedName("FieldValue") + @Expose + private String fieldValue; + @SerializedName("KPIFieldEnable") + @Expose + private Boolean kPIFieldEnable; + + public String getKPIName() { + return kPIName; + } + + public void setKPIName(String kPIName) { + this.kPIName = kPIName; + } + + public String getFieldValueType() { + return fieldValueType; + } + + public void setFieldValueType(String fieldValueType) { + this.fieldValueType = fieldValueType; + } + + public String getFieldValue() { + return fieldValue; + } + + public void setFieldValue(String fieldValue) { + this.fieldValue = fieldValue; + } + + public Boolean getKPIFieldEnable() { + return kPIFieldEnable; + } + + public void setKPIFieldEnable(Boolean kPIFieldEnable) { + this.kPIFieldEnable = kPIFieldEnable; + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MappingCounterGroupBrand.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MappingCounterGroupBrand.java new file mode 100644 index 0000000..c86d5e2 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MappingCounterGroupBrand.java @@ -0,0 +1,30 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class MappingCounterGroupBrand { + @SerializedName("CounterGroupId") + @Expose + private Integer counterGroupId; + @SerializedName("BrandId") + @Expose + private Integer brandId; + + public Integer getCounterGroupId() { + return counterGroupId; + } + + public void setCounterGroupId(Integer counterGroupId) { + this.counterGroupId = counterGroupId; + } + + public Integer getBrandId() { + return brandId; + } + + public void setBrandId(Integer brandId) { + this.brandId = brandId; + } + +} \ No newline at end of file diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MappingVisibility.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MappingVisibility.java new file mode 100644 index 0000000..031fffa --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MappingVisibility.java @@ -0,0 +1,31 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class MappingVisibility { + + @SerializedName("CounterId") + @Expose + private Integer counterId; + @SerializedName("PosmId") + @Expose + private Integer posmId; + + public Integer getCounterId() { + return counterId; + } + + public void setCounterId(Integer counterId) { + this.counterId = counterId; + } + + public Integer getPosmId() { + return posmId; + } + + public void setPosmId(Integer posmId) { + this.posmId = posmId; + } + +} \ No newline at end of file diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterAgeLimit.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterAgeLimit.java new file mode 100644 index 0000000..c71422a --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterAgeLimit.java @@ -0,0 +1,20 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class MasterAgeLimit { + + @SerializedName("AgeLimit") + @Expose + private String ageLimit; + + public String getAgeLimit() { + return ageLimit; + } + + public void setAgeLimit(String ageLimit) { + this.ageLimit = ageLimit; + } + +} \ No newline at end of file diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterBAProfile.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterBAProfile.java new file mode 100644 index 0000000..319929e --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterBAProfile.java @@ -0,0 +1,68 @@ + +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +import java.io.Serializable; + +public class MasterBAProfile implements Serializable { + + @SerializedName("EmpId") + @Expose + private Integer empId; + @SerializedName("QuestionId") + @Expose + private Integer questionId; + @SerializedName("AnswerId") + @Expose + private Integer answerId; + @SerializedName("Answer") + @Expose + private String answer; + + public String getOthersValue() { + return othersValue; + } + + public void setOthersValue(String othersValue) { + this.othersValue = othersValue; + } + + @SerializedName("OthersValue") + @Expose + private String othersValue; + + public Integer getEmpId() { + return empId; + } + + public void setEmpId(Integer empId) { + this.empId = empId; + } + + public Integer getQuestionId() { + return questionId; + } + + public void setQuestionId(Integer questionId) { + this.questionId = questionId; + } + + public Integer getAnswerId() { + return answerId; + } + + public void setAnswerId(Integer answerId) { + this.answerId = answerId; + } + + public String getAnswer() { + return answer; + } + + public void setAnswer(String answer) { + this.answer = answer; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterBAProfileGetterSetter.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterBAProfileGetterSetter.java new file mode 100644 index 0000000..0ff636d --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterBAProfileGetterSetter.java @@ -0,0 +1,101 @@ + +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import java.io.Serializable; +import java.util.List; +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; +import com.cpm.lorealbaautomation.reportGetterSetter.ReportAttendanceDetail; +import com.cpm.lorealbaautomation.reportGetterSetter.ReportAttendanceSummary; +import com.cpm.lorealbaautomation.reportGetterSetter.ReportBAAvailability; +import com.cpm.lorealbaautomation.reportGetterSetter.ReportInwardStockSummary; + +public class MasterBAProfileGetterSetter implements Serializable { + + @SerializedName("Master_BAProfile") + @Expose + private List masterBAProfile = null; + + public List getMasterBAProfile() { + return masterBAProfile; + } + + @SerializedName("Master_PromoOffers") + @Expose + private List masterPromoOffers = null; + + public List getMasterPromoOffers() { + return masterPromoOffers; + } + @SerializedName("Consumer_SalesHistory") + @Expose + private List consumerSalesHistory = null; + + public List getConsumerSalesHistory() { + return consumerSalesHistory; + } + @SerializedName("Report_AttendanceDetail") + @Expose + private List reportAttendanceDetail = null; + + public List getReportAttendanceDetail() { + return reportAttendanceDetail; + } + @SerializedName("Report_AttendanceSummary") + @Expose + private List reportAttendanceSummary = null; + + public List getReportAttendanceSummary() { + return reportAttendanceSummary; + } + @SerializedName("Report_InwardStockSummary") + @Expose + private List reportInwardStockSummary = null; + + public List getReportInwardStockSummary() { + return reportInwardStockSummary; + } + @SerializedName("Report_BA_Availability") + @Expose + private List reportBAAvailability = null; + + public List getReportBAAvailability() { + return reportBAAvailability; + } + + @SerializedName("Consumer_TermsConditionAccept") + @Expose + private List consumerTermsConditionAccept = null; + + public List getConsumerTermsConditionAccept() { + return consumerTermsConditionAccept; + } + @SerializedName("Master_Looks") + @Expose + private List masterLooks = null; + + public List getMasterLooks() { + return masterLooks; + } + @SerializedName("ME_MEAuditQuestion") + @Expose + private List mEMEAuditQuestion = null; + + public List getMEMEAuditQuestion() { + return mEMEAuditQuestion; + } + + @SerializedName("ME_MEAuditQuestion_UploadStatus") + @Expose + private List mEMEAuditQuestionUploadStatus = null; + + public List getMEMEAuditQuestionUploadStatus() { + return mEMEAuditQuestionUploadStatus; + } + @SerializedName("Mapping_AppRestrictedKPI") + private List mappingAppRestrictedKPI; + + public List getMappingAppRestrictedKPI() { + return mappingAppRestrictedKPI; + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterBreak.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterBreak.java new file mode 100644 index 0000000..9fa2449 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterBreak.java @@ -0,0 +1,111 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; +import com.cpm.lorealbaautomation.constant.CommonString; + +import java.io.Serializable; + +public class MasterBreak implements Serializable { + + @SerializedName("BreakId") + @Expose + private Integer breakId; + @SerializedName("BreakType") + @Expose + private String breakType; + + public Integer getBreakId() { + return breakId; + } + + public void setBreakId(Integer breakId) { + this.breakId = breakId; + } + + public String getBreakType() { + return breakType; + } + + public void setBreakType(String breakType) { + this.breakType = breakType; + } + + String startTym = ""; + String EndTym = ""; + + public String getUserId() { + return userId; + } + + public void setUserId(String userId) { + this.userId = userId; + } + + String userId=""; + + public String getStartTym() { + return startTym; + } + + public void setStartTym(String startTym) { + this.startTym = startTym; + } + + public String getEndTym() { + return EndTym; + } + + public void setEndTym(String endTym) { + EndTym = endTym; + } + + public String getTotalDuration() { + return TotalDuration; + } + + public void setTotalDuration(String totalDuration) { + TotalDuration = totalDuration; + } + + String TotalDuration = ""; + + public String getLoginTym() { + return loginTym; + } + + public void setLoginTym(String loginTym) { + this.loginTym = loginTym; + } + + String loginTym = ""; + String TransId=""; + + public String getTransId() { + return TransId; + } + + public void setTransId(String transId) { + TransId = transId; + } + + public String getUpload_status() { + return upload_status; + } + + public void setUpload_status(String upload_status) { + this.upload_status = upload_status; + } + + String upload_status= CommonString.KEY_N; + + public String getKeyId() { + return keyId; + } + + public void setKeyId(String keyId) { + this.keyId = keyId; + } + + String keyId=""; +} \ No newline at end of file diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterCompetitionOfferGet.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterCompetitionOfferGet.java new file mode 100644 index 0000000..bf5b90d --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterCompetitionOfferGet.java @@ -0,0 +1,51 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class MasterCompetitionOfferGet { + @SerializedName("CompetitionOfferGetId") + @Expose + private Integer cometitionOfferGetId; + @SerializedName("CompetitionOfferGet") + @Expose + private String competitionOfferGet; + @SerializedName("CompetitionOfferSetId") + @Expose + private Integer competitionOfferSetId; + @SerializedName("ShowProductTypeDropdown") + @Expose + private Boolean showProductTypeDropdown; + + + public Integer getCometitionOfferGetId() { + return cometitionOfferGetId; + } + + public void setCometitionOfferGetId(Integer cometitionOfferGetId) { + this.cometitionOfferGetId = cometitionOfferGetId; + } + + public String getCompetitionOfferGet() { + return competitionOfferGet; + } + + public void setCompetitionOfferGet(String competitionOfferGet) { + this.competitionOfferGet = competitionOfferGet; + } + + public Integer getCompetitionOfferSetId() { + return competitionOfferSetId; + } + + public void setCompetitionOfferSetId(Integer competitionOfferSetId) { + this.competitionOfferSetId = competitionOfferSetId; + } + public Boolean getShowProductTypeDropdown() { + return showProductTypeDropdown; + } + + public void setShowProductTypeDropdown(Boolean showProductTypeDropdown) { + this.showProductTypeDropdown = showProductTypeDropdown; + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterCompetitionOfferSet.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterCompetitionOfferSet.java new file mode 100644 index 0000000..307bc52 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterCompetitionOfferSet.java @@ -0,0 +1,30 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class MasterCompetitionOfferSet { + @SerializedName("CompetitionOfferSetId") + @Expose + private Integer competitionOfferSetId; + @SerializedName("CompetitionOfferSet") + @Expose + private String competitionOfferSet; + + public Integer getCompetitionOfferSetId() { + return competitionOfferSetId; + } + + public void setCompetitionOfferSetId(Integer competitionOfferSetId) { + this.competitionOfferSetId = competitionOfferSetId; + } + + public String getCompetitionOfferSet() { + return competitionOfferSet; + } + + public void setCompetitionOfferSet(String competitionOfferSet) { + this.competitionOfferSet = competitionOfferSet; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterCompetitionProductType.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterCompetitionProductType.java new file mode 100644 index 0000000..7facd33 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterCompetitionProductType.java @@ -0,0 +1,29 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class MasterCompetitionProductType { + @SerializedName("CompetitionProductTypeId") + @Expose + private Integer competitionProductTypeId; + @SerializedName("CompetitionProductType") + @Expose + private String competitionProductType; + + public Integer getCompetitionProductTypeId() { + return competitionProductTypeId; + } + + public void setCompetitionProductTypeId(Integer competitionProductTypeId) { + this.competitionProductTypeId = competitionProductTypeId; + } + + public String getCompetitionProductType() { + return competitionProductType; + } + + public void setCompetitionProductType(String competitionProductType) { + this.competitionProductType = competitionProductType; + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterCompetitionPromoType.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterCompetitionPromoType.java new file mode 100644 index 0000000..594ea45 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterCompetitionPromoType.java @@ -0,0 +1,30 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class MasterCompetitionPromoType { + @SerializedName("CompetitionPromoTypeId") + @Expose + private Integer competitionPromoTypeId; + @SerializedName("CompetitionPromoType") + @Expose + private String competitionPromoType; + + public Integer getCompetitionPromoTypeId() { + return competitionPromoTypeId; + } + + public void setCompetitionPromoTypeId(Integer competitionPromoTypeId) { + this.competitionPromoTypeId = competitionPromoTypeId; + } + + public String getCompetitionPromoType() { + return competitionPromoType; + } + + public void setCompetitionPromoType(String competitionPromoType) { + this.competitionPromoType = competitionPromoType; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterCompetitonBrandWiseNuance.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterCompetitonBrandWiseNuance.java new file mode 100644 index 0000000..fefd33a --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterCompetitonBrandWiseNuance.java @@ -0,0 +1,405 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.gettersetter.BaTenureDetail; + +import java.util.List; + +public class MasterCompetitonBrandWiseNuance { + @SerializedName("CompetitionBrandId") + @Expose + private Integer competitionBrandId; + @SerializedName("CompetitionNuanceId") + @Expose + private Integer competitionNuanceId; + @SerializedName("CompetitionBrand") + @Expose + private String competitionBrand; + @SerializedName("CompetitionNuance") + @Expose + private String competitionNuance; + + public Integer getCompetitionBrandId() { + return competitionBrandId; + } + + public void setCompetitionBrandId(Integer competitionBrandId) { + this.competitionBrandId = competitionBrandId; + } + + public Integer getCompetitionNuanceId() { + return competitionNuanceId; + } + + public void setCompetitionNuanceId(Integer competitionNuanceId) { + this.competitionNuanceId = competitionNuanceId; + } + + public String getCompetitionBrand() { + return competitionBrand; + } + + public void setCompetitionBrand(String competitionBrand) { + this.competitionBrand = competitionBrand; + } + + public String getCompetitionNuance() { + return competitionNuance; + } + + public void setCompetitionNuance(String competitionNuance) { + this.competitionNuance = competitionNuance; + } + + String newLaunchMrp = ""; + + String avgtarget = ""; + String avgOfftake = ""; + String tvapercent = ""; + + + public String getAvgtarget() { + return avgtarget; + } + + public void setAvgtarget(String avgtarget) { + this.avgtarget = avgtarget; + } + + public String getAvgOfftake() { + return avgOfftake; + } + + public void setAvgOfftake(String avgOfftake) { + this.avgOfftake = avgOfftake; + } + + public String getTvapercent() { + return tvapercent; + } + + public void setTvapercent(String tvapercent) { + this.tvapercent = tvapercent; + } + + + + public String getNewLaunchMrp() { + return newLaunchMrp; + } + + public void setNewLaunchMrp(String newLaunchMrp) { + this.newLaunchMrp = newLaunchMrp; + } + + + String present_str = "",dateOfMonth = "",promoType="",compOfferset="",compOfferGet="",fromDate="",toDate="",compPromDetail="",compOfferImg=""; + int promoTypeId=0; + int compOffersetId=0; + + String buyType = ""; + int buyTypeId = 0; + + String buyTypeInput = ""; + + public String getBuyType() { + return buyType; + } + + public void setBuyType(String buyType) { + this.buyType = buyType; + } + + public int getBuyTypeId() { + return buyTypeId; + } + + public void setBuyTypeId(int buyTypeId) { + this.buyTypeId = buyTypeId; + } + + public String getBuyTypeInput() { + return buyTypeInput; + } + + public void setBuyTypeInput(String buyTypeInput) { + this.buyTypeInput = buyTypeInput; + } + + public int getBuyTypeInputId() { + return buyTypeInputId; + } + + public void setBuyTypeInputId(int buyTypeInputId) { + this.buyTypeInputId = buyTypeInputId; + } + + public String getGetTypeInput() { + return getTypeInput; + } + + public void setGetTypeInput(String getTypeInput) { + this.getTypeInput = getTypeInput; + } + + public int getGetTypeInputId() { + return getTypeInputId; + } + + public void setGetTypeInputId(int getTypeInputId) { + this.getTypeInputId = getTypeInputId; + } + + String Counter = ""; + String noOfBa = ""; + + public String getCounter() { + return Counter; + } + + public void setCounter(String counter) { + Counter = counter; + } + + public String getNoOfBa() { + return noOfBa; + } + + public void setNoOfBa(String noOfBa) { + this.noOfBa = noOfBa; + } + + public String getSaleRange() { + return saleRange; + } + + public void setSaleRange(String saleRange) { + this.saleRange = saleRange; + } + + public int getSaleRangeId() { + return saleRangeId; + } + + public void setSaleRangeId(int saleRangeId) { + this.saleRangeId = saleRangeId; + } + + String saleRange = ""; + int saleRangeId = 0; + + int buyTypeInputId = 0; + + String getTypeInput = ""; + int getTypeInputId = 0; + + + public String getPresent_str() { + return present_str; + } + + public void setPresent_str(String present_str) { + this.present_str = present_str; + } + + public String getDateOfMonth() { + return dateOfMonth; + } + + public void setDateOfMonth(String dateOfMonth) { + this.dateOfMonth = dateOfMonth; + } + + public String getPromoType() { + return promoType; + } + + public void setPromoType(String promoType) { + this.promoType = promoType; + } + + public String getCompOfferset() { + return compOfferset; + } + + public void setCompOfferset(String compOfferset) { + this.compOfferset = compOfferset; + } + + public String getCompOfferGet() { + return compOfferGet; + } + + public void setCompOfferGet(String compOfferGet) { + this.compOfferGet = compOfferGet; + } + + public String getFromDate() { + return fromDate; + } + + public void setFromDate(String fromDate) { + this.fromDate = fromDate; + } + + public String getToDate() { + return toDate; + } + + public void setToDate(String toDate) { + this.toDate = toDate; + } + + public String getCompPromDetail() { + return compPromDetail; + } + + public void setCompPromDetail(String compPromDetail) { + this.compPromDetail = compPromDetail; + } + + public String getCompOfferImg() { + return compOfferImg; + } + + public void setCompOfferImg(String compOfferImg) { + this.compOfferImg = compOfferImg; + } + + public int getPromoTypeId() { + return promoTypeId; + } + + public void setPromoTypeId(int promoTypeId) { + this.promoTypeId = promoTypeId; + } + + public int getCompOffersetId() { + return compOffersetId; + } + + public void setCompOffersetId(int compOffersetId) { + this.compOffersetId = compOffersetId; + } + + public int getCompOfferGetId() { + return compOfferGetId; + } + + public void setCompOfferGetId(int compOfferGetId) { + this.compOfferGetId = compOfferGetId; + } + + int compOfferGetId=0; + + public String getKeyId() { + return keyId; + } + + public void setKeyId(String keyId) { + this.keyId = keyId; + } + + String keyId; + String uUId; + + public String getuUId() { + return uUId; + } + + public void setuUId(String uUId) { + this.uUId = uUId; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + String status= CommonString.KEY_N; + + public String get_userId() { + return _userId; + } + + public void set_userId(String _userId) { + this._userId = _userId; + } + + String _userId; + + public String getProductType() { + return productType; + } + + public void setProductType(String productType) { + this.productType = productType; + } + + String productType; + + public String getBuyQuantity() { + return buyQuantity; + } + + public void setBuyQuantity(String buyQuantity) { + this.buyQuantity = buyQuantity; + } + + public String getGetQuantity() { + return getQuantity; + } + + public void setGetQuantity(String getQuantity) { + this.getQuantity = getQuantity; + } + + String buyQuantity=""; + String getQuantity=""; + + public int getProductTypeId() { + return productTypeId; + } + + public void setProductTypeId(int productTypeId) { + this.productTypeId = productTypeId; + } + + int productTypeId; + + + public List getBaTenureDetailList() { + return baTenureDetailList; + } + + public void setBaTenureDetailList(List baTenureDetailList) { + this.baTenureDetailList = baTenureDetailList; + } + + List baTenureDetailList ; + + String gwpAvailable = ""; + + public String getGwpAvailable() { + return gwpAvailable; + } + + public void setGwpAvailable(String gwpAvailable) { + this.gwpAvailable = gwpAvailable; + } + String gwpImage=""; + public String getGwpImage() { + return gwpImage; + } + + public void setGwpImage(String gwpImage) { + this.gwpImage = gwpImage; + } + + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterInvoiceType.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterInvoiceType.java new file mode 100644 index 0000000..8f780d1 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterInvoiceType.java @@ -0,0 +1,19 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class MasterInvoiceType { + @SerializedName("InvoiceType") + @Expose + private String invoiceType; + + public String getInvoiceType() { + return invoiceType; + } + + public void setInvoiceType(String invoiceType) { + this.invoiceType = invoiceType; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterInvoiceTypeGetterSetter.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterInvoiceTypeGetterSetter.java new file mode 100644 index 0000000..2ce62fc --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterInvoiceTypeGetterSetter.java @@ -0,0 +1,21 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +import java.util.List; + +public class MasterInvoiceTypeGetterSetter { + @SerializedName("Master_InvoiceType") + @Expose + private List masterInvoiceType = null; + + public List getMasterInvoiceType() { + return masterInvoiceType; + } + + public void setMasterInvoiceType(List masterInvoiceType) { + this.masterInvoiceType = masterInvoiceType; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterLeaveType.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterLeaveType.java new file mode 100644 index 0000000..3f68df4 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterLeaveType.java @@ -0,0 +1,42 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class MasterLeaveType { + + @SerializedName("LeaveTypeId") + @Expose + private Integer leaveTypeId; + @SerializedName("LeaveType") + @Expose + private String leaveType; + @SerializedName("Show") + @Expose + private Boolean show; + + public Integer getLeaveTypeId() { + return leaveTypeId; + } + + public void setLeaveTypeId(Integer leaveTypeId) { + this.leaveTypeId = leaveTypeId; + } + + public String getLeaveType() { + return leaveType; + } + + public void setLeaveType(String leaveType) { + this.leaveType = leaveType; + } + + public Boolean getShow() { + return show; + } + + public void setShow(Boolean show) { + this.show = show; + } + +} \ No newline at end of file diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterLook.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterLook.java new file mode 100644 index 0000000..4c86aa1 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterLook.java @@ -0,0 +1,20 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class MasterLook { + + @SerializedName("Looks") + @Expose + private String looks; + + public String getLooks() { + return looks; + } + + public void setLooks(String looks) { + this.looks = looks; + } + +} \ No newline at end of file diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterNonStockReason.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterNonStockReason.java new file mode 100644 index 0000000..72c98b3 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterNonStockReason.java @@ -0,0 +1,41 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class MasterNonStockReason { + @SerializedName("ReasonId") + @Expose + private Integer reasonId; + @SerializedName("Reason") + @Expose + private String reason; + @SerializedName("Applicable") + @Expose + private Boolean applicable; + + public Integer getReasonId() { + return reasonId; + } + + public void setReasonId(Integer reasonId) { + this.reasonId = reasonId; + } + + public String getReason() { + return reason; + } + + public void setReason(String reason) { + this.reason = reason; + } + + public Boolean getApplicable() { + return applicable; + } + + public void setApplicable(Boolean applicable) { + this.applicable = applicable; + } +} + diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterNonStockReasonGetterSetter.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterNonStockReasonGetterSetter.java new file mode 100644 index 0000000..4b2bbcf --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterNonStockReasonGetterSetter.java @@ -0,0 +1,21 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +import java.util.List; + +public class MasterNonStockReasonGetterSetter { + @SerializedName("Master_NonStockReason") + @Expose + private List masterNonStockReason = null; + + public List getMasterNonStockReason() { + return masterNonStockReason; + } + + public void setMasterNonStockReason(List masterNonStockReason) { + this.masterNonStockReason = masterNonStockReason; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterNonVisibility.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterNonVisibility.java new file mode 100644 index 0000000..412a638 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterNonVisibility.java @@ -0,0 +1,34 @@ + +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +import java.io.Serializable; + +public class MasterNonVisibility implements Serializable { + + @SerializedName("ReasonId") + @Expose + private Integer reasonId; + @SerializedName("Reason") + @Expose + private String reason; + + public Integer getReasonId() { + return reasonId; + } + + public void setReasonId(Integer reasonId) { + this.reasonId = reasonId; + } + + public String getReason() { + return reason; + } + + public void setReason(String reason) { + this.reason = reason; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterNonVisibilityGetterSetter.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterNonVisibilityGetterSetter.java new file mode 100644 index 0000000..15580f0 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterNonVisibilityGetterSetter.java @@ -0,0 +1,24 @@ + +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import java.io.Serializable; +import java.util.List; +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class MasterNonVisibilityGetterSetter implements Serializable { + + @SerializedName("Master_NonVisibility") + @Expose + private List masterNonVisibility = null; + + + public List getMasterNonVisibility() { + return masterNonVisibility; + } + + public void setMasterNonVisibility(List masterNonVisibility) { + this.masterNonVisibility = masterNonVisibility; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterPosm.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterPosm.java new file mode 100644 index 0000000..600e5eb --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterPosm.java @@ -0,0 +1,120 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +import java.io.Serializable; + +public class MasterPosm implements Serializable { + + @SerializedName("PosmId") + @Expose + private Integer posmId; + @SerializedName("Posm") + @Expose + private String posm; + @SerializedName("PosmTypeId") + @Expose + private Integer posmTypeId; + @SerializedName("RefImage") + @Expose + private String refImage; + + public Integer getPosmId() { + return posmId; + } + + public void setPosmId(Integer posmId) { + this.posmId = posmId; + } + + public String getPosm() { + return posm; + } + + public void setPosm(String posm) { + this.posm = posm; + } + + public Integer getPosmTypeId() { + return posmTypeId; + } + + public void setPosmTypeId(Integer posmTypeId) { + this.posmTypeId = posmTypeId; + } + + public String getRefImage() { + return refImage; + } + + public void setRefImage(String refImage) { + this.refImage = refImage; + } + + String promotion_exists_state =""; + String promotion_img =""; + String promotion_currect_ans =""; + String promotion_currect_ans_Id =""; + String ImageName; + + public String getUserId() { + return userId; + } + + public void setUserId(String userId) { + this.userId = userId; + } + + String userId=""; + + public String getImageName() { + return ImageName; + } + + public void setImageName(String imageName) { + ImageName = imageName; + } + + public String getPromotion_exists_state() { + return promotion_exists_state; + } + + public void setPromotion_exists_state(String promotion_exists_state) { + this.promotion_exists_state = promotion_exists_state; + } + + public String getPromotion_img() { + return promotion_img; + } + + public void setPromotion_img(String promotion_img) { + this.promotion_img = promotion_img; + } + + public String getPromotion_currect_ans() { + return promotion_currect_ans; + } + + public void setPromotion_currect_ans(String promotion_currect_ans) { + this.promotion_currect_ans = promotion_currect_ans; + } + + public String getPromotion_currect_ans_Id() { + return promotion_currect_ans_Id; + } + + public void setPromotion_currect_ans_Id(String promotion_currect_ans_Id) { + this.promotion_currect_ans_Id = promotion_currect_ans_Id; + } + + public String getTransId() { + return transId; + } + + public void setTransId(String transId) { + this.transId = transId; + } + + String transId=""; +} \ No newline at end of file diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterProfile.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterProfile.java new file mode 100644 index 0000000..53e63aa --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterProfile.java @@ -0,0 +1,183 @@ + +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; +import com.cpm.lorealbaautomation.constant.CommonString; + +import java.io.Serializable; + +public class MasterProfile implements Serializable { + + @SerializedName("EmpCode") + @Expose + private String empCode; + @SerializedName("FullName") + @Expose + private String fullName; + @SerializedName("Supervisor") + @Expose + private String supervisor; + @SerializedName("Gender") + @Expose + private String gender; + @SerializedName("Address") + @Expose + private String address; + @SerializedName("dob") + @Expose + private String dob; + @SerializedName("Current_BPgrade") + @Expose + private String currentBPgrade; + @SerializedName("Mobile") + @Expose + private String mobile; + @SerializedName("Email") + @Expose + private String email; + @SerializedName("InstragramAddress") + @Expose + private String instragramAddress; + @SerializedName("Profile_Pic") + @Expose + private String profilePic; + @SerializedName("VisitDate") + @Expose + private String viisitDate; + @SerializedName("UserId") + @Expose + private String userId; + String location,landmark; + + public String getLocation() { + return location; + } + + public void setLocation(String location) { + this.location = location; + } + + public String getLandmark() { + return landmark; + } + + public void setLandmark(String landmark) { + this.landmark = landmark; + } + + public String getViisitDate() { + return viisitDate; + } + + public void setViisitDate(String viisitDate) { + this.viisitDate = viisitDate; + } + + public String getUserId() { + return userId; + } + + public void setUserId(String userId) { + this.userId = userId; + } + + public String getEmpCode() { + return empCode; + } + + public void setEmpCode(String empCode) { + this.empCode = empCode; + } + + public String getFullName() { + return fullName; + } + + public void setFullName(String fullName) { + this.fullName = fullName; + } + + public String getSupervisor() { + return supervisor; + } + + public void setSupervisor(String supervisor) { + this.supervisor = supervisor; + } + + public String getGender() { + return gender; + } + + public void setGender(String gender) { + this.gender = gender; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } + + public String getDob() { + return dob; + } + + public void setDob(String dob) { + this.dob = dob; + } + + public String getCurrentBPgrade() { + return currentBPgrade; + } + + public void setCurrentBPgrade(String currentBPgrade) { + this.currentBPgrade = currentBPgrade; + } + + public String getMobile() { + return mobile; + } + + public void setMobile(String mobile) { + this.mobile = mobile; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getInstragramAddress() { + return instragramAddress; + } + + public void setInstragramAddress(String instragramAddress) { + this.instragramAddress = instragramAddress; + } + + public String getProfilePic() { + return profilePic; + } + + public void setProfilePic(String profilePic) { + this.profilePic = profilePic; + } + + public String getUpload_status() { + return upload_status; + } + + public void setUpload_status(String upload_status) { + this.upload_status = upload_status; + } + + String upload_status= CommonString.KEY_N; + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterProfileGetterSetter.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterProfileGetterSetter.java new file mode 100644 index 0000000..0afb10b --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterProfileGetterSetter.java @@ -0,0 +1,22 @@ + +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import java.util.List; +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class MasterProfileGetterSetter { + + @SerializedName("Master_Profile") + @Expose + private List masterProfile = null; + + public List getMasterProfile() { + return masterProfile; + } + + public void setMasterProfile(List masterProfile) { + this.masterProfile = masterProfile; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterProfileQuestion.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterProfileQuestion.java new file mode 100644 index 0000000..b5dfbbb --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterProfileQuestion.java @@ -0,0 +1,122 @@ + +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +import java.io.Serializable; + +public class MasterProfileQuestion implements Serializable { + + @SerializedName("CategoryId") + @Expose + private Integer categoryId; + @SerializedName("Category") + @Expose + private String category; + @SerializedName("QuestionId") + @Expose + private Integer questionId; + @SerializedName("Question") + @Expose + private String question; + @SerializedName("QuestionType") + @Expose + private String questionType; + @SerializedName("AnswerId") + @Expose + private Integer answerId; + @SerializedName("Answer") + @Expose + private String answer; + @SerializedName("BA") + @Expose + private Integer bA; + @SerializedName("TBA") + @Expose + private Integer tBA; + @SerializedName("ME") + @Expose + private Integer mE; + + public Integer getCategoryId() { + return categoryId; + } + + public void setCategoryId(Integer categoryId) { + this.categoryId = categoryId; + } + + public String getCategory() { + return category; + } + + public void setCategory(String category) { + this.category = category; + } + + public Integer getQuestionId() { + return questionId; + } + + public void setQuestionId(Integer questionId) { + this.questionId = questionId; + } + + public String getQuestion() { + return question; + } + + public void setQuestion(String question) { + this.question = question; + } + + public String getQuestionType() { + return questionType; + } + + public void setQuestionType(String questionType) { + this.questionType = questionType; + } + + public Integer getAnswerId() { + return answerId; + } + + public void setAnswerId(Integer answerId) { + this.answerId = answerId; + } + + public String getAnswer() { + return answer; + } + + public void setAnswer(String answer) { + this.answer = answer; + } + + public Integer getBA() { + return bA; + } + + public void setBA(Integer bA) { + this.bA = bA; + } + + public Integer getTBA() { + return tBA; + } + + public void setTBA(Integer tBA) { + this.tBA = tBA; + } + + public Integer getME() { + return mE; + } + + public void setME(Integer mE) { + this.mE = mE; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterProfileQuestionGetterSetter.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterProfileQuestionGetterSetter.java new file mode 100644 index 0000000..cdb76f3 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterProfileQuestionGetterSetter.java @@ -0,0 +1,117 @@ + +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import java.io.Serializable; +import java.util.List; + +import com.google.gson.annotations.SerializedName; +import com.cpm.lorealbaautomation.reportGetterSetter.ReportAvgBillValue; +import com.cpm.lorealbaautomation.reportGetterSetter.ReportAvgLinPerBill; +import com.cpm.lorealbaautomation.reportGetterSetter.ReportAvgTransactionPerDay; +import com.cpm.lorealbaautomation.reportGetterSetter.ReportAvgUnitsPerBill; +import com.cpm.lorealbaautomation.reportGetterSetter.ReportSalesValue; +import com.cpm.lorealbaautomation.reportGetterSetter.ReportSellingPrice; +import com.cpm.lorealbaautomation.reportGetterSetter.ReportTop10Value; +import com.cpm.lorealbaautomation.reportGetterSetter.ReportTop10Volume; + +public class MasterProfileQuestionGetterSetter implements Serializable { + @SerializedName("Master_ProfileQuestion") + private List masterProfileQuestion = null; + public List getMasterProfileQuestion() { + return masterProfileQuestion; + } + @SerializedName("Master_ReturnReason") + private List masterReturnReason = null; + + public List getMasterReturnReason() { + return masterReturnReason; + } + @SerializedName("Master_TermsCondition") + private List masterTermsCondition = null; + public List getMasterTermsCondition() { + return masterTermsCondition; + } + public List gettLeaveRequestList() { + return tLeaveRequestList; + } + + @SerializedName("T_LeaveRequest") + private List tLeaveRequestList = null; + + @SerializedName("T_LeaveLedger") + private List tLeaveLedger = null; + public List getTLeaveLedger() { + return tLeaveLedger; + } + + @SerializedName("Master_Break") + private List masterBreak = null; + public List getMasterBreak() { + return masterBreak; + } + + @SerializedName("Report_SalesValue") + private List reportSalesValue = null; + public List getReportSalesValue() { + return reportSalesValue; + } + @SerializedName("Report_AvgTransactionPerDay") + private List reportAvgTransactionPerDay = null; + public List getReportAvgTransactionPerDay() { + return reportAvgTransactionPerDay; + } + + @SerializedName("Report_AvgBillValue") + private List reportAvgBillValue = null; + public List getReportAvgBillValue() { + return reportAvgBillValue; + } + + @SerializedName("Report_AvgLinPerBill") + private List reportAvgLinPerBill = null; + public List getReportAvgLinPerBill() { + return reportAvgLinPerBill; + } + @SerializedName("Report_SellingPrice") + private List reportSellingPrice = null; + public List getReportSellingPrice() { + return reportSellingPrice; + } + + @SerializedName("Report_Top10Volume") + private List reportTop10Volume = null; + public List getReportTop10Volume() { + return reportTop10Volume; + } + + @SerializedName("Report_Top10Value") + private List reportTop10Value = null; + public List getReportTop10Value() { + return reportTop10Value; + } + + @SerializedName("Report_AvgUnitsPerBill") + private List reportAvgUnitsPerBill = null; + public List getReportAvgUnitsPerBill() { + return reportAvgUnitsPerBill; + } + + @SerializedName("Report_Sales_Detail") + private List reportSalesDetail = null; + public List getReportSalesDetail() { + return reportSalesDetail; + } + public List getReportMeSaleList() { + return reportMeSaleList; + } + + @SerializedName("Report_ME_Sale") + private List reportMeSaleList = null; + @SerializedName("Report_Sales_DetailME") + private List reportSalesDetailMe = null; + public List getReportSalesDetailMe() { + return reportSalesDetailMe; + } + + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterPromoOffer.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterPromoOffer.java new file mode 100644 index 0000000..5389333 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterPromoOffer.java @@ -0,0 +1,86 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class MasterPromoOffer { + + @SerializedName("PromoId") + @Expose + private String promoId; + @SerializedName("PromoPath") + @Expose + private String promoPath; + @SerializedName("PromoOfferTab") + @Expose + private String promoOfferTab; + @SerializedName("PromoOfferMobile") + @Expose + private String promoOfferMobile; + @SerializedName("Description") + @Expose + private String description; + @SerializedName("StartDate") + @Expose + private String startDate; + @SerializedName("EndDate") + @Expose + private String endDate; + + public String getPromoId() { + return promoId; + } + + public void setPromoId(String promoId) { + this.promoId = promoId; + } + + public String getPromoPath() { + return promoPath; + } + + public void setPromoPath(String promoPath) { + this.promoPath = promoPath; + } + + public String getPromoOfferTab() { + return promoOfferTab; + } + + public void setPromoOfferTab(String promoOfferTab) { + this.promoOfferTab = promoOfferTab; + } + + public String getPromoOfferMobile() { + return promoOfferMobile; + } + + public void setPromoOfferMobile(String promoOfferMobile) { + this.promoOfferMobile = promoOfferMobile; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getStartDate() { + return startDate; + } + + public void setStartDate(String startDate) { + this.startDate = startDate; + } + + public String getEndDate() { + return endDate; + } + + public void setEndDate(String endDate) { + this.endDate = endDate; + } + +} \ No newline at end of file diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterPromotion.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterPromotion.java new file mode 100644 index 0000000..5a8a033 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterPromotion.java @@ -0,0 +1,284 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class MasterPromotion { + + @SerializedName("CounterId") + @Expose + private Integer counterId; + @SerializedName("PromoId") + @Expose + private Integer promoId; + @SerializedName("PromotionSetEntityType") + @Expose + private String promotionSetEntityType; + @SerializedName("PromotionGetEntityType") + @Expose + private String promotionGetEntityType; + @SerializedName("PromotionSetEntityValue") + @Expose + private String promotionSetEntityValue; + @SerializedName("PromotionGetEntityValue") + @Expose + private String promotionGetEntityValue; + @SerializedName("PromotionCode") + @Expose + private String promotionCode; + @SerializedName("PromotionName") + @Expose + private String promotionName; + @SerializedName("StartTime") + @Expose + private String startTime; + @SerializedName("EndTime") + @Expose + private String endTime; + + @SerializedName("StartDate") + @Expose + private String StartDate; + + @SerializedName("EndDate") + @Expose + private String EndDate; + + @SerializedName("PromoPath") + @Expose + private String PromoPath; + + @SerializedName("MaxValue") + @Expose + private String maxValue; + + public String getPromoType() { + return PromoType; + } + + public void setPromoType(String promoType) { + PromoType = promoType; + } + + @SerializedName("PromoType") + @Expose + private String PromoType; + + public String getMaxValue() { + return maxValue; + } + + public void setMaxValue(String maxValue) { + this.maxValue = maxValue; + } + + + public String getStartDate() { + return StartDate; + } + + public void setStartDate(String startDate) { + StartDate = startDate; + } + + public String getEndDate() { + return EndDate; + } + + public void setEndDate(String endDate) { + EndDate = endDate; + } + + public String getPromoPath() { + return PromoPath; + } + + public void setPromoPath(String promoPath) { + PromoPath = promoPath; + } + + public String getPromoOfferTab() { + return PromoOfferTab; + } + + public void setPromoOfferTab(String promoOfferTab) { + PromoOfferTab = promoOfferTab; + } + + public String getPromoOfferMobile() { + return PromoOfferMobile; + } + + public void setPromoOfferMobile(String promoOfferMobile) { + PromoOfferMobile = promoOfferMobile; + } + + public String getPromo_mrp_product() { + return promo_mrp_product; + } + + @SerializedName("PromoOfferTab") + @Expose + private String PromoOfferTab; + + @SerializedName("PromoOfferMobile") + @Expose + private String PromoOfferMobile; + + + public Integer getCounterId() { + return counterId; + } + + public void setCounterId(Integer counterId) { + this.counterId = counterId; + } + + public Integer getPromoId() { + return promoId; + } + + public void setPromoId(Integer promoId) { + this.promoId = promoId; + } + + public String getPromotionSetEntityType() { + return promotionSetEntityType; + } + + public void setPromotionSetEntityType(String promotionSetEntityType) { + this.promotionSetEntityType = promotionSetEntityType; + } + + public String getPromotionGetEntityType() { + return promotionGetEntityType; + } + + public void setPromotionGetEntityType(String promotionGetEntityType) { + this.promotionGetEntityType = promotionGetEntityType; + } + + public String getPromotionSetEntityValue() { + return promotionSetEntityValue; + } + + public void setPromotionSetEntityValue(String promotionSetEntityValue) { + this.promotionSetEntityValue = promotionSetEntityValue; + } + + public String getPromotionGetEntityValue() { + return promotionGetEntityValue; + } + + public void setPromotionGetEntityValue(String promotionGetEntityValue) { + this.promotionGetEntityValue = promotionGetEntityValue; + } + + public String getPromotionCode() { + return promotionCode; + } + + public void setPromotionCode(String promotionCode) { + this.promotionCode = promotionCode; + } + + public String getPromotionName() { + return promotionName; + } + + public void setPromotionName(String promotionName) { + this.promotionName = promotionName; + } + + public String getStartTime() { + return startTime; + } + + public void setStartTime(String startTime) { + this.startTime = startTime; + } + + public String getEndTime() { + return endTime; + } + + public void setEndTime(String endTime) { + this.endTime = endTime; + } + + public boolean isPromotionactive() { + return promotionactive; + } + + public void setPromotionactive(boolean promotionactive) { + this.promotionactive = promotionactive; + } + + public boolean promotionactive=false; + + public String getSelected_promo_productId() { + return selected_promo_productId; + } + + public void setSelected_promo_productId(String selected_promo_productId) { + this.selected_promo_productId = selected_promo_productId; + } + + String selected_promo_productId ="0"; + + public String getSelected_promoproduct() { + return selected_promoproduct; + } + + public void setSelected_promoproduct(String selected_promoproduct) { + this.selected_promoproduct = selected_promoproduct; + } + + String selected_promoproduct=""; + + public String getSelected_promoproductQTY() { + return selected_promoproductQTY; + } + + public void setSelected_promoproductQTY(String selected_promoproductQTY) { + this.selected_promoproductQTY = selected_promoproductQTY; + } + + String selected_promoproductQTY="0"; + public void setPromo_mrp_product(String promo_mrp_product) { + this.promo_mrp_product = promo_mrp_product; + } + + String promo_mrp_product =""; + + public String getPromo_ean_code() { + return promo_ean_code; + } + + public void setPromo_ean_code(String promo_ean_code) { + this.promo_ean_code = promo_ean_code; + } + + String promo_ean_code =""; + + public String getStr_promo_on_applyed_productId() { + return str_promo_on_applyed_productId; + } + + public void setStr_promo_on_applyed_productId(String str_promo_on_applyed_productId) { + this.str_promo_on_applyed_productId = str_promo_on_applyed_productId; + } + + String str_promo_on_applyed_productId; + + public String getStr_promo_on_applyed_productname() { + return str_promo_on_applyed_productname; + } + + public void setStr_promo_on_applyed_productname(String str_promo_on_applyed_productname) { + this.str_promo_on_applyed_productname = str_promo_on_applyed_productname; + } + + String str_promo_on_applyed_productname ="0"; + +} \ No newline at end of file diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterPromotionGetEntityItem.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterPromotionGetEntityItem.java new file mode 100644 index 0000000..f09f6c5 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterPromotionGetEntityItem.java @@ -0,0 +1,42 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class MasterPromotionGetEntityItem { + + @SerializedName("PromoId") + @Expose + private Integer promoId; + @SerializedName("GetEntityListType") + @Expose + private String getEntityListType; + @SerializedName("GetEntityListItem") + @Expose + private String getEntityListItem; + + public Integer getPromoId() { + return promoId; + } + + public void setPromoId(Integer promoId) { + this.promoId = promoId; + } + + public String getGetEntityListType() { + return getEntityListType; + } + + public void setGetEntityListType(String getEntityListType) { + this.getEntityListType = getEntityListType; + } + + public String getGetEntityListItem() { + return getEntityListItem; + } + + public void setGetEntityListItem(String getEntityListItem) { + this.getEntityListItem = getEntityListItem; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterPromotionGetExclusionList.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterPromotionGetExclusionList.java new file mode 100644 index 0000000..4b15f43 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterPromotionGetExclusionList.java @@ -0,0 +1,41 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class MasterPromotionGetExclusionList { + + @SerializedName("Id") + @Expose + private Integer id; + @SerializedName("PromoId") + @Expose + private Integer promoId; + @SerializedName("GetExclusionList") + @Expose + private String getExclusionList; + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public Integer getPromoId() { + return promoId; + } + + public void setPromoId(Integer promoId) { + this.promoId = promoId; + } + + public String getGetExclusionList() { + return getExclusionList; + } + + public void setGetExclusionList(String getExclusionList) { + this.getExclusionList = getExclusionList; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterPromotionGetProductCatalog.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterPromotionGetProductCatalog.java new file mode 100644 index 0000000..a7d9fef --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterPromotionGetProductCatalog.java @@ -0,0 +1,31 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class MasterPromotionGetProductCatalog { + + @SerializedName("CatalogId") + @Expose + private Integer catalogId; + @SerializedName("ProductId") + @Expose + private Integer productId; + + public Integer getCatalogId() { + return catalogId; + } + + public void setCatalogId(Integer catalogId) { + this.catalogId = catalogId; + } + + public Integer getProductId() { + return productId; + } + + public void setProductId(Integer productId) { + this.productId = productId; + } + +} \ No newline at end of file diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterPromotionGetProductGroup.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterPromotionGetProductGroup.java new file mode 100644 index 0000000..2b499e7 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterPromotionGetProductGroup.java @@ -0,0 +1,31 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class MasterPromotionGetProductGroup { + + @SerializedName("ProductGroupId") + @Expose + private Integer productGroupId; + @SerializedName("ProductId") + @Expose + private Integer productId; + + public Integer getProductGroupId() { + return productGroupId; + } + + public void setProductGroupId(Integer productGroupId) { + this.productGroupId = productGroupId; + } + + public Integer getProductId() { + return productId; + } + + public void setProductId(Integer productId) { + this.productId = productId; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterPromotionSetEntityItem.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterPromotionSetEntityItem.java new file mode 100644 index 0000000..888ca7a --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterPromotionSetEntityItem.java @@ -0,0 +1,68 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class MasterPromotionSetEntityItem { + + @SerializedName("PromoId") + @Expose + private Integer promoId; + + public Integer getId() { + return Id; + } + + public void setId(Integer id) { + Id = id; + } + + @SerializedName("Id") + @Expose + private Integer Id; + + @SerializedName("SetEntityListType") + @Expose + private String setEntityListType; + @SerializedName("SetEntityListItem") + @Expose + private String setEntityListItem; + + + public Integer getItemCount() { + return ItemCount; + } + + public void setItemCount(Integer itemCount) { + ItemCount = itemCount; + } + + @SerializedName("ItemCount") + @Expose + private Integer ItemCount; + + public Integer getPromoId() { + return promoId; + } + + public void setPromoId(Integer promoId) { + this.promoId = promoId; + } + + public String getSetEntityListType() { + return setEntityListType; + } + + public void setSetEntityListType(String setEntityListType) { + this.setEntityListType = setEntityListType; + } + + public String getSetEntityListItem() { + return setEntityListItem; + } + + public void setSetEntityListItem(String setEntityListItem) { + this.setEntityListItem = setEntityListItem; + } + +} \ No newline at end of file diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterPromotionSetExclusionList.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterPromotionSetExclusionList.java new file mode 100644 index 0000000..4f66d94 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterPromotionSetExclusionList.java @@ -0,0 +1,41 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class MasterPromotionSetExclusionList { + + @SerializedName("Id") + @Expose + private Integer id; + @SerializedName("PromoId") + @Expose + private Integer promoId; + @SerializedName("SetExclusionList") + @Expose + private String setExclusionList; + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public Integer getPromoId() { + return promoId; + } + + public void setPromoId(Integer promoId) { + this.promoId = promoId; + } + + public String getSetExclusionList() { + return setExclusionList; + } + + public void setSetExclusionList(String setExclusionList) { + this.setExclusionList = setExclusionList; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterPromotionSetProductCatalog.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterPromotionSetProductCatalog.java new file mode 100644 index 0000000..c3964e2 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterPromotionSetProductCatalog.java @@ -0,0 +1,31 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class MasterPromotionSetProductCatalog { + + @SerializedName("CatalogId") + @Expose + private Integer catalogId; + @SerializedName("ProductId") + @Expose + private Integer productId; + + public Integer getCatalogId() { + return catalogId; + } + + public void setCatalogId(Integer catalogId) { + this.catalogId = catalogId; + } + + public Integer getProductId() { + return productId; + } + + public void setProductId(Integer productId) { + this.productId = productId; + } + +} \ No newline at end of file diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterPromotionSetProductGroup.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterPromotionSetProductGroup.java new file mode 100644 index 0000000..6f651b8 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterPromotionSetProductGroup.java @@ -0,0 +1,117 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class MasterPromotionSetProductGroup { + + @SerializedName("ProductGroupId") + @Expose + private Integer productGroupId; + @SerializedName("ProductId") + @Expose + private Integer productId; + + public Integer getProductGroupId() { + return productGroupId; + } + + public void setProductGroupId(Integer productGroupId) { + this.productGroupId = productGroupId; + } + + public Integer getProductId() { + return productId; + } + + public void setProductId(Integer productId) { + this.productId = productId; + } + String productname=""; + + public String getProductname() { + return productname; + } + + public void setProductname(String productname) { + this.productname = productname; + } + + public String getMrp_product() { + return mrp_product; + } + + public void setMrp_product(String mrp_product) { + this.mrp_product = mrp_product; + } + + String mrp_product=""; + + public String getEan_code() { + return ean_code; + } + + public void setEan_code(String ean_code) { + this.ean_code = ean_code; + } + + String ean_code=""; + + public int getSelected_item_qty() { + return selected_item_qty; + } + + public void setSelected_item_qty(int selected_item_qty) { + this.selected_item_qty = selected_item_qty; + } + + int selected_item_qty=0; + + public String getSallable_stock_qty() { + return sallable_stock_qty; + } + + public void setSallable_stock_qty(String sallable_stock_qty) { + this.sallable_stock_qty = sallable_stock_qty; + } + + String sallable_stock_qty="0"; + String promotion_name=""; + String promotionId="0"; + String promotion_deducted_price="0"; + + public String getPromotion_name() { + return promotion_name; + } + + public void setPromotion_name(String promotion_name) { + this.promotion_name = promotion_name; + } + + public String getPromotionId() { + return promotionId; + } + + public void setPromotionId(String promotionId) { + this.promotionId = promotionId; + } + + public String getPromotion_deducted_price() { + return promotion_deducted_price; + } + + public void setPromotion_deducted_price(String promotion_deducted_price) { + this.promotion_deducted_price = promotion_deducted_price; + } + + public String getPromotion_deducted_price_percentage() { + return promotion_deducted_price_percentage; + } + + public void setPromotion_deducted_price_percentage(String promotion_deducted_price_percentage) { + this.promotion_deducted_price_percentage = promotion_deducted_price_percentage; + } + + String promotion_deducted_price_percentage="0"; + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterRetailExcellence.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterRetailExcellence.java new file mode 100644 index 0000000..f8b0b63 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterRetailExcellence.java @@ -0,0 +1,88 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +import java.io.Serializable; + +public class MasterRetailExcellence implements Serializable { + @SerializedName("ItemCategoryId") + @Expose + private Integer itemCatId; + + @SerializedName("ItemCategoryName") + @Expose + private String itemCatName; + + @SerializedName("ItemName") + @Expose + private String itemName; + + @SerializedName("ItemId") + @Expose + private Integer itemId; + + String answer=""; + + public String getAnswer() { + return answer; + } + + public void setAnswer(String answer) { + this.answer = answer; + } + + + + public Integer getItemCatId() { + return itemCatId; + } + + public void setItemCatId(Integer itemCatId) { + this.itemCatId = itemCatId; + } + + public String getItemCatName() { + return itemCatName; + } + + public void setItemCatName(String itemCatName) { + this.itemCatName = itemCatName; + } + + public String getItemName() { + return itemName; + } + + public void setItemName(String itemName) { + this.itemName = itemName; + } + + public Integer getItemId() { + return itemId; + } + + public void setItemId(Integer itemId) { + this.itemId = itemId; + } + + public String getUser_Id() { + return User_Id; + } + + public void setUser_Id(String user_Id) { + User_Id = user_Id; + } + + public String getKeyId() { + return KeyId; + } + + public void setKeyId(String keyId) { + KeyId = keyId; + } + + String User_Id = ""; + String KeyId = ""; + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterReturnReason.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterReturnReason.java new file mode 100644 index 0000000..2f5f03f --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterReturnReason.java @@ -0,0 +1,31 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class MasterReturnReason { + + @SerializedName("ReasonId") + @Expose + private Integer reasonId; + @SerializedName("Reason") + @Expose + private String reason; + + public Integer getReasonId() { + return reasonId; + } + + public void setReasonId(Integer reasonId) { + this.reasonId = reasonId; + } + + public String getReason() { + return reason; + } + + public void setReason(String reason) { + this.reason = reason; + } + +} \ No newline at end of file diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterSkinType.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterSkinType.java new file mode 100644 index 0000000..7205698 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterSkinType.java @@ -0,0 +1,20 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class MasterSkinType { + + @SerializedName("SkinType") + @Expose + private String skinType; + + public String getSkinType() { + return skinType; + } + + public void setSkinType(String skinType) { + this.skinType = skinType; + } + +} \ No newline at end of file diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterSourcesOfSale.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterSourcesOfSale.java new file mode 100644 index 0000000..7f59c9d --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterSourcesOfSale.java @@ -0,0 +1,19 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class MasterSourcesOfSale { + + @SerializedName("SourcesOfSale") + @Expose + private String sourcesOfSale; + + public String getSourcesOfSale() { + return sourcesOfSale; + } + + public void setSourcesOfSale(String sourcesOfSale) { + this.sourcesOfSale = sourcesOfSale; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterSurvey.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterSurvey.java new file mode 100644 index 0000000..36402e4 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterSurvey.java @@ -0,0 +1,148 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class MasterSurvey { + + @SerializedName("SurveyId") + @Expose + private Integer surveyId; + @SerializedName("SurveyName") + @Expose + private String surveyName; + @SerializedName("SurveyType") + @Expose + private String surveyType; + @SerializedName("SurveyQuestionId") + @Expose + private Integer surveyQuestionId; + @SerializedName("SurveyQuestion") + @Expose + private String surveyQuestion; + @SerializedName("SurveyQuestionType") + @Expose + private String surveyQuestionType; + @SerializedName("SurveyAnswerId") + @Expose + private Integer surveyAnswerId; + @SerializedName("SurveyAnswer") + @Expose + private String surveyAnswer; + @SerializedName("ImageAllow") + @Expose + private Boolean imageAllow; + + @SerializedName("UploadStatus") + @Expose + private Integer uploadStatus; + + String correct_answer_id = ""; + String cam_image=""; + String common_id = ""; + + public String getCommon_id() { + return common_id; + } + + public void setCommon_id(String common_id) { + this.common_id = common_id; + } + + public String getCorrect_answer_id() { + return correct_answer_id; + } + + public void setCorrect_answer_id(String correct_answer_id) { + this.correct_answer_id = correct_answer_id; + } + + public String getCam_image() { + return cam_image; + } + + public void setCam_image(String cam_image) { + this.cam_image = cam_image; + } + + public Integer getUploadStatus() { + return uploadStatus; + } + + public void setUploadStatus(Integer uploadStatus) { + this.uploadStatus = uploadStatus; + } + + public Integer getSurveyId() { + return surveyId; + } + + public void setSurveyId(Integer surveyId) { + this.surveyId = surveyId; + } + + public String getSurveyName() { + return surveyName; + } + + public void setSurveyName(String surveyName) { + this.surveyName = surveyName; + } + + public String getSurveyType() { + return surveyType; + } + + public void setSurveyType(String surveyType) { + this.surveyType = surveyType; + } + + public Integer getSurveyQuestionId() { + return surveyQuestionId; + } + + public void setSurveyQuestionId(Integer surveyQuestionId) { + this.surveyQuestionId = surveyQuestionId; + } + + public String getSurveyQuestion() { + return surveyQuestion; + } + + public void setSurveyQuestion(String surveyQuestion) { + this.surveyQuestion = surveyQuestion; + } + + public String getSurveyQuestionType() { + return surveyQuestionType; + } + + public void setSurveyQuestionType(String surveyQuestionType) { + this.surveyQuestionType = surveyQuestionType; + } + + public Integer getSurveyAnswerId() { + return surveyAnswerId; + } + + public void setSurveyAnswerId(Integer surveyAnswerId) { + this.surveyAnswerId = surveyAnswerId; + } + + public String getSurveyAnswer() { + return surveyAnswer; + } + + public void setSurveyAnswer(String surveyAnswer) { + this.surveyAnswer = surveyAnswer; + } + + public Boolean getImageAllow() { + return imageAllow; + } + + public void setImageAllow(Boolean imageAllow) { + this.imageAllow = imageAllow; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterSurveyUploadstatus.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterSurveyUploadstatus.java new file mode 100644 index 0000000..c29c1e2 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterSurveyUploadstatus.java @@ -0,0 +1,75 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class MasterSurveyUploadstatus { + + @SerializedName("CounterId") + @Expose + private Integer counterId; + @SerializedName("EmpId") + @Expose + private Integer empId; + @SerializedName("SurveyId") + @Expose + private Integer surveyId; + @SerializedName("SurveyType") + @Expose + private String surveyType; + @SerializedName("CounterSurveyUpload") + @Expose + private String counterSurveyUpload; + @SerializedName("BASurveyUpload") + @Expose + private String bASurveyUpload; + + public Integer getCounterId() { + return counterId; + } + + public void setCounterId(Integer counterId) { + this.counterId = counterId; + } + + public Integer getEmpId() { + return empId; + } + + public void setEmpId(Integer empId) { + this.empId = empId; + } + + public Integer getSurveyId() { + return surveyId; + } + + public void setSurveyId(Integer surveyId) { + this.surveyId = surveyId; + } + + public String getSurveyType() { + return surveyType; + } + + public void setSurveyType(String surveyType) { + this.surveyType = surveyType; + } + + public String getCounterSurveyUpload() { + return counterSurveyUpload; + } + + public void setCounterSurveyUpload(String counterSurveyUpload) { + this.counterSurveyUpload = counterSurveyUpload; + } + + public String getBASurveyUpload() { + return bASurveyUpload; + } + + public void setBASurveyUpload(String bASurveyUpload) { + this.bASurveyUpload = bASurveyUpload; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterTermsCondition.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterTermsCondition.java new file mode 100644 index 0000000..61aaef1 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/MasterTermsCondition.java @@ -0,0 +1,20 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class MasterTermsCondition { + + @SerializedName("TermsCondition") + @Expose + private String termsCondition; + + public String getTermsCondition() { + return termsCondition; + } + + public void setTermsCondition(String termsCondition) { + this.termsCondition = termsCondition; + } + +} \ No newline at end of file diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/NonPromotionReason.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/NonPromotionReason.java new file mode 100644 index 0000000..a25b345 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/NonPromotionReason.java @@ -0,0 +1,26 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; + +public class NonPromotionReason { + @Expose + private Integer pReasonId; + @Expose + private String pReason; + + public Integer getPReasonId() { + return pReasonId; + } + + public void setPReasonId(Integer pReasonId) { + this.pReasonId = pReasonId; + } + + public String getPReason() { + return pReason; + } + + public void setPReason(String pReason) { + this.pReason = pReason; + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/NonStockReason.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/NonStockReason.java new file mode 100644 index 0000000..08d8b77 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/NonStockReason.java @@ -0,0 +1,29 @@ + +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; + +public class NonStockReason { + + @Expose + private Integer reasonId; + @Expose + private String reason; + + public Integer getReasonId() { + return reasonId; + } + + public void setReasonId(Integer reasonId) { + this.reasonId = reasonId; + } + + public String getReason() { + return reason; + } + + public void setReason(String reason) { + this.reason = reason; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/NonStockReasonGetterSetter.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/NonStockReasonGetterSetter.java new file mode 100644 index 0000000..fdf7753 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/NonStockReasonGetterSetter.java @@ -0,0 +1,21 @@ + +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; + +import java.util.List; + +public class NonStockReasonGetterSetter { + + @Expose + private List nonStockReason = null; + + public List getNonStockReason() { + return nonStockReason; + } + + public void setNonStockReason(List nonStockReason) { + this.nonStockReason = nonStockReason; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/NonWorkingReason.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/NonWorkingReason.java new file mode 100644 index 0000000..e7fd7bf --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/NonWorkingReason.java @@ -0,0 +1,58 @@ + +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; + +public class NonWorkingReason { + + @Expose + private Integer reasonId; + @Expose + private String reason; + @Expose + private Boolean entryAllow; + @Expose + private Boolean imageAllow; + @Expose + private Boolean gPSMandatory; + + public Integer getReasonId() { + return reasonId; + } + + public void setReasonId(Integer reasonId) { + this.reasonId = reasonId; + } + + public String getReason() { + return reason; + } + + public void setReason(String reason) { + this.reason = reason; + } + + public Boolean getEntryAllow() { + return entryAllow; + } + + public void setEntryAllow(Boolean entryAllow) { + this.entryAllow = entryAllow; + } + + public Boolean getImageAllow() { + return imageAllow; + } + + public void setImageAllow(Boolean imageAllow) { + this.imageAllow = imageAllow; + } + + public Boolean getGPSMandatory() { + return gPSMandatory; + } + + public void setGPSMandatory(Boolean gPSMandatory) { + this.gPSMandatory = gPSMandatory; + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/NonWorkingReasonGetterSetter.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/NonWorkingReasonGetterSetter.java new file mode 100644 index 0000000..39c624a --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/NonWorkingReasonGetterSetter.java @@ -0,0 +1,83 @@ + +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; + +import java.util.List; + +public class NonWorkingReasonGetterSetter { + + @Expose + private List nonWorkingReason = null; + + public List getNonWorkingReason() { + return nonWorkingReason; + } + + @Expose + private List dashboardData = null; + + public List getDashboardData() { + return dashboardData; + } + + @Expose + private List promotionMaster = null; + + public List getPromotionMaster() { + return promotionMaster; + } + + @Expose + private List nonPromotionReason = null; + + public List getNonPromotionReason() { + return nonPromotionReason; + } + @Expose + private List consumerSalesHistory = null; + + public List getConsumerSalesHistory() { + return consumerSalesHistory; + } + + @Expose + private List attendanceHistory = null; + + public List getAttendanceHistory() { + return attendanceHistory; + } + @Expose + private List salesPerformance = null; + + public List getSalesPerformance() { + return salesPerformance; + } + + @Expose + private List dashboardAchivementDetail = null; + + public List getDashboardAchivementDetail() { + return dashboardAchivementDetail; + } + + @Expose + private List customerVisited = null; + + public List getCustomerVisited() { + return customerVisited; + } + + + @Expose + private List customerVisitedCurMonth = null; + + public List getCustomerVisitedCurMonth() { + return customerVisitedCurMonth; + } + + public void setCustomerVisitedCurMonth(List customerVisitedCurMonth) { + this.customerVisitedCurMonth = customerVisitedCurMonth; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/NoticeBoard.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/NoticeBoard.java new file mode 100644 index 0000000..3c1a35b --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/NoticeBoard.java @@ -0,0 +1,21 @@ + +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class NoticeBoard { + + @SerializedName("Notice_Board_Url") + @Expose + private String noticeBoardUrl; + + public String getNoticeBoardUrl() { + return noticeBoardUrl; + } + + public void setNoticeBoardUrl(String noticeBoardUrl) { + this.noticeBoardUrl = noticeBoardUrl; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/NoticeBoardGetterSetter.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/NoticeBoardGetterSetter.java new file mode 100644 index 0000000..923244a --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/NoticeBoardGetterSetter.java @@ -0,0 +1,21 @@ + +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; + +import java.util.List; + +public class NoticeBoardGetterSetter { + + @Expose + private List noticeBoard = null; + + public List getNoticeBoard() { + return noticeBoard; + } + + public void setNoticeBoard(List noticeBoard) { + this.noticeBoard = noticeBoard; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/NotificationData.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/NotificationData.java new file mode 100644 index 0000000..0fb95ef --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/NotificationData.java @@ -0,0 +1,68 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +public class NotificationData { + String title; + String body; + String path; + String visited_date; + String id=""; + String read_status = ""; + + public String getRead_status() { + return read_status; + } + + public void setRead_status(String read_status) { + this.read_status = read_status; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + String type; + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getBody() { + return body; + } + + public void setBody(String body) { + this.body = body; + } + + public String getPath() { + return path; + } + + public void setPath(String path) { + this.path = path; + } + + public String getVisited_date() { + return visited_date; + } + + public void setVisited_date(String visited_date) { + this.visited_date = visited_date; + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/NotificationsGetterSetter.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/NotificationsGetterSetter.java new file mode 100644 index 0000000..5b5dc0e --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/NotificationsGetterSetter.java @@ -0,0 +1,32 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +public class NotificationsGetterSetter { + String date; + String notifications; + + public String getDate() { + return date; + } + + public void setDate(String date) { + this.date = date; + } + + public String getNotifications() { + return notifications; + } + + public void setNotifications(String notifications) { + this.notifications = notifications; + } + + public String getSendar() { + return sendar; + } + + public void setSendar(String sendar) { + this.sendar = sendar; + } + + String sendar; +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/ProductMaster.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/ProductMaster.java new file mode 100644 index 0000000..3bce945 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/ProductMaster.java @@ -0,0 +1,561 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +import java.io.Serializable; + +public class ProductMaster implements Comparable, Serializable { + @SerializedName("ProductId") + @Expose + private Integer productId; + @SerializedName("LorealCode") + @Expose + private String lorealCode; + @SerializedName("ProductName") + @Expose + private String productName; + + @SerializedName("NuanceId") + @Expose + private Integer nuanceId; + @SerializedName("NuanceName") + @Expose + private String nuanceName; + @SerializedName("SubAxeId") + @Expose + private Integer subAxeId; + @SerializedName("SubAxeName") + @Expose + private String subAxeName; + @SerializedName("AxeId") + @Expose + private Integer axeId; + @SerializedName("AxeName") + @Expose + private String axeName; + @SerializedName("ReferenceId") + @Expose + private Integer referenceId; + @SerializedName("ReferenceName") + @Expose + private String referenceName; + @SerializedName("SubBrandId") + @Expose + private Integer subBrandId; + @SerializedName("SubBrandName") + @Expose + private String subBrandName; + @SerializedName("BrandId") + @Expose + private Integer brandId; + @SerializedName("BrandName") + @Expose + private String brandName; + @SerializedName("SignatureId") + @Expose + private Integer signatureId; + @SerializedName("SignatureName") + @Expose + private String signatureName; + + @SerializedName("EanCode") + @Expose + private String eanCode; + @SerializedName("Mrp") + @Expose + private Integer mrp; + + @SerializedName("VisitDate") + @Expose + private String visit_date; + + private String InvId= ""; + + public String getKeyId() { + return keyId; + } + + public void setKeyId(String keyId) { + this.keyId = keyId; + } + + String keyId = ""; + + public String getUploadStatus() { + return uploadStatus; + } + + public void setUploadStatus(String uploadStatus) { + this.uploadStatus = uploadStatus; + } + + String uploadStatus = ""; + + public String getInvId() { + return InvId; + } + + public void setInvId(String invId) { + InvId = invId; + } + + public String getProductType() { + return productType; + } + + public void setProductType(String productType) { + this.productType = productType; + } + + @SerializedName("ProductType") + @Expose + private String productType; + + private String actualQty = ""; + boolean confirmChecked = false; + private int reasonId = 0; + private String Transaction_Id=""; + private String Invoice_Status = "0"; + private String source = ""; + private String counter_id = ""; + private String invoice_number=""; + private String invoice_type=""; + private String user_id =""; + private String invoice_date = ""; + private String draft_status = ""; + private String upload_status = ""; + + public String getInvoice_img() { + return invoice_img; + } + + public void setInvoice_img(String invoice_img) { + this.invoice_img = invoice_img; + } + + private String invoice_img=""; + public String getUpload_status() { + return upload_status; + } + + public void setUpload_status(String upload_status) { + this.upload_status = upload_status; + } + + public String getDraft_status() { + return draft_status; + } + + public void setDraft_status(String draft_status) { + this.draft_status = draft_status; + } + + public String getInvoice_date() { + return invoice_date; + } + + public void setInvoice_date(String invoice_date) { + this.invoice_date = invoice_date; + } + + public String getUser_id() { + return user_id; + } + + public void setUser_id(String user_id) { + this.user_id = user_id; + } + + public String getInvoice_number() { + return invoice_number; + } + + public void setInvoice_number(String invoice_number) { + this.invoice_number = invoice_number; + } + + public String getInvoice_type() { + return invoice_type; + } + + public void setInvoice_type(String invoice_type) { + this.invoice_type = invoice_type; + } + + public String getCounter_id() { + return counter_id; + } + + public void setCounter_id(String counter_id) { + this.counter_id = counter_id; + } + + public String getSource() { + return source; + } + + public void setSource(String source) { + this.source = source; + } + + public String getTransaction_Id() { + return Transaction_Id; + } + + public void setTransaction_Id(String transaction_Id) { + Transaction_Id = transaction_Id; + } + + public String getInvoice_Status() { + return Invoice_Status; + } + + public void setInvoice_Status(String invoice_Status) { + Invoice_Status = invoice_Status; + } + + public int getReasonId() { + return reasonId; + } + + public void setReasonId(int reasonId) { + this.reasonId = reasonId; + } + + public boolean isConfirmChecked() { + return confirmChecked; + } + + public void setConfirmChecked(boolean confirmChecked) { + this.confirmChecked = confirmChecked; + } + + public String getActualQty() { + return actualQty; + } + + public void setActualQty(String actualQty) { + this.actualQty = actualQty; + } + + public String getImagePath() { + return imagePath; + } + + public void setImagePath(String imagePath) { + this.imagePath = imagePath; + } + + String imagePath = ""; + + public Integer getProductId() { + return productId; + } + + public String getEanCode() { + return eanCode; + } + + public void setEanCode(String eanCode) { + this.eanCode = eanCode; + } + + public Integer getMrp() { + return mrp; + } + + public void setMrp(Integer mrp) { + this.mrp = mrp; + } + + public void setProductId(Integer productId) { + this.productId = productId; + } + + public String getLorealCode() { + return lorealCode; + } + + public void setLorealCode(String lorealCode) { + this.lorealCode = lorealCode; + } + + public String getProductName() { + return productName; + } + + public void setProductName(String productName) { + this.productName = productName; + } + + + public Integer getNuanceId() { + return nuanceId; + } + + public void setNuanceId(Integer nuanceId) { + this.nuanceId = nuanceId; + } + + public String getNuanceName() { + return nuanceName; + } + + public void setNuanceName(String nuanceName) { + this.nuanceName = nuanceName; + } + + public Integer getSubAxeId() { + return subAxeId; + } + + public void setSubAxeId(Integer subAxeId) { + this.subAxeId = subAxeId; + } + + public String getSubAxeName() { + return subAxeName; + } + + public void setSubAxeName(String subAxeName) { + this.subAxeName = subAxeName; + } + + public Integer getAxeId() { + return axeId; + } + + public void setAxeId(Integer axeId) { + this.axeId = axeId; + } + + public String getAxeName() { + return axeName; + } + + public void setAxeName(String axeName) { + this.axeName = axeName; + } + + public Integer getReferenceId() { + return referenceId; + } + + public void setReferenceId(Integer referenceId) { + this.referenceId = referenceId; + } + + public String getReferenceName() { + return referenceName; + } + + public void setReferenceName(String referenceName) { + this.referenceName = referenceName; + } + + public Integer getSubBrandId() { + return subBrandId; + } + + public void setSubBrandId(Integer subBrandId) { + this.subBrandId = subBrandId; + } + + public String getSubBrandName() { + return subBrandName; + } + + public void setSubBrandName(String subBrandName) { + this.subBrandName = subBrandName; + } + + public Integer getBrandId() { + return brandId; + } + + public void setBrandId(Integer brandId) { + this.brandId = brandId; + } + + public String getBrandName() { + return brandName; + } + + public void setBrandName(String brandName) { + this.brandName = brandName; + } + + public Integer getSignatureId() { + return signatureId; + } + + public void setSignatureId(Integer signatureId) { + this.signatureId = signatureId; + } + + public String getSignatureName() { + return signatureName; + } + + public void setSignatureName(String signatureName) { + this.signatureName = signatureName; + } + + private int stock = -1; + private int stock_receive = 0; + + public int getSaleable_stock() { + return saleable_stock; + } + + public void setSaleable_stock(int saleable_stock) { + this.saleable_stock = saleable_stock; + } + + private int saleable_stock = 0; + + public int getBlockproductId() { + return blockproductId; + } + + public void setBlockproductId(int blockproductId) { + this.blockproductId = blockproductId; + } + + private int blockproductId=0; + private int resion_id = 0; + private String resion = ""; + + + public int getResion_id() { + return resion_id; + } + + public void setResion_id(int resion_id) { + this.resion_id = resion_id; + } + + public String getResion() { + return resion; + } + + public void setResion(String resion) { + this.resion = resion; + } + + public int getStock_receive() { + return stock_receive; + } + + public void setStock_receive(int stock_receive) { + this.stock_receive = stock_receive; + } + + public int getStock() { + return stock; + } + + public void setStock(int stock) { + this.stock = stock; + } + + public String getConsumer_name() { + return consumer_name; + } + + public void setConsumer_name(String consumer_name) { + this.consumer_name = consumer_name; + } + + String consumer_name; + + public String getVisit_date() { + return visit_date; + } + + public void setVisit_date(String visit_date) { + this.visit_date = visit_date; + } + + public String getConsumer_qty() { + return consumer_qty; + } + + public void setConsumer_qty(String consumer_qty) { + this.consumer_qty = consumer_qty; + } + + String consumer_qty; + + public String getMobile_no() { + return mobile_no; + } + + public void setMobile_no(String mobile_no) { + this.mobile_no = mobile_no; + } + + String mobile_no; + + boolean isSelected = false; + + public boolean isSelected() { + return isSelected; + } + + /** + * @param isSelected the isSelected to set + */ + public void setSelected(boolean isSelected) { + this.isSelected = isSelected; + } + + + @Override + public int compareTo(ProductMaster productMaster) { + return 0; + } + + public double getSaleValue() { + return saleValue; + } + + public void setSaleValue(double saleValue) { + this.saleValue = saleValue; + } + + public double saleValue =0.0; + + public int getMaster_transaction_id() { + return master_transaction_id; + } + + public void setMaster_transaction_id(int master_transaction_id) { + this.master_transaction_id = master_transaction_id; + } + + int master_transaction_id=0; + String stock_type=""; + + public String getStock_type() { + return stock_type; + } + + public void setStock_type(String stock_type) { + this.stock_type = stock_type; + } + + public String getEntry_type() { + return entry_type; + } + + public void setEntry_type(String entry_type) { + this.entry_type = entry_type; + } + + String entry_type=""; + + +} + diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/ProfileDetail.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/ProfileDetail.java new file mode 100644 index 0000000..95ddfc3 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/ProfileDetail.java @@ -0,0 +1,87 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; +import com.google.gson.annotations.Expose; + +public class ProfileDetail { + + @Expose + private Integer empId; + @Expose + private String userId; + @Expose + private String employeeName; + @Expose + private String designationName; + @Expose + private String storeName; + @Expose + private String address; + @Expose + private String cityName; + @Expose + private String profilePic; + + public Integer getEmpId() { + return empId; + } + + public void setEmpId(Integer empId) { + this.empId = empId; + } + + public String getUserId() { + return userId; + } + + public void setUserId(String userId) { + this.userId = userId; + } + + public String getEmployeeName() { + return employeeName; + } + + public void setEmployeeName(String employeeName) { + this.employeeName = employeeName; + } + + public String getDesignationName() { + return designationName; + } + + public void setDesignationName(String designationName) { + this.designationName = designationName; + } + + public String getStoreName() { + return storeName; + } + + public void setStoreName(String storeName) { + this.storeName = storeName; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } + + public String getCityName() { + return cityName; + } + + public void setCityName(String cityName) { + this.cityName = cityName; + } + + public String getProfilePic() { + return profilePic; + } + + public void setProfilePic(String profilePic) { + this.profilePic = profilePic; + } + +} \ No newline at end of file diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/PromotionGetterSetter.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/PromotionGetterSetter.java new file mode 100644 index 0000000..a66df7b --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/PromotionGetterSetter.java @@ -0,0 +1,68 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +public class PromotionGetterSetter { + String promotion_name; + String posm_exists_state=""; + String posm_img=""; + String posm_qr_data=""; + + public String getPromotion_name() { + return promotion_name; + } + + public void setPromotion_name(String promotion_name) { + this.promotion_name = promotion_name; + } + + public String getPosm_exists_state() { + return posm_exists_state; + } + + public void setPosm_exists_state(String posm_exists_state) { + this.posm_exists_state = posm_exists_state; + } + + public String getPosm_img() { + return posm_img; + } + + public void setPosm_img(String posm_img) { + this.posm_img = posm_img; + } + + public String getPosm_qr_data() { + return posm_qr_data; + } + + public void setPosm_qr_data(String posm_qr_data) { + this.posm_qr_data = posm_qr_data; + } + + public String getPosm_currect_ans() { + return posm_currect_ans; + } + + public void setPosm_currect_ans(String posm_currect_ans) { + this.posm_currect_ans = posm_currect_ans; + } + + public String getReason_name() { + return reason_name; + } + + public void setReason_name(String reason_name) { + this.reason_name = reason_name; + } + + public String getReason_Id() { + return reason_Id; + } + + public void setReason_Id(String reason_Id) { + this.reason_Id = reason_Id; + } + + String posm_currect_ans=""; + String reason_name=""; + String reason_Id="0"; +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/PromotionMaster.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/PromotionMaster.java new file mode 100644 index 0000000..f327470 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/PromotionMaster.java @@ -0,0 +1,175 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; + +public class PromotionMaster { + @Expose + private Integer promotionId; + @Expose + private String promotionName; + @Expose + private Integer promotionTypeId; + @Expose + private String promotionType; + @Expose + private Integer counterGroupId; + @Expose + private String counterGroupName; + @Expose + private Integer productClusterId; + @Expose + private String productCluster; + @Expose + private String startDate; + @Expose + private String imageName; + @Expose + private String endDate; + @Expose + private String url; + + public Integer getPromotionId() { + return promotionId; + } + + public void setPromotionId(Integer promotionId) { + this.promotionId = promotionId; + } + + public String getPromotionName() { + return promotionName; + } + + public void setPromotionName(String promotionName) { + this.promotionName = promotionName; + } + + public Integer getPromotionTypeId() { + return promotionTypeId; + } + + public void setPromotionTypeId(Integer promotionTypeId) { + this.promotionTypeId = promotionTypeId; + } + + public String getPromotionType() { + return promotionType; + } + + public void setPromotionType(String promotionType) { + this.promotionType = promotionType; + } + + public Integer getCounterGroupId() { + return counterGroupId; + } + + public void setCounterGroupId(Integer counterGroupId) { + this.counterGroupId = counterGroupId; + } + + public String getCounterGroupName() { + return counterGroupName; + } + + public void setCounterGroupName(String counterGroupName) { + this.counterGroupName = counterGroupName; + } + + public Integer getProductClusterId() { + return productClusterId; + } + + public void setProductClusterId(Integer productClusterId) { + this.productClusterId = productClusterId; + } + + public String getProductCluster() { + return productCluster; + } + + public void setProductCluster(String productCluster) { + this.productCluster = productCluster; + } + + public String getStartDate() { + return startDate; + } + + public void setStartDate(String startDate) { + this.startDate = startDate; + } + + public String getImageName() { + return imageName; + } + + public void setImageName(String imageName) { + this.imageName = imageName; + } + + public String getEndDate() { + return endDate; + } + + public void setEndDate(String endDate) { + this.endDate = endDate; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + String promotion_exists_state =""; + String promotion_img =""; + String promotion_qr_data =""; + + public String getPromotion_exists_state() { + return promotion_exists_state; + } + + public void setPromotion_exists_state(String promotion_exists_state) { + this.promotion_exists_state = promotion_exists_state; + } + + public String getPromotion_img() { + return promotion_img; + } + + public void setPromotion_img(String promotion_img) { + this.promotion_img = promotion_img; + } + + public String getPromotion_qr_data() { + return promotion_qr_data; + } + + public void setPromotion_qr_data(String promotion_qr_data) { + this.promotion_qr_data = promotion_qr_data; + } + + public String getPromotion_currect_ans() { + return promotion_currect_ans; + } + + public void setPromotion_currect_ans(String promotion_currect_ans) { + this.promotion_currect_ans = promotion_currect_ans; + } + + String promotion_currect_ans =""; + + public String getPromotion_currect_ans_Id() { + return promotion_currect_ans_Id; + } + + public void setPromotion_currect_ans_Id(String promotion_currect_ans_Id) { + this.promotion_currect_ans_Id = promotion_currect_ans_Id; + } + + String promotion_currect_ans_Id =""; + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/ReportDamageStockHistory.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/ReportDamageStockHistory.java new file mode 100644 index 0000000..046b8d7 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/ReportDamageStockHistory.java @@ -0,0 +1,106 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class ReportDamageStockHistory { + @SerializedName("CounterId") + @Expose + private Integer counterId; + @SerializedName("VisitDate") + @Expose + private String visitDate; + @SerializedName("ProductCode") + @Expose + private String productCode; + @SerializedName("ProductName") + @Expose + private String productName; + @SerializedName("EanCode") + @Expose + private String eanCode; + @SerializedName("Mrp") + @Expose + private Double mrp; + @SerializedName("DamageQty") + @Expose + private Integer damageQty; + @SerializedName("Verify") + @Expose + private String verify; + @SerializedName("VerifyDate") + @Expose + private String verifyDate; + + public Integer getCounterId() { + return counterId; + } + + public void setCounterId(Integer counterId) { + this.counterId = counterId; + } + + public String getVisitDate() { + return visitDate; + } + + public void setVisitDate(String visitDate) { + this.visitDate = visitDate; + } + + public String getProductCode() { + return productCode; + } + + public void setProductCode(String productCode) { + this.productCode = productCode; + } + + public String getProductName() { + return productName; + } + + public void setProductName(String productName) { + this.productName = productName; + } + + public String getEanCode() { + return eanCode; + } + + public void setEanCode(String eanCode) { + this.eanCode = eanCode; + } + + public Double getMrp() { + return mrp; + } + + public void setMrp(Double mrp) { + this.mrp = mrp; + } + + public Integer getDamageQty() { + return damageQty; + } + + public void setDamageQty(Integer damageQty) { + this.damageQty = damageQty; + } + + public String getVerify() { + return verify; + } + + public void setVerify(String verify) { + this.verify = verify; + } + + public String getVerifyDate() { + return verifyDate; + } + + public void setVerifyDate(String verifyDate) { + this.verifyDate = verifyDate; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/ReportMESale.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/ReportMESale.java new file mode 100644 index 0000000..51f4fc5 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/ReportMESale.java @@ -0,0 +1,68 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class ReportMESale { + + @SerializedName("CounterCode") + @Expose + private String counterCode; + + @SerializedName("CounterName") + @Expose + private String counterName; + + @SerializedName("VisitDate") + @Expose + private String visitDate; + + @SerializedName("TotalUnitSale") + @Expose + private Integer totalunitsale; + + @SerializedName("TotalSale") + @Expose + private Double totalsale; + + public String getCounterCode() { + return counterCode; + } + + public void setCounterCode(String counterCode) { + this.counterCode = counterCode; + } + + public String getCounterName() { + return counterName; + } + + public void setCounterName(String counterName) { + this.counterName = counterName; + } + + public String getVisitDate() { + return visitDate; + } + + public void setVisitDate(String visitDate) { + this.visitDate = visitDate; + } + + public Integer getTotalunitsale() { + return totalunitsale; + } + + public void setTotalunitsale(Integer totalunitsale) { + this.totalunitsale = totalunitsale; + } + + public Double getTotalsale() { + return totalsale; + } + + public void setTotalsale(Double totalsale) { + this.totalsale = totalsale; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/ReportMTDWorkingCounterME.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/ReportMTDWorkingCounterME.java new file mode 100644 index 0000000..fad3e22 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/ReportMTDWorkingCounterME.java @@ -0,0 +1,36 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; +import com.google.gson.annotations.SerializedName; + +public class ReportMTDWorkingCounterME { + @SerializedName("VisitDate") + private String visitDate; + @SerializedName("CounterCode") + private String counterCode; + @SerializedName("CounterName") + private String counterName; + + public String getVisitDate() { + return visitDate; + } + + public void setVisitDate(String visitDate) { + this.visitDate = visitDate; + } + + public String getCounterCode() { + return counterCode; + } + + public void setCounterCode(String counterCode) { + this.counterCode = counterCode; + } + + public String getCounterName() { + return counterName; + } + + public void setCounterName(String counterName) { + this.counterName = counterName; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/ReportProductGroupWiseSalesValue.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/ReportProductGroupWiseSalesValue.java new file mode 100644 index 0000000..6f16409 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/ReportProductGroupWiseSalesValue.java @@ -0,0 +1,86 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class ReportProductGroupWiseSalesValue { + + @SerializedName("CounterId") + @Expose + private Integer counterId; + @SerializedName("ProductGroupId") + @Expose + private Integer productGroupId; + @SerializedName("ProductGroupName") + @Expose + private String productGroupName; + @SerializedName("MTDTg") + @Expose + private Double mTDTg; + @SerializedName("MTDAch") + @Expose + private Double mTDAch; + @SerializedName("AchPer") + @Expose + private Double achPer; + @SerializedName("Pending") + @Expose + private Double pending; + + public Integer getCounterId() { + return counterId; + } + + public void setCounterId(Integer counterId) { + this.counterId = counterId; + } + + public Integer getProductGroupId() { + return productGroupId; + } + + public void setProductGroupId(Integer productGroupId) { + this.productGroupId = productGroupId; + } + + public String getProductGroupName() { + return productGroupName; + } + + public void setProductGroupName(String productGroupName) { + this.productGroupName = productGroupName; + } + + public Double getMTDTg() { + return mTDTg; + } + + public void setMTDTg(Double mTDTg) { + this.mTDTg = mTDTg; + } + + public Double getMTDAch() { + return mTDAch; + } + + public void setMTDAch(Double mTDAch) { + this.mTDAch = mTDAch; + } + + public Double getAchPer() { + return achPer; + } + + public void setAchPer(Double achPer) { + this.achPer = achPer; + } + + public Double getPending() { + return pending; + } + + public void setPending(Double pending) { + this.pending = pending; + } + +} \ No newline at end of file diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/ReportSalesConsumerProductwise.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/ReportSalesConsumerProductwise.java new file mode 100644 index 0000000..b329272 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/ReportSalesConsumerProductwise.java @@ -0,0 +1,88 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +import java.io.Serializable; + +public class ReportSalesConsumerProductwise implements Serializable { + + @SerializedName("CounterId") + @Expose + private Integer counterId; + @SerializedName("VisitDate") + @Expose + private String visitDate; + @SerializedName("Week_Day") + @Expose + private String weekDay; + @SerializedName("TId") + @Expose + private Integer tId; + @SerializedName("ProductName") + @Expose + private String productName; + @SerializedName("Qty") + @Expose + private Integer qty; + @SerializedName("SalesValue") + @Expose + private Double salesValue; + + public Integer getCounterId() { + return counterId; + } + + public void setCounterId(Integer counterId) { + this.counterId = counterId; + } + + public String getVisitDate() { + return visitDate; + } + + public void setVisitDate(String visitDate) { + this.visitDate = visitDate; + } + + public String getWeekDay() { + return weekDay; + } + + public void setWeekDay(String weekDay) { + this.weekDay = weekDay; + } + + public Integer getTId() { + return tId; + } + + public void setTId(Integer tId) { + this.tId = tId; + } + + public String getProductName() { + return productName; + } + + public void setProductName(String productName) { + this.productName = productName; + } + + public Integer getQty() { + return qty; + } + + public void setQty(Integer qty) { + this.qty = qty; + } + + public Double getSalesValue() { + return salesValue; + } + + public void setSalesValue(Double salesValue) { + this.salesValue = salesValue; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/ReportSalesConsumerWise.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/ReportSalesConsumerWise.java new file mode 100644 index 0000000..3ab0243 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/ReportSalesConsumerWise.java @@ -0,0 +1,98 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +import java.io.Serializable; + +public class ReportSalesConsumerWise implements Serializable { + @SerializedName("CounterId") + @Expose + private Integer counterId; + @SerializedName("VisitDate") + @Expose + private String visitDate; + @SerializedName("WeekDays") + @Expose + private String weekDays; + @SerializedName("TId") + @Expose + private Integer tId; + @SerializedName("ConsumerName") + @Expose + private String consumerName; + @SerializedName("MobileNumber") + @Expose + private String mobileNumber; + @SerializedName("Qty") + @Expose + private Integer qty; + @SerializedName("SalesValue") + @Expose + private Double salesValue; + + public Integer getCounterId() { + return counterId; + } + + public void setCounterId(Integer counterId) { + this.counterId = counterId; + } + + public String getVisitDate() { + return visitDate; + } + + public void setVisitDate(String visitDate) { + this.visitDate = visitDate; + } + + public String getWeekDays() { + return weekDays; + } + + public void setWeekDays(String weekDays) { + this.weekDays = weekDays; + } + + public Integer getTId() { + return tId; + } + + public void setTId(Integer tId) { + this.tId = tId; + } + + public String getConsumerName() { + return consumerName; + } + + public void setConsumerName(String consumerName) { + this.consumerName = consumerName; + } + + public String getMobileNumber() { + return mobileNumber; + } + + public void setMobileNumber(String mobileNumber) { + this.mobileNumber = mobileNumber; + } + + public Integer getQty() { + return qty; + } + + public void setQty(Integer qty) { + this.qty = qty; + } + + public Double getSalesValue() { + return salesValue; + } + + public void setSalesValue(Double salesValue) { + this.salesValue = salesValue; + } + +} \ No newline at end of file diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/ReportSalesDateWise.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/ReportSalesDateWise.java new file mode 100644 index 0000000..f97455a --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/ReportSalesDateWise.java @@ -0,0 +1,64 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class ReportSalesDateWise { + + @SerializedName("CounterId") + @Expose + private Integer counterId; + @SerializedName("VisitDate") + @Expose + private String visitDate; + @SerializedName("WeekDays") + @Expose + private String weekDays; + @SerializedName("Qty") + @Expose + private Integer qty; + @SerializedName("SalesValue") + @Expose + private Double salesValue; + + public Integer getCounterId() { + return counterId; + } + + public void setCounterId(Integer counterId) { + this.counterId = counterId; + } + + public String getVisitDate() { + return visitDate; + } + + public void setVisitDate(String visitDate) { + this.visitDate = visitDate; + } + + public String getWeekDays() { + return weekDays; + } + + public void setWeekDays(String weekDays) { + this.weekDays = weekDays; + } + + public Integer getQty() { + return qty; + } + + public void setQty(Integer qty) { + this.qty = qty; + } + + public Double getSalesValue() { + return salesValue; + } + + public void setSalesValue(Double salesValue) { + this.salesValue = salesValue; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/ReportSalesDetail.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/ReportSalesDetail.java new file mode 100644 index 0000000..a472874 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/ReportSalesDetail.java @@ -0,0 +1,61 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class ReportSalesDetail { + + @SerializedName("CounterId") + @Expose + private Integer counterId; + @SerializedName("ProductId") + @Expose + private Integer productId; + @SerializedName("Qty") + @Expose + private Integer qty; + @SerializedName("SalesValue") + @Expose + private Double salesValue; + + public Integer getCounterId() { + return counterId; + } + + public void setCounterId(Integer counterId) { + this.counterId = counterId; + } + + public Integer getProductId() { + return productId; + } + + public void setProductId(Integer productId) { + this.productId = productId; + } + + public Integer getQty() { + return qty; + } + + public void setQty(Integer qty) { + this.qty = qty; + } + + public Double getSalesValue() { + return salesValue; + } + + public void setSalesValue(Double salesValue) { + this.salesValue = salesValue; + } + String productName=""; + + public String getProductName() { + return productName; + } + + public void setProductName(String productName) { + this.productName = productName; + } +} \ No newline at end of file diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/ReportSalesL3MValue.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/ReportSalesL3MValue.java new file mode 100644 index 0000000..6eada00 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/ReportSalesL3MValue.java @@ -0,0 +1,40 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class ReportSalesL3MValue { + @SerializedName("Month") + @Expose + private String month; + @SerializedName("Qty") + @Expose + private Integer qty; + @SerializedName("SalesValue") + @Expose + private double salesValue; + public String getMonth() { + return month; + } + + public void setMonth(String month) { + this.month = month; + } + + public Integer getQty() { + return qty; + } + + public void setQty(Integer qty) { + this.qty = qty; + } + + public double getSalesValue() { + return salesValue; + } + + public void setSalesValue(double salesValue) { + this.salesValue = salesValue; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/ReportsGetterSetter.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/ReportsGetterSetter.java new file mode 100644 index 0000000..0cf0ca4 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/ReportsGetterSetter.java @@ -0,0 +1,69 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +public class ReportsGetterSetter { +String report_date; + String sale_value; + String selected_attendance; + String intime_outtime; + String incentive; + + public String getSelected_attendance() { + return selected_attendance; + } + + public void setSelected_attendance(String selected_attendance) { + this.selected_attendance = selected_attendance; + } + + public String getIntime_outtime() { + return intime_outtime; + } + + public void setIntime_outtime(String intime_outtime) { + this.intime_outtime = intime_outtime; + } + + public String getIncentive() { + return incentive; + } + + public void setIncentive(String incentive) { + this.incentive = incentive; + } + + public String getIncentive_value_name() { + return incentive_value_name; + } + + public void setIncentive_value_name(String incentive_value_name) { + this.incentive_value_name = incentive_value_name; + } + + String incentive_value_name; +int color_code; + + public int getColor_code() { + return color_code; + } + + public void setColor_code(int color_code) { + this.color_code = color_code; + } + + public String getReport_date() { + return report_date; + } + + public void setReport_date(String report_date) { + this.report_date = report_date; + } + + public String getSale_value() { + return sale_value; + } + + public void setSale_value(String sale_value) { + this.sale_value = sale_value; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/ResponseResult.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/ResponseResult.java new file mode 100644 index 0000000..c2f5cdf --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/ResponseResult.java @@ -0,0 +1,396 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.SerializedName; +import com.cpm.lorealbaautomation.gettersetter.MasterCompetitionOffer; +import com.cpm.lorealbaautomation.gettersetter.MasterCompetitionOfferSaleRange; +import com.cpm.lorealbaautomation.gsonGetterSetter.batbasale.BATBAPromoSale; +import com.cpm.lorealbaautomation.gsonGetterSetter.batbasale.BATBASale; +import com.cpm.lorealbaautomation.gsonGetterSetter.countervolune.ReportConterValue; +import com.cpm.lorealbaautomation.gsonGetterSetter.countervolune.ReportConterValueDetail; +import com.cpm.lorealbaautomation.gsonGetterSetter.countervolune.ReportCounterVolume; +import com.cpm.lorealbaautomation.gsonGetterSetter.countervolune.ReportCounterVolumeDetail; +import com.cpm.lorealbaautomation.gsonGetterSetter.inwordDetail.ReportCounterInwardStock; +import com.cpm.lorealbaautomation.gsonGetterSetter.inwordDetail.ReportCounterInwardStockDetail; +import com.cpm.lorealbaautomation.gsonGetterSetter.leaves.MasterHoliday; +import com.cpm.lorealbaautomation.gsonGetterSetter.leaves.TLeaveLedgerSummary; +import com.cpm.lorealbaautomation.gsonGetterSetter.leaves.TLeaveRequestDetail; +import com.cpm.lorealbaautomation.gsonGetterSetter.stockledger.ReportCounterStockLedger; +import com.cpm.lorealbaautomation.gsonGetterSetter.stockledger.ReportCounterStockLedgerDetail; +import com.cpm.lorealbaautomation.reportGetterSetter.AppDashboardIncentive; +import com.cpm.lorealbaautomation.reportGetterSetter.AppDashboardLeaderBoard; +import com.cpm.lorealbaautomation.reports.dailyTva.DailyTVA; +import com.cpm.lorealbaautomation.reports.offtakemodels.L3MOffTakeCounter; +import com.cpm.lorealbaautomation.reports.offtakemodels.L3MOffTakeNuance; +import com.cpm.lorealbaautomation.reports.offtakemodels.L3MOffTakeSubAxe; +import com.cpm.lorealbaautomation.reports.offtakemodels.SalesGrowthCounter; +import com.cpm.lorealbaautomation.reports.offtakemodels.SalesGrowthSubAxe; +import com.cpm.lorealbaautomation.reports.testerdetails.ReportTesterCounterDetail; + +import java.util.List; + +public class ResponseResult { + @SerializedName("Report_DamageStockHistory") + private List reportDamageStockHistory = null; + + public List getReportDamageStockHistory() { + return reportDamageStockHistory; + } + @SerializedName("Report_SalesL3MValue") + private List reportSalesL3MValue = null; + public List getReportSalesL3MValue() { + return reportSalesL3MValue; + } + + @SerializedName("Report_SalesL3MValueME") + private List reportSalesL3MValueMe = null; + + public List getReportSalesL3MValueMe() { + return reportSalesL3MValueMe; + } + + @SerializedName("Master_Promotion") + private List masterPromotion = null; + + public List getMasterPromotion() { + return masterPromotion; + } + + @SerializedName("Master_PromotionSetEntityItem") + + private List masterPromotionSetEntityItem = null; + + public List getMasterPromotionSetEntityItem() { + return masterPromotionSetEntityItem; + } + + + @SerializedName("Master_PromotionGetEntityItem") + + private List masterPromotionGetEntityItem = null; + + public List getMasterPromotionGetEntityItem() { + return masterPromotionGetEntityItem; + } + + + @SerializedName("Master_PromotionSetProductGroup") + + private List masterPromotionSetProductGroup = null; + + public List getMasterPromotionSetProductGroup() { + return masterPromotionSetProductGroup; + } + + @SerializedName("Master_PromotionGetProductGroup") + + private List masterPromotionGetProductGroup = null; + + public List getMasterPromotionGetProductGroup() { + return masterPromotionGetProductGroup; + } + + + @SerializedName("Master_Survey") + + private List masterSurvey = null; + + public List getMasterSurvey() { + return masterSurvey; + } + + + @SerializedName("Master_LeaveType") + + private List masterLeaveType = null; + + public List getMasterLeaveType() { + return masterLeaveType; + } + + @SerializedName("Damage_ReturnToDistributor") + + private List damageReturnToDistributor = null; + + public List getDamageReturnToDistributor() { + return damageReturnToDistributor; + } + + @SerializedName("Master_Survey_UploadStatus") + + private List masterSurveyUploadStatus = null; + + public List getMasterSurveyUploadStatus() { + return masterSurveyUploadStatus; + } + + @SerializedName("Master_PromotionSetProductCatalog") + + private List masterPromotionSetProductCatalog = null; + + public List getMasterPromotionSetProductCatalog() { + return masterPromotionSetProductCatalog; + } + @SerializedName("Master_PromotionGetProductCatalog") + + private List masterPromotionGetProductCatalog = null; + + public List getMasterPromotionGetProductCatalog() { + return masterPromotionGetProductCatalog; + } + @SerializedName("Report_ProductGroupWiseSalesValue") + + private List reportProductGroupWiseSalesValue = null; + + public List getReportProductGroupWiseSalesValue() { + return reportProductGroupWiseSalesValue; + } + + @SerializedName("Report_SalesDateWise") + private List reportSalesDateWise = null; + public List getReportSalesDateWise() { + return reportSalesDateWise; + } + @SerializedName("Report_SalesDateWiseME") + private List reportSalesDateWiseMe = null; + public List getReportSalesDateWiseMe() { + return reportSalesDateWiseMe; + } + @SerializedName("Damage_PreviousPending") + + private List damagePreviousPending = null; + + public List getDamagePreviousPending() { + return damagePreviousPending; + } + + @SerializedName("Master_PromotionGetExclusionList") + + private List masterPromotionGetExclusionList = null; + + public List getMasterPromotionGetExclusionList() { + return masterPromotionGetExclusionList; + } + @SerializedName("Master_PromotionSetExclusionList") + + private List masterPromotionSetExclusionList = null; + + public List getMasterPromotionSetExclusionList() { + return masterPromotionSetExclusionList; + } + @SerializedName("Master_SourcesOfSales") + + private List masterSourcesOfSales = null; + + public List getMasterSourcesOfSales() { + return masterSourcesOfSales; + } + + @SerializedName("Master_CompetitonBrandWiseNuance") + + private List masterCompetitonBrandWiseNuance = null; + + public List getMasterCompetitonBrandWiseNuance() { + return masterCompetitonBrandWiseNuance; + } + + @SerializedName("Master_CompetitionOfferSet") + private List masterCompetitionOfferSet = null; + public List getMasterCompetitionOfferSet() { + return masterCompetitionOfferSet; + } + @SerializedName("Master_CompetitionOfferGet") + private List masterCompetitionOfferGet = null; + public List getMasterCompetitionOfferGet() { + return masterCompetitionOfferGet; + } + @SerializedName("Master_CompetitionPromoType") + private List masterCompetitionPromoType = null; + public List getMasterCompetitionPromoType() { + return masterCompetitionPromoType; + } + + @SerializedName("Master_CompetitionProductType") + private List masterCompetitionProductType = null; + public List getMasterCompetitionProductType() { + return masterCompetitionProductType; + } + public List getMastercompetitionoffer() { + return mastercompetitionoffer; + } + + public void setMastercompetitionoffer(List mastercompetitionoffer) { + this.mastercompetitionoffer = mastercompetitionoffer; + } + + @SerializedName("Master_CompetitionOffer") + private List mastercompetitionoffer = null; + + + @SerializedName("Master_CompetitionOfferSaleRange") + private List masterCompetitionOfferSaleRange = null; + public List getMasterCompetitionOfferSaleRange() { + return masterCompetitionOfferSaleRange; + } + public List getMasterRetailExcellenceList() { + return masterRetailExcellenceList; + } + @SerializedName("Master_RetailExcellence_Item") + private List masterRetailExcellenceList = null; + + @SerializedName("Report_MTD_WorkingCounterME") + private List reportMTDWorkingCounterME; + public List getReportMTDWorkingCounterME() { + return reportMTDWorkingCounterME; + } + + @SerializedName("AppDashboard_TVA") + private List appDashboardTVA; + public List getAppDashboardTVA() { + return appDashboardTVA; + } + + @SerializedName("AppDashboard_TVADrillDown") + private List appDashboardTVADrillDown; + public List getAppDashboardTVADrillDown() { + return appDashboardTVADrillDown; + } + + @SerializedName("AppDashboard_LeaderBoard") + private List appDashboardLeaderBoard; + public List getAppDashboardLeaderBoard() { + return appDashboardLeaderBoard; + } + + @SerializedName("AppDashboard_Incentive") + private List appDashboardIncentive; + + public List getAppDashboardIncentive() { + return appDashboardIncentive; + } + + @SerializedName("AppDashboard_L3MOffTake_Counter") + private List l3MOffTakeCounter; + public List getL3MOffTakeCounter() { + return l3MOffTakeCounter; + } + + @SerializedName("AppDashboard_L3MOffTake_Nuance") + private List l3MOffTakeNuance; + + public List getL3MOffTakeNuance() { + return l3MOffTakeNuance; + } + + @SerializedName("AppDashboard_L3MOffTake_SubAxe") + private List l3MOffTakeSubAxe; + + public List getL3MOffTakeSubAxe() { + return l3MOffTakeSubAxe; + } + + @SerializedName("ReportDaily_TVA") + private List reportDailyTVA; + + public List getReportDailyTVA() { + return reportDailyTVA; + } + + @SerializedName("Report_SalesGrowth_Counter") + private List reportSalesGrowthCounter; + + public List getReportSalesGrowthCounter() { + return reportSalesGrowthCounter; + } + @SerializedName("Report_SalesGrowth_CounterDetail") + private List reportSalesGrowthSubAxe; + public List getReportSalesGrowthSubAxe() { + return reportSalesGrowthSubAxe; + } + @SerializedName("Report_TesterCounterDetail") + private List reportTesterCounterDetail; + public List getReportTesterCounterDetail() { + return reportTesterCounterDetail; + } + @SerializedName("Report_CounterVolume") + private List reportCounterVolume; + public List getReportCounterVolume() { + return reportCounterVolume; + } + @SerializedName("Report_CounterVolumeDetail") + private List reportCounterVolumeDetail; + + public List getReportCounterVolumeDetail() { + return reportCounterVolumeDetail; + } + @SerializedName("Report_ConterValue") + private List reportConterValue; + + public List getReportConterValue() { + return reportConterValue; + } + + @SerializedName("Report_ConterValueDetail") + private List reportConterValueDetail; + public List getReportConterValueDetail() { + return reportConterValueDetail; + } + + @SerializedName("Report_CounterInwardStock") + private List reportCounterInwardStock; + + public List getReportCounterInwardStock() { + return reportCounterInwardStock; + } + @SerializedName("Report_CounterInwardStockDetail") + private List reportCounterInwardStockDetail; + + public List getReportCounterInwardStockDetail() { + return reportCounterInwardStockDetail; + } + + @SerializedName("Report_CounterStockLedger") + private List reportCounterStockLedger; + + public List getReportCounterStockLedger() { + return reportCounterStockLedger; + } + @SerializedName("Report_CounterStockLedgerDetail") + private List reportCounterStockLedgerDetail; + + public List getReportCounterStockLedgerDetail() { + return reportCounterStockLedgerDetail; + } + + @SerializedName("Report_BA_TBASale") + private List reportBATBASale; + public List gettBATBASale() { + return reportBATBASale; + } + + @SerializedName("Report_BA_TBAPromoSale") + private List reportBATBAPromoSale; + public List gettBATBAPromoSale() { + return reportBATBAPromoSale; + } + + @SerializedName("T_LeaveRequestDetail") + private List tLeaveRequestDetail; + + public List getTLeaveRequestDetail() { + return tLeaveRequestDetail; + } + @SerializedName("Master_HolidayList") + private List masterHolidayList; + + public List getMasterHolidayList() { + return masterHolidayList; + } + + @SerializedName("T_LeaveLedgerSummary") + private List tLeaveLedgerSummary; + + public List getTLeaveLedgerSummary() { + return tLeaveLedgerSummary; + } + +} \ No newline at end of file diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/SalesPerformance.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/SalesPerformance.java new file mode 100644 index 0000000..bd15da4 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/SalesPerformance.java @@ -0,0 +1,48 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; + +public class SalesPerformance { + @Expose + private String counterName; + @Expose + private String date; + @Expose + private Integer totalQty; + @Expose + private Integer totalSales; + + public String getCounterName() { + return counterName; + } + + public void setCounterName(String counterName) { + this.counterName = counterName; + } + + public String getDate() { + return date; + } + + public void setDate(String date) { + this.date = date; + } + + public Integer getTotalQty() { + return totalQty; + } + + public void setTotalQty(Integer totalQty) { + this.totalQty = totalQty; + } + + public Integer getTotalSales() { + return totalSales; + } + + public void setTotalSales(Integer totalSales) { + this.totalSales = totalSales; + } + + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/SampleGetterSetter.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/SampleGetterSetter.java new file mode 100644 index 0000000..1bb9092 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/SampleGetterSetter.java @@ -0,0 +1,68 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +public class SampleGetterSetter { + String sample_name; + String img_one=""; + + public String getSample_name() { + return sample_name; + } + + public void setSample_name(String sample_name) { + this.sample_name = sample_name; + } + + public String getImg_one() { + return img_one; + } + + public void setImg_one(String img_one) { + this.img_one = img_one; + } + + public String getImg_two() { + return img_two; + } + + public void setImg_two(String img_two) { + this.img_two = img_two; + } + + public String getImg_three() { + return img_three; + } + + public void setImg_three(String img_three) { + this.img_three = img_three; + } + + public String getImg_four() { + return img_four; + } + + public void setImg_four(String img_four) { + this.img_four = img_four; + } + + public String getLast_entered_value() { + return last_entered_value; + } + + public void setLast_entered_value(String last_entered_value) { + this.last_entered_value = last_entered_value; + } + + public String getCurrent_stock() { + return current_stock; + } + + public void setCurrent_stock(String current_stock) { + this.current_stock = current_stock; + } + + String img_two=""; + String img_three=""; + String img_four=""; + String last_entered_value=""; + String current_stock=""; +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/ServerTime.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/ServerTime.java new file mode 100644 index 0000000..15c068b --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/ServerTime.java @@ -0,0 +1,31 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class ServerTime { + + @SerializedName("ServerDate") + @Expose + private String serverDate; + @SerializedName("ServerTime") + @Expose + private String serverTime; + + public String getServerDate() { + return serverDate; + } + + public void setServerDate(String serverDate) { + this.serverDate = serverDate; + } + + public String getServerTime() { + return serverTime; + } + + public void setServerTime(String serverTime) { + this.serverTime = serverTime; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/ServerTimeGetterSetter.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/ServerTimeGetterSetter.java new file mode 100644 index 0000000..98fee6b --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/ServerTimeGetterSetter.java @@ -0,0 +1,28 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +import java.util.List; + +public class ServerTimeGetterSetter { + + @SerializedName("ServerTime") + @Expose + private List serverTime = null; + + public List getServerTime() { + return serverTime; + } + + public void setServerTime(List serverTime) { + this.serverTime = serverTime; + } + @SerializedName("StockSummary_Check") + @Expose + private List stockSummaryCheck = null; + + public List getStockSummaryCheck() { + return stockSummaryCheck; + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/StockDataGetterSetter.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/StockDataGetterSetter.java new file mode 100644 index 0000000..14c61b9 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/StockDataGetterSetter.java @@ -0,0 +1,21 @@ + +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; + +import java.util.List; + +public class StockDataGetterSetter { + + @Expose + private List stockData = null; + + public List getStockData() { + return stockData; + } + + public void setStockData(List stockData) { + this.stockData = stockData; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/StockDatum.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/StockDatum.java new file mode 100644 index 0000000..55062cd --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/StockDatum.java @@ -0,0 +1,39 @@ + +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; + +public class StockDatum { + + @Expose + private Integer storeId; + @Expose + private Integer productId; + @Expose + private Integer stock; + + public Integer getStoreId() { + return storeId; + } + + public void setStoreId(Integer storeId) { + this.storeId = storeId; + } + + public Integer getProductId() { + return productId; + } + + public void setProductId(Integer productId) { + this.productId = productId; + } + + public Integer getStock() { + return stock; + } + + public void setStock(Integer stock) { + this.stock = stock; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/StockGetterSetter.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/StockGetterSetter.java new file mode 100644 index 0000000..907604d --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/StockGetterSetter.java @@ -0,0 +1,69 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +public class StockGetterSetter { + String category_Id; + String category; + String sku_Id; + String sku; + String po_stock_qty=""; + + public String getValidity() { + return validity; + } + + public void setValidity(String validity) { + this.validity = validity; + } + + String validity; + + public String getCategory_Id() { + return category_Id; + } + + public void setCategory_Id(String category_Id) { + this.category_Id = category_Id; + } + + public String getCategory() { + return category; + } + + public void setCategory(String category) { + this.category = category; + } + + public String getSku_Id() { + return sku_Id; + } + + public void setSku_Id(String sku_Id) { + this.sku_Id = sku_Id; + } + + public String getSku() { + return sku; + } + + public void setSku(String sku) { + this.sku = sku; + } + + public String getPo_stock_qty() { + return po_stock_qty; + } + + public void setPo_stock_qty(String po_stock_qty) { + this.po_stock_qty = po_stock_qty; + } + + public String getStock_entry_qty() { + return stock_entry_qty; + } + + public void setStock_entry_qty(String stock_entry_qty) { + this.stock_entry_qty = stock_entry_qty; + } + + String stock_entry_qty=""; +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/StockPwpGwpDataGetterSetter.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/StockPwpGwpDataGetterSetter.java new file mode 100644 index 0000000..fdcc4e6 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/StockPwpGwpDataGetterSetter.java @@ -0,0 +1,20 @@ + +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; + +import java.util.List; + +public class StockPwpGwpDataGetterSetter { + @Expose + private List stockPwpGwpData = null; + + public List getStockPwpGwpData() { + return stockPwpGwpData; + } + + public void setStockPwpGwpData(List stockPwpGwpData) { + this.stockPwpGwpData = stockPwpGwpData; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/StockPwpGwpDatum.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/StockPwpGwpDatum.java new file mode 100644 index 0000000..a29c647 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/StockPwpGwpDatum.java @@ -0,0 +1,58 @@ + +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; + +public class StockPwpGwpDatum { + + @Expose + private Integer storeId; + @Expose + private String storeName; + @Expose + private Integer productId; + @Expose + private String productName; + @Expose + private Integer stock; + + public Integer getStoreId() { + return storeId; + } + + public void setStoreId(Integer storeId) { + this.storeId = storeId; + } + + public String getStoreName() { + return storeName; + } + + public void setStoreName(String storeName) { + this.storeName = storeName; + } + + public Integer getProductId() { + return productId; + } + + public void setProductId(Integer productId) { + this.productId = productId; + } + + public String getProductName() { + return productName; + } + + public void setProductName(String productName) { + this.productName = productName; + } + + public Integer getStock() { + return stock; + } + + public void setStock(Integer stock) { + this.stock = stock; + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/StockSampleDataGetterSetter.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/StockSampleDataGetterSetter.java new file mode 100644 index 0000000..eef145f --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/StockSampleDataGetterSetter.java @@ -0,0 +1,21 @@ + +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; + +import java.util.List; + +public class StockSampleDataGetterSetter { + + @Expose + private List stockSampleData = null; + + public List getStockSampleData() { + return stockSampleData; + } + + public void setStockSampleData(List stockSampleData) { + this.stockSampleData = stockSampleData; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/StockSampleDatum.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/StockSampleDatum.java new file mode 100644 index 0000000..c9b18b2 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/StockSampleDatum.java @@ -0,0 +1,39 @@ + +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; + +public class StockSampleDatum { + + @Expose + private Integer storeId; + @Expose + private Integer productId; + @Expose + private Integer stock; + + public Integer getStoreId() { + return storeId; + } + + public void setStoreId(Integer storeId) { + this.storeId = storeId; + } + + public Integer getProductId() { + return productId; + } + + public void setProductId(Integer productId) { + this.productId = productId; + } + + public Integer getStock() { + return stock; + } + + public void setStock(Integer stock) { + this.stock = stock; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/StockSummaryCheck.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/StockSummaryCheck.java new file mode 100644 index 0000000..255c506 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/StockSummaryCheck.java @@ -0,0 +1,52 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class StockSummaryCheck { + + @SerializedName("CounterId") + @Expose + private Integer counterId; + @SerializedName("TotalLine") + @Expose + private Integer totalLine; + @SerializedName("TotalStock") + @Expose + private Integer totalStock; + @SerializedName("VisitDate") + @Expose + private String visitDate; + + public Integer getCounterId() { + return counterId; + } + + public void setCounterId(Integer counterId) { + this.counterId = counterId; + } + + public Integer getTotalLine() { + return totalLine; + } + + public void setTotalLine(Integer totalLine) { + this.totalLine = totalLine; + } + + public Integer getTotalStock() { + return totalStock; + } + + public void setTotalStock(Integer totalStock) { + this.totalStock = totalStock; + } + + public String getVisitDate() { + return visitDate; + } + + public void setVisitDate(String visitDate) { + this.visitDate = visitDate; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/StockTesterDataGetterSetter.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/StockTesterDataGetterSetter.java new file mode 100644 index 0000000..a0dbca7 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/StockTesterDataGetterSetter.java @@ -0,0 +1,21 @@ + +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; + +import java.util.List; + +public class StockTesterDataGetterSetter { + + @Expose + private List stockTesterData = null; + + public List getStockTesterData() { + return stockTesterData; + } + + public void setStockTesterData(List stockTesterData) { + this.stockTesterData = stockTesterData; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/StockTesterDatum.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/StockTesterDatum.java new file mode 100644 index 0000000..0e04db5 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/StockTesterDatum.java @@ -0,0 +1,39 @@ + +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; + +public class StockTesterDatum { + + @Expose + private Integer storeId; + @Expose + private Integer productId; + @Expose + private Integer stock; + + public Integer getStoreId() { + return storeId; + } + + public void setStoreId(Integer storeId) { + this.storeId = storeId; + } + + public Integer getProductId() { + return productId; + } + + public void setProductId(Integer productId) { + this.productId = productId; + } + + public Integer getStock() { + return stock; + } + + public void setStock(Integer stock) { + this.stock = stock; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/TCounterInvoice.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/TCounterInvoice.java new file mode 100644 index 0000000..84374be --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/TCounterInvoice.java @@ -0,0 +1,228 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +import java.io.Serializable; + +public class TCounterInvoice implements Serializable { + @SerializedName("InvId") + @Expose + private Integer invId; + @SerializedName("CounterId") + @Expose + private Integer counterId; + @SerializedName("InvoiceNo") + @Expose + private String invoiceNo; + @SerializedName("InvoiceDate") + @Expose + private String invoiceDate; + @SerializedName("ProductId") + @Expose + private Integer productId; + @SerializedName("Qty") + @Expose + private Integer qty; + @SerializedName("Amount") + @Expose + private Double amount; + @SerializedName("InvoiceType") + @Expose + private String invoiceType; + @SerializedName("CounterConfirm") + @Expose + private Boolean counterConfirm; + @SerializedName("InvoiceStatus") + @Expose + private Boolean invoiceStatus; + @SerializedName("VisitDate") + @Expose + private String visitDate; + @SerializedName("ActualQty") + @Expose + private Integer actualQty; + @SerializedName("ReasonId") + @Expose + private Integer reasonId; + @SerializedName("TranId") + @Expose + private String tranId; + + public String getTranId() { + return tranId; + } + + public void setTranId(String tranId) { + this.tranId = tranId; + } + + public Integer getActualQty() { + return actualQty; + } + + public void setActualQty(Integer actualQty) { + this.actualQty = actualQty; + } + + public Integer getReasonId() { + return reasonId; + } + + public void setReasonId(Integer reasonId) { + this.reasonId = reasonId; + } + + public String getVisitDate() { + return visitDate; + } + + public void setVisitDate(String visitDate) { + this.visitDate = visitDate; + } + + private String finalAmount; + private String No_ofLine; + private String approved_line = ""; + private String source = ""; + private String upload_status = ""; + private String transactionId = ""; + + public String getInvoice_img() { + return invoice_img; + } + + public void setInvoice_img(String invoice_img) { + this.invoice_img = invoice_img; + } + + private String invoice_img=""; + + public String getTransactionId() { + return transactionId; + } + + public void setTransactionId(String transactionId) { + this.transactionId = transactionId; + } + + public String getUpload_status() { + return upload_status; + } + + public void setUpload_status(String upload_status) { + this.upload_status = upload_status; + } + + public String getSource() { + return source; + } + + public void setSource(String source) { + this.source = source; + } + + public String getApproved_line() { + return approved_line; + } + + public void setApproved_line(String approved_line) { + this.approved_line = approved_line; + } + + public String getFinalAmount() { + return finalAmount; + } + + public void setFinalAmount(String finalAmount) { + this.finalAmount = finalAmount; + } + + public String getNo_ofLine() { + return No_ofLine; + } + + public void setNo_ofLine(String no_ofLine) { + No_ofLine = no_ofLine; + } + + public Integer getInvId() { + return invId; + } + + public void setInvId(Integer invId) { + this.invId = invId; + } + + public Integer getCounterId() { + return counterId; + } + + public void setCounterId(Integer counterId) { + this.counterId = counterId; + } + + public String getInvoiceNo() { + return invoiceNo; + } + + public void setInvoiceNo(String invoiceNo) { + this.invoiceNo = invoiceNo; + } + + public String getInvoiceDate() { + return invoiceDate; + } + + public void setInvoiceDate(String invoiceDate) { + this.invoiceDate = invoiceDate; + } + + public Integer getProductId() { + return productId; + } + + public void setProductId(Integer productId) { + this.productId = productId; + } + + public Integer getQty() { + return qty; + } + + public void setQty(Integer qty) { + this.qty = qty; + } + + public Double getAmount() { + return amount; + } + + public void setAmount(Double amount) { + this.amount = amount; + } + + public String getInvoiceType() { + return invoiceType; + } + + public void setInvoiceType(String invoiceType) { + this.invoiceType = invoiceType; + } + + public Boolean getCounterConfirm() { + return counterConfirm; + } + + public void setCounterConfirm(Boolean counterConfirm) { + this.counterConfirm = counterConfirm; + } + + public Boolean getInvoiceStatus() { + return invoiceStatus; + } + + public void setInvoiceStatus(Boolean invoiceStatus) { + this.invoiceStatus = invoiceStatus; + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/TCounterInvoiceGetterSetter.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/TCounterInvoiceGetterSetter.java new file mode 100644 index 0000000..5910bdb --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/TCounterInvoiceGetterSetter.java @@ -0,0 +1,21 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +import java.util.List; + +public class TCounterInvoiceGetterSetter { + @SerializedName("T_CounterInvoice") + @Expose + private List tCounterInvoice = null; + + public List getTCounterInvoice() { + return tCounterInvoice; + } + + public void setTCounterInvoice(List tCounterInvoice) { + this.tCounterInvoice = tCounterInvoice; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/TLeaveLedger.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/TLeaveLedger.java new file mode 100644 index 0000000..dfb5f51 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/TLeaveLedger.java @@ -0,0 +1,54 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class TLeaveLedger { + @SerializedName("UserId") + @Expose + private String userId; + @SerializedName("TotalLeave") + @Expose + private double totalLeave; + @SerializedName("LeaveTaken") + @Expose + private double leaveTaken; + @SerializedName("BalanceLeave") + @Expose + private double balanceLeave; + + public String getUserId() { + return userId; + } + + public void setUserId(String userId) { + this.userId = userId; + } + + public double getTotalLeave() { + return totalLeave; + } + + public void setTotalLeave(double totalLeave) { + this.totalLeave = totalLeave; + } + + public double getLeaveTaken() { + return leaveTaken; + } + + public void setLeaveTaken(double leaveTaken) { + this.leaveTaken = leaveTaken; + } + + public double getBalanceLeave() { + return balanceLeave; + } + + public void setBalanceLeave(double balanceLeave) { + this.balanceLeave = balanceLeave; + } + + String start_date="",end_date="",reason="",date_of_applied=""; + +} \ No newline at end of file diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/TStockSummary.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/TStockSummary.java new file mode 100644 index 0000000..0d9d8a4 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/TStockSummary.java @@ -0,0 +1,316 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.SerializedName; + +public class TStockSummary { + @SerializedName("Id") + private Integer id; + @SerializedName("SaleableIn") + private Integer saleableIn; + @SerializedName("CounterId") + private Integer counterId; + @SerializedName("SaleableOut") + + private Integer saleableOut; + @SerializedName("SaleableDamage") + + private Integer saleableDamage; + @SerializedName("ProductId") + + private Integer productId; + @SerializedName("SaleableBalance") + + private Integer saleableBalance; + @SerializedName("TesterIn") + + private Integer testerIn; + @SerializedName("TesterOut") + + private Integer TesterOut; + @SerializedName("TesterDamage") + + private Integer testerDamage; + @SerializedName("TesterBalance") + + private Integer testerBalance; + @SerializedName("SampleIn") + + private Integer sampleIn; + @SerializedName("SampleOut") + + private Integer sampleOut; + @SerializedName("SampleDamage") + + private Integer sampleDamage; + @SerializedName("SampleBalance") + + private Integer sampleBalance; + @SerializedName("GwpIn") + + private Integer gwpIn; + @SerializedName("GwpOut") + + private Integer gwpOut; + @SerializedName("GwpDamage") + + private Integer gwpDamage; + @SerializedName("GwpBalance") + + private Integer gwpBalance; + @SerializedName("SaleableStatus") + + private String saleableStatus; + @SerializedName("TesterStatus") + + private String TesterStatus; + @SerializedName("SampleStatus") + + private String sampleStatus; + @SerializedName("GwpStatus") + + private String gwpStatus; + @SerializedName("VisitDate") + + private String visitDate; + + public String getVisitDate() { + return visitDate; + } + + public void setVisitDate(String visitDate) { + this.visitDate = visitDate; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public Integer getSaleableIn() { + return saleableIn; + } + + public void setSaleableIn(Integer saleableIn) { + this.saleableIn = saleableIn; + } + + public Integer getCounterId() { + return counterId; + } + + public void setCounterId(Integer counterId) { + this.counterId = counterId; + } + + public Integer getSaleableOut() { + return saleableOut; + } + + public void setSaleableOut(Integer saleableOut) { + this.saleableOut = saleableOut; + } + + public Integer getSaleableDamage() { + return saleableDamage; + } + + public void setSaleableDamage(Integer saleableDamage) { + this.saleableDamage = saleableDamage; + } + + public Integer getProductId() { + return productId; + } + + public void setProductId(Integer productId) { + this.productId = productId; + } + + public Integer getSaleableBalance() { + return saleableBalance; + } + + public void setSaleableBalance(Integer saleableBalance) { + this.saleableBalance = saleableBalance; + } + + public Integer getTesterIn() { + return testerIn; + } + + public void setTesterIn(Integer testerIn) { + this.testerIn = testerIn; + } + + public Integer getTesterOut() { + return TesterOut; + } + + public void setTesterOut(Integer testerOut) { + TesterOut = testerOut; + } + + public Integer getTesterDamage() { + return testerDamage; + } + + public void setTesterDamage(Integer testerDamage) { + this.testerDamage = testerDamage; + } + + public Integer getTesterBalance() { + return testerBalance; + } + + public void setTesterBalance(Integer testerBalance) { + this.testerBalance = testerBalance; + } + + public Integer getSampleIn() { + return sampleIn; + } + + public void setSampleIn(Integer sampleIn) { + this.sampleIn = sampleIn; + } + + public Integer getSampleOut() { + return sampleOut; + } + + public void setSampleOut(Integer sampleOut) { + this.sampleOut = sampleOut; + } + + public Integer getSampleDamage() { + return sampleDamage; + } + + public void setSampleDamage(Integer sampleDamage) { + this.sampleDamage = sampleDamage; + } + + public Integer getSampleBalance() { + return sampleBalance; + } + + public void setSampleBalance(Integer sampleBalance) { + this.sampleBalance = sampleBalance; + } + + public Integer getGwpIn() { + return gwpIn; + } + + public void setGwpIn(Integer gwpIn) { + this.gwpIn = gwpIn; + } + + public Integer getGwpOut() { + return gwpOut; + } + + public void setGwpOut(Integer gwpOut) { + this.gwpOut = gwpOut; + } + + public Integer getGwpDamage() { + return gwpDamage; + } + + public void setGwpDamage(Integer gwpDamage) { + this.gwpDamage = gwpDamage; + } + + public Integer getGwpBalance() { + return gwpBalance; + } + + public void setGwpBalance(Integer gwpBalance) { + this.gwpBalance = gwpBalance; + } + + public String getSaleableStatus() { + return saleableStatus; + } + + public void setSaleableStatus(String saleableStatus) { + this.saleableStatus = saleableStatus; + } + + public String getTesterStatus() { + return TesterStatus; + } + + public void setTesterStatus(String testerStatus) { + TesterStatus = testerStatus; + } + + public String getSampleStatus() { + return sampleStatus; + } + + public void setSampleStatus(String sampleStatus) { + this.sampleStatus = sampleStatus; + } + + public String getGwpStatus() { + return gwpStatus; + } + + public void setGwpStatus(String gwpStatus) { + this.gwpStatus = gwpStatus; + } + + public String getProductName() { + return productName; + } + + public void setProductName(String productName) { + this.productName = productName; + } + + String productName=""; + + public String getBrand_name() { + return brand_name; + } + + public void setBrand_name(String brand_name) { + this.brand_name = brand_name; + } + + String brand_name=""; + + public String getBlocked_product_Id() { + return blocked_product_Id; + } + + public void setBlocked_product_Id(String blocked_product_Id) { + this.blocked_product_Id = blocked_product_Id; + } + + int stock=0; + + public int getMrp() { + return mrp; + } + + public void setMrp(int mrp) { + this.mrp = mrp; + } + + int mrp=0; + + String blocked_product_Id="0"; + public int getStock() { + return stock; + } + + public void setStock(int stock) { + this.stock = stock; + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/TStockSummaryGetterSetter.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/TStockSummaryGetterSetter.java new file mode 100644 index 0000000..44814f3 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/TStockSummaryGetterSetter.java @@ -0,0 +1,20 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +import java.util.List; + +public class TStockSummaryGetterSetter { + @SerializedName("T_StockSummary") + @Expose + private List tStockSummary = null; + + public List gettStockSummary() { + return tStockSummary; + } + + public void settStockSummary(List tStockSummary) { + this.tStockSummary = tStockSummary; + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/T_LeaveRequest.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/T_LeaveRequest.java new file mode 100644 index 0000000..a3fda0c --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/T_LeaveRequest.java @@ -0,0 +1,190 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; +import com.cpm.lorealbaautomation.constant.CommonString; + +import java.io.Serializable; + +public class T_LeaveRequest implements Serializable { + + @SerializedName("Id") + @Expose + private Integer id; + @SerializedName("RequestDate") + @Expose + private String requestDate; + @SerializedName("UserId") + @Expose + private String userId; + @SerializedName("FromDate") + @Expose + private String fromDate; + @SerializedName("ToDate") + @Expose + private String toDate; + @SerializedName("LeaveStatus") + @Expose + private String leaveStatus; + + @SerializedName("LeaveType") + @Expose + private String LeaveType; + + public String getLeaveType() { + return LeaveType; + } + + public void setLeaveType(String leaveType) { + LeaveType = leaveType; + } + + public String getLeaveTypeDesc() { + return LeaveTypeDesc; + } + + public void setLeaveTypeDesc(String leaveTypeDesc) { + LeaveTypeDesc = leaveTypeDesc; + } + + @SerializedName("LeaveTypeDesc") + @Expose + private String LeaveTypeDesc; + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getRequestDate() { + return requestDate; + } + + public void setRequestDate(String requestDate) { + this.requestDate = requestDate; + } + + public String getUserId() { + return userId; + } + + public void setUserId(String userId) { + this.userId = userId; + } + + public String getFromDate() { + return fromDate; + } + + public void setFromDate(String fromDate) { + this.fromDate = fromDate; + } + + public String getToDate() { + return toDate; + } + + public void setToDate(String toDate) { + this.toDate = toDate; + } + + public String getLeaveStatus() { + return leaveStatus; + } + + public void setLeaveStatus(String leaveStatus) { + this.leaveStatus = leaveStatus; + } + + public String getTransId() { + return TransId; + } + + public void setTransId(String transId) { + TransId = transId; + } + + String TransId = ""; + String upload_start_date_str=""; + + public String getUpload_request_date() { + return upload_request_date; + } + + public void setUpload_request_date(String upload_request_date) { + this.upload_request_date = upload_request_date; + } + + String upload_request_date=""; + + public String getUpload_start_date_str() { + return upload_start_date_str; + } + + public void setUpload_start_date_str(String upload_start_date_str) { + this.upload_start_date_str = upload_start_date_str; + } + + public String getUpload_end_date_str() { + return upload_end_date_str; + } + + public void setUpload_end_date_str(String upload_end_date_str) { + this.upload_end_date_str = upload_end_date_str; + } + + public String getLeave_reason() { + return leave_reason; + } + + public void setLeave_reason(String leave_reason) { + this.leave_reason = leave_reason; + } + + String upload_end_date_str=""; + String leave_reason=""; + + public String getUpload_status() { + return upload_status; + } + + public void setUpload_status(String upload_status) { + this.upload_status = upload_status; + } + + String upload_status = CommonString.KEY_N; + + public String getOne_day_leave_str() { + return one_day_leave_str; + } + + public void setOne_day_leave_str(String one_day_leave_str) { + this.one_day_leave_str = one_day_leave_str; + } + + String one_day_leave_str=""; + + public String getStr_leaveType() { + return str_leaveType; + } + + public void setStr_leaveType(String str_leaveType) { + this.str_leaveType = str_leaveType; + } + + String str_leaveType=""; + + public String getStr_leaveTypeId() { + return str_leaveTypeId; + } + + public void setStr_leaveTypeId(String str_leaveTypeId) { + this.str_leaveTypeId = str_leaveTypeId; + } + + String str_leaveTypeId="0"; + +} \ No newline at end of file diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/TableStructure.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/TableStructure.java new file mode 100644 index 0000000..92f1821 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/TableStructure.java @@ -0,0 +1,19 @@ + +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class TableStructure { + @SerializedName("SqlText") + @Expose + private String sqlText; + + public String getSqlText() { + return sqlText; + } + + public void setSqlText(String sqlText) { + this.sqlText = sqlText; + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/TableStructureGetterSetter.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/TableStructureGetterSetter.java new file mode 100644 index 0000000..131ae95 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/TableStructureGetterSetter.java @@ -0,0 +1,73 @@ + +package com.cpm.lorealbaautomation.gsonGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; +import com.cpm.lorealbaautomation.reportGetterSetter.SkinGeniusUrl; + +import java.util.List; + +public class TableStructureGetterSetter { + @SerializedName("Table_Structure") + @Expose + private List tableStructure = null; + + public List getTableStructure() { + return tableStructure; + } + + @SerializedName("Product_Master") + @Expose + private List productMaster = null; + + public List getProductMaster() { + return productMaster; + } + + @Expose + private List inwardSalesPO = null; + + public List getInwardSalesPO() { + return inwardSalesPO; + } + + @SerializedName("Mapping_Visibility") + @Expose + private List mappingVisibility = null; + + public List getMappingVisibility() { + return mappingVisibility; + } + + @SerializedName("Master_Posm") + @Expose + private List masterPosm = null; + + public List getMasterPosm() { + return masterPosm; + } + + @SerializedName("Master_SkinType") + @Expose + private List masterSkinType = null; + + public List getMasterSkinType() { + return masterSkinType; + } + + @SerializedName("Master_AgeLimit") + @Expose + private List masterAgeLimit = null; + + public List getMasterAgeLimit() { + return masterAgeLimit; + } + + @SerializedName("SkinGeniusUrl") + @Expose + private List skinGeniusUrl = null; + + public List getSkinGeniusUrl() { + return skinGeniusUrl; + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/batbasale/BATBAPromoSale.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/batbasale/BATBAPromoSale.java new file mode 100644 index 0000000..12c0bb4 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/batbasale/BATBAPromoSale.java @@ -0,0 +1,90 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter.batbasale; + +import com.google.gson.annotations.SerializedName; + +public class BATBAPromoSale { + @SerializedName("CounterId") + private Integer counterId; + @SerializedName("CounterCode") + private String counterCode; + @SerializedName("ProductId") + private Integer productId; + @SerializedName("ProductCode") + private String productCode; + @SerializedName("ProductName") + private String productName; + @SerializedName("VisitDate") + private String visitDate; + @SerializedName("SaleQty") + private Integer saleQty; + @SerializedName("SaleValues") + private Double saleValues; + @SerializedName("PromoType") + private String promoType; + + public Integer getCounterId() { + return counterId; + } + + public void setCounterId(Integer counterId) { + this.counterId = counterId; + } + + public String getCounterCode() { + return counterCode; + } + + public void setCounterCode(String counterCode) { + this.counterCode = counterCode; + } + + public Integer getProductId() { + return productId; + } + + public void setProductId(Integer productId) { + this.productId = productId; + } + + public String getProductCode() { + return productCode; + } + + public void setProductCode(String productCode) { + this.productCode = productCode; + } + + public String getProductName() { + return productName; + } + + public void setProductName(String productName) { + this.productName = productName; + } + + public String getVisitDate() { + return visitDate; + } + + public void setVisitDate(String visitDate) { + this.visitDate = visitDate; + } + + public Integer getSaleQty() { + return saleQty; + } + + public void setSaleQty(Integer saleQty) { + this.saleQty = saleQty; + } + + public Double getSaleValues() { + return saleValues; + } + + public void setSaleValues(Double saleValues) { + this.saleValues = saleValues; + } + public String getpromoType() {return promoType;} + public void setpromoType(String promoType) {this.promoType = promoType;} +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/batbasale/BATBASale.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/batbasale/BATBASale.java new file mode 100644 index 0000000..50e1373 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/batbasale/BATBASale.java @@ -0,0 +1,86 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter.batbasale; + +import com.google.gson.annotations.SerializedName; + +public class BATBASale { + @SerializedName("CounterId") + private Integer counterId; + @SerializedName("CounterCode") + private String counterCode; + @SerializedName("ProductId") + private Integer productId; + @SerializedName("ProductCode") + private String productCode; + @SerializedName("ProductName") + private String productName; + @SerializedName("VisitDate") + private String visitDate; + @SerializedName("SaleQty") + private Integer saleQty; + @SerializedName("SaleValues") + private Double saleValues; + + public Integer getCounterId() { + return counterId; + } + + public void setCounterId(Integer counterId) { + this.counterId = counterId; + } + + public String getCounterCode() { + return counterCode; + } + + public void setCounterCode(String counterCode) { + this.counterCode = counterCode; + } + + public Integer getProductId() { + return productId; + } + + public void setProductId(Integer productId) { + this.productId = productId; + } + + public String getProductCode() { + return productCode; + } + + public void setProductCode(String productCode) { + this.productCode = productCode; + } + + public String getProductName() { + return productName; + } + + public void setProductName(String productName) { + this.productName = productName; + } + + public String getVisitDate() { + return visitDate; + } + + public void setVisitDate(String visitDate) { + this.visitDate = visitDate; + } + + public Integer getSaleQty() { + return saleQty; + } + + public void setSaleQty(Integer saleQty) { + this.saleQty = saleQty; + } + + public Double getSaleValues() { + return saleValues; + } + + public void setSaleValues(Double saleValues) { + this.saleValues = saleValues; + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/countervolune/ReportConterValue.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/countervolune/ReportConterValue.java new file mode 100644 index 0000000..2f56d8f --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/countervolune/ReportConterValue.java @@ -0,0 +1,67 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter.countervolune; + +import com.google.gson.annotations.SerializedName; + +public class ReportConterValue { + @SerializedName("KPI") + private String kpi; + @SerializedName("CounterId") + private Integer counterId; + @SerializedName("CounterCode") + private String counterCode; + @SerializedName("CounterName") + private String counterName; + @SerializedName("MTDValue") + private Double mTDValue; + @SerializedName("AvgPerDayValue") + private Double avgPerDayValue; + + public String getKpi() { + return kpi; + } + + public void setKpi(String kpi) { + this.kpi = kpi; + } + + public Integer getCounterId() { + return counterId; + } + + public void setCounterId(Integer counterId) { + this.counterId = counterId; + } + + public String getCounterCode() { + return counterCode; + } + + public void setCounterCode(String counterCode) { + this.counterCode = counterCode; + } + + public String getCounterName() { + return counterName; + } + + public void setCounterName(String counterName) { + this.counterName = counterName; + } + + public Double getMTDValue() { + return mTDValue; + } + + public void setMTDValue(Double mTDValue) { + this.mTDValue = mTDValue; + } + + public Double getAvgPerDayValue() { + return avgPerDayValue; + } + + public void setAvgPerDayValue(Double avgPerDayValue) { + this.avgPerDayValue = avgPerDayValue; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/countervolune/ReportConterValueDetail.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/countervolune/ReportConterValueDetail.java new file mode 100644 index 0000000..3e1926f --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/countervolune/ReportConterValueDetail.java @@ -0,0 +1,97 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter.countervolune; + +import com.google.gson.annotations.SerializedName; + +public class ReportConterValueDetail { + @SerializedName("KPI") + private String kpi; + @SerializedName("CounterId") + private Integer counterId; + @SerializedName("CounterCode") + private String counterCode; + @SerializedName("CounterName") + private String counterName; + @SerializedName("ParamId") + private Integer paramId; + @SerializedName("ParamCode") + private String paramCode; + @SerializedName("ParamName") + private String paramName; + @SerializedName("MTDValue") + private Double mTDValue; + @SerializedName("AvgPerDayValue") + private Double avgPerDayValue; + + public String getKpi() { + return kpi; + } + + public void setKpi(String kpi) { + this.kpi = kpi; + } + + public Integer getCounterId() { + return counterId; + } + + public void setCounterId(Integer counterId) { + this.counterId = counterId; + } + + public String getCounterCode() { + return counterCode; + } + + public void setCounterCode(String counterCode) { + this.counterCode = counterCode; + } + + public String getCounterName() { + return counterName; + } + + public void setCounterName(String counterName) { + this.counterName = counterName; + } + + public Integer getParamId() { + return paramId; + } + + public void setParamId(Integer paramId) { + this.paramId = paramId; + } + + public String getParamCode() { + return paramCode; + } + + public void setParamCode(String paramCode) { + this.paramCode = paramCode; + } + + public String getParamName() { + return paramName; + } + + public void setParamName(String paramName) { + this.paramName = paramName; + } + + public Double getMTDValue() { + return mTDValue; + } + + public void setMTDValue(Double mTDValue) { + this.mTDValue = mTDValue; + } + + public Double getAvgPerDayValue() { + return avgPerDayValue; + } + + public void setAvgPerDayValue(Double avgPerDayValue) { + this.avgPerDayValue = avgPerDayValue; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/countervolune/ReportCounterVolume.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/countervolune/ReportCounterVolume.java new file mode 100644 index 0000000..f27a627 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/countervolune/ReportCounterVolume.java @@ -0,0 +1,64 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter.countervolune; + +import com.google.gson.annotations.SerializedName; + +public class ReportCounterVolume { + @SerializedName("KPI") + private String kpi; + @SerializedName("CounterId") + private Integer counterId; + @SerializedName("CounterCode") + private String counterCode; + @SerializedName("CounterName") + private String counterName; + @SerializedName("MTDVolume") + private Double mTDVolume; + @SerializedName("AvgPerDayVolume") + private Double avgPerDayVolume; + public String getKpi() { + return kpi; + } + public void setKpi(String kpi) { + this.kpi = kpi; + } + + public Integer getCounterId() { + return counterId; + } + + public void setCounterId(Integer counterId) { + this.counterId = counterId; + } + + public String getCounterCode() { + return counterCode; + } + + public void setCounterCode(String counterCode) { + this.counterCode = counterCode; + } + + public String getCounterName() { + return counterName; + } + + public void setCounterName(String counterName) { + this.counterName = counterName; + } + + public Double getMTDVolume() { + return mTDVolume; + } + + public void setMTDVolume(Double mTDVolume) { + this.mTDVolume = mTDVolume; + } + + public Double getAvgPerDayVolume() { + return avgPerDayVolume; + } + + public void setAvgPerDayVolume(Double avgPerDayVolume) { + this.avgPerDayVolume = avgPerDayVolume; + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/countervolune/ReportCounterVolumeDetail.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/countervolune/ReportCounterVolumeDetail.java new file mode 100644 index 0000000..e84a425 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/countervolune/ReportCounterVolumeDetail.java @@ -0,0 +1,96 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter.countervolune; + +import com.google.gson.annotations.SerializedName; + +public class ReportCounterVolumeDetail { + @SerializedName("KPI") + private String kpi; + @SerializedName("CounterId") + private Integer counterId; + @SerializedName("CounterCode") + private String counterCode; + @SerializedName("CounterName") + private String counterName; + @SerializedName("ParamId") + private Integer paramId; + @SerializedName("ParamCode") + private String paramCode; + @SerializedName("ParamName") + private String paramName; + @SerializedName("MTDVolume") + private Double mTDVolume; + @SerializedName("AvgPerDayVolume") + private Double avgPerDayVolume; + + public String getKpi() { + return kpi; + } + + public void setKpi(String kpi) { + this.kpi = kpi; + } + + public Integer getCounterId() { + return counterId; + } + + public void setCounterId(Integer counterId) { + this.counterId = counterId; + } + + public String getCounterCode() { + return counterCode; + } + + public void setCounterCode(String counterCode) { + this.counterCode = counterCode; + } + + public String getCounterName() { + return counterName; + } + + public void setCounterName(String counterName) { + this.counterName = counterName; + } + + public Integer getParamId() { + return paramId; + } + + public void setParamId(Integer paramId) { + this.paramId = paramId; + } + + public String getParamCode() { + return paramCode; + } + + public void setParamCode(String paramCode) { + this.paramCode = paramCode; + } + + public String getParamName() { + return paramName; + } + + public void setParamName(String paramName) { + this.paramName = paramName; + } + + public Double getMTDVolume() { + return mTDVolume; + } + + public void setMTDVolume(Double mTDVolume) { + this.mTDVolume = mTDVolume; + } + + public Double getAvgPerDayVolume() { + return avgPerDayVolume; + } + + public void setAvgPerDayVolume(Double avgPerDayVolume) { + this.avgPerDayVolume = avgPerDayVolume; + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/inwordDetail/ReportCounterInwardStock.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/inwordDetail/ReportCounterInwardStock.java new file mode 100644 index 0000000..5e476e7 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/inwordDetail/ReportCounterInwardStock.java @@ -0,0 +1,85 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter.inwordDetail; + +import com.google.gson.annotations.SerializedName; + +public class ReportCounterInwardStock { + @SerializedName("KPI") + private String kpi; + @SerializedName("CounterId") + private Integer counterId; + @SerializedName("CounterCode") + private String counterCode; + @SerializedName("CounterName") + private String counterName; + @SerializedName("InvoiceQty") + private Integer invoiceQty; + @SerializedName("ActualQty") + private Integer actualQty; + @SerializedName("DamageQty") + private Integer damageQty; + @SerializedName("MissedQty") + private Integer missedQty; + + public String getKpi() { + return kpi; + } + + public void setKpi(String kpi) { + this.kpi = kpi; + } + + public Integer getCounterId() { + return counterId; + } + + public void setCounterId(Integer counterId) { + this.counterId = counterId; + } + + public String getCounterCode() { + return counterCode; + } + + public void setCounterCode(String counterCode) { + this.counterCode = counterCode; + } + + public String getCounterName() { + return counterName; + } + + public void setCounterName(String counterName) { + this.counterName = counterName; + } + + public Integer getInvoiceQty() { + return invoiceQty; + } + + public void setInvoiceQty(Integer invoiceQty) { + this.invoiceQty = invoiceQty; + } + + public Integer getActualQty() { + return actualQty; + } + + public void setActualQty(Integer actualQty) { + this.actualQty = actualQty; + } + + public Integer getDamageQty() { + return damageQty; + } + + public void setDamageQty(Integer damageQty) { + this.damageQty = damageQty; + } + public Integer getMissedQty() { + return missedQty; + } + + public void setMissedQty(Integer missedQty) { + this.missedQty = missedQty; + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/inwordDetail/ReportCounterInwardStockDetail.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/inwordDetail/ReportCounterInwardStockDetail.java new file mode 100644 index 0000000..56db800 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/inwordDetail/ReportCounterInwardStockDetail.java @@ -0,0 +1,116 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter.inwordDetail; + +import com.google.gson.annotations.SerializedName; + +public class ReportCounterInwardStockDetail { + @SerializedName("KPI") + private String kpi; + @SerializedName("CounterId") + private Integer counterId; + @SerializedName("CounterCode") + private String counterCode; + @SerializedName("CounterName") + private String counterName; + @SerializedName("ParamId") + private Integer paramId; + @SerializedName("ParamCode") + private String paramCode; + @SerializedName("ParamName") + private String paramName; + @SerializedName("InvoiceQty") + private Integer invoiceQty; + @SerializedName("ActualQty") + private Integer actualQty; + @SerializedName("DamageQty") + private Integer damageQty; + @SerializedName("MissedQty") + private Integer missedQty; + + public Integer getMissedQty() { + return missedQty; + } + + public void setMissedQty(Integer missedQty) { + this.missedQty = missedQty; + } + + public String getKpi() { + return kpi; + } + + public void setKpi(String kpi) { + this.kpi = kpi; + } + + public Integer getCounterId() { + return counterId; + } + + public void setCounterId(Integer counterId) { + this.counterId = counterId; + } + + public String getCounterCode() { + return counterCode; + } + + public void setCounterCode(String counterCode) { + this.counterCode = counterCode; + } + + public String getCounterName() { + return counterName; + } + + public void setCounterName(String counterName) { + this.counterName = counterName; + } + + public Integer getParamId() { + return paramId; + } + + public void setParamId(Integer paramId) { + this.paramId = paramId; + } + + public String getParamCode() { + return paramCode; + } + + public void setParamCode(String paramCode) { + this.paramCode = paramCode; + } + + public String getParamName() { + return paramName; + } + + public void setParamName(String paramName) { + this.paramName = paramName; + } + + public Integer getInvoiceQty() { + return invoiceQty; + } + + public void setInvoiceQty(Integer invoiceQty) { + this.invoiceQty = invoiceQty; + } + + public Integer getActualQty() { + return actualQty; + } + + public void setActualQty(Integer actualQty) { + this.actualQty = actualQty; + } + + public Integer getDamageQty() { + return damageQty; + } + + public void setDamageQty(Integer damageQty) { + this.damageQty = damageQty; + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/leaves/MasterHoliday.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/leaves/MasterHoliday.java new file mode 100644 index 0000000..5d9e21d --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/leaves/MasterHoliday.java @@ -0,0 +1,37 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter.leaves; + +import com.google.gson.annotations.SerializedName; + +public class MasterHoliday { + @SerializedName("Id") + private Integer id; + @SerializedName("Date") + private String date; + @SerializedName("Occasion") + private String occasion; + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getDate() { + return date; + } + + public void setDate(String date) { + this.date = date; + } + + public String getOccasion() { + return occasion; + } + + public void setOccasion(String occasion) { + this.occasion = occasion; + } +} + diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/leaves/TLeaveLedgerSummary.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/leaves/TLeaveLedgerSummary.java new file mode 100644 index 0000000..a1634b2 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/leaves/TLeaveLedgerSummary.java @@ -0,0 +1,67 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter.leaves; + +import com.google.gson.annotations.SerializedName; + +public class TLeaveLedgerSummary { + @SerializedName("UserId") + private String userId; + @SerializedName("LeaveType") + private String leaveType; + @SerializedName("Earned") + private Double earned; + @SerializedName("TakenThisMonth") + private Double takenThisMonth; + @SerializedName("TotalLeavesTaken") + private Double totalLeavesTaken; + @SerializedName("Balance") + private Double balance; + + public String getEmpId() { + return userId; + } + + public void setEmpId(String userId) { + this.userId = userId; + } + + public String getLeaveType() { + return leaveType; + } + + public void setLeaveType(String leaveType) { + this.leaveType = leaveType; + } + + public Double getEarned() { + return earned; + } + + public void setEarned(Double earned) { + this.earned = earned; + } + + public Double getTakenThisMonth() { + return takenThisMonth; + } + + public void setTakenThisMonth(Double takenThisMonth) { + this.takenThisMonth = takenThisMonth; + } + + public Double getTotalLeavesTaken() { + return totalLeavesTaken; + } + + public void setTotalLeavesTaken(Double totalLeavesTaken) { + this.totalLeavesTaken = totalLeavesTaken; + } + + public Double getBalance() { + return balance; + } + + public void setBalance(Double balance) { + this.balance = balance; + } + +} \ No newline at end of file diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/leaves/TLeaveRequestDetail.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/leaves/TLeaveRequestDetail.java new file mode 100644 index 0000000..556893a --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/leaves/TLeaveRequestDetail.java @@ -0,0 +1,97 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter.leaves; + +import com.google.gson.annotations.SerializedName; + +public class TLeaveRequestDetail { + @SerializedName("Id") + private Integer id; + @SerializedName("UserId") + private String userId; + @SerializedName("Year") + private Integer year; + @SerializedName("Month") + private Integer month; + @SerializedName("Day") + private Integer day; + @SerializedName("LeaveType") + private String leaveType; + @SerializedName("LeaveSubType") + private String leaveSubType; + @SerializedName("Reason") + private String reason; + @SerializedName("ApprovedStatus") + private String approvedStatus; + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getUserId() { + return userId; + } + + public void setUserId(String userId) { + this.userId = userId; + } + + public Integer getYear() { + return year; + } + + public void setYear(Integer year) { + this.year = year; + } + + public Integer getMonth() { + return month; + } + + public void setMonth(Integer month) { + this.month = month; + } + + public Integer getDay() { + return day; + } + + public void setDay(Integer day) { + this.day = day; + } + + public String getLeaveType() { + return leaveType; + } + + public void setLeaveType(String leaveType) { + this.leaveType = leaveType; + } + + public String getLeaveSubType() { + return leaveSubType; + } + + public void setLeaveSubType(String leaveSubType) { + this.leaveSubType = leaveSubType; + } + + public String getReason() { + return reason; + } + + public void setReason(String reason) { + this.reason = reason; + } + + public String getApprovedStatus() { + return approvedStatus; + } + + public void setApprovedStatus(String approvedStatus) { + this.approvedStatus = approvedStatus; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/stockledger/ReportCounterStockLedger.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/stockledger/ReportCounterStockLedger.java new file mode 100644 index 0000000..a7aba31 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/stockledger/ReportCounterStockLedger.java @@ -0,0 +1,94 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter.stockledger; + +import com.google.gson.annotations.SerializedName; + +public class ReportCounterStockLedger { + @SerializedName("KPI") + + private String kpi; + @SerializedName("CounterId") + + private Integer counterId; + @SerializedName("CounterCode") + + private String counterCode; + @SerializedName("CounterName") + + private String counterName; + @SerializedName("OpeningStock") + + private Integer openingStock; + @SerializedName("StockIn") + + private Integer stockIn; + @SerializedName("SaleOut") + + private Integer saleOut; + @SerializedName("SaleableBalance") + + private Integer saleableBalance; + + public String getKpi() { + return kpi; + } + + public void setKpi(String kpi) { + this.kpi = kpi; + } + + public Integer getCounterId() { + return counterId; + } + + public void setCounterId(Integer counterId) { + this.counterId = counterId; + } + + public String getCounterCode() { + return counterCode; + } + + public void setCounterCode(String counterCode) { + this.counterCode = counterCode; + } + + public String getCounterName() { + return counterName; + } + + public void setCounterName(String counterName) { + this.counterName = counterName; + } + + public Integer getOpeningStock() { + return openingStock; + } + + public void setOpeningStock(Integer openingStock) { + this.openingStock = openingStock; + } + + public Integer getStockIn() { + return stockIn; + } + + public void setStockIn(Integer stockIn) { + this.stockIn = stockIn; + } + + public Integer getSaleOut() { + return saleOut; + } + + public void setSaleOut(Integer saleOut) { + this.saleOut = saleOut; + } + + public Integer getSaleableBalance() { + return saleableBalance; + } + + public void setSaleableBalance(Integer saleableBalance) { + this.saleableBalance = saleableBalance; + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/stockledger/ReportCounterStockLedgerDetail.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/stockledger/ReportCounterStockLedgerDetail.java new file mode 100644 index 0000000..22ff79b --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/stockledger/ReportCounterStockLedgerDetail.java @@ -0,0 +1,127 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter.stockledger; + +import com.google.gson.annotations.SerializedName; + +public class ReportCounterStockLedgerDetail { + @SerializedName("KPI") + + private String kpi; + @SerializedName("CounterId") + + private Integer counterId; + @SerializedName("CounterCode") + + private String counterCode; + @SerializedName("CounterName") + + private String counterName; + @SerializedName("ParamId") + + private Integer paramId; + @SerializedName("ParamCode") + + private String paramCode; + @SerializedName("ParamName") + + private String paramName; + @SerializedName("OpeningStock") + + private Integer openingStock; + @SerializedName("StockIn") + + private Integer stockIn; + @SerializedName("SaleOut") + + private Integer saleOut; + @SerializedName("SaleableBalance") + + private Integer saleableBalance; + + public String getKpi() { + return kpi; + } + + public void setKpi(String kpi) { + this.kpi = kpi; + } + + public Integer getCounterId() { + return counterId; + } + + public void setCounterId(Integer counterId) { + this.counterId = counterId; + } + + public String getCounterCode() { + return counterCode; + } + + public void setCounterCode(String counterCode) { + this.counterCode = counterCode; + } + + public String getCounterName() { + return counterName; + } + + public void setCounterName(String counterName) { + this.counterName = counterName; + } + + public Integer getParamId() { + return paramId; + } + + public void setParamId(Integer paramId) { + this.paramId = paramId; + } + + public String getParamCode() { + return paramCode; + } + + public void setParamCode(String paramCode) { + this.paramCode = paramCode; + } + + public String getParamName() { + return paramName; + } + + public void setParamName(String paramName) { + this.paramName = paramName; + } + + public Integer getOpeningStock() { + return openingStock; + } + + public void setOpeningStock(Integer openingStock) { + this.openingStock = openingStock; + } + + public Integer getStockIn() { + return stockIn; + } + + public void setStockIn(Integer stockIn) { + this.stockIn = stockIn; + } + + public Integer getSaleOut() { + return saleOut; + } + + public void setSaleOut(Integer saleOut) { + this.saleOut = saleOut; + } + + public Integer getSaleableBalance() { + return saleableBalance; + } + + public void setSaleableBalance(Integer saleableBalance) { + this.saleableBalance = saleableBalance; + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/testerreports/ReportTesterCounter.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/testerreports/ReportTesterCounter.java new file mode 100644 index 0000000..35af737 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/testerreports/ReportTesterCounter.java @@ -0,0 +1,106 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter.testerreports; + +import com.google.gson.annotations.SerializedName; + +public class ReportTesterCounter { + @SerializedName("KPI") + private String kpi; + @SerializedName("CounterId") + private Integer counterId; + @SerializedName("CounterCode") + private String counterCode; + @SerializedName("CounterName") + private String counterName; + @SerializedName("Opening_Stock") + private Integer openingStock; + @SerializedName("InvoicedQty") + private Integer invoicedQty; + @SerializedName("ReceivedQty") + private Integer receivedQty; + @SerializedName("TesterStockAvailable") + private Integer testerStockAvailable; + @SerializedName("TesterUsed") + private Integer testerUsed; + @SerializedName("TesterUsedPer") + private Double testerUsedPer; + + public String getKPI() { + return kpi; + } + + public void setKpi(String kpi) { + this.kpi = kpi; + } + + public Integer getCounterId() { + return counterId; + } + + public void setCounterId(Integer counterId) { + this.counterId = counterId; + } + + public String getCounterCode() { + return counterCode; + } + + public void setCounterCode(String counterCode) { + this.counterCode = counterCode; + } + + public String getCounterName() { + return counterName; + } + + public void setCounterName(String counterName) { + this.counterName = counterName; + } + + public Integer getOpeningStock() { + return openingStock; + } + + public void setOpeningStock(Integer openingStock) { + this.openingStock = openingStock; + } + + public Integer getInvoicedQty() { + return invoicedQty; + } + + public void setInvoicedQty(Integer invoicedQty) { + this.invoicedQty = invoicedQty; + } + + public Integer getReceivedQty() { + return receivedQty; + } + + public void setReceivedQty(Integer receivedQty) { + this.receivedQty = receivedQty; + } + + public Integer getTesterStockAvailable() { + return testerStockAvailable; + } + + public void setTesterStockAvailable(Integer testerStockAvailable) { + this.testerStockAvailable = testerStockAvailable; + } + + public Integer getTesterUsed() { + return testerUsed; + } + + public void setTesterUsed(Integer testerUsed) { + this.testerUsed = testerUsed; + } + + public Double getTesterUsedPer() { + return testerUsedPer; + } + + public void setTesterUsedPer(Double testerUsedPer) { + this.testerUsedPer = testerUsedPer; + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/testerreports/TesterCounter.java b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/testerreports/TesterCounter.java new file mode 100644 index 0000000..cf95ddc --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/gsonGetterSetter/testerreports/TesterCounter.java @@ -0,0 +1,13 @@ +package com.cpm.lorealbaautomation.gsonGetterSetter.testerreports; + +import com.google.gson.annotations.SerializedName; + +import java.util.List; + +public class TesterCounter { + @SerializedName("Report_TesterCounter") + private List reportTesterCounter; + public List getReportTesterCounter() { + return reportTesterCounter; + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/leavemanagement/ApplyForLeaveActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/leavemanagement/ApplyForLeaveActivity.java new file mode 100644 index 0000000..f8cc0f5 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/leavemanagement/ApplyForLeaveActivity.java @@ -0,0 +1,485 @@ +package com.cpm.lorealbaautomation.leavemanagement; + +import android.annotation.SuppressLint; +import android.app.AlertDialog; +import android.app.DatePickerDialog; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; + +import androidx.annotation.NonNull; +import androidx.appcompat.app.AppCompatActivity; + +import android.os.Bundle; + +import androidx.cardview.widget.CardView; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; +import androidx.appcompat.widget.Toolbar; + +import android.view.LayoutInflater; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; +import android.view.WindowManager; +import android.widget.AdapterView; +import android.widget.ArrayAdapter; +import android.widget.Button; +import android.widget.EditText; +import android.widget.ImageView; +import android.widget.LinearLayout; +import android.widget.RadioButton; +import android.widget.RadioGroup; +import android.widget.Spinner; +import android.widget.TextView; + + +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.constant.AlertandMessages; +import com.cpm.lorealbaautomation.constant.CommonFunctions; +import com.cpm.lorealbaautomation.constant.CommonString; + +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.download.Downloader; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterLeaveType; +import com.cpm.lorealbaautomation.gsonGetterSetter.T_LeaveRequest; + +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.List; +import java.util.Objects; + +import static com.cpm.lorealbaautomation.dailyactivity.CounterProfileActivity.getDateDiff; + + +public class ApplyForLeaveActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemSelectedListener { + String counterId, visit_date, username, dob_start_date = "", End_date_str = "", TransId = "", start_day_Of_Month = "", str_onedayLeave = "", leaveType = "", leaveTypeId = "0"; + ArrayList leaveTypeList = new ArrayList<>(); + ArrayList leaveRequestList = new ArrayList<>(); + T_LeaveRequest object = new T_LeaveRequest(); + EditText apply_forleave_reason_edt; + ImageView img_cal_end_date, img_cal_start_date; + TextView txt_start_date, txt_end_date, tvHeader; + RecyclerView recycl_leave_status; + LinearLayout rl_leave_status, onedayRl; + private RadioGroup radioSexGroup; + private RadioButton radioSexButton; + ArrayAdapter leaveTypeAdapter; + Spinner leaveTypeSpin; + Button btn_save; + CardView card_applyLeave; + Lorealba_Database db; + Context context; + + int mYear, mMonth, mDay; + DatePickerDialog dpd; + Calendar c; + boolean clicked_flag = false; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_apply_for_leave); + context = this; + db = new Lorealba_Database(context); + db.open(); + Toolbar toolbar = findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + Objects.requireNonNull(getSupportActionBar()).setHomeButtonEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + if (!CommonFunctions.isTablet(context)) { + toolbar.setTitleTextAppearance(context, R.style.changestext_sizefor_mobile); + } + + iduserinterface(); + } + + @SuppressLint({"RestrictedApi", "CommitPrefEdits"}) + private void iduserinterface() { + ((ApplyForLeaveActivity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); + SharedPreferences preferences = PrefHelper.getPrefs(context); + counterId = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + username = preferences.getString(CommonString.KEY_USERNAME, ""); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + apply_forleave_reason_edt = (EditText) findViewById(R.id.apply_forleave_reason_edt); + img_cal_start_date = (ImageView) findViewById(R.id.img_cal_start_date); + img_cal_end_date = (ImageView) findViewById(R.id.img_cal_end_date); + txt_start_date = (TextView) findViewById(R.id.txt_start_date); + txt_end_date = (TextView) findViewById(R.id.txt_end_date); + btn_save = (Button) findViewById(R.id.btn_apply_leave); + card_applyLeave = (CardView) findViewById(R.id.card_applyLeave); + rl_leave_status = (LinearLayout) findViewById(R.id.rl_leave_status); + onedayRl = (LinearLayout) findViewById(R.id.onedayRl); + recycl_leave_status = (RecyclerView) findViewById(R.id.recycl_leave_status); + tvHeader = (TextView) findViewById(R.id.tvHeader); + radioSexGroup = (RadioGroup) findViewById(R.id.radioGrp_leave); + leaveTypeSpin = (Spinner) findViewById(R.id.leaveTypeSpin); + img_cal_start_date.setOnClickListener(this); + img_cal_end_date.setOnClickListener(this); + btn_save.setOnClickListener(this); + TransId = CommonFunctions.getUUID(context); + setTitle("Apply For Leave -" + username); + card_applyLeave.setVisibility(View.VISIBLE); + leaveDetails(); + db.open(); + leaveTypeList = db.getmasterLeaveType(true); + validate_spin(leaveTypeList); + } + + private void validate_spin(ArrayList leaveTypeList) { + leaveTypeAdapter = new ArrayAdapter<>(context, R.layout.spinner_custom_item); + leaveTypeAdapter.add("- Select Leave Type -"); + for (int i = 0; i < leaveTypeList.size(); i++) { + leaveTypeAdapter.add(leaveTypeList.get(i).getLeaveType()); + } + leaveTypeSpin.setAdapter(leaveTypeAdapter); + leaveTypeAdapter.setDropDownViewResource(R.layout.spinner_custom_item); + leaveTypeSpin.setOnItemSelectedListener(this); + } + + @SuppressLint("NonConstantResourceId") + @Override + public void onClick(View view) { + if (view.getId() == R.id.img_cal_start_date) { + clicked_flag = true; + c = Calendar.getInstance(); + mYear = c.get(Calendar.YEAR); + mMonth = c.get(Calendar.MONTH); + mDay = c.get(Calendar.DAY_OF_MONTH); + // Launch Date Picker Dialog + dpd = new DatePickerDialog(context, (view1, year, monthOfYear, dayOfMonth) -> { + String month_of_year = ""; + if ((monthOfYear + 1) < 10) { + month_of_year = "0" + (monthOfYear + 1); + } else { + month_of_year = String.valueOf(monthOfYear + 1); + } + if ((dayOfMonth) < 10) { + start_day_Of_Month = "0" + dayOfMonth; + } else { + start_day_Of_Month = String.valueOf(dayOfMonth); + } + dob_start_date = month_of_year + "/" + start_day_Of_Month + "/" + year; + txt_start_date.setText(dob_start_date); + txt_end_date.setText(""); + }, mYear, mMonth, mDay); + + Calendar calendar = Calendar.getInstance(); + ///disable current date + // calendar.add(Calendar.DATE, +1); + //Set yesterday time milliseconds as date pickers minimum date + dpd.getDatePicker().setMinDate(calendar.getTimeInMillis()); + dpd.getDatePicker().setMaxDate(System.currentTimeMillis() - (1000 * 60 * 60 * 24 * 25)); + dpd.show(); + } else if (view.getId() == R.id.img_cal_end_date) { + clicked_flag = true; + c = Calendar.getInstance(); + mYear = c.get(Calendar.YEAR); + mMonth = c.get(Calendar.MONTH); + mDay = c.get(Calendar.DAY_OF_MONTH); + // Launch Date Picker Dialog + dpd = new DatePickerDialog(context, (view12, year, monthOfYear, dayOfMonth) -> { + try { + String month_of_year = "", day_Of_Month = ""; + if ((monthOfYear + 1) < 10) { + month_of_year = "0" + (monthOfYear + 1); + } else { + month_of_year = String.valueOf(monthOfYear + 1); + } + + if ((dayOfMonth) < 10) { + day_Of_Month = "0" + dayOfMonth; + } else { + day_Of_Month = String.valueOf(dayOfMonth); + } + + End_date_str = month_of_year + "/" + day_Of_Month + "/" + year; + @SuppressLint("SimpleDateFormat") int monthDiffence = (int) getDateDiff(new SimpleDateFormat("MM"), dob_start_date, End_date_str); + if (dob_start_date.equalsIgnoreCase(End_date_str)) { + if (dob_start_date.equalsIgnoreCase(visit_date) && End_date_str.equalsIgnoreCase(visit_date)) { + db.open(); + leaveTypeList = db.getmasterLeaveType(false); + validate_spin(leaveTypeList); + } + txt_end_date.setText(End_date_str); + onedayRl.setVisibility(View.VISIBLE); + leaveTypeSpin.setVisibility(View.VISIBLE); + } else if (monthDiffence == 0) { + str_onedayLeave = ""; + onedayRl.setVisibility(View.GONE); + leaveTypeSpin.setVisibility(View.VISIBLE); + int startdayofmonth = Integer.parseInt(start_day_Of_Month); + int enddayofmonth = Integer.parseInt(day_Of_Month); + if (startdayofmonth > enddayofmonth) { + txt_end_date.setText(""); + AlertandMessages.showToastMsg(context, "End Date Should be greater than Start Date"); + } else { + txt_end_date.setText(End_date_str); + } + db.open(); + leaveTypeList = db.getmasterLeaveType(true); + validate_spin(leaveTypeList); + } else if (monthDiffence != 0) { + str_onedayLeave = ""; + onedayRl.setVisibility(View.GONE); + txt_end_date.setText(End_date_str); + leaveTypeSpin.setVisibility(View.VISIBLE); + leaveTypeList = db.getmasterLeaveType(true); + validate_spin(leaveTypeList); + } else { + str_onedayLeave = ""; + db.open(); + leaveTypeList = db.getmasterLeaveType(true); + validate_spin(leaveTypeList); + onedayRl.setVisibility(View.GONE); + txt_end_date.setText(End_date_str); + leaveTypeSpin.setVisibility(View.VISIBLE); + } + + } catch (Exception e) { + e.fillInStackTrace(); + } + }, mYear, mMonth, mDay); + // TODO Hide Future Date Here + // dpd.getDatePicker().setMaxDate(System.currentTimeMillis()); + // TODO Hide Past Date Here + Calendar calendar = Calendar.getInstance(); + //calendar.add(Calendar.DATE); + //Set yesterday time milliseconds as date pickers minimum date + dpd.getDatePicker().setMinDate(calendar.getTimeInMillis()); + dpd.getDatePicker().setMaxDate(System.currentTimeMillis() - (1000 * 60 * 60 * 24 * 25)); + dpd.show(); + } else if (view.getId() == R.id.btn_apply_leave) { + if (txt_start_date.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Select Start Date Of Leave "); + } else if (txt_end_date.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Select End Date Of Leave "); + } else if (leaveTypeSpin.getSelectedItemId() == 0) { + AlertandMessages.showToastMsg(context, "Please Select Leave Type"); + } else if (!checksameapplyeidDate()) { + AlertandMessages.showToastMsg(context, "You have already applied for a leave on the specified date"); + } else { + AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle(R.string.parinaam).setMessage(R.string.alertsaveData_approval); + builder.setPositiveButton(android.R.string.yes, (dialogInterface, i) -> { + try { + object = new T_LeaveRequest(); + // get selected radio button from radioGroup + int selectedId = radioSexGroup.getCheckedRadioButtonId(); + // find the radiobutton by returned id + radioSexButton = (RadioButton) findViewById(selectedId); + object.setUserId(username); + object.setRequestDate(visit_date); + object.setFromDate(txt_start_date.getText().toString()); + object.setUpload_start_date_str(dob_start_date); + object.setToDate(txt_end_date.getText().toString()); + object.setUpload_end_date_str(End_date_str); + object.setLeave_reason(apply_forleave_reason_edt.getText().toString().trim().replaceAll("[(!@#$%^&*?)\"]", " ")); + object.setLeaveStatus("Pending"); + object.setTransId(TransId); + if (dob_start_date.equalsIgnoreCase(End_date_str)) { + str_onedayLeave = radioSexButton.getText().toString(); + } else { + str_onedayLeave = ""; + } + object.setStr_leaveType(leaveType); + object.setStr_leaveTypeId(leaveTypeId); + object.setOne_day_leave_str(str_onedayLeave); + object.setTransId(TransId); + db.open(); + db.insert_leave_management_data(username, visit_date, counterId, object); + //download service + Intent intent = new Intent(context, Downloader.class); + intent.putExtra(CommonString.KEY_LEAVE_Mangemennt, object); + Downloader.enqueueWork(context, intent); + AlertandMessages.showToastMsg(context, "Data Saved Successfully"); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + apply_forleave_reason_edt.setText(""); + apply_forleave_reason_edt.setHint("Please Fill Reason"); + radioSexGroup.clearCheck(); + ((RadioButton) findViewById(R.id.radioM)).setChecked(true); + leaveTypeSpin.setSelection(0); + txt_start_date.setText(""); + txt_end_date.setText(""); + clicked_flag = false; + leaveDetails(); + } catch (Exception e) { + e.fillInStackTrace(); + } + }); + builder.setNegativeButton(android.R.string.cancel, (dialogInterface, i) -> dialogInterface.cancel()); + builder.show(); + } + + } + } + + private boolean checksameapplyeidDate() { + boolean result = true; + if (!leaveRequestList.isEmpty()) { + for (int k = 0; k < leaveRequestList.size(); k++) { + if (leaveRequestList.get(k).getFromDate().equalsIgnoreCase(txt_start_date.getText().toString()) || leaveRequestList.get(k).getToDate().equalsIgnoreCase(txt_start_date.getText().toString())) { + result = false; + break; + } + } + } + + return result; + } + + @Override + public void onItemSelected(AdapterView adapterView, View view, int pos, long l) { + if (adapterView.getId() == R.id.leaveTypeSpin) { + if (pos != 0) { + leaveType = leaveTypeList.get(pos - 1).getLeaveType(); + leaveTypeId = leaveTypeList.get(pos - 1).getLeaveTypeId().toString(); + } else { + leaveType = ""; + leaveTypeId = "0"; + } + } + } + + @Override + public void onNothingSelected(AdapterView adapterView) { + + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + if (id == android.R.id.home) { + if (clicked_flag) { + AlertDialog.Builder builder = new AlertDialog.Builder(context).setMessage(CommonString.ONBACK_ALERT_MESSAGE).setCancelable(false).setPositiveButton("Ok", (dialog, id1) -> { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + ApplyForLeaveActivity.this.finish(); + }).setNegativeButton("Cancel", (dialog, id12) -> dialog.cancel()); + AlertDialog alert = builder.create(); + alert.show(); + } else { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + ApplyForLeaveActivity.this.finish(); + } + } + + + return super.onOptionsItemSelected(item); + } + + @Override + public void onBackPressed() { + if (clicked_flag) { + AlertDialog.Builder builder = new AlertDialog.Builder(context).setMessage(CommonString.ONBACK_ALERT_MESSAGE).setCancelable(false).setPositiveButton("Ok", (dialog, id) -> { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + ApplyForLeaveActivity.this.finish(); + }).setNegativeButton("Cancel", (dialog, id) -> dialog.cancel()); + AlertDialog alert = builder.create(); + alert.show(); + } else { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + ApplyForLeaveActivity.this.finish(); + } + } + + + @SuppressLint("SetTextI18n") + private void leaveDetails() { + db.open(); + if (!db.getinserted_leave_requestList(counterId, username, visit_date, null).isEmpty()) { + db.open(); + leaveRequestList = db.get_leave_List(username, visit_date, false); + } else { + db.open(); + leaveRequestList = db.get_leave_List(username, visit_date, true); + } + + if (!leaveRequestList.isEmpty()) { + //Collections.reverse(leaveRequestList); + tvHeader.setVisibility(View.VISIBLE); + recycl_leave_status.setVisibility(View.VISIBLE); + recycl_leave_status.setAdapter(new ValueAdapter(context, leaveRequestList)); + recycl_leave_status.setLayoutManager(new LinearLayoutManager(context)); + } else { + tvHeader.setVisibility(View.GONE); + recycl_leave_status.setVisibility(View.GONE); + } + } + + private class ValueAdapter extends RecyclerView.Adapter { + LayoutInflater inflator; + List data; + + public ValueAdapter(Context context, List data) { + inflator = LayoutInflater.from(context); + this.data = data; + } + + @NonNull + @Override + public ValueAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) { + View view = inflator.inflate(R.layout.details_leave_mangement, parent, false); + return new ValueAdapter.MyViewHolder(view); + } + + @SuppressLint("SetTextI18n") + @Override + public void onBindViewHolder(final ValueAdapter.MyViewHolder holder, final int position) { + final T_LeaveRequest current = data.get(position); + + holder.txt_date_of_applied_leave.setText(current.getRequestDate()); + holder.txt_date_of_applied_leave.setId(position); + + holder.txt_from_date.setText(current.getFromDate()); + holder.txt_from_date.setId(position); + + holder.txt_to_date.setText(current.getToDate()); + holder.txt_to_date.setId(position); + + holder.txt_leavetype.setText(current.getStr_leaveType()); + holder.txt_leavetype.setId(position); + + if (current.getLeaveStatus().equalsIgnoreCase("Pending")) { + holder.txt_leave_status.setText(" " + current.getLeaveStatus()); + holder.txt_leave_status.setTextColor(getResources().getColor(R.color.red)); + holder.txt_leave_status.setId(position); + } else if (current.getLeaveStatus().equalsIgnoreCase("Accept")) { + holder.txt_leave_status.setText(" " + current.getLeaveStatus()); + holder.txt_leave_status.setTextColor(getResources().getColor(R.color.green)); + holder.txt_leave_status.setId(position); + } else if (current.getLeaveStatus().equalsIgnoreCase("Reject")) { + holder.txt_leave_status.setText(" " + current.getLeaveStatus()); + holder.txt_leave_status.setTextColor(getResources().getColor(R.color.sticky)); + holder.txt_leave_status.setId(position); + } else { + holder.txt_leave_status.setText(" " + current.getLeaveStatus()); + holder.txt_leave_status.setId(position); + holder.txt_leave_status.setTextColor(getResources().getColor(R.color.black)); + } + } + + + @Override + public int getItemCount() { + return data.size(); + } + + class MyViewHolder extends RecyclerView.ViewHolder { + TextView txt_date_of_applied_leave, txt_from_date, txt_to_date, txt_leave_status, txt_leavetype; + + public MyViewHolder(View itemView) { + super(itemView); + txt_date_of_applied_leave = (TextView) itemView.findViewById(R.id.txt_date_of_applied_leave); + txt_from_date = (TextView) itemView.findViewById(R.id.txt_from_date); + txt_to_date = (TextView) itemView.findViewById(R.id.txt_to_date); + txt_leave_status = (TextView) itemView.findViewById(R.id.txt_leave_status); + txt_leavetype = (TextView) itemView.findViewById(R.id.txt_leavetype); + } + } + } + + +} + diff --git a/app/src/main/java/com/cpm/lorealbaautomation/leavemanagement/LeaveCalenderViewActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/leavemanagement/LeaveCalenderViewActivity.java new file mode 100644 index 0000000..a490460 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/leavemanagement/LeaveCalenderViewActivity.java @@ -0,0 +1,248 @@ +package com.cpm.lorealbaautomation.leavemanagement; + +import static com.prolificinteractive.materialcalendarview.CalendarDay.from; + +import android.annotation.SuppressLint; +import android.content.Context; +import android.content.SharedPreferences; +import android.graphics.Typeface; +import android.os.Bundle; +import android.text.style.RelativeSizeSpan; +import android.text.style.StyleSpan; +import android.util.DisplayMetrics; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; + +import androidx.appcompat.app.AppCompatActivity; + +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.adapter.ApprovedLeaveAdapter; +import com.cpm.lorealbaautomation.constant.CommonFunctions; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.databinding.ActivityLeaveCalenderBinding; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.gsonGetterSetter.leaves.TLeaveRequestDetail; +import com.prolificinteractive.materialcalendarview.CalendarDay; +import com.prolificinteractive.materialcalendarview.DayViewDecorator; +import com.prolificinteractive.materialcalendarview.DayViewFacade; +import com.prolificinteractive.materialcalendarview.spans.DotSpan; + +import org.threeten.bp.LocalDate; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +import androidx.core.content.ContextCompat; +import androidx.recyclerview.widget.LinearLayoutManager; + +import com.cpm.lorealbaautomation.R; + +public class LeaveCalenderViewActivity extends AppCompatActivity implements View.OnClickListener { + List appliedLeaves = new ArrayList<>(); + List approvedLeaves = new ArrayList<>(); + List rejectLeaves = new ArrayList<>(); + String counter_Id, username, visit_date; + private ActivityLeaveCalenderBinding binding = null; + Lorealba_Database db; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + binding = ActivityLeaveCalenderBinding.inflate(getLayoutInflater()); + setContentView(binding.getRoot()); + db = new Lorealba_Database(this); + db.open(); + setSupportActionBar(binding.toolbar); + Objects.requireNonNull(getSupportActionBar()).setHomeButtonEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + SharedPreferences preferences = PrefHelper.getPrefs(this); + counter_Id = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + username = preferences.getString(CommonString.KEY_USERNAME, ""); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + if (!CommonFunctions.isTablet(this)) { + binding.toolbar.setTitleTextAppearance(this, R.style.changestext_sizefor_mobile); + } + setTitle("Leave/Govt. holidays Details - " + username); + db.open(); + appliedLeaves = db.getLeaveDetails(username, "Pending"); + approvedLeaves = db.getLeaveDetails(username, "Accept"); + rejectLeaves = db.getLeaveDetails(username, "Reject"); + // Apply decorators for Applied Leaves, Approved Leaves, and Government Holidays + if (CommonFunctions.isTablet(this)) { + // Get display metrics + DisplayMetrics displayMetrics = getResources().getDisplayMetrics(); + // Calculate height as 50% of screen height + int height = (int) (displayMetrics.widthPixels * 0.9); + // Set height for MaterialCalendarView + ViewGroup.LayoutParams layoutParams = binding.contentCalenarView.calendarView.getLayoutParams(); + layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT; + layoutParams.height = height; + binding.contentCalenarView.calendarView.setLayoutParams(layoutParams); + binding.contentCalenarView.calendarView.requestLayout(); + + binding.contentCalenarView.calendarView.setDateTextAppearance(R.style.CalendarDateText); + binding.contentCalenarView.calendarView.setWeekDayTextAppearance(R.style.CalendarWeekDayText); + } + binding.contentCalenarView.calendarView.addDecorator(new TextAndDotDecorator(ContextCompat.getColor(this, R.color.applied_leave), appliedLeaves, this)); // Applied Leaves - Red + binding.contentCalenarView.calendarView.addDecorator(new TextAndDotDecorator(ContextCompat.getColor(this, R.color.approved_leave), approvedLeaves, this)); // Approved Leaves - Green + binding.contentCalenarView.calendarView.addDecorator(new TextAndDotDecorator(ContextCompat.getColor(this, R.color.reject_leave), rejectLeaves, this)); + // Handle the click event on the calendar + binding.contentCalenarView.calendarView.setOnDateChangedListener((widget, date, selected) -> { + // Call the method to show leave info for the clicked date + showLeaveInfo(date); + }); + + binding.btnCalendarView.setOnClickListener(this); + binding.btnTabullarView.setOnClickListener(this); + binding.btnGovHoliday.setOnClickListener(this); + showLeaveInfo(today()); + } + + private CalendarDay today() { + return from(LocalDate.now()); + } + + /** + * Show leave info for a particular date + */ + @SuppressLint("SetTextI18n") + private void showLeaveInfo(CalendarDay date) { + //test("CalendarDay", date.getMonth() + "-" + date.getDay() + "-" + date.getYear()); + TLeaveRequestDetail details = null; + if (appliedLeaves.contains(date)) { + db.open(); + details = db.getLeaveDetails(username, getString(R.string.pending), date.getYear(), date.getMonth(), date.getDay()); + } else if (approvedLeaves.contains(date)) { + db.open(); + details = db.getLeaveDetails(username, getString(R.string.approved), date.getYear(), date.getMonth(), date.getDay()); + } else if (rejectLeaves.contains(date)) { + db.open(); + details = db.getLeaveDetails(username, getString(R.string.reject), date.getYear(), date.getMonth(), date.getDay()); + } + if (details != null) { + binding.contentCalenarView.rlLeaveDetail.setVisibility(View.VISIBLE); + String day = String.valueOf(date.getDay()).length() == 1 ? "0" + date.getDay() : String.valueOf(date.getDay()); + String month = String.valueOf(date.getMonth()).length() == 1 ? "0" + date.getMonth() : String.valueOf(date.getMonth()); + binding.contentCalenarView.tvLeaveDate.setText(CommonFunctions.formatDate(month + "/" + day + "/" + date.getYear())); + binding.contentCalenarView.tvLeaveType.setText(details.getLeaveSubType() != null && !details.getLeaveSubType().isEmpty() ? details.getLeaveType() + " - " + details.getLeaveSubType() : details.getLeaveType()); + if (details.getReason() != null && !details.getReason().isEmpty()) { + binding.contentCalenarView.tvLeaveReason.setVisibility(View.VISIBLE); + binding.contentCalenarView.tvLeaveReason.setText(details.getReason()); + } else binding.contentCalenarView.tvLeaveReason.setVisibility(View.GONE); + } else { + binding.contentCalenarView.rlLeaveDetail.setVisibility(View.GONE); + } + } + + + @SuppressLint({"NonConstantResourceId", "UseCompatLoadingForDrawables"}) + @Override + public void onClick(View view) { + + if (view.getId() == R.id.btnCalendarView) { + binding.btnCalendarView.setBackground(getResources().getDrawable(R.drawable.rouded_corner)); + binding.btnCalendarView.setTextColor(getResources().getColor(R.color.white)); + binding.btnTabullarView.setBackground(null); + binding.btnTabullarView.setTextColor(getResources().getColor(R.color.grayfor_login)); + binding.btnGovHoliday.setBackground(null); + binding.btnGovHoliday.setTextColor(getResources().getColor(R.color.grayfor_login)); + binding.contentCalenarView.parent.setVisibility(View.VISIBLE); + binding.tabullarView.parent.setVisibility(View.GONE); + + } else if (view.getId() == R.id.btnTabullarView) { + binding.btnTabullarView.setBackground(getResources().getDrawable(R.drawable.rouded_corner)); + binding.btnTabullarView.setTextColor(getResources().getColor(R.color.white)); + binding.btnCalendarView.setBackground(null); + binding.btnCalendarView.setTextColor(getResources().getColor(R.color.grayfor_login)); + binding.btnGovHoliday.setBackground(null); + binding.btnGovHoliday.setTextColor(getResources().getColor(R.color.grayfor_login)); + binding.contentCalenarView.parent.setVisibility(View.GONE); + binding.tabullarView.parent.setVisibility(View.VISIBLE); + CallRecycler("TabularView"); + + } else if (view.getId() == R.id.btnGovHoliday) { + binding.btnGovHoliday.setBackground(getResources().getDrawable(R.drawable.rouded_corner)); + binding.btnGovHoliday.setTextColor(getResources().getColor(R.color.white)); + binding.btnCalendarView.setBackground(null); + binding.btnCalendarView.setTextColor(getResources().getColor(R.color.grayfor_login)); + binding.btnTabullarView.setBackground(null); + binding.btnTabullarView.setTextColor(getResources().getColor(R.color.grayfor_login)); + binding.contentCalenarView.parent.setVisibility(View.GONE); + binding.tabullarView.parent.setVisibility(View.VISIBLE); + CallRecycler("GovtHolidays"); + + } + + } + + // Custom decorator class to mark dates with colored dots + public static class TextAndDotDecorator implements DayViewDecorator { + private final int color; + private final List dates; + Context context; + + public TextAndDotDecorator(int color, List dates, Context context) { + this.color = color; + this.dates = dates; + this.context = context; + } + + @Override + public boolean shouldDecorate(CalendarDay day) { + return dates.contains(day); // Only decorate the dates in this list + } + + @Override + public void decorate(DayViewFacade view) { + // Add a dot below the date + view.addSpan(new DotSpan(10f, color)); // Draw a dot with the color + if (CommonFunctions.isTablet(context)) + view.addSpan(new RelativeSizeSpan(1f)); // 1.5x the default size + view.addSpan(new StyleSpan(Typeface.BOLD)); // Optional: Make text bold + } + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + if (id == android.R.id.home) { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + this.finish(); + + } + + return super.onOptionsItemSelected(item); + } + + @Override + public void onBackPressed() { + super.onBackPressed(); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + this.finish(); + + } + + @SuppressLint("SetTextI18n") + private void CallRecycler(String type) { + db.open(); + ArrayList list = db.getHolidaysOrLeaves(username, type); + if (type.equals("TabularView")) { + binding.tabullarView.tvHeader.setText(getString(R.string.applied_approved_leave_details)); + } else { + binding.tabullarView.tvHeader.setText(getString(R.string.gov_holidays) + " Details"); + } + + if (!list.isEmpty()) { + binding.tabullarView.tvNodata.setVisibility(View.GONE); + binding.tabullarView.leveRecyl.setVisibility(View.VISIBLE); + binding.tabullarView.leveRecyl.setAdapter(new ApprovedLeaveAdapter(this, type, list)); + binding.tabullarView.leveRecyl.setLayoutManager(new LinearLayoutManager(this)); + } else { + binding.tabullarView.tvNodata.setVisibility(View.VISIBLE); + binding.tabullarView.leveRecyl.setVisibility(View.GONE); + } + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/leavemanagement/LeaveManagemntActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/leavemanagement/LeaveManagemntActivity.java new file mode 100644 index 0000000..6fc8365 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/leavemanagement/LeaveManagemntActivity.java @@ -0,0 +1,153 @@ +package com.cpm.lorealbaautomation.leavemanagement; + +import android.annotation.SuppressLint; +import android.content.Intent; +import android.content.SharedPreferences; + +import androidx.appcompat.app.AppCompatActivity; + +import android.os.Bundle; + +import androidx.appcompat.widget.Toolbar; + +import android.view.MenuItem; +import android.view.View; + +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.constant.CommonFunctions; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.databinding.ActivityLeaveCalenderBinding; +import com.cpm.lorealbaautomation.databinding.ActivityLeaveManagemntBinding; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.gsonGetterSetter.leaves.TLeaveLedgerSummary; + +import java.util.Objects; + +public class LeaveManagemntActivity extends AppCompatActivity implements View.OnClickListener { + String counter_Id, visit_date, username; + Lorealba_Database db; + private ActivityLeaveManagemntBinding binding = null; + String from = ""; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + binding = ActivityLeaveManagemntBinding.inflate(getLayoutInflater()); + setContentView(binding.getRoot()); + db = new Lorealba_Database(this); + db.open(); + Toolbar toolbar = findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + Objects.requireNonNull(getSupportActionBar()).setHomeButtonEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + if (!CommonFunctions.isTablet(this)) { + toolbar.setTitleTextAppearance(this, R.style.changestext_sizefor_mobile); + } + if (getIntent().getStringExtra(CommonString.TAG_FROM) != null) { + from = getIntent().getStringExtra(CommonString.TAG_FROM); + } + iduserinterface(); + setTitle(from.isEmpty() ? "Leave Management - " + username : "Leave Ledger - " + username); + } + + private void iduserinterface() { + SharedPreferences preferences = PrefHelper.getPrefs(this); + counter_Id = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + username = preferences.getString(CommonString.KEY_USERNAME, ""); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + + if (!from.isEmpty()) { + binding.contentLeave.cardApplyLeave.setVisibility(View.INVISIBLE); + } else { + binding.contentLeave.cardApplyLeave.setVisibility(View.VISIBLE); + } + binding.contentLeave.cardApplyLeave.setOnClickListener(this); + binding.contentLeave.cardLeaveStatus.setOnClickListener(this); + db.open(); + } + + @Override + protected void onResume() { + super.onResume(); + db.open(); + leaveLedgerDetails(); + } + + @SuppressLint("NonConstantResourceId") + @Override + public void onClick(View view) { + if (view.getId() == R.id.card_apply_leave) { + startActivity(new Intent(this, ApplyForLeaveActivity.class)); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + } else if (view.getId() == R.id.card_leave_status) { + startActivity(new Intent(this, LeaveCalenderViewActivity.class)); + } + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + if (id == android.R.id.home) { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + LeaveManagemntActivity.this.finish(); + + } + + return super.onOptionsItemSelected(item); + } + + @Override + public void onBackPressed() { + super.onBackPressed(); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + LeaveManagemntActivity.this.finish(); + } + + @SuppressLint("SetTextI18n") + private void leaveLedgerDetails() { + db.open(); + TLeaveLedgerSummary personalLeave = db.getLeaveLedger(username, true); + TLeaveLedgerSummary leaveLedgerTotal = db.getLeaveLedgerTotal(username); + binding.contentLeave.tvHeader.setText(getString(R.string.leaveLedgerDetails)); + if (personalLeave != null) { + binding.contentLeave.rlPersonalLeave.setVisibility(View.VISIBLE); + binding.contentLeave.tvPersonalLeave.setText(personalLeave.getLeaveType()); + binding.contentLeave.earnedleaveTV.setText(personalLeave.getEarned().toString()); + binding.contentLeave.takenmonthleaveTV.setText(personalLeave.getTakenThisMonth().toString()); + binding.contentLeave.totleavetakenTV.setText(personalLeave.getTotalLeavesTaken().toString()); + binding.contentLeave.balanceleaveTV.setText(personalLeave.getBalance().toString()); + } else { + binding.contentLeave.rlPersonalLeave.setVisibility(View.GONE); + } + + TLeaveLedgerSummary emergencyLeave = db.getLeaveLedger(username, false); + if (personalLeave != null) { + binding.contentLeave.rlEmrLeave.setVisibility(View.VISIBLE); + binding.contentLeave.tvEmrLeave.setText(emergencyLeave.getLeaveType()); + binding.contentLeave.earnedleaveSLTV.setText(emergencyLeave.getEarned().toString()); + binding.contentLeave.takenmonthleaveSLTV.setText(emergencyLeave.getTakenThisMonth().toString()); + binding.contentLeave.totleavetakenSLTV.setText(emergencyLeave.getTotalLeavesTaken().toString()); + binding.contentLeave.balanceleaveSLTV.setText(emergencyLeave.getBalance().toString()); + } else binding.contentLeave.rlEmrLeave.setVisibility(View.GONE); + + if (leaveLedgerTotal != null) { + binding.contentLeave.rlTotalLeave.setVisibility(View.VISIBLE); + binding.contentLeave.totleavetakentot.setText(leaveLedgerTotal.getTotalLeavesTaken().toString()); + binding.contentLeave.takenmonthleaveTotTV.setText(leaveLedgerTotal.getTakenThisMonth().toString()); + binding.contentLeave.earnedleaveTotalTV.setText(leaveLedgerTotal.getEarned().toString()); + binding.contentLeave.balanceleaveTotTV.setText(leaveLedgerTotal.getBalance().toString()); + } else { + binding.contentLeave.rlTotalLeave.setVisibility(View.GONE); + } + + if (emergencyLeave != null || personalLeave != null) { + binding.contentLeave.tvNodata.setVisibility(View.GONE); + binding.contentLeave.rlLeaveLeadger.setVisibility(View.VISIBLE); + } else { + binding.contentLeave.rlLeaveLeadger.setVisibility(View.GONE); + binding.contentLeave.tvNodata.setVisibility(View.VISIBLE); + } + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/makeupexpert/BaProfileMultiSelection.java b/app/src/main/java/com/cpm/lorealbaautomation/makeupexpert/BaProfileMultiSelection.java new file mode 100644 index 0000000..d1cd540 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/makeupexpert/BaProfileMultiSelection.java @@ -0,0 +1,220 @@ +package com.cpm.lorealbaautomation.makeupexpert; + +import android.app.AlertDialog; +import android.content.Context; +import android.content.DialogInterface; +import android.content.res.TypedArray; +import android.graphics.Typeface; +import androidx.appcompat.widget.AppCompatSpinner; +import android.util.AttributeSet; +import android.util.Log; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.ArrayAdapter; +import android.widget.BaseAdapter; +import android.widget.CheckBox; +import android.widget.ListView; +import android.widget.TextView; + +import com.androidbuts.multispinnerfilter.KeyPairBoolData; +import com.androidbuts.multispinnerfilter.SpinnerListener; +import com.cpm.lorealbaautomation.R; + + +import java.util.ArrayList; +import java.util.List; + +public class BaProfileMultiSelection extends AppCompatSpinner implements DialogInterface.OnCancelListener { + private static final String TAG = BaProfileMultiSelection.class.getSimpleName(); + private String defaultText = ""; + private String spinnerTitle = ""; + private SpinnerListener listener; + private int selected = 0; + MultipleSelectionSpinAdapter adapter; + List productList = new ArrayList<>(); + public static AlertDialog ad; + + public BaProfileMultiSelection(Context context) { + super(context); + } + + public BaProfileMultiSelection(Context arg0, AttributeSet arg1) { + super(arg0, arg1); + TypedArray a = arg0.obtainStyledAttributes(arg1, R.styleable.MultiSpinnerSearch); + for (int i = 0; i < a.getIndexCount(); ++i) { + int attr = a.getIndex(i); + if (attr == R.styleable.MultiSpinnerSearch_hintText) { + spinnerTitle = a.getString(attr); + defaultText = spinnerTitle; + break; + } + } + Log.i(TAG, "spinnerTitle: " + spinnerTitle); + a.recycle(); + } + + public BaProfileMultiSelection(Context arg0, AttributeSet arg1, int arg2) { + super(arg0, arg1, arg2); + } + + @Override + public void onCancel(DialogInterface dialog) { + // refresh text on spinner + StringBuilder spinnerBuffer = new StringBuilder(); + for (int i = 0; i < productList.size(); i++) { + if (productList.get(i).isSelected()) { + spinnerBuffer.append(productList.get(i).getName().trim()); + spinnerBuffer.append(", "); + } + } + + String spinnerText = spinnerBuffer.toString(); + if (spinnerText.length() > 2) + spinnerText = spinnerText.substring(0, spinnerText.length() - 2); + else + spinnerText = defaultText; + + ArrayAdapter adapterSpinner = new ArrayAdapter<>(getContext(), R.layout.spinner_custom_item, new String[]{spinnerText}); + setAdapter(adapterSpinner); + if (adapter != null) + adapter.notifyDataSetChanged(); + listener.onItemsSelected(productList); + } + + @Override + public boolean performClick() { + AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); + builder.setTitle("Please Select"); + final LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); + final View view = inflater.inflate(R.layout.alert_dialog_listview_multi, null); + builder.setView(view); + final ListView listView = view.findViewById(R.id.alertSearchListView); + listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); + listView.setFastScrollEnabled(false); + adapter = new MultipleSelectionSpinAdapter(getContext(), productList); + listView.setAdapter(adapter); + builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { + + @Override + public void onClick(DialogInterface dialog, int which) { + Log.i(TAG, " ITEMS : " + productList.size()); + dialog.cancel(); + } + }); + + builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialogInterface, int i) { + Log.i(TAG, " ITEMS : " + productList.size()); + dialogInterface.dismiss(); + } + }); + builder.setOnCancelListener(this); + ad = builder.show(); + return true; + } + + public void setItemsProduct(List items, int position, SpinnerListener listener) { + this.productList = items; + this.listener = (SpinnerListener) listener; + StringBuilder spinnerBuffer = new StringBuilder(); + + for (int i = 0; i < items.size(); i++) { + if (items.get(i).isSelected()) { + spinnerBuffer.append(items.get(i).getName()); + spinnerBuffer.append(", "); + } + } + + + if (spinnerBuffer.length() > 2) + defaultText = spinnerBuffer.toString().substring(0, spinnerBuffer.toString().length() - 2); + + ArrayAdapter adapterSpinner = new ArrayAdapter<>(getContext(), R.layout.spinner_custom_item, new String[]{defaultText}); + setAdapter(adapterSpinner); + + if (position != -1) { + items.get(position).setSelected(true); + onCancel(null); + } + } + + //Adapter Class + public class MultipleSelectionSpinAdapter extends BaseAdapter { + + List arrayList; + ArrayList mOriginalValues; // Original Values + LayoutInflater inflater; + + public MultipleSelectionSpinAdapter(Context context, List arrayList) { + this.arrayList = arrayList; + inflater = LayoutInflater.from(context); + } + + @Override + public int getCount() { + return arrayList.size(); + } + + + @Override + public Object getItem(int position) { + return position; + } + + @Override + public long getItemId(int position) { + return position; + } + + private class ViewHolder { + TextView textView; + CheckBox checkBox; + } + + @Override + public View getView(final int position, View convertView, ViewGroup parent) { + MultipleSelectionSpinAdapter.ViewHolder holder; + if (convertView == null) { + holder = new MultipleSelectionSpinAdapter.ViewHolder(); + convertView = inflater.inflate(R.layout.item_listview_multiple_row, parent, false); + holder.textView = (TextView) convertView.findViewById(R.id.alertTextView); + holder.checkBox = (CheckBox) convertView.findViewById(R.id.alertCheckbox); + convertView.setTag(holder); + } else { + holder = (MultipleSelectionSpinAdapter.ViewHolder) convertView.getTag(); + } + + final KeyPairBoolData data = arrayList.get(position); + + holder.textView.setText(data.getName()); + holder.textView.setTypeface(null, Typeface.NORMAL); + holder.checkBox.setChecked(data.isSelected()); + + convertView.setOnClickListener(new OnClickListener() { + public void onClick(View v) { + if (data.isSelected()) { // deselect + selected--; + } else {// selected + selected++; + } + + final MultipleSelectionSpinAdapter.ViewHolder temp = (MultipleSelectionSpinAdapter.ViewHolder) v.getTag(); + temp.checkBox.setChecked(!temp.checkBox.isChecked()); + data.setSelected(!data.isSelected()); + Log.i("", "On Click Selected Item : " + data.getName() + " : " + data.isSelected()); + notifyDataSetChanged(); + } + }); + + + if (data.isSelected()) { + holder.textView.setTypeface(null, Typeface.NORMAL); + } + + holder.checkBox.setTag(holder); + return convertView; + } + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/makeupexpert/CategorySpinnerInterface.java b/app/src/main/java/com/cpm/lorealbaautomation/makeupexpert/CategorySpinnerInterface.java new file mode 100644 index 0000000..3955efe --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/makeupexpert/CategorySpinnerInterface.java @@ -0,0 +1,11 @@ +package com.cpm.lorealbaautomation.makeupexpert; + + +import com.cpm.lorealbaautomation.gsonGetterSetter.MEMEAuditQuestion; + +import java.util.ArrayList; + + +public interface CategorySpinnerInterface { + void onItemsSelectedCategory(ArrayList items); +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/makeupexpert/MEQuizActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/makeupexpert/MEQuizActivity.java new file mode 100644 index 0000000..9a3fefe --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/makeupexpert/MEQuizActivity.java @@ -0,0 +1,730 @@ +package com.cpm.lorealbaautomation.makeupexpert; + +import android.annotation.SuppressLint; +import android.app.Activity; +import android.app.AlertDialog; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.os.Bundle; + +import com.google.android.material.floatingactionbutton.FloatingActionButton; + +import androidx.core.content.ContextCompat; +import androidx.appcompat.app.AppCompatActivity; +import androidx.cardview.widget.CardView; +import androidx.recyclerview.widget.RecyclerView; +import androidx.appcompat.widget.Toolbar; + +import android.text.InputFilter; +import android.text.InputType; +import android.text.Spanned; +import android.util.Log; +import android.view.LayoutInflater; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; +import android.view.inputmethod.InputMethodManager; +import android.widget.AbsListView; +import android.widget.AdapterView; +import android.widget.ArrayAdapter; +import android.widget.BaseExpandableListAdapter; +import android.widget.EditText; +import android.widget.ExpandableListView; +import android.widget.ImageView; +import android.widget.RelativeLayout; +import android.widget.Spinner; +import android.widget.TextView; + +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.constant.AlertandMessages; +import com.cpm.lorealbaautomation.constant.CommonFunctions; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.download.Downloader; +import com.cpm.lorealbaautomation.gsonGetterSetter.MEMEAuditQuestion; + +import java.io.File; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Objects; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class MEQuizActivity extends AppCompatActivity implements View.OnClickListener { + String error_msg = "", pathforcheck = "", _path = "", str, img_str = "", visit_date, username, counter_Id; + HashMap> listDataChild; + ArrayList question_list; + List checkHeaderArray = new ArrayList<>(); + List checkGroupArray = new ArrayList<>(); + ArrayList listDataHeader; + boolean checkflag = true, multitouch = false, Singletouch = false, update_flag = false; + SharedPreferences preferences; + ExpandableListView expandableListView; + ExpandableListAdapter adapter; + FloatingActionButton fab; + private static int child_position = -1, group_position = -1; + MEMEAuditQuestion obj = null; + Lorealba_Database db; + Toolbar toolbar; + Context context; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_audit); + context = this; + db = new Lorealba_Database(context); + db.open(); + + toolbar = (Toolbar) findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + preferences = PrefHelper.getPrefs(context); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + username = preferences.getString(CommonString.KEY_USERNAME, ""); + counter_Id = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + if (!CommonFunctions.isTablet(context)) { + toolbar.setTitleTextAppearance(context, R.style.changestext_sizefor_mobile); + } + obj = (MEMEAuditQuestion) getIntent().getSerializableExtra(CommonString.TAG_OBJECT); + if (obj != null) { + setTitle(obj.getQuizName().trim() + " - " + username); + } + str = CommonString.getImagesFolder(context); + expandableListView = (ExpandableListView) findViewById(R.id.list); + fab = (FloatingActionButton) findViewById(R.id.fab); + fab.setOnClickListener(this); + validate_ui_data(); + } + + private void validate_ui_data() { + //Header + db.open(); + listDataHeader = db.getAuditQuestionCategoryDataNew(obj.getQuizId().toString()); + question_list = new ArrayList<>(); + listDataChild = new HashMap<>(); + for (int i = 0; i < listDataHeader.size(); i++) { + db.open(); + question_list = db.getme_quiz_from_database(listDataHeader.get(i).getCategoryId().toString(), username, visit_date, counter_Id, obj.getQuizId().toString()); + if (question_list.size() == 0) { + question_list = db.getAuditCategoryWiseDataNew(listDataHeader.get(i).getCategoryId(), obj.getQuizId().toString()); + } else { + update_flag = true; + fab.setImageDrawable(ContextCompat.getDrawable(this, R.mipmap.edit)); + } + ArrayList list = new ArrayList<>(); + if (question_list.size() > 0) { + String select = getString(R.string.title_activity_select_dropdown); + // Adding child data + for (int j = 0; j < question_list.size(); j++) { + question_list.get(j).setAnswerList(db.getAuditAnswerDataNew(question_list.get(j), select)); + list.add(question_list.get(j)); + } + } + listDataChild.put(listDataHeader.get(i), list); + } + + adapter = new ExpandableListAdapter(context, listDataHeader, listDataChild); + expandableListView.setAdapter(adapter); + + for (int i = 0; i < adapter.getGroupCount(); i++) { + expandableListView.expandGroup(i); + } + + expandableListView.setOnScrollListener(new AbsListView.OnScrollListener() { + @Override + public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { + expandableListView.invalidate(); + int lastItem = firstVisibleItem + visibleItemCount; + if (firstVisibleItem == 0) { + fab.show();//.setVisibility(View.VISIBLE); + } else if (lastItem == totalItemCount) { + fab.hide();//setVisibility(View.INVISIBLE); + } else { + fab.show();//setVisibility(View.VISIBLE); + } + } + + @Override + public void onScrollStateChanged(AbsListView arg0, int arg1) { + InputMethodManager inputManager = (InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE); + if (getCurrentFocus() != null) { + inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0); + getCurrentFocus().clearFocus(); + } + expandableListView.invalidateViews(); + } + }); + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // Handle action bar item clicks here. The action bar will + // automatically handle clicks on the Home/Up button, so long + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + if (id == android.R.id.home) { + if (checkflag) { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + MEQuizActivity.this.finish(); + } else { + AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle(R.string.parinaam).setMessage(getResources().getString(R.string.data_will_be_lost)).setCancelable(false) + .setPositiveButton(getString(R.string.ok), (dialog, id1) -> { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + MEQuizActivity.this.finish(); + }).setNegativeButton(getString(R.string.cancel), (dialog, which) -> dialog.dismiss()); + AlertDialog alert = builder.create(); + alert.show(); + } + } + + return super.onOptionsItemSelected(item); + } + + @Override + public void onBackPressed() { + if (checkflag) { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + MEQuizActivity.this.finish(); + } else { + AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle(R.string.parinaam).setMessage(getResources().getString(R.string.data_will_be_lost)).setCancelable(false) + .setPositiveButton(getString(R.string.ok), (dialog, id) -> { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + MEQuizActivity.this.finish(); + }).setNegativeButton(getString(R.string.cancel), (dialog, which) -> dialog.dismiss()); + AlertDialog alert = builder.create(); + alert.show(); + } + } + + @Override + public void onClick(View view) { + if (view.getId() == R.id.fab) { + expandableListView.clearFocus(); + expandableListView.invalidateViews(); + if (validateData(listDataHeader, listDataChild)) { + AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle(R.string.dialog_title).setMessage(R.string.title_activity_Want_save) + .setCancelable(false).setPositiveButton(R.string.yes, (dialog, id) -> { + db.open(); + db.insert_me_quiz_data(counter_Id, visit_date, username, listDataHeader, listDataChild, obj, CommonFunctions.getUUID(context)); + //download service + Intent intent = new Intent(context, Downloader.class); + intent.putExtra(CommonString.KEY_ME_QUIZ, listDataHeader); + Downloader.enqueueWork(context, intent); + + AlertandMessages.showToastMsg(context, "Data Saved Successfully"); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + MEQuizActivity.this.finish(); + dialog.dismiss(); + }).setNegativeButton(R.string.no, (dialog, id) -> dialog.cancel()); + AlertDialog alert = builder.create(); + alert.show(); + } else { + AlertandMessages.showToastMsg(context, error_msg); + } + } + + } + + + public class ExpandableListAdapter extends BaseExpandableListAdapter { + private Context _context; + private ArrayList listDataHeader; // header titles + private HashMap> listDataChild; + + public ExpandableListAdapter(Context context, ArrayList listDataHeader, HashMap> listDataChild) { + this._context = context; + this.listDataHeader = listDataHeader; + this.listDataChild = listDataChild; + } + + @Override + public Object getChild(int groupPosition, int childPosititon) { + return this.listDataChild.get(this.listDataHeader.get(groupPosition)).get(childPosititon); + } + + @Override + public long getChildId(int groupPosition, int childPosition) { + return childPosition; + } + + @SuppressLint({"NewApi", "ClickableViewAccessibility"}) + @Override + public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { + final MEMEAuditQuestion checkList = (MEMEAuditQuestion) getChild(groupPosition, childPosition); + ViewHolder holder = null; + if (convertView == null) { + LayoutInflater infalInflater = (LayoutInflater) this._context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); + convertView = infalInflater.inflate(R.layout.quiz_list_item, null); + holder = new ViewHolder(convertView); + convertView.setTag(holder); + } else { + holder = (ViewHolder) convertView.getTag(); + } + + holder.data = checkList; + holder.txt_question.setText(holder.data.getQuestion()); + holder.txt_question.setId(childPosition); + + final ArrayList ans_list = (holder.data).getAnswerList(); + + if (holder.data.getQuestionType().equalsIgnoreCase("List Single Choice")) { + holder.sp_auditAnswer.setVisibility(View.VISIBLE); + holder.sp_auditAnswer.setId(childPosition); + + holder.edt_answer.setVisibility(View.GONE); + holder.edt_answer.setId(childPosition); + + holder.relay_multisppener.setVisibility(View.GONE); + holder.relay_multisppener.setId(childPosition); + + } else if (holder.data.getQuestionType().equalsIgnoreCase("List Multiple Choice")) { + holder.sp_auditAnswer.setVisibility(View.GONE); + holder.sp_auditAnswer.setId(childPosition); + + holder.edt_answer.setVisibility(View.GONE); + holder.edt_answer.setId(childPosition); + + holder.relay_multisppener.setVisibility(View.VISIBLE); + holder.relay_multisppener.setId(childPosition); + } else if (holder.data.getQuestionType().equalsIgnoreCase("Text")) { + holder.sp_auditAnswer.setVisibility(View.GONE); + holder.sp_auditAnswer.setId(childPosition); + + holder.edt_answer.setVisibility(View.VISIBLE); + holder.edt_answer.setId(childPosition); + + holder.relay_multisppener.setVisibility(View.GONE); + holder.relay_multisppener.setId(childPosition); + } else if (holder.data.getQuestionType().equalsIgnoreCase("Number")) { + holder.sp_auditAnswer.setVisibility(View.GONE); + holder.sp_auditAnswer.setId(childPosition); + + holder.edt_answer.setVisibility(View.VISIBLE); + holder.edt_answer.setId(childPosition); + + holder.relay_multisppener.setVisibility(View.GONE); + holder.relay_multisppener.setId(childPosition); + + holder.edt_answer.setInputType(InputType.TYPE_CLASS_NUMBER); + holder.edt_answer.setFilters(new InputFilter[]{new InputFilter.LengthFilter(10)}); + + + } else if (holder.data.getQuestionType().equalsIgnoreCase("Decimal")) { + holder.sp_auditAnswer.setVisibility(View.GONE); + holder.sp_auditAnswer.setId(childPosition); + + holder.edt_answer.setVisibility(View.VISIBLE); + holder.edt_answer.setId(childPosition); + + holder.relay_multisppener.setVisibility(View.GONE); + holder.relay_multisppener.setId(childPosition); + holder.edt_answer.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL); + holder.edt_answer.setFilters(new InputFilter[]{new DecimalDigitsInputFilter(10, 1)}); + + } + + if (ans_list.size() > 0) { + holder.sp_auditAnswer.setAdapter(new AnswerSpinnerAdapter(context, R.layout.custom_spinner_audit_item, ans_list)); + holder.sp_auditAnswer.setId(childPosition); + } + + holder.sp_auditAnswer.setOnTouchListener((view, motionEvent) -> { + Singletouch = true; + return false; + }); + + + final ArrayList finalAns_list = ans_list; + final ViewHolder finalHolder = holder; + holder.sp_auditAnswer.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { + @Override + public void onItemSelected(AdapterView parent, View view, int position, long id) { + if (Singletouch) { + if (position != 0) { + MEMEAuditQuestion ans = finalAns_list.get(position); + finalHolder.data.setAnswerId(ans.getAnswerId()); + finalHolder.data.setAnswer(ans.getAnswer()); + finalHolder.data.setImageAllow(ans.getImageAllow()); + if (finalHolder.data.getImageAllow()) { + finalHolder.parent_cam_layout.setVisibility(View.VISIBLE); + finalHolder.parent_cam_layout.setId(childPosition); + } else { + finalHolder.parent_cam_layout.setVisibility(View.GONE); + finalHolder.parent_cam_layout.setId(childPosition); + + if (!finalHolder.data.getStr_audit_img().equals("")) { + if (new File(str + finalHolder.data.getStr_audit_img()).exists()) { + new File(str + finalHolder.data.getStr_audit_img()).delete(); + } + } + finalHolder.data.setStr_audit_img(""); + finalHolder.img_cam.setImageResource(R.mipmap.camera_bs); + finalHolder.img_cam.setId(childPosition); + } + } else { + if ((finalHolder.data.getQuestionType().equalsIgnoreCase("List Single Choice"))) { + finalHolder.data.setAnswerId(0); + finalHolder.data.setAnswer(""); + } + } + } + Singletouch = false; + } + + @Override + public void onNothingSelected(AdapterView parent) { + + } + }); + + + holder.img_cam.setOnClickListener(v -> { + child_position = childPosition; + group_position = groupPosition; + pathforcheck = counter_Id + username + "_" + checkList.getQuestionId().toString() + "_QuizPic-" + visit_date.replace("/", "") + CommonFunctions.getCurrentTime_only().replace(":", "") + ".jpg"; + _path = CommonString.getImagesFolder(context) + pathforcheck; + CommonFunctions.startAnncaCameraActivity(context, _path, null, false, CommonString.CAMERA_FACE_REAR); + }); + + + holder.edt_answer.setOnFocusChangeListener((v, hasFocus) -> { + if (!hasFocus) { + final EditText Caption = (EditText) v; + String value1 = Caption.getText().toString(); + if (!value1.equals("")) { + finalHolder.data.setAnswer(value1); + } else { + finalHolder.data.setAnswer(""); + } + } + }); + + holder.edt_answer.setText(holder.data.getAnswer()); + holder.edt_answer.setId(childPosition); + + if ((holder.data.getQuestionType().equalsIgnoreCase("List Single Choice"))) { + if (ans_list.size() > 0) { + for (int i = 0; i < ans_list.size(); i++) { + if (ans_list.get(i).getAnswerId().toString().equals(holder.data.getAnswerId().toString())) { + holder.sp_auditAnswer.setSelection(i); + break; + } + + } + } + } else if (holder.data.getQuestionType().equalsIgnoreCase("Number") || holder.data.getQuestionType().equalsIgnoreCase("Decimal") || holder.data.getQuestionType().equalsIgnoreCase("Text")) { + holder.edt_answer.setText(holder.data.getAnswer()); + holder.edt_answer.setId(childPosition); + } + + + holder.searchSpinner.setOnTouchListener((view, motionEvent) -> { + multitouch = true; + return false; + }); + + if (update_flag) { + if (holder.data.getQuestionType().equalsIgnoreCase("List Multiple Choice")) { + for (int k3 = 0; k3 < holder.data.getAnswerList().size(); k3++) { + if (db.ischeckedgetquiz_answer(holder.data.getKeyId(), username, holder.data.getAnswerList().get(k3).getAnswerId().toString())) { + holder.data.getAnswerList().get(k3).setSelected(true); + } + } + } + } + + holder.searchSpinner.setItemsProduct(holder.data.getAnswerList(), -1, items -> { + if (multitouch) { + for (int i = 0; i < items.size(); i++) { + if (items.get(i).isSelected()) { + + } + } + } + + multitouch = false; + + }); + + if (!img_str.equals("")) { + if (group_position == groupPosition) { + if (child_position == childPosition) { + holder.data.setStr_audit_img(img_str); + img_str = ""; + } + + } + } + + + if (!holder.data.getStr_audit_img().equals("")) { + holder.img_cam.setImageResource(R.mipmap.camera_bsd); + holder.img_cam.setId(childPosition); + } else { + holder.img_cam.setImageResource(R.mipmap.camera_bs); + holder.img_cam.setId(childPosition); + } + + if (holder.data.getImageAllow()) { + finalHolder.parent_cam_layout.setVisibility(View.VISIBLE); + finalHolder.parent_cam_layout.setId(childPosition); + } else { + finalHolder.parent_cam_layout.setVisibility(View.GONE); + finalHolder.parent_cam_layout.setId(childPosition); + } + + if (!checkflag) { + if (checkGroupArray.contains(groupPosition) && checkHeaderArray.contains(childPosition)) { + holder.card_view.setBackgroundColor(getResources().getColor(R.color.red)); + holder.card_view.setId(childPosition); + } else { + holder.card_view.setBackgroundColor(getResources().getColor(R.color.white)); + holder.card_view.setId(childPosition); + } + } else { + holder.card_view.setBackgroundColor(getResources().getColor(R.color.white)); + holder.card_view.setId(childPosition); + } + + return convertView; + } + + @Override + public int getChildrenCount(int groupPosition) { + return this.listDataChild.get(this.listDataHeader.get(groupPosition)).size(); + } + + @Override + public Object getGroup(int groupPosition) { + return this.listDataHeader.get(groupPosition); + } + + @Override + public int getGroupCount() { + return this.listDataHeader.size(); + } + + @Override + public long getGroupId(int groupPosition) { + return groupPosition; + } + + @Override + public View getGroupView(final int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { + + if (convertView == null) { + LayoutInflater infalInflater = (LayoutInflater) this._context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); + convertView = infalInflater.inflate(R.layout.item_header_expandable_window, parent, false); + } + + final MEMEAuditQuestion headerTitle = (MEMEAuditQuestion) getGroup(groupPosition); + + TextView lblListHeader = (TextView) convertView.findViewById(R.id.txt_header); + CardView cardView = (CardView) convertView.findViewById(R.id.cardview_exists); + lblListHeader.setText(headerTitle.getCategory()); + + cardView.setOnClickListener(v -> { + if (expandableListView.isGroupExpanded(groupPosition)) { + expandableListView.collapseGroup(groupPosition); + } else { + expandableListView.expandGroup(groupPosition); + } + }); + + if (!checkflag) { + if (checkGroupArray.contains(groupPosition)) { + cardView.setBackgroundColor(getResources().getColor(R.color.red)); + } else { + cardView.setBackgroundColor(getResources().getColor(R.color.bright_red)); + } + } else { + cardView.setBackgroundColor(getResources().getColor(R.color.bright_red)); + } + + return convertView; + } + + @Override + public boolean hasStableIds() { + return false; + } + + @Override + public boolean isChildSelectable(int groupPosition, int childPosition) { + return true; + } + + public class ViewHolder extends RecyclerView.ViewHolder { + public final View mView; + public final TextView txt_question; + public final Spinner sp_auditAnswer; + public final EditText edt_answer; + public final ImageView img_cam; + public final RelativeLayout parent_cam_layout; + CardView card_view; + MEMEAuditQuestion data; + public final RelativeLayout relay_multisppener; + MultiselectionCategorySpinnerSearch searchSpinner; + + public ViewHolder(View view) { + super(view); + mView = view; + txt_question = (TextView) view.findViewById(R.id.txt_question); + sp_auditAnswer = (Spinner) view.findViewById(R.id.sp_auditAnswer); + card_view = (CardView) view.findViewById(R.id.card_view); + edt_answer = (EditText) view.findViewById(R.id.edt_answer); + img_cam = (ImageView) view.findViewById(R.id.img_cam); + parent_cam_layout = (RelativeLayout) view.findViewById(R.id.parent_cam_layout); + relay_multisppener = (RelativeLayout) view.findViewById(R.id.relay_multisppener); + searchSpinner = (MultiselectionCategorySpinnerSearch) view.findViewById(R.id.multispin_search); + } + } + } + + public class AnswerSpinnerAdapter extends ArrayAdapter { + List list; + Context context; + int resourceId; + + public AnswerSpinnerAdapter(Context context, int resourceId, ArrayList list) { + super(context, resourceId, list); + this.context = context; + this.list = list; + this.resourceId = resourceId; + } + + @Override + public View getView(int position, View convertView, ViewGroup parent) { + + View view = convertView; + LayoutInflater inflater = ((Activity) context).getLayoutInflater(); + view = inflater.inflate(resourceId, parent, false); + MEMEAuditQuestion cm = list.get(position); + TextView txt_spinner = (TextView) view.findViewById(R.id.tv_text); + txt_spinner.setText(list.get(position).getAnswer()); + + return view; + } + + @Override + public View getDropDownView(int position, View convertView, ViewGroup parent) { + View view = convertView; + LayoutInflater inflater = ((Activity) context).getLayoutInflater(); + view = inflater.inflate(resourceId, parent, false); + + MEMEAuditQuestion cm = list.get(position); + + TextView txt_spinner = (TextView) view.findViewById(R.id.tv_text); + txt_spinner.setText(cm.getAnswer()); + + return view; + } + } + + boolean validateData(ArrayList listDataHeader, HashMap> listDataChild) { + checkHeaderArray.clear(); + checkGroupArray.clear(); + checkflag = true; + for (int j = 0; j < listDataHeader.size(); j++) { + ArrayList data = listDataChild.get(listDataHeader.get(j)); + assert data != null; + for (int i = 0; i < data.size(); i++) { + if (data.get(i).getQuestionType().equalsIgnoreCase("List Single Choice") + && !data.get(i).getAnswerId().toString().equals("0") && + data.get(i).getImageAllow() + && data.get(i).getStr_audit_img().equals("")) { + error_msg = getString(R.string.pls_click_image); + checkflag = false; + break; + } else if (data.get(i).getQuestionType().equalsIgnoreCase("List Single Choice") + && data.get(i).getAnswerId().toString().equals("0")) { + error_msg = getString(R.string.pls_answer_all_qns); + checkflag = false; + break; + } else if (data.get(i).getQuestionType().equalsIgnoreCase("Text") + || data.get(i).getQuestionType().equalsIgnoreCase("Number") || + data.get(i).getQuestionType().equalsIgnoreCase("Decimal")) { + if (data.get(i).getAnswer().equals("")) { + error_msg = getString(R.string.pls_answer_all_qns); + checkflag = false; + break; + } + } else if (data.get(i).getQuestionType().equalsIgnoreCase("List Multiple Choice") && data.get(i).getAnswerList().size() > 0 && !check(data.get(i).getAnswerList())) { + error_msg = getString(R.string.pls_answer_all_qns); + checkflag = false; + break; + } + + if (!checkflag) { + if (!checkHeaderArray.contains(i)) { + checkHeaderArray.add(i); + checkGroupArray.add(j); + } + break; + } + } + if (!checkflag) { + break; + } + } + + return checkflag; + } + + + private boolean check(ArrayList answerList) { + boolean flag = true; + if (answerList.size() > 0) { + for (int k = 0; k < answerList.size(); k++) { + if (!answerList.get(k).isSelected()) { + flag = false; + break; + } + } + } + return flag; + } + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + super.onActivityResult(requestCode, resultCode, data); + Log.i("MakeMachine", "resultCode: " + resultCode); + switch (resultCode) { + case 0: + Log.i("MakeMachine", "User cancelled"); + break; + case -1: + if (pathforcheck != null && !pathforcheck.equals("")) { + if (new File(str + pathforcheck).exists()) { + img_str = pathforcheck; + pathforcheck = ""; + adapter.notifyDataSetChanged(); + } + } + + } + } + + public class DecimalDigitsInputFilter implements InputFilter { + Pattern mPattern; + public DecimalDigitsInputFilter(int digitsBeforeZero, int digitsAfterZero) { + mPattern = Pattern.compile("[0-9]{0," + (digitsBeforeZero - 1) + "}+((\\.[0-9]{0," + (digitsAfterZero - 1) + "})?)||(\\.)?"); + } + + @Override + public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { + Matcher matcher = mPattern.matcher(dest); + if (!matcher.matches()) + return ""; + return null; + } + + } + + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/makeupexpert/MakeoverActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/makeupexpert/MakeoverActivity.java new file mode 100644 index 0000000..8995915 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/makeupexpert/MakeoverActivity.java @@ -0,0 +1,223 @@ +package com.cpm.lorealbaautomation.makeupexpert; + +import android.app.AlertDialog; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.SharedPreferences; + +import androidx.appcompat.app.AppCompatActivity; +import android.os.Bundle; +import androidx.cardview.widget.CardView; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; +import androidx.appcompat.widget.Toolbar; +import android.view.LayoutInflater; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; +import android.widget.ImageView; +import android.widget.TextView; + +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.constant.CommonFunctions; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.gsonGetterSetter.InvoiceGetterSetter; + +import java.util.ArrayList; +import java.util.List; + +public class MakeoverActivity extends AppCompatActivity implements View.OnClickListener { + String CounterId, visit_date, username; + private SharedPreferences preferences; + private SharedPreferences.Editor editor = null; + ArrayList invoice_List = new ArrayList<>(); + ImageView btn_saletra_add_performa; + TextView count_cst; + Lorealba_Database db; + Context context; + RecyclerView sale_tracking_recycle; + boolean clicked_flag = false; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_makeover); + context = this; + db = new Lorealba_Database(context); + db.open(); + iduserinterface(); + Toolbar toolbar = findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + getSupportActionBar().setHomeButtonEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + if (!CommonFunctions.isTablet(context)) { + toolbar.setTitleTextAppearance(context, R.style.changestext_sizefor_mobile); + } + setTitle("Makeover Capture -" + username); + } + + private void iduserinterface() { + preferences = PrefHelper.getPrefs(context); + editor = preferences.edit(); + CounterId = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + username = preferences.getString(CommonString.KEY_USERNAME, ""); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + btn_saletra_add_performa = (ImageView) findViewById(R.id.btn_saletra_add_performa); + sale_tracking_recycle = (RecyclerView) findViewById(R.id.sale_tracking_recycle); + count_cst = (TextView) findViewById(R.id.count_cst); + + btn_saletra_add_performa.setOnClickListener(this); + + } + + @Override + protected void onResume() { + super.onResume(); + db = new Lorealba_Database(context); + db.open(); + invoice_List = db.getMakeoverCaptureByUserMobile(0, null, visit_date, CounterId, username); + if (invoice_List.size() > 0) { + sale_tracking_recycle.setAdapter(new ValueAdapter(context, invoice_List)); + sale_tracking_recycle.setLayoutManager(new LinearLayoutManager(context)); + } + db.open(); + count_cst.setText("" + db.getMakeover(visit_date, CounterId, null,null,false).size()); + } + + @Override + public void onClick(View v) { + if (v.getId() == R.id.btn_saletra_add_performa) { + startActivity(new Intent(context, MakeoverDetailsActivity.class)); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + } + } + + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + if (id == android.R.id.home) { + if (clicked_flag) { + AlertDialog.Builder builder = new AlertDialog.Builder(context).setMessage(CommonString.ONBACK_ALERT_MESSAGE).setCancelable(false).setPositiveButton("Ok", + new DialogInterface.OnClickListener() { + public void onClick( + DialogInterface dialog, int id) { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + MakeoverActivity.this.finish(); + } + }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { + dialog.cancel(); + } + }); + AlertDialog alert = builder.create(); + alert.show(); + } else { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + MakeoverActivity.this.finish(); + } + } + return super.onOptionsItemSelected(item); + } + + @Override + public void onBackPressed() { + if (clicked_flag) { + AlertDialog.Builder builder = new AlertDialog.Builder(context).setMessage(CommonString.ONBACK_ALERT_MESSAGE).setCancelable(false).setPositiveButton("Ok", + new DialogInterface.OnClickListener() { + public void onClick( + DialogInterface dialog, int id) { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + MakeoverActivity.this.finish(); + } + }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { + dialog.cancel(); + } + }); + AlertDialog alert = builder.create(); + alert.show(); + } else { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + MakeoverActivity.this.finish(); + } + } + + + public class ValueAdapter extends RecyclerView.Adapter { + private LayoutInflater inflator; + List data; + + public ValueAdapter(Context context, List data) { + inflator = LayoutInflater.from(context); + this.data = data; + } + + @Override + public ValueAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int i) { + View view = inflator.inflate(R.layout.details_makeover_list, parent, false); + return new ValueAdapter.MyViewHolder(view); + } + + @Override + public void onBindViewHolder(final ValueAdapter.MyViewHolder holder, final int position) { + final InvoiceGetterSetter current = data.get(position); + if (current.isPos_sale_flag()) { + holder.pos_icon.setVisibility(View.GONE); + holder.pos_icon.setId(position); + } else { + holder.pos_icon.setVisibility(View.VISIBLE); + holder.pos_icon.setId(position); + } + + holder.sale_trcking_name.setText(current.getCustomer_name() + " - Mobile No. : " + current.getMobile_no()); + holder.sale_trcking_name.setId(position); + + holder.look_created.setText("Look Created : " + current.getLook_creater_str()); + holder.look_created.setId(position); + + holder.sale_card.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + db.open(); + if (!current.isPos_sale_flag()) { + startActivity(new Intent(context, MakeoverDetailsActivity.class) + .putExtra(CommonString.TAG_OBJECT, db.getMakeoverCaptureByUserMobile(current.getReccept_count(), current.getMobile_no(), visit_date, CounterId, current.getUserName())) + .putExtra(CommonString.Key_For_Consumer_Update, "1")); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + } else { + startActivity(new Intent(context, MakeoverDetailsActivity.class).putExtra(CommonString.TAG_OBJECT, + db.getMakeoverCaptureByUserMobile(current.getReccept_count(), current.getMobile_no(), visit_date, CounterId, current.getUserName())) + .putExtra(CommonString.Key_For_Consumer_Update, "0")); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + + } + } + }); + } + + + @Override + public int getItemCount() { + return data.size(); + } + + class MyViewHolder extends RecyclerView.ViewHolder { + TextView sale_trcking_name, look_created; + CardView sale_card; + ImageView pos_icon; + + public MyViewHolder(View itemView) { + super(itemView); + sale_card = (CardView) itemView.findViewById(R.id.sale_card); + sale_trcking_name = (TextView) itemView.findViewById(R.id.sale_trcking_name); + look_created = (TextView) itemView.findViewById(R.id.look_created); + pos_icon = (ImageView) itemView.findViewById(R.id.pos_icon); + } + } + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/makeupexpert/MakeoverDetailsActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/makeupexpert/MakeoverDetailsActivity.java new file mode 100644 index 0000000..a82ba0c --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/makeupexpert/MakeoverDetailsActivity.java @@ -0,0 +1,955 @@ +package com.cpm.lorealbaautomation.makeupexpert; + +import android.annotation.SuppressLint; +import android.app.Activity; +import android.app.AlertDialog; +import android.app.Dialog; +import android.app.ProgressDialog; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.SharedPreferences; + +import com.google.android.material.floatingactionbutton.FloatingActionButton; + +import androidx.appcompat.app.AppCompatActivity; + +import android.os.Bundle; + +import androidx.appcompat.widget.Toolbar; + +import android.text.Editable; +import android.text.TextWatcher; +import android.util.Log; +import android.view.Gravity; +import android.view.MenuItem; +import android.view.View; +import android.view.Window; +import android.view.WindowManager; +import android.widget.AdapterView; +import android.widget.ArrayAdapter; +import android.widget.CheckBox; +import android.widget.EditText; +import android.widget.ImageView; +import android.widget.LinearLayout; +import android.widget.RadioButton; +import android.widget.RadioGroup; +import android.widget.ScrollView; +import android.widget.Spinner; +import android.widget.TextView; +import android.widget.Toast; + +import com.google.gson.Gson; +import com.google.zxing.integration.android.IntentIntegrator; +import com.google.zxing.integration.android.IntentResult; +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.constant.AlertandMessages; +import com.cpm.lorealbaautomation.constant.CommonFunctions; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.download.Downloader; +import com.cpm.lorealbaautomation.gsonGetterSetter.ConsumerTermsConditionAccept; +import com.cpm.lorealbaautomation.gsonGetterSetter.InvoiceGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.JourneyPlan; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterBAProfileGetterSetter; +import com.cpm.lorealbaautomation.retrofit.PostApi; + +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.TimeUnit; + +import okhttp3.MediaType; +import okhttp3.OkHttpClient; +import okhttp3.RequestBody; +import okhttp3.ResponseBody; +import retrofit2.Retrofit; +import retrofit2.converter.gson.GsonConverterFactory; + +import static com.cpm.lorealbaautomation.constant.CommonFunctions.getCurrentTime; +import static com.cpm.lorealbaautomation.dailyactivity.StoreImageActivity.convertBitmap; + +public class MakeoverDetailsActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemSelectedListener { + String CounterId, visit_date, username, str_termCondition = "0", response_term_condition = "", _pathforcheck = "", _path = "", + otp_code = "", flag_for_makeover_Update = "", before_makeover_img_str = "", after_makeover_img_str = "", feed_back_str = ""; + boolean no_name_flag = false, no_mobile_no_flag = false, flag_for_term_condition = false, clicked_flag = false, feed_back_flag = false; + ArrayAdapter AgeAdapter, SkinTypeAdapter, lookCreatedAdapter; + public ArrayList selected_list = new ArrayList<>(); + EditText edt_customer, edt_mobile_no, edt_otp, edt_email_address; + Spinner spin_age, spin_skin_type, spin_look_created; + ImageView img_before_makeover, img_after_makeover; + JourneyPlan storeDataObject = new JourneyPlan(); + private SharedPreferences.Editor editor = null; + CheckBox mobile_checkbox, no_name_checkbox; + TextView rl_term_condition, text_user_nm; + private SharedPreferences preferences; + FloatingActionButton fab, draft_fab; + MultiPurposeDialog multidialog; + private RadioButton radioSexButton; + private RadioGroup radioSexGroup; + InvoiceGetterSetter object; + ScrollView scroll_view; + ProgressDialog loading; + ///new changes19/08/19 + Lorealba_Database db; + LinearLayout rl_otp; + Context context; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_makeover_details); + context = this; + ((MakeoverDetailsActivity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); + iduserinterface(); + Toolbar toolbar = findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + if (!CommonFunctions.isTablet(context)) { + toolbar.setTitleTextAppearance(context, R.style.changestext_sizefor_mobile); + } + getSupportActionBar().setHomeButtonEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + setTitle("Makeover Details -" + username); + + } + + @SuppressLint("RestrictedApi") + private void iduserinterface() { + db = new Lorealba_Database(context); + db.open(); + preferences = PrefHelper.getPrefs(context); + editor = preferences.edit(); + CounterId = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + username = preferences.getString(CommonString.KEY_USERNAME, ""); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + scroll_view = (ScrollView) findViewById(R.id.scroll_view); + fab = (FloatingActionButton) findViewById(R.id.fab); + draft_fab = (FloatingActionButton) findViewById(R.id.draft_fab); + edt_customer = (EditText) findViewById(R.id.edt_customer); + edt_mobile_no = (EditText) findViewById(R.id.edt_mobile_no); + mobile_checkbox = (CheckBox) findViewById(R.id.mobile_checkbox); + no_name_checkbox = (CheckBox) findViewById(R.id.no_name_checkbox); + radioSexGroup = (RadioGroup) findViewById(R.id.radioGrp); + ///new changes19--08-19 + rl_term_condition = (TextView) findViewById(R.id.rl_term_condition); + text_user_nm = (TextView) findViewById(R.id.text_user_nm); + rl_otp = (LinearLayout) findViewById(R.id.rl_otp); + edt_otp = (EditText) findViewById(R.id.edt_otp); + edt_email_address = (EditText) findViewById(R.id.edt_email_address); + spin_age = (Spinner) findViewById(R.id.spin_age); + spin_skin_type = (Spinner) findViewById(R.id.spin_skin_type); + spin_look_created = (Spinner) findViewById(R.id.spin_look_created); + img_before_makeover = (ImageView) findViewById(R.id.img_before_makeover); + img_after_makeover = (ImageView) findViewById(R.id.img_after_makeover); + + fab.setOnClickListener(this); + mobile_checkbox.setOnClickListener(this); + no_name_checkbox.setOnClickListener(this); + draft_fab.setOnClickListener(this); + rl_otp.setOnClickListener(this); + rl_term_condition.setOnClickListener(this); + img_after_makeover.setOnClickListener(this); + img_before_makeover.setOnClickListener(this); + db.open(); + storeDataObject = db.getspecific_storenamewith_counter_name(visit_date, CounterId, username); + flag_for_makeover_Update = getIntent().getStringExtra(CommonString.Key_For_Consumer_Update); + selected_list = (ArrayList) getIntent().getSerializableExtra(CommonString.TAG_OBJECT); + if (flag_for_makeover_Update != null && flag_for_makeover_Update.equals("1")) { + edt_mobile_no.setEnabled(false); + rl_term_condition.setTextColor(getResources().getColor(R.color.gray)); + rl_term_condition.setEnabled(false); + mobile_checkbox.setEnabled(false); + } else if (flag_for_makeover_Update != null && flag_for_makeover_Update.equals("0")) { + + draft_fab.setVisibility(View.GONE); + fab.setVisibility(View.GONE); + no_name_checkbox.setEnabled(false); + mobile_checkbox.setEnabled(false); + edt_customer.setEnabled(false); + edt_mobile_no.setEnabled(false); + rl_term_condition.setTextColor(getResources().getColor(R.color.gray)); + rl_term_condition.setEnabled(false); + mobile_checkbox.setEnabled(false); + edt_email_address.setEnabled(false); + spin_age.setEnabled(false); + spin_skin_type.setEnabled(false); + spin_look_created.setEnabled(false); + radioSexGroup.setEnabled(false); + img_before_makeover.setEnabled(false); + img_after_makeover.setEnabled(false); + } + + if (selected_list != null && selected_list.size() > 0) { + object = selected_list.get(0); + username = object.getUserName(); + edt_customer.setText(object.getCustomer_name().trim().replaceAll("[(!@#$%^&*?)\"]", "")); + edt_mobile_no.setText(object.getMobile_no()); + edt_email_address.setText(object.getConsumer_email_Id()); + str_termCondition = object.getStr_termcondition(); + /////for radio group + if (selected_list.get(0).getCustomer_gender().equalsIgnoreCase("Male")) { + //radioSexButton + radioSexGroup.check(R.id.radioM); + } else if (selected_list.get(0).getCustomer_gender().equalsIgnoreCase("Female")) { + //radioSexButton + radioSexGroup.check(R.id.radioF); + } else { + radioSexGroup.check(R.id.radio_other); + } + + if (!object.getBefore_makeover_img().equals("")) { + img_before_makeover.setImageResource((R.mipmap.camera_bsd)); + before_makeover_img_str = object.getBefore_makeover_img(); + img_before_makeover.setEnabled(false); + } + + if (!object.getAfter_makeover_img().equals("")) { + img_after_makeover.setImageResource((R.mipmap.camera_bsd)); + after_makeover_img_str = object.getAfter_makeover_img(); + } + } + + ///calling of age adapter + adapterforAgeLimit_SkinType(); + getstatusof_termcondition(); + } + + private boolean checkotp_validation() { + boolean status = true; + if (edt_otp.getText().toString().equals("0000")) { + status = true; + str_termCondition = "1"; + } else if (edt_otp.getText().toString().equals(otp_code)) { + status = true; + str_termCondition = "1"; + } else { + status = false; + } + + return status; + + } + + private void custom_dialog_for_termand_condition(final Context context) { + multidialog = new MultiPurposeDialog(context); + multidialog.requestWindowFeature(Window.FEATURE_NO_TITLE); + multidialog.setContentView(R.layout.custom_dialog_for_term_condition); + final WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); + lp.copyFrom(multidialog.getWindow().getAttributes()); + lp.width = WindowManager.LayoutParams.MATCH_PARENT; + lp.height = WindowManager.LayoutParams.WRAP_CONTENT; + lp.gravity = Gravity.CENTER; + multidialog.getWindow().setAttributes(lp); + multidialog.setCancelable(false); + ///new changes 19 aug + CheckBox checkbox_accept = (CheckBox) multidialog.findViewById(R.id.checkbox_accept); + CheckBox checkbox_reject = (CheckBox) multidialog.findViewById(R.id.checkbox_reject); + TextView txt_term_condition = (TextView) multidialog.findViewById(R.id.txt_term_condition); + + if (flag_for_term_condition) { + checkbox_accept.setChecked(true); + } + + db.open(); + txt_term_condition.setText(db.getterm_and_condition().getTermsCondition()); + + checkbox_accept.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + try { + flag_for_term_condition = true; + multidialog.dismiss(); + rl_otp.setVisibility(View.VISIBLE); + JSONObject jsonObject = new JSONObject(); + jsonObject.put("MobileNumber", edt_mobile_no.getText().toString()); + getotp_from_mobile_no(jsonObject.toString()); + } catch (JSONException e) { + e.fillInStackTrace(); + } + } + }); + + checkbox_reject.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + multidialog.dismiss(); + rl_otp.setVisibility(View.GONE); + flag_for_term_condition = false; + rl_term_condition.setTextColor(getResources().getColor(R.color.gray)); + rl_term_condition.setEnabled(false); + } + }); + + multidialog.show(); + } + + + @Override + public void onClick(View view) { + if (view.getId() == R.id.img_before_makeover) { + _pathforcheck = CounterId + "_before_makeo_img_" + username + "_" + visit_date.replace("/", "") + "_" + getCurrentTime().replace(":", "") + ".jpg"; + _path = CommonString.getImagesFolder(context) + _pathforcheck; + CommonFunctions.startAnncaCameraActivity(context, _path, null, false, CommonString.CAMERA_FACE_REAR); + } else if (view.getId() == R.id.img_after_makeover) { + if (flag_for_makeover_Update != null && !flag_for_makeover_Update.equals("") && flag_for_makeover_Update.equals("1")) { + _pathforcheck = CounterId + "_after_makeo_img_" + username + "_" + visit_date.replace("/", "") + "_" + getCurrentTime().replace(":", "") + ".jpg"; + _path = CommonString.getImagesFolder(context) + _pathforcheck; + CommonFunctions.startAnncaCameraActivity(context, _path, null, false, CommonString.CAMERA_FACE_REAR); + } + + } else if (view.getId() == R.id.rl_term_condition) { + if (checkindex()) { + custom_dialog_for_termand_condition(context); + } + + } else if (view.getId() == R.id.mobile_checkbox) { + clicked_flag = true; + if (mobile_checkbox.isChecked()) { + no_mobile_no_flag = true; + flag_for_term_condition = false; + edt_mobile_no.setText("0000000000"); + rl_otp.setVisibility(View.GONE); + edt_mobile_no.setEnabled(false); + rl_term_condition.setTextColor(getResources().getColor(R.color.gray)); + } else { + edt_mobile_no.setText(""); + no_mobile_no_flag = false; + edt_mobile_no.setEnabled(true); + rl_term_condition.setTextColor(getResources().getColor(R.color.blue)); + } + + } else if (view.getId() == R.id.no_name_checkbox) { + clicked_flag = true; + if (no_name_checkbox.isChecked()) { + no_name_flag = true; + edt_customer.setText("No Name"); + edt_customer.setEnabled(false); + } else { + edt_customer.setText(""); + no_name_flag = false; + edt_customer.setEnabled(true); + } + + } else if (view.getId() == R.id.fab) { + if (flag_for_makeover_Update != null && !flag_for_makeover_Update.equals("") && flag_for_makeover_Update.equals("1")) { + CustomerfeedBack_dialog(context); + } + + ((MakeoverDetailsActivity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); + if (!no_name_flag && edt_customer.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter Customer Name"); + } else if (!no_mobile_no_flag && edt_mobile_no.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter Mobile Number "); + } else if (!no_mobile_no_flag && edt_mobile_no.getText().toString().length() < 10) { + AlertandMessages.showToastMsg(context, "Please Enter Atleast 10 Digit Contact Number "); + } else if (checkindex() && rl_term_condition.isEnabled() && otp_code.equals("")) { + AlertandMessages.showToastMsg(context, "Please Check Terms & Condition"); + } else if (!edt_email_address.getText().toString().isEmpty() && + !CommonFunctions.isValidEmail(edt_email_address.getText().toString())) { + AlertandMessages.showToastMsg(context, "Please Enter Valid Email Id "); + } else if (spin_age.getSelectedItemId() == 0) { + AlertandMessages.showToastMsg(context, "Please Select Age Range"); + } else if (spin_skin_type.getSelectedItemId() == 0) { + AlertandMessages.showToastMsg(context, "Please Select Skin Type "); + } else if (spin_look_created.getSelectedItemId() == 0) { + AlertandMessages.showToastMsg(context, "Please Select Look Created"); + } else if (!no_mobile_no_flag && flag_for_term_condition && edt_otp.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter OTP"); + } else if (!no_mobile_no_flag && flag_for_term_condition && !checkotp_validation()) { + AlertandMessages.showToastMsg(context, "Incorrect OTP"); + } else if (before_makeover_img_str.equals("")) { + AlertandMessages.showToastMsg(context, "Please Capture Before Makeover Image"); + } else if (flag_for_makeover_Update != null && !flag_for_makeover_Update.equals("") && flag_for_makeover_Update.equals("1") && after_makeover_img_str.equals("")) { + AlertandMessages.showToastMsg(context, "Please Capture After Makeover Image"); + } else if (flag_for_makeover_Update != null && !flag_for_makeover_Update.equals("") && flag_for_makeover_Update.equals("1") && !feed_back_flag) { + AlertandMessages.showToastMsg(context, "Please Choose Customer Feedback"); + } else { + AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle(R.string.parinaam).setMessage(R.string.alertsaveData); + builder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialogInterface, int i) { + try { + InvoiceGetterSetter maekoverobject = new InvoiceGetterSetter(); + // get selected radio button from radioGroup + int selectedId = radioSexGroup.getCheckedRadioButtonId(); + // find the radiobutton by returned id + radioSexButton = (RadioButton) findViewById(selectedId); + maekoverobject.setCustomer_name(edt_customer.getText().toString().trim().replaceAll("[(!@#$%^&*?)1234567890\"]", "")); + maekoverobject.setMobile_no(edt_mobile_no.getText().toString()); + maekoverobject.setConsumer_email_Id(edt_email_address.getText().toString()); + + if (spin_age.getSelectedItemId() == 0) { + maekoverobject.setConsumer_age(""); + } else { + maekoverobject.setConsumer_age(spin_age.getSelectedItem().toString()); + } + + if (spin_skin_type.getSelectedItemId() == 0) { + maekoverobject.setConsumer_skinType(""); + } else { + maekoverobject.setConsumer_skinType(spin_skin_type.getSelectedItem().toString()); + } + + if (spin_look_created.getSelectedItemId() == 0) { + maekoverobject.setLook_creater_str(""); + } else { + maekoverobject.setLook_creater_str(spin_look_created.getSelectedItem().toString()); + } + + maekoverobject.setCustomer_gender(radioSexButton.getText().toString()); + maekoverobject.setBefore_makeover_img(before_makeover_img_str); + maekoverobject.setAfter_makeover_img(after_makeover_img_str); + maekoverobject.setCst_feed_back_value(feed_back_str); + maekoverobject.setStr_termcondition(str_termCondition); + maekoverobject.setUnique_code(CommonFunctions.getUUID(context)); + maekoverobject.setPos_sale_flag(false); + if (flag_for_makeover_Update != null && !flag_for_makeover_Update.equals("") && flag_for_makeover_Update.equals("1")) { + db.open(); + maekoverobject.setPos_sale_flag(true); + maekoverobject.setReccept_count(object.getReccept_count()); + db.update_makeover_capture(CounterId, visit_date, username, maekoverobject); + //download service + Intent intent = new Intent(context, Downloader.class); + intent.putExtra(CommonString.KEY_Me_MakeOver_Capture, maekoverobject); + Downloader.enqueueWork(context, intent); + + } else { + db.open(); + db.insert_makeover_capture(username, visit_date, CounterId, maekoverobject); + } + + AlertandMessages.showToastMsg(context, "Data Saved Successfully"); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + MakeoverDetailsActivity.this.finish(); + dialogInterface.dismiss(); + + } catch (Exception e) { + e.fillInStackTrace(); + } + + } + }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialogInterface, int i) { + dialogInterface.cancel(); + } + }); + + builder.show(); + } + + } else if (view.getId() == R.id.draft_fab) { + ((MakeoverDetailsActivity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); + if (!no_name_flag && edt_customer.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter Customer Name"); + } else if (!no_mobile_no_flag && edt_mobile_no.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter Mobile Number"); + } else if (!no_mobile_no_flag && edt_mobile_no.getText().toString().length() < 10) { + AlertandMessages.showToastMsg(context, "Please Enter Atleast 10 Digit Contact Number"); + } else if (checkindex() && rl_term_condition.isEnabled() && otp_code.equals("")) { + AlertandMessages.showToastMsg(context, "Please Check Terms & Condition"); + } else if (!edt_email_address.getText().toString().isEmpty() && !CommonFunctions.isValidEmail(edt_email_address.getText().toString())) { + AlertandMessages.showToastMsg(context, "Please Enter Valid Email Id"); + } else if (spin_age.getSelectedItemId() == 0) { + AlertandMessages.showToastMsg(context, "Please Select Age Range "); + } else if (spin_skin_type.getSelectedItemId() == 0) { + AlertandMessages.showToastMsg(context, "Please Select Skin Type"); + } else if (spin_look_created.getSelectedItemId() == 0) { + AlertandMessages.showToastMsg(context, "Please Select Look Created"); + } else if (flag_for_term_condition && edt_otp.getText().toString().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Enter OTP"); + } else if (flag_for_term_condition && !checkotp_validation()) { + AlertandMessages.showToastMsg(context, "Incorrect OTP"); + } else if (before_makeover_img_str.equals("")) { + AlertandMessages.showToastMsg(context, "Please Capture Before Makeover Image"); + } else if (flag_for_makeover_Update != null && !flag_for_makeover_Update.equals("") && flag_for_makeover_Update.equals("1") && after_makeover_img_str.equals("")) { + AlertandMessages.showToastMsg(context, "Please Capture After Makeover Image"); + } else { + AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle(R.string.dialog_title).setMessage(R.string.alertsaveData); + builder.setPositiveButton(android.R.string.yes, (dialogInterface, i) -> { + InvoiceGetterSetter maekoverobject = new InvoiceGetterSetter(); + // get selected radio button from radioGroup + int selectedId = radioSexGroup.getCheckedRadioButtonId(); + // find the radiobutton by returned id + radioSexButton = (RadioButton) findViewById(selectedId); + maekoverobject.setCustomer_name(edt_customer.getText().toString().trim().replaceAll("[(!@#$%^&*?)1234567890\"]", "")); + maekoverobject.setMobile_no(edt_mobile_no.getText().toString()); + maekoverobject.setConsumer_email_Id(edt_email_address.getText().toString()); + if (spin_age.getSelectedItemId() == 0) { + maekoverobject.setConsumer_age(""); + } else { + maekoverobject.setConsumer_age(spin_age.getSelectedItem().toString()); + } + if (spin_skin_type.getSelectedItemId() == 0) { + maekoverobject.setConsumer_skinType(""); + } else { + maekoverobject.setConsumer_skinType(spin_skin_type.getSelectedItem().toString()); + } + + if (spin_look_created.getSelectedItemId() == 0) { + maekoverobject.setLook_creater_str(""); + } else { + maekoverobject.setLook_creater_str(spin_look_created.getSelectedItem().toString()); + } + + maekoverobject.setCustomer_gender(radioSexButton.getText().toString()); + maekoverobject.setBefore_makeover_img(before_makeover_img_str); + maekoverobject.setAfter_makeover_img(after_makeover_img_str); + maekoverobject.setCst_feed_back_value(feed_back_str); + maekoverobject.setStr_termcondition(str_termCondition); + maekoverobject.setUnique_code(CommonFunctions.getUUID(context)); + maekoverobject.setPos_sale_flag(false); + if (flag_for_makeover_Update != null && !flag_for_makeover_Update.equals("") && flag_for_makeover_Update.equals("1")) { + db.open(); + maekoverobject.setReccept_count(object.getReccept_count()); + db.update_makeover_capture(CounterId, visit_date, username, maekoverobject); + } else { + db.open(); + db.insert_makeover_capture(username, visit_date, CounterId, maekoverobject); + } + + AlertandMessages.showToastMsg(context, "Data Saved Successfully"); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + MakeoverDetailsActivity.this.finish(); + dialogInterface.dismiss(); + }); + + builder.setNegativeButton(android.R.string.cancel, (dialogInterface, i) -> dialogInterface.cancel()); + + builder.show(); + + } + } + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + if (id == android.R.id.home) { + if (clicked_flag) { + AlertDialog.Builder builder = new AlertDialog.Builder(context).setMessage(CommonString.ONBACK_ALERT_MESSAGE).setCancelable(false).setPositiveButton("Ok", + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + MakeoverDetailsActivity.this.finish(); + } + }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { + dialog.cancel(); + } + }); + AlertDialog alert = builder.create(); + alert.show(); + } else { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + MakeoverDetailsActivity.this.finish(); + } + } + + return super.onOptionsItemSelected(item); + } + + @Override + public void onBackPressed() { + if (clicked_flag) { + AlertDialog.Builder builder = new AlertDialog.Builder(context).setMessage(CommonString.ONBACK_ALERT_MESSAGE).setCancelable(false).setPositiveButton("Ok", + new DialogInterface.OnClickListener() { + public void onClick( + DialogInterface dialog, int id) { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + MakeoverDetailsActivity.this.finish(); + } + }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { + dialog.cancel(); + } + }); + AlertDialog alert = builder.create(); + alert.show(); + } else { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + MakeoverDetailsActivity.this.finish(); + } + } + + @Override + public void onItemSelected(AdapterView adapterView, View view, int pos, long l) { + switch (adapterView.getId()) { + } + } + + @Override + public void onNothingSelected(AdapterView adapterView) { + + } + + public class MultiPurposeDialog extends Dialog { + public MultiPurposeDialog(Context context) { + super(context); + // DIALOG USER_INTERFACE TEMPLATE + WindowManager.LayoutParams wmLayoutParams = getWindow().getAttributes(); + wmLayoutParams.gravity = Gravity.CENTER; + getWindow().setAttributes(wmLayoutParams); + setTitle(null); + setCancelable(false); + setOnCancelListener(null); + LinearLayout layout = new LinearLayout(context); + layout.setOrientation(LinearLayout.VERTICAL); + } + } + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data); + if (result == null) { + switch (resultCode) { + case 0: + Log.i("MakeMachine", "User cancelled"); + break; + + case -1: + if (_pathforcheck != null && !_pathforcheck.equals("")) { + try { + if (new File(CommonString.getImagesFolder(context) + _pathforcheck).exists()) { + convertBitmap(CommonString.getImagesFolder(context) + _pathforcheck); + if (_pathforcheck.contains("_before_makeo_img_")) { + before_makeover_img_str = _pathforcheck; + img_before_makeover.setImageResource((R.mipmap.camera_bsd)); + } else { + after_makeover_img_str = _pathforcheck; + img_after_makeover.setImageResource((R.mipmap.camera_bsd)); + } + + _pathforcheck = ""; + } + } catch (Exception e) { + e.fillInStackTrace(); + } + } + + break; + } + + } else + super.onActivityResult(requestCode, resultCode, data); + } + + public void getotp_from_mobile_no(String jsondata) { + try { + loading = ProgressDialog.show(context, "Processing", "Please wait...", false, false); + OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, + TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build(); + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsondata.toString()); + Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build(); + PostApi api = adapter.create(PostApi.class); + retrofit2.Call call = api.getOTPMethod(jsonData); + call.enqueue(new retrofit2.Callback() { + @Override + public void onResponse(retrofit2.Call call, retrofit2.Response response) { + ResponseBody responseBody = response.body(); + String data = null; + if (responseBody != null && response.isSuccessful()) { + try { + data = response.body().string(); + JSONObject jObject = new JSONObject(data); + otp_code = jObject.getString("SendOTPResult"); + loading.dismiss(); + + } catch (Exception e) { + e.fillInStackTrace(); + loading.dismiss(); + } + } else { + loading.dismiss(); + Toast.makeText(context, "Server Not Responding . Please Try Again.", Toast.LENGTH_SHORT).show(); + } + } + + @Override + public void onFailure(retrofit2.Call call, Throwable t) { + loading.dismiss(); + AlertandMessages.showAlertlogin((Activity) context, t.toString()); + } + }); + } catch (Exception e) { + e.fillInStackTrace(); + loading.dismiss(); + } + } + + private boolean checkindex() { + boolean status = false; + String str = edt_mobile_no.getText().toString(); + String strArray[] = str.split(" "); + //print elements of String array + for (int i = 0; i < strArray.length; i++) { + if (strArray[i].contains("1") || strArray[i].contains("2") || strArray[i].contains("3") || strArray[i].contains("4") || strArray[i].contains("5") || strArray[i].contains("6") || strArray[i].contains("7") || strArray[i].contains("9") || strArray[i].contains("8")) { + status = true; + break; + } + } + return status; + } + + private void getstatusof_termcondition() { + edt_mobile_no.addTextChangedListener(new TextWatcher() { + @Override + public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { + + } + + @Override + public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { + + } + + @Override + public void afterTextChanged(Editable editable) { + if (!editable.toString().equals("") && editable.toString().length() == 10) { + if (CommonFunctions.checkNetIsAvailable(context) && checkindex()) { + try { + JSONObject jsonObject1 = new JSONObject(); + jsonObject1.put("Downloadtype", "Consumer_TermsConditionAccept"); + jsonObject1.put("Username", username); + jsonObject1.put("Param2", CounterId); + jsonObject1.put("Param1", edt_mobile_no.getText().toString()); + getstatusoftermscondition_status(context, jsonObject1.toString()); + } catch (JSONException e) { + e.fillInStackTrace(); + } + } else { + response_term_condition = "0"; + } + } else { + rl_term_condition.setTextColor(getResources().getColor(R.color.blue)); + rl_term_condition.setEnabled(true); + } + } + }); + + } + + public void getstatusoftermscondition_status(final Context context, String jsondata) { + try { + OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, + TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build(); + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsondata.toString()); + Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build(); + PostApi api = adapter.create(PostApi.class); + retrofit2.Call call = api.getDownloadAll(jsonData); + call.enqueue(new retrofit2.Callback() { + @Override + public void onResponse(retrofit2.Call call, retrofit2.Response response) { + String responseBody = response.body(); + String data_for = null; + if (responseBody != null && response.isSuccessful()) { + data_for = response.body(); + if (data_for.equals("")) { + } else { + if (!data_for.contains("No Data")) { + MasterBAProfileGetterSetter reportbaAvailabilityGetterSetter = new Gson().fromJson(data_for, MasterBAProfileGetterSetter.class); + if (reportbaAvailabilityGetterSetter != null) { + List dataresponce = reportbaAvailabilityGetterSetter.getConsumerTermsConditionAccept(); + if (dataresponce.get(0).getTermsConditionAccept()) { + response_term_condition = "1"; + + rl_term_condition.setTextColor(getResources().getColor(R.color.gray)); + rl_term_condition.setEnabled(false); + + } else { + response_term_condition = "0"; + } + } else { + response_term_condition = "0"; + } + + } else { + response_term_condition = "0"; + } + } + } else { + loading.dismiss(); + response_term_condition = "0"; + } + } + + @Override + public void onFailure(retrofit2.Call call, Throwable t) { + loading.dismiss(); + response_term_condition = "0"; + } + }); + } catch (Exception e) { + e.fillInStackTrace(); + response_term_condition = "0"; + loading.dismiss(); + } + } + + private void adapterforAgeLimit_SkinType() { + AgeAdapter = new ArrayAdapter<>(this, R.layout.spinner_custom_item); + AgeAdapter.add("- Select Age Range -"); + db.open(); + for (int i = 0; i < db.getAgeLimitMasterData().size(); i++) { + AgeAdapter.add(db.getAgeLimitMasterData().get(i).getAgeLimit()); + } + spin_age.setAdapter(AgeAdapter); + AgeAdapter.setDropDownViewResource(R.layout.spinner_custom_item); + spin_age.setOnItemSelectedListener(this); + + SkinTypeAdapter = new ArrayAdapter<>(this, R.layout.spinner_custom_item); + SkinTypeAdapter.add("- Select Skin Type -"); + for (int i = 0; i < db.getskinTypeMaster().size(); i++) { + SkinTypeAdapter.add(db.getskinTypeMaster().get(i).getSkinType()); + } + spin_skin_type.setAdapter(SkinTypeAdapter); + SkinTypeAdapter.setDropDownViewResource(R.layout.spinner_custom_item); + spin_skin_type.setOnItemSelectedListener(this); + + lookCreatedAdapter = new ArrayAdapter<>(this, R.layout.spinner_custom_item); + lookCreatedAdapter.add("- Select Look -"); + for (int i = 0; i < db.getlook_creation().size(); i++) { + lookCreatedAdapter.add(db.getlook_creation().get(i).getLooks()); + } + spin_look_created.setAdapter(lookCreatedAdapter); + lookCreatedAdapter.setDropDownViewResource(R.layout.spinner_custom_item); + spin_look_created.setOnItemSelectedListener(this); + + + if (flag_for_makeover_Update != null && flag_for_makeover_Update.equals("1") || flag_for_makeover_Update != null && flag_for_makeover_Update.equals("0")) { + db.open(); + for (int k = 0; k < db.getAgeLimitMasterData().size(); k++) { + if (!object.getConsumer_age().equals("")) + if (db.getAgeLimitMasterData().get(k).getAgeLimit().equals(object.getConsumer_age())) { + spin_age.setSelection(k + 1); + break; + } + } + db.open(); + for (int k = 0; k < db.getskinTypeMaster().size(); k++) { + if (!object.getConsumer_skinType().equals("")) + if (db.getskinTypeMaster().get(k).getSkinType().equals(object.getConsumer_skinType())) { + spin_skin_type.setSelection(k + 1); + break; + } + } + db.open(); + for (int k = 0; k < db.getlook_creation().size(); k++) { + if (!object.getLook_creater_str().equals("")) + if (db.getlook_creation().get(k).getLooks().equals(object.getLook_creater_str())) { + spin_look_created.setSelection(k + 1); + break; + } + } + } + } + + + @Override + protected void onResume() { + super.onResume(); + if (!response_term_condition.equals("") && !response_term_condition.equals("0")) { + rl_term_condition.setTextColor(getResources().getColor(R.color.gray)); + rl_term_condition.setEnabled(false); + } + } + + private boolean CustomerfeedBack_dialog(final Context context) { + final MultiPurposeDialog multiPurposeDialog = new MultiPurposeDialog(context); + multiPurposeDialog.requestWindowFeature(Window.FEATURE_NO_TITLE); + multiPurposeDialog.setContentView(R.layout.customer_feedback_dialog); + final WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); + lp.copyFrom(multiPurposeDialog.getWindow().getAttributes()); + lp.width = WindowManager.LayoutParams.MATCH_PARENT; + lp.height = WindowManager.LayoutParams.WRAP_CONTENT; + lp.gravity = Gravity.CENTER; + multiPurposeDialog.getWindow().setAttributes(lp); + multiPurposeDialog.setCancelable(false); + + final ImageView excellent = (ImageView) multiPurposeDialog.findViewById(R.id.excellent); + final ImageView very_good = (ImageView) multiPurposeDialog.findViewById(R.id.very_good); + final ImageView good_img = (ImageView) multiPurposeDialog.findViewById(R.id.good); + final ImageView img_bad = (ImageView) multiPurposeDialog.findViewById(R.id.img_bad); + final ImageView ok = (ImageView) multiPurposeDialog.findViewById(R.id.ok); + + excellent.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + feed_back_str = "Excellent"; + excellent.setImageResource((R.mipmap.tick_excellent)); + very_good.setImageResource((R.mipmap.emogi_verygood)); + good_img.setImageResource((R.mipmap.emogi_good)); + img_bad.setImageResource((R.mipmap.emogi_bad)); + } + }); + + very_good.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + feed_back_str = "Very Good"; + excellent.setImageResource((R.mipmap.emogi_excellent)); + very_good.setImageResource((R.mipmap.tick_verygood)); + good_img.setImageResource((R.mipmap.emogi_good)); + img_bad.setImageResource((R.mipmap.emogi_bad)); + + } + }); + + good_img.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + feed_back_str = "Good"; + excellent.setImageResource((R.mipmap.emogi_excellent)); + very_good.setImageResource((R.mipmap.emogi_verygood)); + good_img.setImageResource((R.mipmap.tick_good)); + img_bad.setImageResource((R.mipmap.emogi_bad)); + } + }); + img_bad.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + feed_back_str = "Bad"; + excellent.setImageResource((R.mipmap.emogi_excellent)); + very_good.setImageResource((R.mipmap.emogi_verygood)); + good_img.setImageResource((R.mipmap.emogi_good)); + img_bad.setImageResource((R.mipmap.tick_bad)); + } + }); + + + ok.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + if (feed_back_str.equals("")) { + AlertandMessages.showToastMsg(context, "Please Choose Customer Feedback"); + feed_back_flag = false; + } else { + feed_back_flag = true; + multiPurposeDialog.dismiss(); + } + } + }); + + + final ImageView dismiss_dialog = (ImageView) multiPurposeDialog.findViewById(R.id.dismiss_dialog); + dismiss_dialog.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + multiPurposeDialog.dismiss(); + } + }); + + + if (!feed_back_flag) { + multiPurposeDialog.show(); + } + + return feed_back_flag; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/makeupexpert/MultiselectionCategorySpinnerSearch.java b/app/src/main/java/com/cpm/lorealbaautomation/makeupexpert/MultiselectionCategorySpinnerSearch.java new file mode 100644 index 0000000..2b7d51a --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/makeupexpert/MultiselectionCategorySpinnerSearch.java @@ -0,0 +1,217 @@ +package com.cpm.lorealbaautomation.makeupexpert; + +import android.app.AlertDialog; +import android.content.Context; +import android.content.DialogInterface; +import android.content.res.TypedArray; +import android.graphics.Typeface; +import androidx.appcompat.widget.AppCompatSpinner; +import android.util.AttributeSet; +import android.util.Log; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.ArrayAdapter; +import android.widget.BaseAdapter; +import android.widget.CheckBox; +import android.widget.ListView; +import android.widget.TextView; + +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.gsonGetterSetter.MEMEAuditQuestion; + +import java.util.ArrayList; + +public class MultiselectionCategorySpinnerSearch extends AppCompatSpinner implements DialogInterface.OnCancelListener { + private static final String TAG = MultiselectionCategorySpinnerSearch.class.getSimpleName(); + private String defaultText = ""; + private String spinnerTitle = ""; + private CategorySpinnerInterface listener; + private int selected = 0; + MultipleSelectionSpinAdapter adapter; + ArrayList productList = new ArrayList<>(); + public static AlertDialog ad; + + public MultiselectionCategorySpinnerSearch(Context context) { + super(context); + } + + public MultiselectionCategorySpinnerSearch(Context arg0, AttributeSet arg1) { + super(arg0, arg1); + TypedArray a = arg0.obtainStyledAttributes(arg1, R.styleable.MultiSpinnerSearch); + for (int i = 0; i < a.getIndexCount(); ++i) { + int attr = a.getIndex(i); + if (attr == R.styleable.MultiSpinnerSearch_hintText) { + spinnerTitle = a.getString(attr); + defaultText = spinnerTitle; + break; + } + } + + Log.i(TAG, "spinnerTitle: " + spinnerTitle); + a.recycle(); + } + + public MultiselectionCategorySpinnerSearch(Context arg0, AttributeSet arg1, int arg2) { + super(arg0, arg1, arg2); + } + + @Override + public void onCancel(DialogInterface dialog) { + // refresh text on spinner + StringBuilder spinnerBuffer = new StringBuilder(); + for (int i = 0; i < productList.size(); i++) { + if (productList.get(i).isSelected()) { + spinnerBuffer.append(productList.get(i).getAnswer().trim()); + spinnerBuffer.append(", "); + } + } + + String spinnerText = spinnerBuffer.toString(); + if (spinnerText.length() > 2) + spinnerText = spinnerText.substring(0, spinnerText.length() - 2); + else + spinnerText = defaultText; + + ArrayAdapter adapterSpinner = new ArrayAdapter<>(getContext(), R.layout.spinner_custom_item, new String[]{spinnerText}); + setAdapter(adapterSpinner); + if (adapter != null) + adapter.notifyDataSetChanged(); + listener.onItemsSelectedCategory(productList); + } + + @Override + public boolean performClick() { + AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); + builder.setTitle("Please Select"); + final LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); + final View view = inflater.inflate(R.layout.alert_dialog_listview_multi, null); + builder.setView(view); + final ListView listView = view.findViewById(R.id.alertSearchListView); + listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); + listView.setFastScrollEnabled(false); + adapter = new MultipleSelectionSpinAdapter(getContext(), productList); + listView.setAdapter(adapter); + builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { + + @Override + public void onClick(DialogInterface dialog, int which) { + Log.i(TAG, " ITEMS : " + productList.size()); + dialog.cancel(); + } + }); + builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialogInterface, int i) { + Log.i(TAG, " ITEMS : " + productList.size()); + dialogInterface.dismiss(); + } + }); + builder.setOnCancelListener(this); + ad = builder.show(); + return true; + } + + public void setItemsProduct(ArrayList items, int position, CategorySpinnerInterface listener) { + this.productList = items; + this.listener = (CategorySpinnerInterface) listener; + StringBuilder spinnerBuffer = new StringBuilder(); + + for (int i = 0; i < items.size(); i++) { + if (items.get(i).isSelected()) { + spinnerBuffer.append(items.get(i).getAnswer()); + spinnerBuffer.append(", "); + } + } + + if (spinnerBuffer.length() > 2) + defaultText = spinnerBuffer.toString().substring(0, spinnerBuffer.toString().length() - 2); + + ArrayAdapter adapterSpinner = new ArrayAdapter<>(getContext(), R.layout.spinner_custom_item, new String[]{defaultText}); + setAdapter(adapterSpinner); + + if (position != -1) { + items.get(position).setSelected(true); + onCancel(null); + } + } + + + //Adapter Class + + public class MultipleSelectionSpinAdapter extends BaseAdapter { + + ArrayList arrayList; + ArrayList mOriginalValues; // Original Values + LayoutInflater inflater; + + public MultipleSelectionSpinAdapter(Context context, ArrayList arrayList) { + this.arrayList = arrayList; + inflater = LayoutInflater.from(context); + } + + @Override + public int getCount() { + return arrayList.size(); + } + + @Override + public Object getItem(int position) { + return position; + } + + @Override + public long getItemId(int position) { + return position; + } + + private class ViewHolder { + TextView textView; + CheckBox checkBox; + } + + @Override + public View getView(final int position, View convertView, ViewGroup parent) { + MultiselectionCategorySpinnerSearch.MultipleSelectionSpinAdapter.ViewHolder holder; + if (convertView == null) { + holder = new MultipleSelectionSpinAdapter.ViewHolder(); + convertView = inflater.inflate(R.layout.item_listview_multiple_row, parent, false); + holder.textView = (TextView) convertView.findViewById(R.id.alertTextView); + holder.checkBox = (CheckBox) convertView.findViewById(R.id.alertCheckbox); + convertView.setTag(holder); + } else { + holder = (ViewHolder) convertView.getTag(); + } + + final MEMEAuditQuestion data = arrayList.get(position); + + holder.textView.setText(data.getAnswer()); + holder.textView.setTypeface(null, Typeface.NORMAL); + holder.checkBox.setChecked(data.isSelected()); + + convertView.setOnClickListener(new OnClickListener() { + public void onClick(View v) { + if (data.isSelected()) { // deselect + selected--; + } else {// selected + selected++; + } + + final ViewHolder temp = (ViewHolder) v.getTag(); + temp.checkBox.setChecked(!temp.checkBox.isChecked()); + data.setSelected(!data.isSelected()); + Log.i("", "On Click Selected Item : " + data.getAnswer() + " : " + data.isSelected()); + notifyDataSetChanged(); + } + }); + + + if (data.isSelected()) { + holder.textView.setTypeface(null, Typeface.NORMAL); + } + + holder.checkBox.setTag(holder); + return convertView; + } + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/makeupexpert/SalesActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/makeupexpert/SalesActivity.java new file mode 100644 index 0000000..c5b41e5 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/makeupexpert/SalesActivity.java @@ -0,0 +1,1862 @@ +package com.cpm.lorealbaautomation.makeupexpert; + +import android.annotation.SuppressLint; +import android.app.Activity; +import android.app.Dialog; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.graphics.drawable.ColorDrawable; +import android.os.AsyncTask; +import android.os.Build; +import android.os.Bundle; + +import androidx.annotation.NonNull; +import androidx.annotation.RequiresApi; + +import com.google.android.material.bottomsheet.BottomSheetDialog; +import com.google.android.material.floatingactionbutton.FloatingActionButton; + +import androidx.appcompat.app.AppCompatActivity; +import androidx.cardview.widget.CardView; +import androidx.recyclerview.widget.GridLayoutManager; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; +import androidx.appcompat.widget.Toolbar; + +import android.text.Editable; +import android.text.TextWatcher; +import android.util.Log; +import android.view.Gravity; +import android.view.LayoutInflater; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; +import android.view.Window; +import android.view.WindowManager; +import android.view.inputmethod.InputMethodManager; +import android.widget.AbsListView; +import android.widget.AdapterView; +import android.widget.BaseExpandableListAdapter; +import android.widget.Button; +import android.widget.EditText; +import android.widget.ExpandableListView; +import android.widget.ImageView; +import android.widget.LinearLayout; +import android.widget.ProgressBar; +import android.widget.Spinner; +import android.widget.TextView; + +import com.google.gson.JsonObject; +import com.google.zxing.integration.android.IntentIntegrator; +import com.google.zxing.integration.android.IntentResult; +import com.journeyapps.barcodescanner.CaptureActivity; +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.adapter.ReasonSpinnerAdapter; +import com.cpm.lorealbaautomation.constant.AlertandMessages; +import com.cpm.lorealbaautomation.constant.CommonFunctions; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.download.Downloader; +import com.cpm.lorealbaautomation.gettersetter.SaleableGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.JourneyPlan; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterNonStockReason; +import com.cpm.lorealbaautomation.gsonGetterSetter.ProductMaster; + +import com.cpm.lorealbaautomation.retrofit.PostApi; + + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.File; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.TimeUnit; + +import okhttp3.MediaType; +import okhttp3.OkHttpClient; +import okhttp3.RequestBody; +import retrofit2.Call; +import retrofit2.Callback; +import retrofit2.Response; +import retrofit2.Retrofit; +import retrofit2.converter.gson.GsonConverterFactory; + +import static com.cpm.lorealbaautomation.constant.CommonFunctions.getCurrentTime; +import static com.cpm.lorealbaautomation.constant.CommonFunctions.removeFirstChar; +import static com.cpm.lorealbaautomation.dailyactivity.StoreImageActivity.convertBitmap; + +public class SalesActivity extends AppCompatActivity implements View.OnClickListener { + Spinner sku_spin, brand_spin, sub_axe_spin, axe_spin; + ArrayList brandList = new ArrayList<>(); + ArrayList subBrandList = new ArrayList<>(); + ArrayList referenceList = new ArrayList<>(); + ArrayList signatureList = new ArrayList<>(); + ExpandableListView lvExp_stock_check; + FloatingActionButton fab_save, fab_draft; + Lorealba_Database db; + Context context; + private SharedPreferences preferences; + String counter_id, visit_date, username, _pathforcheck, _path; + ArrayList listDataHeader = new ArrayList<>(); + ArrayList childStockList = new ArrayList<>(); + HashMap> listDataChild; + boolean checkflag = true, changes_flg = false; + ArrayList checkHeaderArray = new ArrayList<>(); + ExpandableListAdapter listAdapter; + String brandName = ""; + String axeName = ""; + String subAxeName = ""; + int groupPositionGlobal = -1; + ProductMaster globalHeaderObject = new ProductMaster(); + EditText et_search; + boolean regularStockFlag = false, check_flag = true; + View sheetView; + ProductMaster selectedSignature, selectedBrand, selectedSubBrand, selectedReference; + + ImageView img_scan, img_clear_subaxe, img_unfilled; + boolean flagScan = true; + String counterGroupId; + RecyclerView recSubAxe; + String selectedSubAxe = ""; + SubAxeValueAdapter subAxeValueAdapter; + ArrayList listSubAxe; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_sales); + context = this; + ((SalesActivity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); + db = new Lorealba_Database(context); + db.open(); + validateUIData(); + + String couter_code = preferences.getString(CommonString.KEY_COUNTER_CODE, ""); + TextView txt_counter_code = (TextView) findViewById(R.id.txt_counter_code); + txt_counter_code.setText("Counter Code - " + couter_code + " / Id - " + counter_id); + new LoadAsync().execute(); + + lvExp_stock_check.setOnScrollListener(new AbsListView.OnScrollListener() { + @Override + public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { + lvExp_stock_check.invalidate(); + int lastItem = firstVisibleItem + visibleItemCount; + if (firstVisibleItem == 0) { + fab_save.show();//.setVisibility(View.VISIBLE); + } else if (lastItem == totalItemCount) { + fab_save.hide();//setVisibility(View.INVISIBLE); + } else { + fab_save.show();//setVisibility(View.VISIBLE); + } + } + + @Override + public void onScrollStateChanged(AbsListView arg0, int arg1) { + InputMethodManager inputManager = (InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE); + if (getCurrentFocus() != null) { + inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0); + getCurrentFocus().clearFocus(); + } + lvExp_stock_check.invalidateViews(); + } + }); + } + + JourneyPlan jcp; + + private void validateUIData() { + preferences = PrefHelper.getPrefs(context); + counter_id = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + username = preferences.getString(CommonString.KEY_USERNAME, ""); + Toolbar toolbar = findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + if (!CommonFunctions.isTablet(context)) { + toolbar.setTitleTextAppearance(context, R.style.changestext_sizefor_mobile); + } + + getSupportActionBar().setHomeButtonEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + setTitle("ME_Sales - " + visit_date); + sku_spin = (Spinner) findViewById(R.id.sku_spin); + brand_spin = (Spinner) findViewById(R.id.stock_brand_spin); + sub_axe_spin = (Spinner) findViewById(R.id.sub_axe_spin); + axe_spin = (Spinner) findViewById(R.id.axe_spin); + lvExp_stock_check = (ExpandableListView) findViewById(R.id.lvExp_stock_check); + fab_save = (FloatingActionButton) findViewById(R.id.save_fab); + fab_draft = (FloatingActionButton) findViewById(R.id.draft_fab); + et_search = (EditText) findViewById(R.id.et_search); + img_scan = (ImageView) findViewById(R.id.img_scan); + img_unfilled = (ImageView) findViewById(R.id.img_unfilled); + img_clear_subaxe = (ImageView) findViewById(R.id.img_clear_subaxe); + ImageView img_filter = (ImageView) findViewById(R.id.img_filter); + recSubAxe = (RecyclerView) findViewById(R.id.rec_subaxe); + fab_save.setOnClickListener(this); + fab_draft.setOnClickListener(this); + db.open(); + + img_filter.setOnClickListener(v -> sheetView = showFilterBottomSheet()); + + et_search.addTextChangedListener(new TextWatcher() { + @Override + public void beforeTextChanged(CharSequence s, int start, int count, int after) { + } + + @Override + public void onTextChanged(CharSequence s, int start, int before, int count) { + String text = s.toString(); + if (text.isEmpty()) { + if (lvExp_stock_check != null && listAdapter != null) { + lvExp_stock_check.setAdapter(listAdapter); + listAdapter.notifyDataSetChanged(); + } + } else { + lvExp_stock_check.invalidate(); + setSearchFilter(listAdapter.get_listDataHeader(), text, listAdapter.get_listDataChild()); + } + } + + @Override + public void afterTextChanged(Editable s) { + String text = s.toString(); + } + }); + + img_scan.setOnClickListener(this); + ///changes icon + img_unfilled.setOnClickListener(this); + img_clear_subaxe.setOnClickListener(this); + db.open(); + String status = db.getStatus(CommonString.KEY_SaleableStatus, counter_id); + + /*db.open(); + String status = db.getStatus(CommonString.KEY_SaleableStatus, counter_id); + //if regular stock need to be captured after First stock capture + if (status != null && !status.equals("") && status.equalsIgnoreCase("Complete")) { + fab_save.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.save_icon)); + regularStockFlag = true; + fab_draft.hide(); + }*/ + } + + View showFilterBottomSheet() { + final CardView cardSignature, cardBrand, cardSubBrand, cardReference; + final BottomSheetDialog mBottomSheetDialog = new BottomSheetDialog(this); + @SuppressLint("InflateParams") final View sheetView = getLayoutInflater().inflate(R.layout.filter_bottom_sheet, null); + mBottomSheetDialog.setContentView(sheetView); + View bottomSheet = mBottomSheetDialog.getWindow().findViewById(com.google.android.material.R.id.design_bottom_sheet); + if (bottomSheet != null) { + bottomSheet.setBackgroundResource(android.R.color.transparent); + } + mBottomSheetDialog.setCancelable(false); + + final RecyclerView recBrand = sheetView.findViewById(R.id.rec_brand); + ImageView img_cancel = sheetView.findViewById(R.id.img_cancel); + TextView tv_clear_filter = sheetView.findViewById(R.id.tv_clear_filter); + recBrand.setAdapter(new ValueAdapter(context, signatureList, CommonString.Signature)); + recBrand.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, true)); + + cardSignature = sheetView.findViewById(R.id.card_signature); + cardBrand = sheetView.findViewById(R.id.card_brand); + cardSubBrand = sheetView.findViewById(R.id.card_sub_brand); + cardReference = sheetView.findViewById(R.id.card_reference); + + cardSignature.setOnClickListener(this); + cardBrand.setOnClickListener(this); + cardSubBrand.setOnClickListener(this); + cardReference.setOnClickListener(this); + + cardSignature.setCardBackgroundColor(getResources().getColor(R.color.dashboard_ach)); + if (selectedSignature != null) { + (sheetView.findViewById(R.id.img_filter_signature)).setVisibility(View.VISIBLE); + } + if (selectedBrand != null) { + (sheetView.findViewById(R.id.img_filter_brand)).setVisibility(View.VISIBLE); + } + if (selectedSubBrand != null) { + (sheetView.findViewById(R.id.img_filter_sub_brand)).setVisibility(View.VISIBLE); + } + if (selectedReference != null) { + (sheetView.findViewById(R.id.img_filter_reference)).setVisibility(View.VISIBLE); + } + + img_cancel.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + mBottomSheetDialog.cancel(); + } + }); + + tv_clear_filter.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + clearFilters(); + cardSignature.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background)); + cardBrand.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background)); + cardSubBrand.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background)); + cardReference.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background)); + ValueAdapter adapter = (ValueAdapter) recBrand.getAdapter(); + String type = adapter.getType(); + ArrayList list = new ArrayList<>(); + switch (type) { + case CommonString.Signature: + list = signatureList; + break; + case CommonString.Brand: + list = brandList; + break; + case CommonString.SubBrand: + list = subBrandList; + break; + case CommonString.Reference: + list = referenceList; + break; + } + recBrand.setLayoutManager(new LinearLayoutManager(SalesActivity.this, LinearLayoutManager.VERTICAL, true)); + recBrand.setAdapter(new ValueAdapter(context, list, CommonString.Signature)); + recBrand.getAdapter().notifyDataSetChanged(); + } + }); + + mBottomSheetDialog.show(); + return sheetView; + } + + private void prepareListData() { + db.open(); + jcp = db.getJCP(); + if (jcp != null) { + db.open(); + listSubAxe = db.getSubAxe(jcp.getCounterGroupId().toString(), true); + } else { + db.open(); + listSubAxe = db.getSubAxe("1", true); + } + + //inserted data + listDataHeader = new ArrayList<>(); + listDataChild = new HashMap<>(); + db.open(); + jcp = db.getJCP(); + if (jcp != null) { + db.open(); + listDataHeader = db.getFunctionMEHeader(jcp.getCounterGroupId().toString(), selectedSubAxe, regularStockFlag, CommonString.ME_SALE, counter_id, visit_date); + // listDataHeader = db.getFunctionName(jcp.getCounterGroupId().toString(), selectedSubAxe, regularStockFlag, CommonString.KEY_SaleableBalance, counter_id, visit_date); + } else { + db.open(); + listDataHeader = db.getMESaleSignatureBrandSubBrandReference("1", false, regularStockFlag, CommonString.ME_SALE); + } + jcp = db.getJCP(); + if (jcp != null) { + db.open(); + brandList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "BrandName", false, selectedSubAxe); + db.open(); + subBrandList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "SubBrandName", false, selectedSubAxe); + db.open(); + referenceList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "ReferenceName", false, selectedSubAxe); + db.open(); + signatureList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "SignatureName", false, selectedSubAxe); + } else { + db.open(); + brandList = db.getsub_brand_name("1", "BrandName", false, selectedSubAxe); + subBrandList = db.getsub_brand_name("1", "SubBrandName", false, selectedSubAxe); + referenceList = db.getsub_brand_name("1", "ReferenceName", false, selectedSubAxe); + signatureList = db.getsub_brand_name("1", "SignatureName", false, selectedSubAxe); + } + + if (listDataHeader.size() > 0) { + for (int i = 0; i < listDataHeader.size(); i++) { + JourneyPlan jcp = db.getJCP(); + if (jcp != null) { + db.open(); + childStockList = db.getInsertedMEChildData(listDataHeader.get(i).getNuanceName(), CommonString.KEY_SaleableBalance, visit_date, counter_id); + // //test("childsize", String.valueOf(childStockList.size())); + if (childStockList.size() == 0) { + db.open(); + childStockList = db.getDefaultMESaleFunctionData(listDataHeader.get(i).getNuanceName(), + CommonString.KEY_SaleableBalance, counter_id, regularStockFlag, visit_date); + } else { + if (childStockList.get(0).getUploadStatus().equalsIgnoreCase("Y")) { + fab_draft.hide(); + } else { + fab_draft.show(); + } + } + } else { + db.open(); + childStockList = db.getInsertedMEChildData(listDataHeader.get(i).getNuanceName(), CommonString.KEY_SaleableBalance, visit_date, counter_id); + //test("childsize", String.valueOf(childStockList.size())); + if (childStockList.size() == 0) { + db.open(); + childStockList = db.getDefaultMESaleFunctionData(listDataHeader.get(i).getNuanceName(), + CommonString.KEY_SaleableBalance, counter_id, regularStockFlag, visit_date); + } else { + if (childStockList.get(0).getUploadStatus().equalsIgnoreCase("Y")) { + fab_draft.hide(); + } else { + fab_draft.show(); + } + } + } + listDataChild.put(listDataHeader.get(i), childStockList); // Header, Child data + } + } + } + + void setFilterSelected(View sheetView, String type) { + CardView cardSignature, cardBrand, cardSubBrand, cardReference; + cardSignature = sheetView.findViewById(R.id.card_signature); + cardBrand = sheetView.findViewById(R.id.card_brand); + cardSubBrand = sheetView.findViewById(R.id.card_sub_brand); + cardReference = sheetView.findViewById(R.id.card_reference); + + cardSignature.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background)); + cardBrand.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background)); + cardSubBrand.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background)); + cardReference.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background)); + + switch (type) { + case CommonString.Signature: + cardSignature.setCardBackgroundColor(getResources().getColor(R.color.dashboard_ach)); + break; + case CommonString.Brand: + cardBrand.setCardBackgroundColor(getResources().getColor(R.color.dashboard_ach)); + break; + case CommonString.SubBrand: + cardSubBrand.setCardBackgroundColor(getResources().getColor(R.color.dashboard_ach)); + break; + case CommonString.Reference: + cardReference.setCardBackgroundColor(getResources().getColor(R.color.dashboard_ach)); + break; + } + } + + @Override + public void onClick(View view) { + if (view.getId() == R.id.save_fab) { + ////for final submit stock using regular stock flag + lvExp_stock_check.clearFocus(); + lvExp_stock_check.invalidateViews(); + if (regularStockFlag) { + if (validate_regular_stock()) { + if (validateData(listDataChild, listDataHeader)) { + dialogFinalSubmit(); + } + } + } else { + if (validateData(listDataChild, listDataHeader)) { + dialogFinalSubmit(); + } + } + } else if (view.getId() == R.id.draft_fab) { + ///save draft stock.... + lvExp_stock_check.clearFocus(); + lvExp_stock_check.invalidateViews(); + if (validateData(listDataChild, listDataHeader)) { + new InsertAsync().execute(false); + } + + } else if (view.getId() == R.id.card_signature) { + RecyclerView recSignature = sheetView.findViewById(R.id.rec_brand); + recSignature.setAdapter(new ValueAdapter(context, signatureList, CommonString.Signature)); + recSignature.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, true)); + setFilterSelected(sheetView, CommonString.Signature); + } else if (view.getId() == R.id.card_brand) { + + RecyclerView recBrand = sheetView.findViewById(R.id.rec_brand); + recBrand.setAdapter(new ValueAdapter(context, brandList, CommonString.Brand)); + recBrand.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, true)); + setFilterSelected(sheetView, CommonString.Brand); + } else if (view.getId() == R.id.card_sub_brand) { + + RecyclerView recSubBrand = sheetView.findViewById(R.id.rec_brand); + recSubBrand.setAdapter(new ValueAdapter(context, subBrandList, CommonString.SubBrand)); + recSubBrand.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, true)); + recSubBrand.getAdapter().notifyDataSetChanged(); + setFilterSelected(sheetView, CommonString.SubBrand); + } else if (view.getId() == R.id.card_reference) { + + RecyclerView recReference = sheetView.findViewById(R.id.rec_brand); + recReference.setAdapter(new ValueAdapter(context, referenceList, CommonString.Reference)); + recReference.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, true)); + setFilterSelected(sheetView, CommonString.Reference); + } else if (view.getId() == R.id.img_scan) { + + if (flagScan) { + openScanner(); + } else { + img_scan.setImageDrawable(getResources().getDrawable(R.mipmap.barcode_icon)); + flagScan = true; + et_search.setText(""); + } + + } else if (view.getId() == R.id.img_unfilled) { + setUnFilledFilter(listAdapter.get_listDataHeader(), listAdapter.get_listDataChild()); + } else if (view.getId() == R.id.img_clear_subaxe) { + et_search.setText(""); + listAdapter = new ExpandableListAdapter(context, listDataHeader, listDataChild); + lvExp_stock_check.setAdapter(listAdapter); + listAdapter.notifyDataSetChanged(); + selectedSubAxe = ""; + subAxeValueAdapter.notifyDataSetChanged(); + //clear filters also + selectedSignature = null; + selectedBrand = null; + selectedSubBrand = null; + selectedReference = null; + db.open(); + brandList = db.getsub_brand_name(counterGroupId, "BrandName", false, selectedSubAxe); + db.open(); + subBrandList = db.getsub_brand_name(counterGroupId, "SubBrandName", false, selectedSubAxe); + db.open(); + referenceList = db.getsub_brand_name(counterGroupId, "ReferenceName", false, selectedSubAxe); + db.open(); + signatureList = db.getsub_brand_name(counterGroupId, "SignatureName", false, selectedSubAxe); + } + } + + private boolean validateData(HashMap> listDataChild, ArrayList listDataHeader) { + checkflag = true; + int sum = 0; + String uploadStatus = ""; + for (int j = 0; j < listDataHeader.size(); j++) { + List data = listDataChild.get(listDataHeader.get(j)); + for (int i = 0; i < data.size(); i++) { + sum = sum + data.get(i).getStock(); + uploadStatus = data.get(i).getUploadStatus(); + } + } + + if (sum == 0) { + AlertandMessages.showToastMsg(context, "Sale qty should be greater than zero"); + checkflag = false; + } else if (uploadStatus.equalsIgnoreCase(CommonString.KEY_Y)) { + AlertandMessages.showToastMsg(context, "Sale Data Already Uploaded"); + checkflag = false; + } else { + checkflag = true; + } + return checkflag; + } + + public void uploadData(boolean finalFlag) { + //download service + // Intent intent =\ new Intent(context, Downloader.class); + SaleableGetterSetter stock = new SaleableGetterSetter(); + ArrayList data = new ArrayList<>(); + for (int i = 0; i < listDataHeader.size(); i++) { + List list = listDataChild.get(listDataHeader.get(i)); + for (int j = 0; j < list.size(); j++) { + //for final - complete data upload + if (finalFlag) { + list.get(j).setImagePath(listDataHeader.get(i).getImagePath()); + data.add(list.get(j)); + } else { + if (list.get(j).isSelected()) { + list.get(j).setImagePath(listDataHeader.get(i).getImagePath()); + data.add(list.get(j)); + } + } + } + } + + if (data.size() > 0) { + stock.setProductList(data); + String uuid = CommonFunctions.getUUID(context); + stock.setTransactionId(uuid); + db.open(); + ////changes by jeevan insert transaction for future use and handle master transaction + if (regularStockFlag) { + db.open(); + db.insertStockTransactionMasterData(counter_id, visit_date, username, CommonString.ME_SALE, stock, "Regular_Stock"); + } else { + if (finalFlag) { + db.open(); + db.insertStockTransactionMasterData(counter_id, visit_date, username, CommonString.ME_SALE, stock, "FirstTime_Stock_Comp"); + } else { + db.open(); + db.insertStockTransactionMasterData(counter_id, visit_date, username, CommonString.ME_SALE, stock, "FirstTime_Stock_Draft"); + } + } + + dialog.cancel(); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + SalesActivity.this.finish(); + CommonFunctions.call_upload(context); + } + } + + + public ArrayList filterListForSignature(List originalList, String text) { + ArrayList filterList = new ArrayList<>(); + for (ProductMaster object : originalList) { + if (object.getSignatureName().equalsIgnoreCase(text)) { + filterList.add(object); + } else { + continue; + } + } + return filterList; + } + + public ArrayList filterListForBrand(List originalList, String text) { + ArrayList filterList = new ArrayList<>(); + for (ProductMaster object : originalList) { + + if (object.getBrandName().equalsIgnoreCase(text) && (selectedSignature == null || object.getSignatureName().equalsIgnoreCase(selectedSignature.getBrandName()))) { + filterList.add(object); + } else { + continue; + } + } + return filterList; + } + + public ArrayList filterListForSubBrand(List originalList, String text) { + ArrayList filterList = new ArrayList<>(); + for (ProductMaster object : originalList) { + if (object.getSubBrandName().equalsIgnoreCase(text) && (selectedSignature == null || object.getSignatureName().equalsIgnoreCase(selectedSignature.getBrandName())) && (selectedBrand == null || object.getBrandName().equalsIgnoreCase(selectedBrand.getBrandName()))) { + filterList.add(object); + } else { + continue; + } + } + return filterList; + } + + public ArrayList filterListForReference(List originalList, String text) { + ArrayList filterList = new ArrayList<>(); + for (ProductMaster object : originalList) { + + if (object.getReferenceName().equalsIgnoreCase(text) && (selectedSignature == null || object.getSignatureName().equalsIgnoreCase(selectedSignature.getBrandName())) + && (selectedBrand == null || object.getBrandName().equalsIgnoreCase(selectedBrand.getBrandName())) && (selectedSubBrand == null || object.getSubBrandName().equalsIgnoreCase(selectedSubBrand.getBrandName()))) { + filterList.add(object); + } else { + continue; + } + } + return filterList; + } + + public ArrayList filterListForAxe(List originalList, String text, String brandName) { + ArrayList filterList = new ArrayList<>(); + for (ProductMaster object : originalList) { + if (object.getAxeName().equalsIgnoreCase(text) && (brandName.equals("") || object.getBrandName().equalsIgnoreCase(brandName))) { + filterList.add(object); + } else { + continue; + } + } + return filterList; + } + + public ArrayList filterListForSubAxe(List originalList, String text, String brandName, String axeName) { + ArrayList filterList = new ArrayList<>(); + for (ProductMaster object : originalList) { + if (object.getSubAxeName().equalsIgnoreCase(text) && (brandName.equals("") || object.getBrandName().equalsIgnoreCase(brandName)) && (axeName.equals("") || object.getAxeName().equalsIgnoreCase(axeName))) { + filterList.add(object); + } else { + continue; + } + } + return filterList; + } + + + public class ExpandableListAdapter extends BaseExpandableListAdapter { + Context _context; + List _listDataHeader; + HashMap> _listDataChild; + + public ExpandableListAdapter(Context context, List listDataHeader, HashMap> listChildData) { + this._context = context; + this._listDataHeader = listDataHeader; + this._listDataChild = listChildData; + } + + public HashMap> get_listDataChild() { + return _listDataChild; + } + + public List get_listDataHeader() { + return _listDataHeader; + } + + @Override + public Object getChild(int groupPosition, int childPosititon) { + return this._listDataChild.get(this._listDataHeader.get(groupPosition)).get(childPosititon); + } + + @Override + public long getChildId(int groupPosition, int childPosition) { + return childPosition; + } + + @SuppressLint("SetTextI18n") + @Override + public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { + + final ProductMaster childText = (ProductMaster) getChild(groupPosition, childPosition); + ViewHolder holder = null; + if (convertView == null) { + LayoutInflater infalInflater = (LayoutInflater) this._context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); + convertView = infalInflater.inflate(R.layout.item_stock_layout, null); + holder = new ViewHolder(); + holder.cardView = convertView.findViewById(R.id.card_view); + holder.ed_Stock = convertView.findViewById(R.id.ed_Stock); + holder.mrp = convertView.findViewById(R.id.mrp); + holder.stock_img_plus = convertView.findViewById(R.id.stock_img_plus); + holder.stock_img_minus = convertView.findViewById(R.id.stock_img_minus); + holder.reasonSpinner = convertView.findViewById(R.id.reason_spinner); + holder.reasonLayout = convertView.findViewById(R.id.reason_layout); + holder.et_stock = convertView.findViewById(R.id.et_stock); + convertView.setTag(holder); + } else { + + holder = (ViewHolder) convertView.getTag(); + } + //test("productIdtag",childText.getBrandName() + ","+childText.getSignatureName()); + TextView txtListChild = convertView.findViewById(R.id.lblListItem); + txtListChild.setText(childText.getProductName() + " (MRP - ₹ " + childText.getMrp() + ")"); + final ViewHolder finalHolder = holder; + holder.stock_img_plus.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + ((ExpandableListAdapter) lvExp_stock_check.getExpandableListAdapter()).notifyDataSetChanged(); + if (!regularStockFlag) { + String stot = finalHolder.et_stock.getText().toString().trim().replaceFirst("^0+(?!$)", ""); + if (!stot.equals("")) { + int st = Integer.parseInt(stot); + childText.setStock(st); + } + } + + int stock = childText.getStock(); + int receivedStock = childText.getStock_receive(); + ++stock; + childText.setStock(stock); + + /*if (regularStockFlag) { + if (receivedStock >= stock) { + childText.setStock(stock); + isDataAdded = true; + childText.setSelected(true); + if (receivedStock == stock) { + finalHolder.reasonLayout.setVisibility(View.GONE); + finalHolder.reasonSpinner.setSelection(0); + childText.setReasonId(0); + } + } else { + AlertandMessages.showToastMsg(context, "Stock cannot be greater than Received Stock"); + } + } else { + if (receivedStock == -1) { + childText.setStock_receive(0); + } + childText.setStock(stock); + isDataAdded = true; + childText.setSelected(true); + }*/ + } + }); + + holder.stock_img_minus.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + ((ExpandableListAdapter) lvExp_stock_check.getExpandableListAdapter()).notifyDataSetChanged(); + if (!regularStockFlag) { + String stot = finalHolder.et_stock.getText().toString().trim().replaceFirst("^0+(?!$)", ""); + if (!stot.equals("")) { + int st = Integer.parseInt(stot); + childText.setStock(st); + } + } + + int stock = childText.getStock(); + int receivedStock = childText.getStock_receive(); + --stock; + + if (stock >= 0) { + childText.setStock(stock); + isDataAdded = true; + childText.setSelected(true); + + } else { + AlertandMessages.showToastMsg(context, "Sale cannot be less than 0"); + } + + } + }); + + holder.et_stock.setOnFocusChangeListener((v, hasFocus) -> { + final EditText caption = (EditText) v; + String stock = caption.getText().toString().replaceFirst("^0+(?!$)", ""); + if (!stock.equals("")) { + childText.setStock(Integer.parseInt(stock)); + isDataAdded = true; + childText.setSelected(true); + } else { + childText.setStock(0); + } + }); + + ArrayList reasonList; + db.open(); + reasonList = db.getReasonData(true); + holder.reasonSpinner.setAdapter(new ReasonSpinnerAdapter(_context, R.layout.spinner_text_view, reasonList)); + final ArrayList finalReasonList = reasonList; + holder.reasonSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { + @Override + public void onItemSelected(AdapterView adapterView, View view, int pos, long l) { + if (pos != 0) { + MasterNonStockReason obj = finalReasonList.get(pos); + childText.setReasonId(obj.getReasonId()); + } else { + childText.setReasonId(0); + } + } + + @Override + public void onNothingSelected(AdapterView adapterView) { + + } + }); + + + for (int i = 0; i < finalReasonList.size(); i++) { + if (finalReasonList.get(i).getReasonId() == childText.getReasonId()) { + holder.reasonSpinner.setSelection(i); + break; + } + } + + + int stock = childText.getStock(); + if (!childText.isSelected() && childText.getStock() == 0) { + stock = childText.getStock_receive(); + childText.setStock(stock); + } + + if (childText.getStock() < childText.getStock_receive()) { + if (regularStockFlag) { + finalHolder.reasonLayout.setVisibility(View.VISIBLE); + finalHolder.reasonLayout.setId(childPosition); + } + } else { + finalHolder.reasonLayout.setVisibility(View.GONE); + finalHolder.reasonLayout.setId(childPosition); + } + + + if (regularStockFlag) { + holder.ed_Stock.setText(String.valueOf(stock)); + holder.ed_Stock.setId(childPosition); + + holder.et_stock.setVisibility(View.GONE); + holder.ed_Stock.setVisibility(View.VISIBLE); + } else { + if (stock == -1) { + holder.et_stock.setText(""); + } else { + holder.et_stock.setText(String.valueOf(stock)); + } + + holder.et_stock.setId(childPosition); + + holder.ed_Stock.setVisibility(View.GONE); + holder.et_stock.setVisibility(View.VISIBLE); + } + + holder.mrp.setText(" MRP = " + childText.getMrp()); + holder.mrp.setId(childPosition); + + return convertView; + } + + @Override + public int getChildrenCount(int groupPosition) { + return this._listDataChild.get(this._listDataHeader.get(groupPosition)).size(); + } + + @Override + public Object getGroup(int groupPosition) { + return this._listDataHeader.get(groupPosition); + } + + @Override + public int getGroupCount() { + return this._listDataHeader.size(); + } + + @Override + public long getGroupId(int groupPosition) { + return groupPosition; + } + + @SuppressLint({"InflateParams", "UseCompatLoadingForDrawables"}) + @Override + public View getGroupView(final int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { + final ProductMaster headerTitle = (ProductMaster) getGroup(groupPosition); + if (convertView == null) { + + LayoutInflater infalInflater = (LayoutInflater) this._context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); + convertView = infalInflater.inflate(R.layout.list_group_me_sale_stock_entry, null); + } + TextView lblListHeader = (TextView) convertView.findViewById(R.id.lblListHeader); + ImageView stock_cam = (ImageView) convertView.findViewById(R.id.stock_cam); + + stock_cam.setOnClickListener(v -> { + groupPositionGlobal = groupPosition; + globalHeaderObject = headerTitle; + _pathforcheck = counter_id + "_stock_check_img_" + visit_date.replace("/", "") + "_" + getCurrentTime().replace(":", "") + ".jpg"; + _path = CommonString.getImagesFolder(context) + _pathforcheck; + CommonFunctions.startAnncaCameraActivity(SalesActivity.this, _path, null, false, CommonString.CAMERA_FACE_REAR); + }); + + if (headerTitle.getImagePath().equals("")) { + stock_cam.setImageDrawable(getResources().getDrawable(R.mipmap.camera)); + } else { + stock_cam.setImageDrawable(getResources().getDrawable(R.mipmap.camera_tick)); + } + + lblListHeader.setText(headerTitle.getNuanceName()); + if (!checkflag) { + if (checkHeaderArray.contains(groupPosition)) { + lblListHeader.setBackgroundColor(getResources().getColor(R.color.red)); + } else { + lblListHeader.setBackgroundColor(getResources().getColor(R.color.bright_red)); + } + + } else { + lblListHeader.setBackgroundColor(getResources().getColor(R.color.bright_red)); + } + + return convertView; + } + + @Override + public boolean hasStableIds() { + return false; + } + + @Override + public boolean isChildSelectable(int groupPosition, int childPosition) { + return true; + } + } + + class ViewHolder { + TextView ed_Stock, mrp; + Button stock_img_plus, stock_img_minus; + CardView cardView; + Spinner reasonSpinner; + LinearLayout reasonLayout; + EditText et_stock; + } + + + public void setFilter(int filterType) { + if (filterType == FILTER_FOR_SIGNATURE) { + listAdapter = new ExpandableListAdapter(context, filterListForSignature(listDataHeader, selectedSignature.getBrandName()), listDataChild); + } else if (filterType == FILTER_FOR_BRAND) { + listAdapter = new ExpandableListAdapter(context, filterListForBrand(listDataHeader, selectedBrand.getBrandName()), listDataChild); + } else if (filterType == FILTER_FOR_SUB_BRAND) { + listAdapter = new ExpandableListAdapter(context, filterListForSubBrand(listDataHeader, selectedSubBrand.getBrandName()), listDataChild); + } else if (filterType == FILTER_FOR_REFERENCE) { + listAdapter = new ExpandableListAdapter(context, filterListForReference(listDataHeader, selectedReference.getBrandName()), listDataChild); + } else if (filterType == FILTER_FOR_AXE) { + listAdapter = new ExpandableListAdapter(context, filterListForAxe(listDataHeader, axeName, brandName), listDataChild); + } else if (filterType == FILTER_FOR_SUBAXE) { + listAdapter = new ExpandableListAdapter(context, filterListForSubAxe(listDataHeader, subAxeName, brandName, axeName), listDataChild); + } else { + listAdapter = new ExpandableListAdapter(context, filterListForSubAxe(listDataHeader, selectedSubAxe), listDataChild); + } + + lvExp_stock_check.setAdapter(listAdapter); + listAdapter.notifyDataSetChanged(); + } + + final int FILTER_FOR_SIGNATURE = 4; + final int FILTER_FOR_SUB_BRAND = 5; + final int FILTER_FOR_REFERENCE = 6; + final int FILTER_FOR_BRAND = 1; + final int FILTER_FOR_AXE = 2; + final int FILTER_FOR_SUBAXE = 3; + final int CLEAR_FILTER = 0; + + public void setSearchFilter(List originalList, String text, HashMap> listDataChild) { + HashMap> filterChildHashMap = new HashMap<>(); + ArrayList filterList = new ArrayList<>(); + for (int i = 0; i < originalList.size(); i++) { + ProductMaster parent = originalList.get(i); + List listChild = listDataChild.get(parent); + List listFilterChild = new ArrayList<>(); + for (int j = 0; j < listChild.size(); j++) { + if (listChild.get(j).getProductName().toLowerCase().contains(text.toLowerCase()) || (listChild.get(j).getEanCode() != null && listChild.get(j).getEanCode().contains(text))) { + listFilterChild.add(listChild.get(j)); + } else { + continue; + } + } + + if (listFilterChild.size() > 0) { + filterList.add(parent); + filterChildHashMap.put(parent, listFilterChild); + + } + + } + + ExpandableListAdapter listAdapter1 = new ExpandableListAdapter(context, filterList, filterChildHashMap); + lvExp_stock_check.setAdapter(listAdapter1); + for (int i = 0; i < listAdapter1.getGroupCount(); i++) { + lvExp_stock_check.expandGroup(i); + } + listAdapter1.notifyDataSetChanged(); + + + } + + boolean isDataAdded = false; + + @Override + public void onBackPressed() { + isChanged(); + } + + void isChanged() { + if (isDataAdded) { + android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(SalesActivity.this); + builder.setTitle(R.string.parinaam); + builder.setMessage(getResources().getString(R.string.data_will_be_lost)).setCancelable(false) + .setPositiveButton(getString(R.string.ok), (dialog, id) -> { + finish(); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + }).setNegativeButton(getString(R.string.cancel), (dialog, which) -> { + + }); + android.app.AlertDialog alert = builder.create(); + alert.show(); + } else { + super.onBackPressed(); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + } + } + + void dialogFinalSubmit() { + android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(SalesActivity.this); + builder.setTitle(R.string.parinaam); + builder.setMessage(getResources().getString(R.string.want_to_final_save)).setCancelable(false) + .setPositiveButton(getString(R.string.ok), (dialog, id) -> { + show_dialog_for_final_submit(context); + dialog.dismiss(); + }).setNegativeButton(getString(R.string.cancel), (dialog, which) -> dialog.dismiss()); + + android.app.AlertDialog alert = builder.create(); + alert.show(); + } + + private void show_dialog_for_final_submit(final Context context) { + final MultiPurposeDialog final_save_dialog = new MultiPurposeDialog(context); + final_save_dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); + final_save_dialog.setContentView(R.layout.custom_dialog_final_save); + final WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); + lp.copyFrom(Objects.requireNonNull(final_save_dialog.getWindow()).getAttributes()); + lp.width = WindowManager.LayoutParams.MATCH_PARENT; + lp.height = WindowManager.LayoutParams.WRAP_CONTENT; + lp.gravity = Gravity.CENTER; + final_save_dialog.getWindow().setAttributes(lp); + final_save_dialog.setCancelable(false); + final EditText txt_hint_yes = (EditText) final_save_dialog.findViewById(R.id.txt_hint_yes); + Button btn_cancel = (Button) final_save_dialog.findViewById(R.id.btn_cancel); + Button btn_okay = (Button) final_save_dialog.findViewById(R.id.btn_okay); + + btn_okay.setOnClickListener(v -> { + if (txt_hint_yes.getText().toString().equals("")) { + AlertandMessages.showToastMsg(context, "Please Enter Text"); + } else if (!txt_hint_yes.getText().toString().trim().equalsIgnoreCase("yes")) { + AlertandMessages.showToastMsg(context, "Please Enter 'Yes' Text"); + } else { + final_save_dialog.dismiss(); + new InsertAsync().execute(true); + } + }); + + + btn_cancel.setOnClickListener(v -> final_save_dialog.dismiss()); + + final_save_dialog.show(); + } + + class MultiPurposeDialog extends Dialog { + public MultiPurposeDialog(Context context) { + super(context); + // DIALOG USER_INTERFACE TEMPLATE + WindowManager.LayoutParams wmLayoutParams = Objects.requireNonNull(getWindow()).getAttributes(); + wmLayoutParams.gravity = Gravity.CENTER; + getWindow().setAttributes(wmLayoutParams); + setTitle(null); + setCancelable(false); + setOnCancelListener(null); + LinearLayout layout = new LinearLayout(context); + layout.setOrientation(LinearLayout.VERTICAL); + } + } + + + @SuppressLint("UseCompatLoadingForDrawables") + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + Log.i("MakeMachine", "resultCode: " + resultCode); + if (requestCode == 131) { + switch (resultCode) { + case 0: + Log.i("MakeMachine", "User cancelled"); + break; + + case -1: + if (_pathforcheck != null && !_pathforcheck.equals("")) { + if (new File(CommonString.getImagesFolder(context) + _pathforcheck).exists()) { + convertBitmap(CommonString.getImagesFolder(context) + _pathforcheck); + + isDataAdded = true; + globalHeaderObject.setImagePath(_pathforcheck); + groupPositionGlobal = -1; + _pathforcheck = ""; + listAdapter.notifyDataSetChanged(); + } + } + break; + } + } else { + IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data); + switch (resultCode) { + case 0: + + break; + + case -1: + db.open(); + ArrayList productList = db.getsku_fromproductusing_eancode(result.getContents(), false, visit_date, counter_id, null); + + if (productList.isEmpty()) { + db.open(); + productList = db.getsku_fromproductusing_eancode(removeFirstChar(result.getContents()), false, visit_date, counter_id, null); + } + + //test("Ean Code", result.getContents()); + if (!productList.isEmpty()) { + flagScan = false; + img_scan.setImageDrawable(getResources().getDrawable(R.mipmap.ok)); + clearFilters(); + setScanFilter(productList); + } else { + AlertandMessages.showToastMsg(context, "Unable To Scan Correct Data. Please Try Again."); + } + + break; + } + } + + super.onActivityResult(requestCode, resultCode, data); + } + + + public class ValueAdapter extends RecyclerView.Adapter { + LayoutInflater inflator; + List data; + String type; + + public String getType() { + return type; + } + + public ValueAdapter(Context context, List data, String type) { + inflator = LayoutInflater.from(context); + this.data = data; + this.type = type; + } + + @NonNull + @Override + public ValueAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) { + View view = inflator.inflate(R.layout.item_filter, parent, false); + return new ValueAdapter.MyViewHolder(view); + } + + @RequiresApi(api = Build.VERSION_CODES.M) + @Override + public void onBindViewHolder(@NonNull final ValueAdapter.MyViewHolder holder, final int position) { + final ProductMaster current = data.get(position); + + final boolean[] selected = {false}; + final int[] filterId = {0}; + + switch (type) { + + case CommonString.Signature: + if (selectedSignature != null && selectedSignature == current) { + selected[0] = true; + } + + break; + + case CommonString.Brand: + if (selectedBrand != null && selectedBrand == current) { + selected[0] = true; + } + + break; + + case CommonString.SubBrand: + if (selectedSubBrand != null && selectedSubBrand == current) { + selected[0] = true; + } + + break; + + case CommonString.Reference: + if (selectedReference != null && selectedReference == current) { + selected[0] = true; + } + + break; + } + + holder.tv_item.setText(current.getBrandName()); + + holder.card.setOnClickListener(v -> { + + et_search.setText(""); + + switch (type) { + case CommonString.Signature: + selectedSignature = current; + filterId[0] = R.id.img_filter_signature; + //clear other sub filters-- + selectedBrand = null; + selectedSubBrand = null; + selectedReference = null; + + (sheetView.findViewById(R.id.img_filter_brand)).setVisibility(View.GONE); + (sheetView.findViewById(R.id.img_filter_sub_brand)).setVisibility(View.GONE); + (sheetView.findViewById(R.id.img_filter_reference)).setVisibility(View.GONE); + + setBottomFilter(listAdapter.get_listDataHeader(), current.getBrandName(), listAdapter.get_listDataChild(), CommonString.Signature); + db.open(); + brandList = db.getSubBrandOrReference(counterGroupId, "BrandName", current.getBrandName(), null, null, false, selectedSubAxe); + db.open(); + subBrandList = db.getSubBrandOrReference(counterGroupId, "SubBrandName", current.getBrandName(), null, null, false, selectedSubAxe); + db.open(); + referenceList = db.getSubBrandOrReference(counterGroupId, "ReferenceName", current.getBrandName(), null, null, false, selectedSubAxe); + + break; + case CommonString.Brand: + selectedBrand = current; + filterId[0] = R.id.img_filter_brand; + + //clear other sub filters-- + selectedSubBrand = null; + selectedReference = null; + + (sheetView.findViewById(R.id.img_filter_sub_brand)).setVisibility(View.GONE); + (sheetView.findViewById(R.id.img_filter_reference)).setVisibility(View.GONE); + //-- + + setBottomFilter(listAdapter.get_listDataHeader(), current.getBrandName(), listAdapter.get_listDataChild(), CommonString.Brand); + //setFilter(FILTER_FOR_BRAND); + db.open(); + subBrandList = db.getSubBrandOrReference(counterGroupId, "SubBrandName", "", current.getBrandName(), null, false, selectedSubAxe); + db.open(); + referenceList = db.getSubBrandOrReference(counterGroupId, "ReferenceName", "", current.getBrandName(), null, false, selectedSubAxe); + + break; + case CommonString.SubBrand: + selectedSubBrand = current; + filterId[0] = R.id.img_filter_sub_brand; + + //clear other sub filters-- + selectedReference = null; + + (sheetView.findViewById(R.id.img_filter_reference)).setVisibility(View.GONE); + //-- + setBottomFilter(listAdapter.get_listDataHeader(), current.getBrandName(), listAdapter.get_listDataChild(), CommonString.SubBrand); + //setFilter(FILTER_FOR_SUB_BRAND); + db.open(); + referenceList = db.getSubBrandOrReference(counterGroupId, "ReferenceName", "", null, current.getBrandName(), false, selectedSubAxe); + break; + case CommonString.Reference: + selectedReference = current; + filterId[0] = R.id.img_filter_reference; + setBottomFilter(listAdapter.get_listDataHeader(), current.getBrandName(), listAdapter.get_listDataChild(), CommonString.Reference); + //setFilter(FILTER_FOR_REFERENCE); + break; + } + + RecyclerView recSubBrand = sheetView.findViewById(R.id.rec_brand); + recSubBrand.getAdapter().notifyDataSetChanged(); + //show filter icon on filter selected + (sheetView.findViewById(filterId[0])).setVisibility(View.VISIBLE); + }); + + if (selected[0]) { + holder.card.setCardBackgroundColor(getColor(R.color.dashboard_ach)); + } else { + holder.card.setCardBackgroundColor(getColor(R.color.grey_dark_background)); + } + } + + @Override + public int getItemCount() { + return data.size(); + } + + class MyViewHolder extends RecyclerView.ViewHolder { + TextView tv_item; + CardView card; + + public MyViewHolder(View itemView) { + super(itemView); + tv_item = (TextView) itemView.findViewById(R.id.tv_item); + card = (CardView) itemView.findViewById(R.id.item_card); + + } + } + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + getMenuInflater().inflate(R.menu.filter_menu_sales_me_stock, menu); + return super.onCreateOptionsMenu(menu); + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // Handle action bar item clicks here. The action bar will + // automatically handle clicks on the Home/Up button, so long + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + + if (id == android.R.id.home) { + isChanged(); + } else if (id == R.id.filter_data) { + sheetView = showFilterBottomSheet(); + } + + return super.onOptionsItemSelected(item); + } + + private void openScanner() { + IntentIntegrator intentIntegrator = new IntentIntegrator((Activity) context); + intentIntegrator.setBeepEnabled(true); + intentIntegrator.setOrientationLocked(false); + intentIntegrator.setPrompt("Scan the barcode or QR code to get the data"); + intentIntegrator.setCaptureActivity(CaptureActivity.class); + intentIntegrator.initiateScan(); + } + + + public void setScanFilter(List scanList) { + + HashMap> filterChildHashMap = new HashMap<>(); + + ArrayList filterList = new ArrayList<>(); + for (int i = 0; i < listDataHeader.size(); i++) { + ProductMaster parent = listDataHeader.get(i); + List listChild = listDataChild.get(parent); + List listFilterChild = new ArrayList<>(); + for (int j = 0; j < listChild.size(); j++) { + if (containsProduct(scanList, listChild.get(j))) { + listFilterChild.add(listChild.get(j)); + } else { + continue; + } + } + + if (listFilterChild.size() > 0) { + filterList.add(parent); + filterChildHashMap.put(parent, listFilterChild); + + } + + } + + ExpandableListAdapter listAdapter1 = new ExpandableListAdapter(context, filterList, filterChildHashMap); + lvExp_stock_check.setAdapter(listAdapter1); + for (int i = 0; i < listAdapter1.getGroupCount(); i++) { + lvExp_stock_check.expandGroup(i); + } + listAdapter1.notifyDataSetChanged(); + + } + + boolean containsProduct(List scanList, ProductMaster obj) { + boolean contains = false; + for (int i = 0; i < scanList.size(); i++) { + if (scanList.get(i).getProductId().equals(obj.getProductId())) { + contains = true; + break; + } + } + + return contains; + } + + void clearFilters() { + et_search.setText(""); + + setFilter(CLEAR_FILTER); + selectedSignature = null; + selectedBrand = null; + selectedSubBrand = null; + selectedReference = null; + + if (sheetView != null) { + (sheetView.findViewById(R.id.img_filter_signature)).setVisibility(View.GONE); + (sheetView.findViewById(R.id.img_filter_brand)).setVisibility(View.GONE); + (sheetView.findViewById(R.id.img_filter_sub_brand)).setVisibility(View.GONE); + (sheetView.findViewById(R.id.img_filter_reference)).setVisibility(View.GONE); + } + db.open(); + brandList = db.getsub_brand_name(counterGroupId, "BrandName", false, selectedSubAxe); + db.open(); + subBrandList = db.getsub_brand_name(counterGroupId, "SubBrandName", false, selectedSubAxe); + db.open(); + referenceList = db.getsub_brand_name(counterGroupId, "ReferenceName", false, selectedSubAxe); + db.open(); + signatureList = db.getsub_brand_name(counterGroupId, "SignatureName", false, selectedSubAxe); + } + + private Dialog dialog; + ProgressBar pb; + + class LoadAsync extends AsyncTask { + @Override + protected void onPreExecute() { + + dialog = new Dialog(context); + dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); + Objects.requireNonNull(dialog.getWindow()).setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT)); + dialog.setContentView(R.layout.circular_progress_bar); + pb = (ProgressBar) dialog.findViewById(R.id.progressBar1); + dialog.setCancelable(false); + dialog.show(); + super.onPreExecute(); + } + + @Override + protected Void doInBackground(Void... voids) { + prepareListData(); + //validate_spin_ui_data(); + + return null; + } + + @SuppressLint("NotifyDataSetChanged") + @Override + protected void onPostExecute(Void aVoid) { + dialog.cancel(); + recSubAxe.setLayoutManager(new GridLayoutManager(SalesActivity.this, 3)); + subAxeValueAdapter = new SubAxeValueAdapter(context, listSubAxe, CommonString.Signature); + recSubAxe.setAdapter(subAxeValueAdapter); + recSubAxe.getAdapter().notifyDataSetChanged(); + + //validate_spin_ui_data(); + listAdapter = new ExpandableListAdapter(context, listDataHeader, listDataChild); + lvExp_stock_check.setAdapter(listAdapter); + db.open(); + JourneyPlan jcp = db.getJCP(); + if (jcp != null) { + counterGroupId = jcp.getCounterGroupId().toString(); + } else { + counterGroupId = "1"; + } + + super.onPostExecute(aVoid); + } + } + + + private void UploadStockRecursive(final String status, final int startIndex, final int endIndex, final SaleableGetterSetter stock) { + try { + JSONArray topUpArray = new JSONArray(); + String key = "SaleableData"; + int mid = 0; + if (stock != null) { + if (jcp != null) { + mid = jcp.getMID(); + } + for (int j = startIndex; j < endIndex; j++) { + JSONObject obj = new JSONObject(); + obj.put("ProductId", stock.getProductList().get(j).getProductId()); + obj.put("MID", mid); + obj.put("REASON_ID", stock.getProductList().get(j).getReasonId()); + obj.put("TranId", stock.getTransactionId()); + obj.put("UserId", username); + obj.put("CounterId", counter_id); + //header image + String img = stock.getProductList().get(j).getImagePath(); + if (img == null) { + img = ""; + } + obj.put("Image", img); + ////for uploaded first time data if status is not null + if (status != null) { + int stk = stock.getProductList().get(j).getStock(); + if (stk == -1) { + stk = 0; + } + obj.put("STOCK", stk); + obj.put("Status", status); + //different key for first time data + key = "SaleableFData"; + } else { + obj.put("STOCK", stock.getProductList().get(j).getStock_receive() - stock.getProductList().get(j).getStock()); + } + topUpArray.put(obj); + } + } + JSONObject jsonObject = new JSONObject(); + jsonObject.put("MID", mid); + jsonObject.put("Keys", key); + jsonObject.put("JsonData", topUpArray.toString()); + jsonObject.put("UserId", username); + String jsonString = jsonObject.toString(); + OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(20, TimeUnit.SECONDS).writeTimeout(20, TimeUnit.SECONDS).connectTimeout(20, TimeUnit.SECONDS).build(); + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsonString); + Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build(); + PostApi api = adapter.create(PostApi.class); + Call call = api.getGeotag(jsonData); + call.enqueue(new Callback() { + @Override + public void onResponse(@NonNull Call call, @NonNull Response response) { + String responseBody = response.body().get("UploadJsonResult").toString(); + String data = null; + if (response.isSuccessful()) { + try { + data = response.body().get("UploadJsonResult").toString(); + if (data.equals("")) { + } else { + data = data.substring(1, data.length() - 1).replace("\\", ""); + if (data.equalsIgnoreCase(CommonString.KEY_SUCCESS)) { + assert stock != null; + if (endIndex < stock.getProductList().size()) { + int startIndex1 = endIndex; + int endIndex1 = 0; + if (startIndex1 + 200 < stock.getProductList().size()) { + endIndex1 = startIndex1 + 200; + } else { + endIndex1 = stock.getProductList().size(); + } + UploadStockRecursive(status, startIndex1, endIndex1, stock); + } else { + db.open(); + db.updateStockTransactionDataStatus(stock.getTransactionId()); + db.updateMasterTransactionDataStatus(stock.getTransactionId()); + dialog.cancel(); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + SalesActivity.this.finish(); + } + } + } + } catch (Exception e) { + db.open(); + dialog.cancel(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE + " - " + e.toString() + " - Please Try Again"); + } + } else { + dialog.cancel(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_NO_RESPONSE_SERVER + " - Please Try Again"); + } + } + + @Override + public void onFailure(@NonNull Call call, @NonNull Throwable t) { + dialog.cancel(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE + " - Please Try Again"); + } + }); + } catch (JSONException e) { + e.fillInStackTrace(); + dialog.cancel(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INVALID_JSON + " - Please Try Again"); + } + } + + @Override + public void onDestroy() { + if (dialog != null && dialog.isShowing()) { + dialog.dismiss(); + } + super.onDestroy(); + } + + public class SubAxeValueAdapter extends RecyclerView.Adapter { + LayoutInflater inflator; + List data; + String type; + + public String getType() { + return type; + } + + public SubAxeValueAdapter(Context context, List data, String type) { + inflator = LayoutInflater.from(context); + this.data = data; + this.type = type; + } + + @NonNull + @Override + public SubAxeValueAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) { + View view = inflator.inflate(R.layout.item_filter, parent, false); + return new SubAxeValueAdapter.MyViewHolder(view); + } + + + @SuppressLint("NotifyDataSetChanged") + @Override + public void onBindViewHolder(final SubAxeValueAdapter.MyViewHolder holder, final int position) { + final ProductMaster current = data.get(position); + + + holder.tv_item.setText(current.getSubAxeName()); + + holder.tv_item.setOnClickListener(v -> { + et_search.setText(""); + listAdapter = new ExpandableListAdapter(context, filterListForSubAxe(listDataHeader, current.getSubAxeName()), listDataChild); + lvExp_stock_check.setAdapter(listAdapter); + listAdapter.notifyDataSetChanged(); + current.setSelected(true); + selectedSubAxe = current.getSubAxeName(); + subAxeValueAdapter.notifyDataSetChanged(); + db.open(); + jcp = db.getJCP(); + if (jcp != null) { + db.open(); + brandList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "BrandName", false, selectedSubAxe); + db.open(); + subBrandList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "SubBrandName", false, selectedSubAxe); + db.open(); + referenceList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "ReferenceName", false, selectedSubAxe); + db.open(); + signatureList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "SignatureName", false, selectedSubAxe); + } else { + db.open(); + brandList = db.getsub_brand_name("1", "BrandName", false, selectedSubAxe); + subBrandList = db.getsub_brand_name("1", "SubBrandName", false, selectedSubAxe); + referenceList = db.getsub_brand_name("1", "ReferenceName", false, selectedSubAxe); + signatureList = db.getsub_brand_name("1", "SignatureName", false, selectedSubAxe); + } + }); + + //if (current.isSelected()) { + if (current.getSubAxeName().equalsIgnoreCase(selectedSubAxe)) { + holder.card.setCardBackgroundColor(getResources().getColor(R.color.dashboard_ach)); + } else { + holder.card.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background)); + } + } + + @Override + public int getItemCount() { + return data.size(); + } + + class MyViewHolder extends RecyclerView.ViewHolder { + TextView tv_item; + CardView card; + + public MyViewHolder(View itemView) { + super(itemView); + tv_item = (TextView) itemView.findViewById(R.id.tv_item); + card = (CardView) itemView.findViewById(R.id.item_card); + + } + } + } + + public ArrayList filterListForSubAxe(List originalList, String text) { + ArrayList filterList = new ArrayList<>(); + for (ProductMaster object : originalList) { + if (object.getSubAxeName().equalsIgnoreCase(text)) { + filterList.add(object); + } else { + continue; + } + } + + return filterList; + } + + public void setBottomFilter(List originalList, String text, HashMap> listDataChild, String type) { + + HashMap> filterChildHashMap = new HashMap<>(); + + ArrayList filterList = new ArrayList<>(); + for (int i = 0; i < originalList.size(); i++) { + ProductMaster parent = originalList.get(i); + List listChild = listDataChild.get(parent); + List listFilterChild = new ArrayList<>(); + for (int j = 0; j < listChild.size(); j++) { + + switch (type) { + case CommonString.Signature: + if (listChild.get(j).getSignatureName().equalsIgnoreCase(text)) { + listFilterChild.add(listChild.get(j)); + } + break; + case CommonString.Brand: + if (listChild.get(j).getBrandName().equalsIgnoreCase(text)) { + listFilterChild.add(listChild.get(j)); + } + + break; + case CommonString.SubBrand: + if (listChild.get(j).getSubBrandName().equalsIgnoreCase(text)) { + listFilterChild.add(listChild.get(j)); + } + break; + case CommonString.Reference: + if (listChild.get(j).getReferenceName().equalsIgnoreCase(text)) { + listFilterChild.add(listChild.get(j)); + } + break; + } + + } + + if (listFilterChild.size() > 0) { + filterList.add(parent); + filterChildHashMap.put(parent, listFilterChild); + + } + + } + + ExpandableListAdapter listAdapter1 = new ExpandableListAdapter(context, filterList, filterChildHashMap); + lvExp_stock_check.setAdapter(listAdapter1); + listAdapter1.notifyDataSetChanged(); + } + + class InsertAsync extends AsyncTask { + boolean flag = false; + + @Override + protected void onPreExecute() { + dialog = new Dialog(context); + dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); + dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT)); + dialog.setContentView(R.layout.circular_progress_bar); + pb = (ProgressBar) dialog.findViewById(R.id.progressBar1); + dialog.setCancelable(false); + dialog.show(); + super.onPreExecute(); + } + + @Override + protected Void doInBackground(Boolean... bool) { + flag = bool[0]; + // db.open(); + // db.insertMESaleCapturedData(visit_date, listDataChild, listDataHeader, flag, counter_id); + // db.insertStockCapturedData(visit_date, listDataChild, listDataHeader, flag, counter_id); + // uploadData(flag); + //validate_spin_ui_data(); + db.open(); + db.insertMESaleCapturedData(visit_date, listDataChild, listDataHeader, "N", counter_id, CommonFunctions.getUUID(context), username); + + return null; + } + + @Override + protected void onPostExecute(Void aVoid) { + super.onPostExecute(aVoid); + dialog.cancel(); + + if (flag) { + Intent intent = new Intent(context, Downloader.class); + intent.putExtra(CommonString.ME_SALE, listDataHeader); + Downloader.enqueueWork(context, intent); + + AlertandMessages.showToastMsg(context, "Data Uploaded Successfully"); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + SalesActivity.this.finish(); + } else { + AlertandMessages.showToastMsg(context, "Data Saved Successfully"); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + SalesActivity.this.finish(); + } + + /*dialog.dismiss(); + finish(); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);*/ + } + } + + public void setUnFilledFilter(List originalList, HashMap> listDataChild) { + HashMap> filterChildHashMap = new HashMap<>(); + ArrayList filterList = new ArrayList<>(); + for (int i = 0; i < originalList.size(); i++) { + ProductMaster parent = originalList.get(i); + List listChild = listDataChild.get(parent); + List listFilterChild = new ArrayList<>(); + for (int j = 0; j < listChild.size(); j++) { + if (listChild.get(j).getStock() == -1) { + listFilterChild.add(listChild.get(j)); + } else { + continue; + } + } + + if (listFilterChild.size() > 0) { + filterList.add(parent); + filterChildHashMap.put(parent, listFilterChild); + + } + } + + ExpandableListAdapter listAdapter1 = new ExpandableListAdapter(context, filterList, filterChildHashMap); + lvExp_stock_check.setAdapter(listAdapter1); + for (int i = 0; i < listAdapter1.getGroupCount(); i++) { + lvExp_stock_check.expandGroup(i); + } + + listAdapter1.notifyDataSetChanged(); + } + + private boolean validate_regular_stock() { + check_flag = true; + if (listDataHeader.size() > 0) { + for (int k = 0; k < listDataHeader.size(); k++) { + List child_list = listDataChild.get(listDataHeader.get(k)); + /*for (int i = 0; i < child_list.size(); i++) { + if (child_list.get(i).isSelected() && child_list.get(i).getStock_receive() != child_list.get(i).getStock()) { + if (child_list.get(i).getReasonId() == 0) { + check_flag = false; + AlertandMessages.showToastMsg(context, "Please Select Reason"); + break; + } + } + + }*/ + + if (!check_flag) { + break; + } + } + } + + return check_flag; + + } + + +} \ No newline at end of file diff --git a/app/src/main/java/com/cpm/lorealbaautomation/notification/NotificationUtils.java b/app/src/main/java/com/cpm/lorealbaautomation/notification/NotificationUtils.java new file mode 100644 index 0000000..cdf1e0f --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/notification/NotificationUtils.java @@ -0,0 +1,69 @@ +package com.cpm.lorealbaautomation.notification; + +import android.app.Notification; +import android.app.NotificationChannel; +import android.app.NotificationManager; +import android.app.PendingIntent; +import android.content.Context; +import android.content.ContextWrapper; +import android.graphics.Color; +import android.media.RingtoneManager; +import android.net.Uri; +import android.os.Build; + +import static android.app.Notification.DEFAULT_SOUND; +import static android.app.Notification.DEFAULT_VIBRATE; + +public class NotificationUtils extends ContextWrapper { + private NotificationManager mManager; + public static final String ANDROID_CHANNEL_ID = "1"; + public static final String ANDROID_CHANNEL_NAME = "ANDROID CHANNEL"; + PendingIntent pendingIntent; + public NotificationUtils(Context base, PendingIntent pendingIntent) { + super(base); + createChannels(); + this.pendingIntent = pendingIntent; + } + + public void createChannels() { + if (Build.VERSION.SDK_INT >= 26) { + NotificationChannel androidChannel = new NotificationChannel(ANDROID_CHANNEL_ID, + ANDROID_CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT); + // Sets whether notifications posted to this channel should display notification lights + androidChannel.enableLights(true); + // Sets whether notification posted to this channel should vibrate. + androidChannel.enableVibration(true); + // Sets the notification light color for notifications posted to this channel + androidChannel.setLightColor(Color.GREEN); + // Sets whether notifications posted to this channel appear on the lockscreen or not + androidChannel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE); + + getManager().createNotificationChannel(androidChannel); + } + // create android channel + } + public NotificationManager getManager () { + if (mManager == null) { + mManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); + } + return mManager; + } + public Notification.Builder getAndroidChannelNotification(String title, String body) { + Uri sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); + if (Build.VERSION.SDK_INT >= 26) { + return new Notification.Builder(getApplicationContext(), ANDROID_CHANNEL_ID) + .setContentTitle(title) + .setContentText(body) + .setSmallIcon(android.R.drawable.ic_dialog_info) + .setAutoCancel(true) + .setSound(sound) + .setDefaults(DEFAULT_SOUND | DEFAULT_VIBRATE) + .setContentIntent(pendingIntent) + .setVibrate(new long[]{0, 500}) + .setPriority(Notification.PRIORITY_HIGH); + } + else { + return null; + } + } +} \ No newline at end of file diff --git a/app/src/main/java/com/cpm/lorealbaautomation/notification/NotificationView.java b/app/src/main/java/com/cpm/lorealbaautomation/notification/NotificationView.java new file mode 100644 index 0000000..3201add --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/notification/NotificationView.java @@ -0,0 +1,15 @@ +package com.cpm.lorealbaautomation.notification; + +import android.os.Bundle; +import androidx.annotation.Nullable; +import androidx.appcompat.app.AppCompatActivity; + +import com.cpm.lorealbaautomation.R; + +public class NotificationView extends AppCompatActivity { + @Override + protected void onCreate(@Nullable Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.inapp_notification); + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/password/ChangePasswordActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/password/ChangePasswordActivity.java new file mode 100644 index 0000000..704bfd1 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/password/ChangePasswordActivity.java @@ -0,0 +1,415 @@ +package com.cpm.lorealbaautomation.password; + +import android.app.Activity; +import android.app.AlertDialog; +import android.app.Dialog; +import android.app.ProgressDialog; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.SharedPreferences; +import android.graphics.drawable.ColorDrawable; +import android.os.Bundle; + +import androidx.appcompat.app.AppCompatActivity; +import androidx.appcompat.widget.Toolbar; + +import android.text.Editable; +import android.text.TextWatcher; +import android.view.MenuItem; +import android.view.View; +import android.view.Window; +import android.view.WindowManager; +import android.widget.Button; +import android.widget.EditText; +import android.widget.ImageView; +import android.widget.Toast; + +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.DealarBoardActivity; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.constant.AlertandMessages; +import com.cpm.lorealbaautomation.constant.CommonFunctions; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.dailyactivity.StoreImageActivity; +import com.cpm.lorealbaautomation.dailyactivity.TabLoginActivity; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.gettersetter.LoginGetterSetter; +import com.cpm.lorealbaautomation.pinviewactivity.PinViewActivity; +import com.cpm.lorealbaautomation.retrofit.PostApi; + +import org.json.JSONException; +import org.json.JSONObject; + +import java.util.ArrayList; +import java.util.concurrent.TimeUnit; +import java.util.regex.Pattern; + +import okhttp3.MediaType; +import okhttp3.OkHttpClient; +import okhttp3.RequestBody; +import okhttp3.ResponseBody; +import retrofit2.Retrofit; +import retrofit2.converter.gson.GsonConverterFactory; + +public class ChangePasswordActivity extends AppCompatActivity implements View.OnClickListener { + String user_id, PASSWORD_CHANGE = "", activity_name = "", new_pw, old_password, visit_date, counterId; + EditText et_old_password, et_new_password, et_confirm_password; + ArrayList allLoginData = new ArrayList<>(); + Button btn_submit; + ImageView img_info; + private SharedPreferences preferences = null; + private SharedPreferences.Editor editor = null; + boolean clicked_flag = false; + ProgressDialog loading; + Lorealba_Database db; + Context context; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_change_password); + context = this; + db = new Lorealba_Database(context); + db.open(); + + getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); + Toolbar toolbar = findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + getSupportActionBar().setHomeButtonEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + if (!CommonFunctions.isTablet(context)) { + toolbar.setTitleTextAppearance(context, R.style.changestext_sizefor_mobile); + } + + et_old_password = (EditText) findViewById(R.id.et_old_password); + et_new_password = (EditText) findViewById(R.id.et_new_password); + et_confirm_password = (EditText) findViewById(R.id.et_confirm_password); + btn_submit = (Button) findViewById(R.id.btn_submit); + img_info = (ImageView) findViewById(R.id.img_info); + preferences = PrefHelper.getPrefs(context); + editor = preferences.edit(); + user_id = preferences.getString(CommonString.KEY_USERNAME, ""); + old_password = preferences.getString(CommonString.KEY_PASSWORD, ""); + + preferences = PrefHelper.getPrefs(context); + editor = preferences.edit(); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + counterId = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + + if (getIntent().getStringExtra(CommonString.KEY_PASSWORD_CHANGE) != null) { + PASSWORD_CHANGE = getIntent().getStringExtra(CommonString.KEY_PASSWORD_CHANGE); + } + + if (getIntent().getStringExtra(CommonString.KEY_ACTIVITY) != null) { + activity_name = getIntent().getStringExtra(CommonString.KEY_ACTIVITY); + } + + db.open(); + allLoginData = db.getlistAllData(visit_date, user_id); + if (allLoginData.size() > 0) { + old_password = allLoginData.get(0).getPassword(); + } + + setTitle("Change Password - " + user_id); + //new password + et_new_password.addTextChangedListener(new TextWatcher() { + @Override + public void beforeTextChanged(CharSequence s, int start, int count, int after) { + + } + + @Override + public void onTextChanged(CharSequence s, int start, int before, int count) { + + } + + @Override + public void afterTextChanged(Editable s) { + String result = s.toString().replaceAll(" ", ""); + clicked_flag = true; + if (!s.toString().equals(result)) { + et_new_password.setText(result); + et_new_password.setSelection(result.length()); + et_new_password.setError(getString(R.string.space_not_allowed_in_password)); + et_new_password.requestFocus(); + // alert the user + } + } + }); + + //confirm password + et_confirm_password.addTextChangedListener(new TextWatcher() { + @Override + public void beforeTextChanged(CharSequence s, int start, int count, int after) { + + } + + @Override + public void onTextChanged(CharSequence s, int start, int before, int count) { + + } + + @Override + public void afterTextChanged(Editable s) { + String result = s.toString().replaceAll(" ", ""); + clicked_flag = true; + if (!s.toString().equals(result)) { + et_confirm_password.setText(result); + et_confirm_password.setSelection(result.length()); + et_confirm_password.setError(getString(R.string.space_not_allowed_in_password)); + et_confirm_password.requestFocus(); + // alert the user + } + } + }); + + + img_info.setOnClickListener(this); + btn_submit.setOnClickListener(this); + + } + + @Override + public void onClick(View v) { + + if (v.getId() == R.id.img_info) { + Dialog dialog = new Dialog(ChangePasswordActivity.this); + dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); + dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT)); + dialog.setContentView(R.layout.password_rule_dialog); + dialog.show(); + + } else if (v.getId() == R.id.btn_submit) { + submit(); + } + } + + void submit() { + boolean cancel = false; + View focusView = null; + //Old Password + String old_pw = et_old_password.getText().toString().trim(); + new_pw = et_new_password.getText().toString(); + Pattern textPattern = Pattern.compile("^(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%])(?=.*\\d).+$"); + if (old_pw.equals("")) { + et_old_password.setError(getString(R.string.error_field_required)); + focusView = et_old_password; + cancel = true; + } else if (!old_password.equals("") && !old_pw.equals(old_password)) { + et_old_password.setError(getString(R.string.error_incorrect_password)); + focusView = et_old_password; + cancel = true; + } else if (new_pw.equals("")) { + //New Password + et_new_password.setError(getString(R.string.error_field_required)); + focusView = et_new_password; + cancel = true; + } else if (new_pw.length() >= 8 && new_pw.length() <= 10 && textPattern.matcher(new_pw).matches()) { + //New Password + String confirm_pw = et_confirm_password.getText().toString(); + if (confirm_pw.equals("")) { + et_confirm_password.setError(getString(R.string.error_field_required)); + focusView = et_confirm_password; + cancel = true; + } else if (!confirm_pw.equals(new_pw)) { + et_confirm_password.setError(getString(R.string.password_and_confirm_password_not_match)); + focusView = et_confirm_password; + cancel = true; + } else { + JSONObject jsonObject = new JSONObject(); + try { + jsonObject.put("UserId", user_id); + jsonObject.put("OldPassword", old_password); + jsonObject.put("NewPassword", new_pw); + AuthenticateTask(jsonObject.toString()); + } catch (JSONException e) { + e.fillInStackTrace(); + } + } + } else { + et_new_password.setError(getString(R.string.invalid_password)); + focusView = et_new_password; + cancel = true; + } + if (cancel) { + // There was an error; don't attempt login and focus the first + // form field with an error. + focusView.requestFocus(); + + } + + } + + + public void AuthenticateTask(String jsondata) { + try { + loading = ProgressDialog.show(context, "Change Password", "Updating.......", false, true); + final OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, + TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build(); + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsondata); + Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build(); + PostApi api = adapter.create(PostApi.class); + retrofit2.Call call = api.getChangePassword(jsonData); + call.enqueue(new retrofit2.Callback() { + @Override + public void onResponse(retrofit2.Call call, retrofit2.Response response) { + ResponseBody responseBody = response.body(); + String data = null; + if (responseBody != null && response.isSuccessful()) { + try { + data = response.body().string(); + data = data.substring(1, data.length() - 1).replace("\\", ""); + if (data.equalsIgnoreCase(CommonString.KEY_SUCCESS)) { + loading.dismiss(); + if (PASSWORD_CHANGE != null && !PASSWORD_CHANGE.equals("") && PASSWORD_CHANGE.equalsIgnoreCase("Change")) { + if (activity_name != null && !activity_name.equals("") && activity_name.equalsIgnoreCase("Start")) { + Toast.makeText(context, getString(R.string.password_updated_successfully), Toast.LENGTH_LONG).show(); + editor.putString(CommonString.KEY_PASSWORD_CHANGE, ""); + editor.commit(); + + Intent in = new Intent(getApplicationContext(), PinViewActivity.class); + in.putExtra(CommonString.IS_PASSWORD_CHECK, false); + in.putExtra(CommonString.KEY_USERNAME, user_id); + startActivity(in); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + finish(); + } else if (activity_name != null && !activity_name.equals("") && activity_name.equalsIgnoreCase("PinView")) { + Toast.makeText(context, getString(R.string.password_updated_successfully), Toast.LENGTH_LONG).show(); + editor.putString(CommonString.KEY_PASSWORD_CHANGE, ""); + editor.commit(); + if (allLoginData.size() > 0) { + if (allLoginData.get(0).getImg().equals("")) { + startActivity(new Intent(context, StoreImageActivity.class)); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + finish(); + } else { + startActivity(new Intent(context, DealarBoardActivity.class)); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + finish(); + } + } + } + } else { + db.open(); + if (db.ischeck_login_data(user_id.toLowerCase())) { + db.open(); + db.deleteTableWithLogin(user_id.toLowerCase()); + } + + if (user_id.toLowerCase().equals(user_id.toLowerCase())) { + editor.putString(CommonString.KEY_PASSWORD, ""); + editor.putString(CommonString.MPIN, null); + editor.putString(CommonString.KEY_USERNAME, ""); + editor.commit(); + } + + startActivity(new Intent(context, TabLoginActivity.class)); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + loading.dismiss(); + showAlert(getString(R.string.password_updated_successfully), true); + } + } else { + loading.dismiss(); + showAlert(data + ". Please Try Again", false); + } + + } catch (Exception e) { + e.fillInStackTrace(); + loading.dismiss(); + } + + } else { + loading.dismiss(); + AlertandMessages.showToastMsg(context, "Server Not Responding . Please Try Again "); + } + } + + @Override + public void onFailure(retrofit2.Call call, Throwable t) { + loading.dismiss(); + AlertandMessages.showAlertlogin((Activity) context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE); + } + }); + + } catch (Exception e) { + e.fillInStackTrace(); + loading.dismiss(); + } + } + + + public void showAlert(String str, final boolean flag_finish) { + AlertDialog.Builder builder = new AlertDialog.Builder(ChangePasswordActivity.this); + builder.setTitle(R.string.dialog_title); + builder.setMessage(str).setCancelable(false) + .setPositiveButton("OK", new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { + if (flag_finish) { + finish(); + } + } + }); + AlertDialog alert = builder.create(); + alert.show(); + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + if (id == android.R.id.home) { + if (clicked_flag) { + AlertDialog.Builder builder = new AlertDialog.Builder(context).setMessage(CommonString.ONBACK_ALERT_MESSAGE).setCancelable(false).setPositiveButton("Ok", + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + ChangePasswordActivity.this.finish(); + } + }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { + dialog.cancel(); + } + }); + AlertDialog alert = builder.create(); + alert.show(); + } else { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + ChangePasswordActivity.this.finish(); + } + } + + return super.onOptionsItemSelected(item); + } + + @Override + public void onBackPressed() { + if (clicked_flag) { + AlertDialog.Builder builder = new AlertDialog.Builder(context).setMessage(CommonString.ONBACK_ALERT_MESSAGE).setCancelable(false).setPositiveButton("Ok", + new DialogInterface.OnClickListener() { + public void onClick( + DialogInterface dialog, int id) { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + ChangePasswordActivity.this.finish(); + } + }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { + dialog.cancel(); + } + }); + AlertDialog alert = builder.create(); + alert.show(); + } else { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + ChangePasswordActivity.this.finish(); + } + } + + @Override + protected void onDestroy() { + super.onDestroy(); + if (loading != null && loading.isShowing()) { + loading.dismiss(); + } + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/password/MPinActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/password/MPinActivity.java new file mode 100644 index 0000000..fd4be57 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/password/MPinActivity.java @@ -0,0 +1,441 @@ +package com.cpm.lorealbaautomation.password; + +import android.app.Dialog; +import android.content.Intent; +import android.content.SharedPreferences; +import android.graphics.Color; +import android.graphics.Typeface; +import android.os.Bundle; + +import com.google.android.material.floatingactionbutton.FloatingActionButton; +import com.google.android.material.snackbar.Snackbar; +import androidx.appcompat.app.AppCompatActivity; +import android.view.View; +import android.view.Window; +import android.view.WindowManager; +import android.widget.ImageView; +import android.widget.Toast; + +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.DealarBoardActivity; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.UserLoginActivity; +import com.cpm.lorealbaautomation.blurlockview.BlurLockView; +import com.cpm.lorealbaautomation.blurlockview.Directions.HideType; +import com.cpm.lorealbaautomation.blurlockview.Directions.ShowType; +import com.cpm.lorealbaautomation.blurlockview.Eases.EaseType; +import com.cpm.lorealbaautomation.blurlockview.Password; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.dailyactivity.StoreImageActivity; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.gettersetter.LoginGetterSetter; + +import java.util.ArrayList; + + +public class MPinActivity extends AppCompatActivity implements + BlurLockView.OnPasswordInputListener, + BlurLockView.OnLeftButtonClickListener { + BlurLockView blurLockView; + ImageView imageView1; + String pin = ""; + boolean IS_PASSWORD_CHECK; + private SharedPreferences preferences = null; + private SharedPreferences.Editor editor = null; + private Dialog dialog; + String user_id; + Lorealba_Database db; + String visit_date; + ArrayList allLoginData = new ArrayList<>(); + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + requestWindowFeature(Window.FEATURE_NO_TITLE); + getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); + setContentView(R.layout.activity_mpin); + db = new Lorealba_Database(this); + db.open(); + preferences = PrefHelper.getPrefs(this); + editor = preferences.edit(); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + IS_PASSWORD_CHECK = getIntent().getBooleanExtra(CommonString.IS_PASSWORD_CHECK, false); + if (getIntent().getSerializableExtra(CommonString.KEY_USERNAME) != null) { + user_id = getIntent().getStringExtra(CommonString.KEY_USERNAME); + + } + + imageView1 = (ImageView) findViewById(R.id.image_1); + + blurLockView = (BlurLockView) findViewById(R.id.blurlockview); + + preferences = PrefHelper.getPrefs(this); + editor = preferences.edit(); + + // Set the view that need to be blurred + blurLockView.setBlurredView(imageView1); + allLoginData = db.getlistAllData(visit_date, user_id); + + // Set the password + if (IS_PASSWORD_CHECK) { + + // String mpin = preferences.getString(CommonString.MPIN, null); + String mpin = preferences.getString(user_id, null); + blurLockView.setCorrectPassword(mpin); + blurLockView.setLeftButton("Forgot MPin"); + blurLockView.setTitle("Please Enter Four Digit MPin"); + } else { + blurLockView.setCorrectPassword("abcd"); + blurLockView.setLeftButton("Set MPin"); + blurLockView.setTitle("Please Set Four Digit MPin"); + } + + blurLockView.setIs_Password_Check_Mode(IS_PASSWORD_CHECK); + + + + + blurLockView.setRightButton("Clear"); + blurLockView.setTypeface(getTypeface()); + blurLockView.setOnLeftButtonClickListener(this); + blurLockView.setOnPasswordInputListener(this); + + //blurLockView.setType(getPasswordType(), false); + //blurLockView.setPasswordLength(4); + + /* blurLockView.show( + getIntent().getIntExtra("SHOW_DURATION", 1000), + getShowType(getIntent().getIntExtra("SHOW_DIRECTION", 0)), + getEaseType(getIntent().getIntExtra("SHOW_EASE_TYPE", 30)));*/ + blurLockView.setType(Password.NUMBER, true); + + FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); + fab.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) + .setAction("Action", null).show(); + } + }); + } + + private Password getPasswordType() { + if ("PASSWORD_NUMBER".equals(getIntent().getStringExtra("PASSWORD_TYPE"))) + return Password.NUMBER; + else if ("PASSWORD_NUMBER".equals(getIntent().getStringExtra("PASSWORD_TYPE"))) + return Password.TEXT; + return Password.NUMBER; + } + + private Typeface getTypeface() { + if ("SAN".equals(getIntent().getStringExtra("TYPEFACE"))) + return Typeface.createFromAsset(getAssets(), "fonts/San Francisco Regular.ttf"); + else if ("DEFAULT".equals(getIntent().getStringExtra("TYPEFACE"))) + return Typeface.DEFAULT; + return Typeface.DEFAULT; + } + + @Override + public void correct(String inputPassword) { + + if (IS_PASSWORD_CHECK) { + // Intent in = new Intent(getApplicationContext(), AutoLoginActivity.class); + editor.putString(CommonString.KEY_USERNAME, user_id.toLowerCase()); + editor.commit(); + + + /* db.open(); + db.updateLoginMpnData(user_id, pin); + Intent in = new Intent(getApplicationContext(), StoreImageActivity.class); + startActivity(in);*/ + + if (allLoginData.size()> 0 && !allLoginData.get(0).getImg().equals("")){ + Intent in = new Intent(getApplicationContext(), DealarBoardActivity.class); + startActivity(in); + finish(); + }else { + Intent in = new Intent(getApplicationContext(), StoreImageActivity.class); + startActivity(in); + finish(); + } + + } else { + Toast.makeText(this, "Correct", Toast.LENGTH_SHORT).show(); + } + } + + @Override + public void incorrect(String inputPassword) { + + if (IS_PASSWORD_CHECK) { + + int incorrect_times = blurLockView.getIncorrectInputTimes(); + if (++incorrect_times >= 3) { + /*Toast.makeText(this, + R.string.error_incorrect_password, + Toast.LENGTH_SHORT).show();*/ + + Snackbar snackbar = Snackbar.make(blurLockView, "Incorrect MPin limit reached", Snackbar.LENGTH_INDEFINITE); + View view = snackbar.getView(); + /*TextView tv = (TextView)view.findViewById(android.support.design.R.id.snackbar_text); + tv.setTextColor(Color.RED);*/ + snackbar.setAction("Reset", new View.OnClickListener() { + @Override + public void onClick(View v) { + + editor.putString(user_id, null); + editor.commit(); + finish(); + Intent in = new Intent(getApplicationContext(), UserLoginActivity.class); + startActivity(in); + + } + }); + snackbar.setActionTextColor(Color.GREEN); + snackbar.show(); + } else { + + int count = 3 - incorrect_times; + String attemt_str; + if (count == 1) { + attemt_str = ". Attempt left - " + count; + } else { + attemt_str = ". Attempts left - " + count; + } + + String msg = getString(R.string.error_incorrect_pin) + attemt_str; + Toast.makeText(this, msg, Toast.LENGTH_SHORT).show(); + } + + } else { + pin = inputPassword; + } + + } + + @Override + public void input(String inputPassword) { + pin = inputPassword; + } + + @Override + public void clear(String remainingPassword) { + pin = remainingPassword; + } + + + @Override + public void onClick() { + if (IS_PASSWORD_CHECK) { + Snackbar snackbar = Snackbar.make(blurLockView, "Need to reset MPin", Snackbar.LENGTH_INDEFINITE); + View view = snackbar.getView(); + /*TextView tv = (TextView)view.findViewById(android.support.design.R.id.snackbar_text); + tv.setTextColor(Color.RED);*/ + snackbar.setAction("Reset", new View.OnClickListener() { + @Override + public void onClick(View v) { + + editor.putString(user_id, null); + editor.commit(); + finish(); + Intent in = new Intent(getApplicationContext(), UserLoginActivity.class); + startActivity(in); + + } + }); + snackbar.setActionTextColor(Color.GREEN); + snackbar.show(); + } else { + if (pin.length() == 4) { + // editor.putString(CommonString.MPIN, pin); + editor.putString(user_id, pin); + editor.putString(CommonString.KEY_USERNAME, user_id.toLowerCase()); + editor.commit(); + // Intent in = new Intent(getApplicationContext(), OneQADActivity.class); + db.open(); + db.updateLoginMpnData(user_id, pin); + //Intent in = new Intent(getApplicationContext(), DealarBoardActivity.class); + Intent in = new Intent(getBaseContext(), StoreImageActivity.class); + startActivity(in); + finish(); + } else { + Toast.makeText(this, "Please fill four digit MPin", Toast.LENGTH_SHORT).show(); + } + } + + } + + + private int downsamepleFactor; + + private ShowType getShowType(int p) { + ShowType showType = ShowType.FROM_TOP_TO_BOTTOM; + switch (p) { + case 0: + showType = ShowType.FROM_TOP_TO_BOTTOM; + break; + case 1: + showType = ShowType.FROM_RIGHT_TO_LEFT; + break; + case 2: + showType = ShowType.FROM_BOTTOM_TO_TOP; + break; + case 3: + showType = ShowType.FROM_LEFT_TO_RIGHT; + break; + case 4: + showType = ShowType.FADE_IN; + break; + } + return showType; + } + + private HideType getHideType(int p) { + HideType hideType = HideType.FROM_TOP_TO_BOTTOM; + switch (p) { + case 0: + hideType = HideType.FROM_TOP_TO_BOTTOM; + break; + case 1: + hideType = HideType.FROM_RIGHT_TO_LEFT; + break; + case 2: + hideType = HideType.FROM_BOTTOM_TO_TOP; + break; + case 3: + hideType = HideType.FROM_LEFT_TO_RIGHT; + break; + case 4: + hideType = HideType.FADE_OUT; + break; + } + return hideType; + } + + private EaseType getEaseType(int p) { + EaseType easeType = EaseType.Linear; + switch (p) { + case 0: + easeType = EaseType.EaseInSine; + break; + case 1: + easeType = EaseType.EaseOutSine; + break; + case 2: + easeType = EaseType.EaseInOutSine; + break; + case 3: + easeType = EaseType.EaseInQuad; + break; + case 4: + easeType = EaseType.EaseOutQuad; + break; + case 5: + easeType = EaseType.EaseInOutQuad; + break; + case 6: + easeType = EaseType.EaseInCubic; + break; + case 7: + easeType = EaseType.EaseOutCubic; + break; + case 8: + easeType = EaseType.EaseInOutCubic; + break; + case 9: + easeType = EaseType.EaseInQuart; + break; + case 10: + easeType = EaseType.EaseOutQuart; + break; + case 11: + easeType = EaseType.EaseInOutQuart; + break; + case 12: + easeType = EaseType.EaseInQuint; + break; + case 13: + easeType = EaseType.EaseOutQuint; + break; + case 14: + easeType = EaseType.EaseInOutQuint; + break; + case 15: + easeType = EaseType.EaseInExpo; + break; + case 16: + easeType = EaseType.EaseOutExpo; + break; + case 17: + easeType = EaseType.EaseInOutExpo; + break; + case 18: + easeType = EaseType.EaseInCirc; + break; + case 19: + easeType = EaseType.EaseOutCirc; + break; + case 20: + easeType = EaseType.EaseInOutCirc; + break; + case 21: + easeType = EaseType.EaseInBack; + break; + case 22: + easeType = EaseType.EaseOutBack; + break; + case 23: + easeType = EaseType.EaseInOutBack; + break; + case 24: + easeType = EaseType.EaseInElastic; + break; + case 25: + easeType = EaseType.EaseOutElastic; + break; + case 26: + easeType = EaseType.EaseInOutElastic; + break; + case 27: + easeType = EaseType.EaseInBounce; + break; + case 28: + easeType = EaseType.EaseOutBounce; + break; + case 29: + easeType = EaseType.EaseInOutBounce; + break; + case 30: + easeType = EaseType.Linear; + break; + } + return easeType; + } + + /*public void showCommentforGrooming(){ + + dialog = new Dialog(MPinActivity.this); + dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); + dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT)); + dialog.setContentView(R.layout.comment_layout); + TextView tv = (TextView) dialog.findViewById(R.id.tv_comment); + + tv.setText(""); + + Window window = dialog.getWindow(); + WindowManager.LayoutParams wlp = window.getAttributes(); + + wlp.gravity = Gravity.TOP; + //wlp.flags &= ~WindowManager.LayoutParams.FLAG_DIM_BEHIND; + window.setAttributes(wlp); + + dialog.show(); + + }*/ + + /** + * Represents an asynchronous login/registration task used to authenticate + * the user. + */ + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/pinviewactivity/PinViewActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/pinviewactivity/PinViewActivity.java new file mode 100644 index 0000000..bbc7e14 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/pinviewactivity/PinViewActivity.java @@ -0,0 +1,780 @@ +package com.cpm.lorealbaautomation.pinviewactivity; + +import static com.cpm.lorealbaautomation.constant.CommonFunctions.hideKeyboard; + +import android.Manifest; +import android.annotation.SuppressLint; +import android.app.Activity; +import android.app.AlertDialog; +import android.app.ProgressDialog; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.IntentSender; +import android.content.SharedPreferences; +import android.content.pm.PackageManager; +import android.graphics.Color; +import android.location.Location; +import android.location.LocationManager; +import android.os.Build; +import android.os.Bundle; +import android.provider.Settings; +import android.view.View; +import android.view.WindowManager; +import android.view.inputmethod.InputMethodManager; +import android.widget.Button; +import android.widget.TextView; +import android.widget.Toast; + +import androidx.annotation.NonNull; +import androidx.appcompat.app.AppCompatActivity; +import androidx.appcompat.widget.Toolbar; +import androidx.cardview.widget.CardView; +import androidx.core.app.ActivityCompat; +import androidx.core.content.ContextCompat; + +import com.goodiebag.pinview.Pinview; +import com.google.android.gms.common.api.ResolvableApiException; +import com.google.android.gms.location.FusedLocationProviderClient; +import com.google.android.gms.location.LocationRequest; +import com.google.android.gms.location.LocationServices; +import com.google.android.gms.location.LocationSettingsRequest; +import com.google.android.gms.location.SettingsClient; +import com.google.gson.Gson; +import com.cpm.lorealbaautomation.AutoUpdateActivity; +import com.cpm.lorealbaautomation.BuildConfig; +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.DealarBoardActivity; +import com.cpm.lorealbaautomation.Get_IMEI_number.ImeiNumberClass; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.UserLoginActivity; +import com.cpm.lorealbaautomation.constant.AlertandMessages; +import com.cpm.lorealbaautomation.constant.CommonFunctions; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.dailyactivity.StoreImageActivity; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.gettersetter.LoginGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.BADeviceLoginGetterSetter; +import com.cpm.lorealbaautomation.password.ChangePasswordActivity; +import com.cpm.lorealbaautomation.retrofit.PostApi; +import com.cpm.lorealbaautomation.timer.TimerActivity; + +import org.json.JSONException; +import org.json.JSONObject; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +import okhttp3.MediaType; +import okhttp3.OkHttpClient; +import okhttp3.RequestBody; +import okhttp3.ResponseBody; +import retrofit2.Call; +import retrofit2.Callback; +import retrofit2.Response; +import retrofit2.Retrofit; +import retrofit2.converter.gson.GsonConverterFactory; + +public class +PinViewActivity extends AppCompatActivity implements View.OnClickListener { + private String counterId = ""; + private final String visitdate = ""; + private String Update_Visit_Date; + private String userType; + Pinview pinview_confirm, pinview_start; + TextView btn_clear, btn_forgot_pin; + Button btn_done; + + ArrayList allLoginData = new ArrayList<>(); + private String user_id, visit_date; + private SharedPreferences.Editor editor = null; + SharedPreferences preferences; + private Lorealba_Database db; + boolean IS_PASSWORD_CHECK; + Toolbar toolbar; + Context context; + + LoginGetterSetter loginGetterSetter; + private int versionCode; + ProgressDialog loading; + private String[] imeiNumbers; + private double lat = 0.0; + private double lon = 0.0; + private static int UPDATE_INTERVAL = 200; // 5 sec + private static int FATEST_INTERVAL = 100; + private static final int PERMISSIONS_REQUEST_READ_PHONE_STATE = 999;// 1 sec + private static int DISPLACEMENT = 1; // 10 meters + private static final int REQUEST_LOCATION = 1; + private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 1000; + private Location mLastLocation; + private LocationRequest mLocationRequest; + private ImeiNumberClass imei; + private static final int PERMISSION_ALL = 99; + private String app_ver; + private String manufacturer; + private String model; + private String os_version; + TextView txt_set_pin, txt_confirm_pin; + CardView card_set_pin_layout, card_confirm_pin_layout; + private FusedLocationProviderClient fusedLocationClient; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_pin_view); + context = this; + fusedLocationClient = LocationServices.getFusedLocationProviderClient(this); + db = new Lorealba_Database(context); + db.open(); + getId(); + check_keyboard(); + checkAndRequestPermissions(); + if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) + != PackageManager.PERMISSION_GRANTED) { + ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_PHONE_STATE}, + PERMISSIONS_REQUEST_READ_PHONE_STATE); + } else { + imeiNumbers = imei.getDeviceImei(); + } + getDeviceName(); + getLastLocation(); + } + + private boolean checkAndRequestPermissions() { + int CAMERA = ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA); + int ACCESS_NETWORK_STATE = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_NETWORK_STATE); + int ACCESS_COARSE_LOCATION = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION); + int locationPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION); + int READ_PHONE_STATE = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE); + List listPermissionsNeeded = new ArrayList<>(); + + if (CAMERA != PackageManager.PERMISSION_GRANTED) { + listPermissionsNeeded.add(Manifest.permission.CAMERA); + } + + if (ACCESS_NETWORK_STATE != PackageManager.PERMISSION_GRANTED) { + listPermissionsNeeded.add(Manifest.permission.ACCESS_NETWORK_STATE); + } + if (ACCESS_COARSE_LOCATION != PackageManager.PERMISSION_GRANTED) { + listPermissionsNeeded.add(Manifest.permission.ACCESS_COARSE_LOCATION); + } + if (locationPermission != PackageManager.PERMISSION_GRANTED) { + listPermissionsNeeded.add(Manifest.permission.ACCESS_FINE_LOCATION); + } + + if (READ_PHONE_STATE != PackageManager.PERMISSION_GRANTED) { + listPermissionsNeeded.add(Manifest.permission.READ_PHONE_STATE); + } + + + if (!listPermissionsNeeded.isEmpty()) { + ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), PERMISSION_ALL); + return false; + } + return true; + } + + private void showDialogOK(String message, DialogInterface.OnClickListener okListener) { + new AlertDialog.Builder(this).setMessage(message).setPositiveButton("OK", okListener).setNegativeButton("Cancel", okListener).create().show(); + } + + @Override + public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) { + super.onRequestPermissionsResult(requestCode, permissions, grantResults); + //test("", "Permission callback called-------"); + if (requestCode == PERMISSION_ALL) { + Map perms = new HashMap<>(); + // Initialize the map with both permissions + perms.put(Manifest.permission.CAMERA, PackageManager.PERMISSION_GRANTED); + perms.put(Manifest.permission.ACCESS_NETWORK_STATE, PackageManager.PERMISSION_GRANTED); + perms.put(Manifest.permission.ACCESS_COARSE_LOCATION, PackageManager.PERMISSION_GRANTED); + perms.put(Manifest.permission.ACCESS_FINE_LOCATION, PackageManager.PERMISSION_GRANTED); + perms.put(Manifest.permission.READ_PHONE_STATE, PackageManager.PERMISSION_GRANTED); + // Fill with actual results from user + if (grantResults.length > 0) { + for (int i = 0; i < permissions.length; i++) + perms.put(permissions[i], grantResults[i]); + // Check for both permissions + + boolean allPermissionsGranted = + Integer.valueOf(PackageManager.PERMISSION_GRANTED).equals(perms.get(Manifest.permission.CAMERA)) && + Integer.valueOf(PackageManager.PERMISSION_GRANTED).equals(perms.get(Manifest.permission.ACCESS_NETWORK_STATE)) && + Integer.valueOf(PackageManager.PERMISSION_GRANTED).equals(perms.get(Manifest.permission.ACCESS_COARSE_LOCATION)) && + Integer.valueOf(PackageManager.PERMISSION_GRANTED).equals(perms.get(Manifest.permission.ACCESS_FINE_LOCATION)) && + Integer.valueOf(PackageManager.PERMISSION_GRANTED).equals(perms.get(Manifest.permission.READ_PHONE_STATE)); + + if (allPermissionsGranted) { + //test("Permissions", "All required permissions granted"); + createLocationRequest(); + fusedLocationClient = LocationServices.getFusedLocationProviderClient((Activity) context); + getLastLocation(); + getDeviceName(); + imeiNumbers = imei.getDeviceImei(); + } else { + //test("", "Some permissions are not granted ask again "); + if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA) || + ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_NETWORK_STATE) || + ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_COARSE_LOCATION) || + ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION) || + ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_PHONE_STATE)) { + showDialogOK("Location,File,Call and Camera Services Permission required for this app", + (dialog, which) -> { + if (which == DialogInterface.BUTTON_POSITIVE) { + checkAndRequestPermissions(); + } else if (which == DialogInterface.BUTTON_NEGATIVE) {// proceed with logic by disabling the related features or quit the app. + Intent startMain = new Intent(Intent.ACTION_MAIN); + startMain.addCategory(Intent.CATEGORY_HOME); + startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + startActivity(startMain); + } + }); + } else { + Toast.makeText(this, "Go to settings and enable permissions", Toast.LENGTH_LONG).show(); + } + } + } + } + } + + private void getLastLocation() { + if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && + ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { + // Request location permissions + return; + } + try { + fusedLocationClient.getLastLocation() + .addOnSuccessListener(this, location -> { + if (location != null) { + lat = location.getLatitude(); + lon = location.getLongitude(); + //test("Location", "Lat: " + lat + ", Lng: " + lon); + } + }); + } catch (Exception e) { + e.fillInStackTrace(); //test("Location", "Lat: " + lat + ", Lng: " + lon);} + } + } + + @SuppressLint("SetTextI18n") + private void getId() { + toolbar = (Toolbar) findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + if (!CommonFunctions.isTablet(context)) { + toolbar.setTitleTextAppearance(context, R.style.changestext_sizefor_mobile); + } + pinview_confirm = (Pinview) findViewById(R.id.pinview_confirm); + pinview_start = (Pinview) findViewById(R.id.pinview_start); + btn_clear = (TextView) findViewById(R.id.btn_clear); + btn_forgot_pin = (TextView) findViewById(R.id.btn_forgot_pin); + btn_done = (Button) findViewById(R.id.btn_done); + + txt_set_pin = (TextView) findViewById(R.id.txt_set_pin); + txt_confirm_pin = (TextView) findViewById(R.id.txt_confirm_pin); + card_set_pin_layout = (CardView) findViewById(R.id.card_set_pin_layout); + card_confirm_pin_layout = (CardView) findViewById(R.id.card_confirm_pin_layout); + + btn_clear.setOnClickListener(this); + btn_done.setOnClickListener(this); + btn_forgot_pin.setOnClickListener(this); + preferences = PrefHelper.getPrefs(context); + editor = preferences.edit(); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + counterId = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + userType = preferences.getString(CommonString.KEY_USER_TYPE, ""); + IS_PASSWORD_CHECK = getIntent().getBooleanExtra(CommonString.IS_PASSWORD_CHECK, false); + if (getIntent().getSerializableExtra(CommonString.KEY_USERNAME) != null) { + user_id = getIntent().getStringExtra(CommonString.KEY_USERNAME); + } + if (getIntent().getSerializableExtra(CommonString.KEY_Update_Visit_Date) != null) { + Update_Visit_Date = getIntent().getStringExtra(CommonString.KEY_Update_Visit_Date); + } + setTitle("PinView - " + user_id); + imei = new ImeiNumberClass(context); + imeiNumbers = imei.getDeviceImei(); + getDeviceName(); + try { + app_ver = String.valueOf(getPackageManager().getPackageInfo(getPackageName(), 0).versionName); + + } catch (PackageManager.NameNotFoundException e) { + // TODO Auto-generated catch block + e.fillInStackTrace(); + } + + db.open(); + allLoginData = db.getlistAllData(visit_date, user_id); + + if (IS_PASSWORD_CHECK) { + btn_done.setText("Submit"); + txt_set_pin.setText("Enter PIN"); + pinview_confirm.requestFocus(); + card_confirm_pin_layout.setVisibility(View.VISIBLE); + card_set_pin_layout.setVisibility(View.GONE); + txt_confirm_pin.setVisibility(View.INVISIBLE); + btn_forgot_pin.setVisibility(View.VISIBLE); + } else { + pinview_start.requestFocus(); + btn_done.setText("Set PIN"); + txt_set_pin.setText("Set PIN"); + card_confirm_pin_layout.setEnabled(false); + card_confirm_pin_layout.setVisibility(View.VISIBLE); + card_set_pin_layout.setVisibility(View.VISIBLE); + btn_forgot_pin.setVisibility(View.GONE); + txt_confirm_pin.setVisibility(View.VISIBLE); + } + + pinview_start.setPinViewEventListener((pinview, fromUser) -> { + if (!IS_PASSWORD_CHECK) { + if (!pinview.getValue().isEmpty()) { + if (!pinview.getValue().isEmpty() && pinview.getValue().length() != 4) { + card_confirm_pin_layout.setEnabled(false); + } else { + pinview_confirm.requestFocus(); + card_confirm_pin_layout.setEnabled(true); + } + } else { + card_confirm_pin_layout.setEnabled(false); + } + } + + }); + + pinview_confirm.setPinViewEventListener((pinview, fromUser) -> { + //Make api calls here or what not + if (!IS_PASSWORD_CHECK) { + if (pinview_start.getValue().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Set First MPIN"); + pinview_confirm.clearValue(); + } + } + }); + + pinview_start.setTextColor(Color.BLACK); + pinview_start.showCursor(true); + pinview_confirm.setTextColor(Color.BLACK); + pinview_confirm.showCursor(true); + } + + public void getDeviceName() { + manufacturer = Build.MANUFACTURER; + model = Build.MODEL; + os_version = Build.VERSION.RELEASE; + } + + + @SuppressLint("NonConstantResourceId") + @Override + public void onClick(View v) { + if (v.getId() == R.id.btn_done) { + hideKeyboard(this); + if (!IS_PASSWORD_CHECK && pinview_start.getValue().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Set MPIN"); + } else if (!IS_PASSWORD_CHECK && pinview_start.getValue().length() != 4) { + AlertandMessages.showToastMsg(context, "Please Set 4 Digit MPin"); + } else if (pinview_confirm.getValue().isEmpty()) { + AlertandMessages.showToastMsg(context, "Please Set Confirm MPIN"); + } else if (pinview_confirm.getValue().length() != 4) { + AlertandMessages.showToastMsg(context, "Please Set 4 Digit Confirm MPIN"); + } else if (!IS_PASSWORD_CHECK && !pinview_start.getValue().equals(pinview_confirm.getValue())) { + AlertandMessages.showToastMsg(context, "MPIN Does Not Match"); + pinview_confirm.clearValue(); + } else if (!allLoginData.isEmpty() && allLoginData.get(0).getMpin() != null && !pinview_confirm.getValue().equalsIgnoreCase(allLoginData.get(0).getMpin())) { + AlertandMessages.showToastMsg(context, "Your MPIN Does Not Match From Inserted Database"); + } else { + if (IS_PASSWORD_CHECK && Update_Visit_Date != null && Update_Visit_Date.equals("1")) { + if (CommonFunctions.checkNetIsAvailable(context)) { + AttempLogin(); + } else { + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE); + } + } else if (IS_PASSWORD_CHECK && Update_Visit_Date == null) { + editor.putString(CommonString.KEY_USERNAME, user_id.toLowerCase()); + if (!allLoginData.isEmpty() && allLoginData.get(0).getUserType() != null) { + editor.putString(CommonString.KEY_USER_TYPE, allLoginData.get(0).getUserType()); + } + editor.commit(); + if (!allLoginData.isEmpty() && !allLoginData.get(0).getImg().isEmpty()) { + if (db.isCheck_Old_Product(visit_date)) { + Intent in = new Intent(context, TimerActivity.class); + startActivity(in); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + finish(); + } else { + Intent in = new Intent(context, DealarBoardActivity.class); + startActivity(in); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + finish(); + } + } else { + Intent in = new Intent(context, StoreImageActivity.class); + startActivity(in); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + finish(); + } + } else { + editor.putString(user_id, pinview_confirm.getValue()); + if (!allLoginData.isEmpty() && allLoginData.get(0).getUserType() != null) { + editor.putString(CommonString.KEY_USER_TYPE, allLoginData.get(0).getUserType()); + } + editor.putString(CommonString.KEY_USERNAME, user_id.toLowerCase()); + editor.commit(); + db.open(); + db.updateLoginMpnData(user_id, pinview_confirm.getValue()); + if (!allLoginData.isEmpty() && !allLoginData.get(0).getImg().isEmpty()) { + if (db.isCheck_Old_Product(visit_date)) { + Intent in = new Intent(context, TimerActivity.class); + startActivity(in); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + finish(); + } else { + Intent in = new Intent(context, DealarBoardActivity.class); + startActivity(in); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + finish(); + } + } else { + Intent in = new Intent(context, StoreImageActivity.class); + startActivity(in); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + finish(); + } + } + } + + } else if (v.getId() == R.id.btn_clear) { + hideKeyboard(this); + if (!pinview_start.getValue().isEmpty() && !pinview_confirm.getValue().isEmpty()) { + pinview_start.clearValue(); + pinview_confirm.clearValue(); + } else if (!pinview_start.getValue().isEmpty() && pinview_confirm.getValue().isEmpty()) { + pinview_start.clearValue(); + } else if (pinview_start.getValue().isEmpty() && !pinview_confirm.getValue().isEmpty()) { + pinview_confirm.clearValue(); + } + + if (!IS_PASSWORD_CHECK) { + pinview_start.requestFocus(); + } else { + pinview_confirm.requestFocus(); + } + + } else if (v.getId() == R.id.btn_forgot_pin) { + ((PinViewActivity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); + AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle(R.string.parinaam).setMessage("Forgot MPIN ?") + .setPositiveButton(android.R.string.yes, (dialogInterface, i) -> { + editor.putString(user_id, null); + editor.commit(); + db.open(); + db.updateLoginMpnData(user_id, null); + Intent in = new Intent(context, UserLoginActivity.class); + startActivity(in); + dialogInterface.cancel(); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + PinViewActivity.this.finish(); + }).setNegativeButton(android.R.string.cancel, (dialogInterface, i) -> dialogInterface.dismiss()); + builder.show(); + } + } + + + private void AttempLogin() { + try { + + loading = ProgressDialog.show(context, "Processing", "Please wait...", false, false); + versionCode = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode; + JSONObject jsonObject = new JSONObject(); + jsonObject.put("UserName", user_id); + jsonObject.put("Password", allLoginData.get(0).getPassword()); + jsonObject.put("CounterId", counterId); + jsonObject.put("Latitude", lat); + jsonObject.put("Longitude", lon); + jsonObject.put("Appversion", app_ver); + jsonObject.put("Attmode", "0"); + jsonObject.put("Networkstatus", "0"); + jsonObject.put("ModelNumber", model); + jsonObject.put("Manufacturer", manufacturer); + jsonObject.put("OSVersion", os_version); + jsonObject.put("AppId", BuildConfig.APPLICATION_ID); + + if (Build.VERSION.SDK_INT > Build.VERSION_CODES.P) { + @SuppressLint("HardwareIds") String android_id = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID); + jsonObject.put("IMEINumber1", android_id); + jsonObject.put("IMEINumber2", android_id); + } else { + if (imeiNumbers != null && imeiNumbers.length > 0) { + jsonObject.put("IMEINumber1", imeiNumbers[0]); + if (imeiNumbers != null && imeiNumbers.length > 1) { + jsonObject.put("IMEINumber2", imeiNumbers[1]); + } else { + jsonObject.put("IMEINumber2", "0"); + } + } else { + jsonObject.put("IMEINumber1", "0"); + jsonObject.put("IMEINumber2", "0"); + } + } + + String jsonString = jsonObject.toString(); + try { + final OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS). + writeTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build(); + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsonString); + Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build(); + PostApi api = adapter.create(PostApi.class); + Call call = api.getLoginUserdetail(jsonData); + + call.enqueue(new Callback() { + @Override + public void onResponse(@NonNull Call call, @NonNull Response response) { + ResponseBody responseBody = response.body(); + String data_Login = null; + if (responseBody != null && response.isSuccessful()) { + try { + assert response.body() != null; + data_Login = response.body().string(); + data_Login = data_Login.substring(1, data_Login.length() - 1).replace("\\", ""); + if (data_Login.contains("Changed")) { + loading.dismiss(); + AlertandMessages.showAlertlogin((Activity) context, CommonString.MESSAGE_CHANGED); + } else if (data_Login.contains("No data")) { + loading.dismiss(); + AlertandMessages.showAlertlogin((Activity) context, CommonString.MESSAGE_LOGIN_NO_DATA); + } else if (data_Login.equalsIgnoreCase(CommonString.KEY_FAILURE)) { + AlertandMessages.showAlertlogin((Activity) context, CommonString.KEY_FAILURE + " Please try again"); + loading.dismiss(); + } else { + JSONObject obj = new JSONObject(); + obj.put("Downloadtype", "LoginTime"); + obj.put("Username", user_id); + obj.put("Param1", counterId); + obj.put("Param2", ""); + + final OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS) + .writeTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build(); + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), obj.toString()); + Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build(); + PostApi api = adapter.create(PostApi.class); + Call call_login_tym = api.getDownloadAll(jsonData); + final String finalData_Login = data_Login; + call_login_tym.enqueue(new Callback() { + @Override + public void onResponse(@NonNull Call call, @NonNull Response response) { + String responseBody = response.body(); + String data_login_time = null; + if (responseBody != null && response.isSuccessful()) { + try { + data_login_time = response.body(); + assert data_login_time != null; + if (data_login_time.isEmpty()) { + } else { + BADeviceLoginGetterSetter data_login_Tym = null; + if (!data_login_time.contains("No Data")) { + data_login_Tym = new Gson().fromJson(data_login_time, BADeviceLoginGetterSetter.class); + } + + loading.dismiss(); + Gson gson = new Gson(); + final BADeviceLoginGetterSetter userObject = gson.fromJson(finalData_Login, BADeviceLoginGetterSetter.class); + editor.putString(CommonString.KEY_USERNAME, user_id); + editor.putString(CommonString.KEY_PASSWORD, allLoginData.get(0).getPassword()); + editor.putString(CommonString.KEY_DATE, userObject.getLOGIN().get(0).getVisitDate()); + editor.putString(CommonString.KEY_PASSWORD_CHANGE, userObject.getLOGIN().get(0).getPasswordStatus()); + editor.commit(); + if (preferences.getString(CommonString.KEY_VERSION, "").equals(Integer.toString(versionCode))) { + loginGetterSetter = new LoginGetterSetter(); + loginGetterSetter.setUserId(user_id); + loginGetterSetter.setPassword(allLoginData.get(0).getPassword()); + loginGetterSetter.setVisitDate(visitdate); + loginGetterSetter.setUserType(userType); + if (data_login_Tym != null) { + loginGetterSetter.setUserLoginTym(data_login_Tym.getLoginTime().get(0).getLoginTime()); + } else { + loginGetterSetter.setUserLoginTym("00:00"); + } + db.open(); + db.updateLoginTym(user_id, visit_date, loginGetterSetter.getUserLoginTym()); + if (!userObject.getLOGIN().get(0).getPasswordStatus().isEmpty() && userObject.getLOGIN().get(0). + getPasswordStatus().equalsIgnoreCase("Change")) { + AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle(R.string.parinaam). + setMessage("Your password has been reset. Please change your password"). + setCancelable(false).setPositiveButton(android.R.string.yes, (dialogInterface, i) -> { + startActivity(new Intent(context, ChangePasswordActivity.class).putExtra(CommonString.KEY_PASSWORD_CHANGE, + userObject.getLOGIN().get(0).getPasswordStatus()).putExtra(CommonString.KEY_ACTIVITY, "PinView")); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + dialogInterface.dismiss(); + finish(); + }); + builder.show(); + } else { + loading.dismiss(); + if (!allLoginData.isEmpty()) { + if (allLoginData.get(0).getImg().isEmpty()) { + startActivity(new Intent(context, StoreImageActivity.class)); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + finish(); + } else { + if (db.isCheck_Old_Product(visit_date)) { + Intent in = new Intent(context, TimerActivity.class); + startActivity(in); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + finish(); + } else { + Intent in = new Intent(context, DealarBoardActivity.class); + startActivity(in); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + finish(); + } + } + } + } + } else { + Intent intent = new Intent(context, AutoUpdateActivity.class); + intent.putExtra(CommonString.KEY_PATH, preferences.getString(CommonString.KEY_PATH, "")); + startActivity(intent); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + finish(); + loading.dismiss(); + } + } + } catch (Exception e) { + e.fillInStackTrace(); + AlertandMessages.showAlertlogin((Activity) context, CommonString.MESSAGE_SOCKETEXCEPTION); + loading.dismiss(); + } + } + } + + @Override + public void onFailure(@NonNull Call call, @NonNull Throwable t) { + loading.dismiss(); + AlertandMessages.showAlertlogin((Activity) context, CommonString.MESSAGE_SOCKETEXCEPTION); + } + }); + } + } catch (Exception e) { + loading.dismiss(); + e.fillInStackTrace(); + AlertandMessages.showAlertlogin((Activity) context, CommonString.MESSAGE_SOCKETEXCEPTION + "(" + e + ")"); + + } + } else { + loading.dismiss(); + AlertandMessages.showAlertlogin((Activity) context, CommonString.MESSAGE_NO_RESPONSE_SERVER); + } + } + + @Override + public void onFailure(@NonNull Call call, @NonNull Throwable t) { + loading.dismiss(); + AlertandMessages.showAlertlogin((Activity) context, CommonString.MESSAGE_SOCKETEXCEPTION); + } + }); + + } catch (Exception e) { + loading.dismiss(); + e.fillInStackTrace(); + AlertandMessages.showAlertlogin((Activity) context, CommonString.MESSAGE_SOCKETEXCEPTION + "(" + e + ")"); + } + + } catch (PackageManager.NameNotFoundException | JSONException e) { + loading.dismiss(); + AlertandMessages.showAlertlogin((Activity) context, CommonString.MESSAGE_SOCKETEXCEPTION + "(" + e + ")"); + + } + } + + @Override + protected void onResume() { + super.onResume(); + checkgpsEnableDevice(); + imeiNumbers = imei.getDeviceImei(); + createLocationRequest(); + } + + @SuppressLint("VisibleForTests") + protected void createLocationRequest() { + LocationRequest mLocationRequest = new LocationRequest(); + // Location updates intervals in sec + // 5 sec + int UPDATE_INTERVAL = 5000; + mLocationRequest.setInterval(UPDATE_INTERVAL); + // 1 sec + int FATEST_INTERVAL = 1000; + mLocationRequest.setFastestInterval(FATEST_INTERVAL); + mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); + // 10 meters + int DISPLACEMENT = 5; + mLocationRequest.setSmallestDisplacement(DISPLACEMENT); + } + + private void checkgpsEnableDevice() { + if (!hasGPSDevice(context)) { + Toast.makeText(context, "Gps not Supported", Toast.LENGTH_SHORT).show(); + } + + final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); + if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER) && hasGPSDevice(context)) { + enableLocationSettings(); + } else { + if (manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { + hasGPSDevice(context); + } + } + } + + private void enableLocationSettings() { + @SuppressLint("VisibleForTests") LocationRequest locationRequest = LocationRequest.create() + .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY) // new Priority constant + .setInterval(30 * 1000) + .setFastestInterval(5 * 1000); + LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder() + .addLocationRequest(locationRequest) + .setAlwaysShow(true); // show dialog if GPS is off + + SettingsClient settingsClient = LocationServices.getSettingsClient(this); + + settingsClient.checkLocationSettings(builder.build()) + .addOnSuccessListener(locationSettingsResponse -> { + // All location settings are satisfied. You can request location updates here. + }).addOnFailureListener(e -> { + if (e instanceof ResolvableApiException) { + try { + ResolvableApiException resolvable = (ResolvableApiException) e; + resolvable.startResolutionForResult((Activity) context, REQUEST_LOCATION); + } catch (IntentSender.SendIntentException sendEx) { + // Ignore the error. + sendEx.fillInStackTrace(); + } + } + }); + } + + private boolean hasGPSDevice(Context context) { + final LocationManager mgr = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); + if (mgr == null) + return false; + final List providers = mgr.getAllProviders(); + if (providers == null) + return false; + return providers.contains(LocationManager.GPS_PROVIDER); + } + + + private void check_keyboard() { + InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); + if (imm.isAcceptingText()) { + getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); + } + } + + @Override + protected void onDestroy() { + super.onDestroy(); + if (loading != null && loading.isShowing()) { + loading.dismiss(); + } + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/printer/DeviceListActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/printer/DeviceListActivity.java new file mode 100644 index 0000000..dfd00fa --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/printer/DeviceListActivity.java @@ -0,0 +1,147 @@ +package com.cpm.lorealbaautomation.printer; + +import android.Manifest; +import android.app.Activity; +import android.bluetooth.BluetoothAdapter; +import android.bluetooth.BluetoothDevice; +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.content.pm.PackageManager; +import android.os.Bundle; +import android.view.View; +import android.view.Window; +import android.widget.AdapterView.OnItemClickListener; +import android.widget.ArrayAdapter; +import android.widget.Button; +import android.widget.ListView; +import android.widget.TextView; + +import androidx.core.app.ActivityCompat; + +import com.hoin.btsdk.BluetoothService; +import com.cpm.lorealbaautomation.R; + +import java.util.Set; + + +public class DeviceListActivity extends Activity { + public static String EXTRA_DEVICE_ADDRESS = "device_address"; + BluetoothService mService = null; + private ArrayAdapter mNewDevicesArrayAdapter; + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); + setContentView(R.layout.device_list); //��ʾ�б���� + setResult(Activity.RESULT_CANCELED); + Button scanButton = (Button) findViewById(R.id.button_scan); + scanButton.setOnClickListener(v -> { + doDiscovery(); + v.setVisibility(View.GONE); + }); + + ArrayAdapter mPairedDevicesArrayAdapter = new ArrayAdapter(this, R.layout.device_name); + mNewDevicesArrayAdapter = new ArrayAdapter(this, R.layout.device_name); + + ListView pairedListView = (ListView) findViewById(R.id.paired_devices); + pairedListView.setAdapter(mPairedDevicesArrayAdapter); + pairedListView.setOnItemClickListener(mDeviceClickListener); + ListView newDevicesListView = (ListView) findViewById(R.id.new_devices); + newDevicesListView.setAdapter(mNewDevicesArrayAdapter); + newDevicesListView.setOnItemClickListener(mDeviceClickListener); + IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); + this.registerReceiver(mReceiver, filter); + filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); + this.registerReceiver(mReceiver, filter); + mService = new BluetoothService(this, null); + Set pairedDevices = mService.getPairedDev(); + if (!pairedDevices.isEmpty()) { + findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE); + for (BluetoothDevice device : pairedDevices) { + if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) { + // TODO: Consider calling + // ActivityCompat#requestPermissions + // here to request the missing permissions, and then overriding + // public void onRequestPermissionsResult(int requestCode, String[] permissions, + // int[] grantResults) + // to handle the case where the user grants the permission. See the documentation + // for ActivityCompat#requestPermissions for more details. + return; + } + mPairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress()); + } + } else { + String noDevices = getResources().getText(R.string.bluetooth_none_paired).toString(); + mPairedDevicesArrayAdapter.add(noDevices); + } + } + + @Override + protected void onDestroy() { + super.onDestroy(); + if (mService != null) { + mService.cancelDiscovery(); + } + mService = null; + this.unregisterReceiver(mReceiver); + } + + private void doDiscovery() { + setProgressBarIndeterminateVisibility(true); + setTitle(R.string.bluetooth_scanning); + findViewById(R.id.title_new_devices).setVisibility(View.VISIBLE); + if (mService.isDiscovering()) { + mService.cancelDiscovery(); + } + mService.startDiscovery(); + } + + //����б�������豸 + private final OnItemClickListener mDeviceClickListener = (av, v, arg2, arg3) -> { + mService.cancelDiscovery(); + + String info = ((TextView) v).getText().toString(); + String address = info.substring(info.length() - 17); + + Intent intent = new Intent(); + intent.putExtra(EXTRA_DEVICE_ADDRESS, address); + //test("���ӵ�ַ", address); + + setResult(Activity.RESULT_OK, intent); + finish(); + }; + + private final BroadcastReceiver mReceiver = new BroadcastReceiver() { + @Override + public void onReceive(Context context, Intent intent) { + String action = intent.getAction(); + if (BluetoothDevice.ACTION_FOUND.equals(action)) { + BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); + if (ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) { + // TODO: Consider calling + // ActivityCompat#requestPermissions + // here to request the missing permissions, and then overriding + // public void onRequestPermissionsResult(int requestCode, String[] permissions, + // int[] grantResults) + // to handle the case where the user grants the permission. See the documentation + // for ActivityCompat#requestPermissions for more details. + return; + } + assert device != null; + if (device.getBondState() != BluetoothDevice.BOND_BONDED) { + mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress()); + } + } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) { + setProgressBarIndeterminateVisibility(false); + setTitle(R.string.bluetooth_select_device); + if (mNewDevicesArrayAdapter.getCount() == 0) { + String noDevices = getResources().getText(R.string.bluetooth_none_found).toString(); + mNewDevicesArrayAdapter.add(noDevices); + } + } + } + }; + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/printer/PrinterActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/printer/PrinterActivity.java new file mode 100644 index 0000000..292eff3 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/printer/PrinterActivity.java @@ -0,0 +1,628 @@ +package com.cpm.lorealbaautomation.printer; + +import android.Manifest; +import android.annotation.SuppressLint; +import android.app.Activity; +import android.bluetooth.BluetoothAdapter; +import android.bluetooth.BluetoothDevice; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.content.pm.PackageManager; +import android.graphics.Bitmap; +import android.os.Build; +import android.os.Bundle; +import android.os.Handler; +import android.os.Message; + +import androidx.activity.result.ActivityResultLauncher; +import androidx.activity.result.contract.ActivityResultContracts; +import androidx.core.app.ActivityCompat; +import androidx.appcompat.app.AppCompatActivity; +import androidx.appcompat.widget.Toolbar; + +import android.view.MenuItem; +import android.view.View; +import android.widget.Button; +import android.widget.Toast; + +import com.google.zxing.BarcodeFormat; +import com.google.zxing.EncodeHintType; +import com.google.zxing.MultiFormatWriter; +import com.google.zxing.WriterException; +import com.google.zxing.common.BitMatrix; +import com.hoin.btsdk.BluetoothService; +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.constant.CommonFunctions; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.gsonGetterSetter.InvoiceGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.JourneyPlan; + +import java.util.ArrayList; +import java.util.BitSet; +import java.util.EnumMap; +import java.util.Map; +import java.util.Objects; + +public class PrinterActivity extends AppCompatActivity { + ArrayList invoice_List = new ArrayList<>(); + InvoiceGetterSetter object = new InvoiceGetterSetter(); + String store_name, counter_name, store_address, visit_date, user_name, countrId, consumerReturnflag, counter_code; + JourneyPlan storeDataObject = new JourneyPlan(); + private static final int REQUEST_CONNECT_DEVICE = 1; //»ñÈ¡É豸ÏûÏ¢ + private static final int REQUEST_ENABLE_BT = 2; + BluetoothService mService = null; + BluetoothDevice con_dev = null; + Lorealba_Database db; + Button btnSearch; + Button btnSend; + Context context; + int receipt_count = 0; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_printer); + context = this; + Toolbar toolbar = findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + Objects.requireNonNull(getSupportActionBar()).setHomeButtonEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + if (!CommonFunctions.isTablet(context)) { + toolbar.setTitleTextAppearance(context, R.style.changestext_sizefor_mobile); + } + db = new Lorealba_Database(context); + db.open(); + btnSearch = (Button) findViewById(R.id.btnSearch); + btnSearch.setOnClickListener(new ClickEvent()); + btnSend = (Button) findViewById(R.id.btnSend); + SharedPreferences preferences = PrefHelper.getPrefs(context); + countrId = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + counter_code = preferences.getString(CommonString.KEY_COUNTER_CODE, ""); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + store_name = preferences.getString(CommonString.KEY_STORE_NAME, ""); + store_address = preferences.getString(CommonString.KEY_STORE_ADDRESS, ""); + user_name = preferences.getString(CommonString.KEY_USERNAME, ""); + setTitle("Printer -" + user_name); + btnSend.setOnClickListener(new ClickEvent()); + consumerReturnflag = getIntent().getStringExtra(CommonString.TAG_FOR_RETURN); + if (consumerReturnflag != null && consumerReturnflag.equals("1")) { + object = (InvoiceGetterSetter) getIntent().getSerializableExtra(CommonString.TAG_HEADER_OBJECT); + } + invoice_List = (ArrayList) getIntent().getSerializableExtra(CommonString.TAG_OBJECT); + if (invoice_List != null && !invoice_List.isEmpty()) { + user_name = invoice_List.get(0).getUserName(); + } + + receipt_count = db.receipt_count_userwise(visit_date, countrId, user_name); + receipt_count = receipt_count + 1; + db.open(); + storeDataObject = db.getspecific_storenamewith_counter_name(visit_date, countrId, user_name); + if (storeDataObject != null && storeDataObject.getStoreName() != null) { + store_name = storeDataObject.getStoreName(); + counter_name = storeDataObject.getCounterName(); + store_address = " " + storeDataObject.getAddress() + " , " + storeDataObject.getCityName(); + } else { + counter_name = ""; + store_name = ""; + store_address = ""; + } + btnSend.setEnabled(false); + requestBluetooth(); + mService = new BluetoothService(context, mHandler); + if (!mService.isAvailable()) { + Toast.makeText(context, "Bluetooth is not available", Toast.LENGTH_LONG).show(); + } + } + + @Override + public void onResume() { + super.onResume(); + if (!mService.isBTopen()) { + Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); + if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) { + // TODO: Consider calling + // ActivityCompat#requestPermissions + // here to request the missing permissions, and then overriding + // public void onRequestPermissionsResult(int requestCode, String[] permissions, + // int[] grantResults) + // to handle the case where the user grants the permission. See the documentation + // for ActivityCompat#requestPermissions for more details. + return; + } + startActivityForResult(enableIntent, REQUEST_ENABLE_BT); + } + } + + @Override + public void onDestroy() { + super.onDestroy(); + if (mService != null) + mService.stop(); + mService = null; + } + + class ClickEvent implements View.OnClickListener { + @SuppressLint("NonConstantResourceId") + public void onClick(View v) { + String msg = ""; + + if (v.getId() == R.id.btnSearch) { + Intent serverIntent = new Intent(getApplicationContext(), DeviceListActivity.class); //ÔËÐÐÁíÍâÒ»¸öÀàµÄ»î¶¯ + startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE); + } else if (v.getId() == R.id.btnSend) { + //msg = edtContext.getText().toString(); + // Bold format center: + if (consumerReturnflag != null && consumerReturnflag.equals("1")) { + msg = "Store : " + store_name + " Counter : " + counter_name + " Counter Code : " + counter_code; + mService.sendMessage(msg + "\n" + " " + store_address, "GBK"); + String pinkSlip = "Consumer Return Slip - " + object.getReccept_count(); + mService.sendMessage(pinkSlip, "GBK"); + // Bold underlined format with right alignment: + String for_date = "Date : " + visit_date + "\n\nCustomer Name : " + object.getCustomer_name() + + "\nMobile No. : " + object.getMobile_no() + "\n Bill No. : " + object.getConsumer_return_bill_no() + "\n" + "Ba Name : " + user_name; + + mService.sendMessage(for_date, "GBK"); + double total_INR_value = 0.0, total = 0.0; + String productPrint = "", ean_code, quantity1, discount = ""; + for (int k = 0; k < invoice_List.size(); k++) { + int quantity = Integer.parseInt(invoice_List.get(k).getQuantity()); + double amount = Double.parseDouble(invoice_List.get(k).getProduct_rate()); + amount = amount * quantity; + invoice_List.get(k).setTotal_amount("" + amount); + productPrint = invoice_List.get(k).getProduct(); + total_INR_value = total_INR_value + Double.parseDouble(invoice_List.get(k).getTotal_amount()); + ean_code = invoice_List.get(k).getScan_ean_code_or_enterd_ean_code(); + quantity1 = "QTY : " + invoice_List.get(k).getQuantity() + " Rate : " + invoice_List.get(k).getProduct_rate() + " Amount : " + invoice_List.get(k).getTotal_amount(); + mService.sendMessage("Product : " + productPrint + "\n" + "Ean Code : " + ean_code + "\n" + quantity1 + "\n" + "Return Reason : " + invoice_List.get(k).getCon_return_reason(), "GBK"); + mService.sendMessage(discount, "GBK"); + } + + total = total_INR_value; + mService.sendMessage("Total Amount : " + total + "\n", "GBK"); + + } else { + ////print data of consumer sales data + msg = "Store : " + store_name + " Counter : " + counter_name; + mService.sendMessage(msg + "\n" + store_address, "GBK"); + String pinkSlip = "Pink Slip - " + receipt_count; + mService.sendMessage(pinkSlip, "GBK"); + // Bold underlined format with right alignment: + String for_date = "Date : " + visit_date + "\n\nCustomer Name : " + invoice_List.get(0).getCustomer_name() + "\nMobile No. : " + invoice_List.get(0).getMobile_no() + "\n" + "Ba Name : " + user_name; + mService.sendMessage(for_date, "GBK"); + + double cCom = 0.0, total_INR_value = 0.0, total = 0.0, off_worth_total = 0.0, worth_total = 0.0; + ; + String productPrint = "", ean_code, quantity1, discount = ""; + for (int k = 0; k < invoice_List.size(); k++) { + if (!invoice_List.get(k).isPromo_flag()) { + + if (invoice_List.get(k).getDiscount() != 0.0) { + int quantity = Integer.parseInt(invoice_List.get(k).getQuantity()); + double amount = Double.parseDouble(invoice_List.get(k).getProduct_rate()); + amount = amount * quantity; + invoice_List.get(k).setTotal_amount("" + amount); + cCom = cCom + ((Double.parseDouble(invoice_List.get(k).getTotal_amount())) * invoice_List.get(k).getDiscount()); + } else { + + int quantity = Integer.parseInt(invoice_List.get(k).getQuantity()); + double amount = Double.parseDouble(invoice_List.get(k).getProduct_rate()); + amount = amount * quantity; + invoice_List.get(k).setTotal_amount("" + amount); + } + + invoice_List.get(k).setStore_name(store_name); + invoice_List.get(k).setStore_address(store_address); + + productPrint = invoice_List.get(k).getProduct(); + double amount_ofproduct = ((Double.parseDouble(invoice_List.get(k).getTotal_amount())) * invoice_List.get(k).getDiscount()); + amount_ofproduct = (Double.parseDouble(invoice_List.get(k).getTotal_amount())) - amount_ofproduct; + total_INR_value = total_INR_value + Double.parseDouble(invoice_List.get(k).getTotal_amount()); + ean_code = invoice_List.get(k).getScan_ean_code_or_enterd_ean_code(); + quantity1 = "QTY : " + invoice_List.get(k).getQuantity() + " Rate : " + invoice_List.get(k).getProduct_rate() + " Amount : " + invoice_List.get(k).getTotal_amount(); + mService.sendMessage(productPrint + "\n" + "Product Type : " + invoice_List.get(k).getStr_invoiceType() + "\n" + ean_code + "\n" + quantity1, "GBK"); + String string = invoice_List.get(k).getDiscount().toString(); + if (invoice_List.get(k).getDiscount() == 0.0 || invoice_List.get(k).getDiscount() == 0) { + discount = "Actual Price : " + (Double.parseDouble(invoice_List.get(k).getTotal_amount())); + } else { + discount = string.substring(string.length() - 1) + "0% Discount - " + ((Double.parseDouble(invoice_List.get(k).getTotal_amount())) * invoice_List.get(k).getDiscount()) + " Actual Price : " + (Double.parseDouble(invoice_List.get(k).getTotal_amount()) - + ((Double.parseDouble(invoice_List.get(k).getTotal_amount())) * invoice_List.get(k).getDiscount())); + } + + mService.sendMessage(discount, "GBK"); + } else { + if (invoice_List.get(k).getPromo_type().equalsIgnoreCase("OffProduct")) { + if (invoice_List.get(k).getDiscount() != 0.0) { + int quantity = Integer.parseInt(invoice_List.get(k).getQuantity()); + double amount = Double.parseDouble(invoice_List.get(k).getProduct_rate()); + amount = amount * quantity; + invoice_List.get(k).setTotal_amount("" + amount); + cCom = cCom + ((Double.parseDouble(invoice_List.get(k).getTotal_amount())) * invoice_List.get(k).getDiscount()); + } else { + + int quantity = Integer.parseInt(invoice_List.get(k).getQuantity()); + double amount = Double.parseDouble(invoice_List.get(k).getProduct_rate()); + amount = amount * quantity; + invoice_List.get(k).setTotal_amount("" + amount); + } + + invoice_List.get(k).setStore_name(store_name); + invoice_List.get(k).setStore_address(store_address); + + productPrint = invoice_List.get(k).getProduct(); + double amount_ofproduct = ((Double.parseDouble(invoice_List.get(k).getTotal_amount())) * invoice_List.get(k).getDiscount()); + amount_ofproduct = (Double.parseDouble(invoice_List.get(k).getTotal_amount())) - amount_ofproduct; + total_INR_value = total_INR_value + Double.parseDouble(invoice_List.get(k).getTotal_amount()); + ean_code = invoice_List.get(k).getScan_ean_code_or_enterd_ean_code(); + quantity1 = "QTY : " + invoice_List.get(k).getQuantity() + " Rate : " + invoice_List.get(k).getProduct_rate() + " Amount : " + invoice_List.get(k).getTotal_amount(); + mService.sendMessage(productPrint + "\n" + "Product Type : " + invoice_List.get(k).getPromo_type() + "\n" + ean_code + "\n" + quantity1, "GBK"); + String string = invoice_List.get(k).getDiscount().toString(); + if (invoice_List.get(k).getDiscount() == 0.0 || invoice_List.get(k).getDiscount() == 0) { + discount = "Actual Price : " + (Double.parseDouble(invoice_List.get(k).getTotal_amount())); + } else { + discount = string.substring(string.length() - 1) + "0% Discount - " + ((Double.parseDouble(invoice_List.get(k).getTotal_amount())) * invoice_List.get(k).getDiscount()) + " Actual Price : " + (Double.parseDouble(invoice_List.get(k).getTotal_amount()) - + ((Double.parseDouble(invoice_List.get(k).getTotal_amount())) * invoice_List.get(k).getDiscount())) + ""; + } + total_INR_value = total_INR_value - Integer.parseInt(invoice_List.get(k).getSkuType()); + mService.sendMessage(discount, "GBK"); + } else if (invoice_List.get(k).getPromo_type().equalsIgnoreCase("OffWorth")) { + if (invoice_List.get(k).getDiscount() != 0.0) { + int quantity = Integer.parseInt(invoice_List.get(k).getQuantity()); + double amount = Double.parseDouble(invoice_List.get(k).getProduct_rate()); + amount = amount * quantity; + invoice_List.get(k).setTotal_amount("" + amount); + cCom = cCom + ((Double.parseDouble(invoice_List.get(k).getTotal_amount())) * invoice_List.get(k).getDiscount()); + } else { + + int quantity = Integer.parseInt(invoice_List.get(k).getQuantity()); + double amount = Double.parseDouble(invoice_List.get(k).getProduct_rate()); + amount = amount * quantity; + invoice_List.get(k).setTotal_amount("" + amount); + } + + invoice_List.get(k).setStore_name(store_name); + invoice_List.get(k).setStore_address(store_address); + + double amount_ofproduct = ((Double.parseDouble(invoice_List.get(k).getTotal_amount())) * invoice_List.get(k).getDiscount()); + amount_ofproduct = (Double.parseDouble(invoice_List.get(k).getTotal_amount())) - amount_ofproduct; + total_INR_value = total_INR_value + Double.parseDouble(invoice_List.get(k).getTotal_amount()); + ean_code = invoice_List.get(k).getScan_ean_code_or_enterd_ean_code(); + mService.sendMessage("Applied Promo - " + invoice_List.get(k).getPromotion_name() + " - " + "Discounted Rs - " + invoice_List.get(k).getProduct(), "GBK"); + off_worth_total = off_worth_total + Double.parseDouble(invoice_List.get(k).getProduct()); + + } else if (invoice_List.get(k).getPromo_type().equalsIgnoreCase("Worth")) { + if (invoice_List.get(k).getDiscount() != 0.0) { + int quantity = Integer.parseInt(invoice_List.get(k).getQuantity()); + double amount = Double.parseDouble(invoice_List.get(k).getProduct_rate()); + amount = amount * quantity; + invoice_List.get(k).setTotal_amount("" + amount); + cCom = cCom + ((Double.parseDouble(invoice_List.get(k).getTotal_amount())) * invoice_List.get(k).getDiscount()); + } else { + + int quantity = Integer.parseInt(invoice_List.get(k).getQuantity()); + double amount = Double.parseDouble(invoice_List.get(k).getProduct_rate()); + amount = amount * quantity; + invoice_List.get(k).setTotal_amount("" + amount); + } + + invoice_List.get(k).setStore_name(store_name); + invoice_List.get(k).setStore_address(store_address); + + double amount_ofproduct = ((Double.parseDouble(invoice_List.get(k).getTotal_amount())) * invoice_List.get(k).getDiscount()); + amount_ofproduct = (Double.parseDouble(invoice_List.get(k).getTotal_amount())) - amount_ofproduct; + total_INR_value = total_INR_value + Double.parseDouble(invoice_List.get(k).getTotal_amount()); + ean_code = invoice_List.get(k).getScan_ean_code_or_enterd_ean_code(); + mService.sendMessage("Applied Promo - " + invoice_List.get(k).getPromotion_name() + " - " + "Discounted Rs - " + invoice_List.get(k).getProduct(), "GBK"); + worth_total = worth_total + Double.parseDouble(invoice_List.get(k).getProduct()); + } + } + } + + total = total_INR_value - cCom; + total = total - off_worth_total; + total = total - worth_total; + + mService.sendMessage("Total Amount : " + total + "\n", "GBK"); + } + } + } + } + + public void writeWithFormat(byte[] buffer, final byte[] pFormat, final byte[] pAlignment) { + // Notify printer it should be printed with given alignment: + mService.write(pAlignment); + // Notify printer it should be printed in the given format://±¶¿í¡¢±¶¸ßģʽ + mService.write(pFormat); + // Write the actual data://±¶¿í¡¢±¶¸ßģʽ + mService.write(buffer); //±¶¿í¡¢±¶¸ßģʽ + //mService.sendMessage("Congratulations!\n", "GBK"); + } + + /** + * ´´½¨Ò»¸öHandlerʵÀý£¬ÓÃÓÚ½ÓÊÕBluetoothServiceÀà·µ»Ø»ØÀ´µÄÏûÏ¢ + */ + @SuppressLint("HandlerLeak") + private final Handler mHandler = new Handler() { + @SuppressLint("HandlerLeak") + @Override + public void handleMessage(Message msg) { + switch (msg.what) { + case BluetoothService.MESSAGE_STATE_CHANGE: + switch (msg.arg1) { + case BluetoothService.STATE_CONNECTED: //ÒÑÁ¬½Ó + Toast.makeText(getApplicationContext(), "Connect successful", + Toast.LENGTH_SHORT).show(); + btnSend.setEnabled(true); + break; + case BluetoothService.STATE_CONNECTING: //ÕýÔÚÁ¬½Ó + //test("À¶ÑÀµ÷ÊÔ", "ÕýÔÚÁ¬½Ó....."); + break; + case BluetoothService.STATE_LISTEN: //¼àÌýÁ¬½ÓµÄµ½À´ + case BluetoothService.STATE_NONE: + //test("À¶ÑÀµ÷ÊÔ", "µÈ´ýÁ¬½Ó....."); + break; + } + break; + case BluetoothService.MESSAGE_CONNECTION_LOST: //À¶ÑÀÒѶϿªÁ¬½Ó + Toast.makeText(getApplicationContext(), "Device connection was lost", + Toast.LENGTH_SHORT).show(); + btnSend.setEnabled(false); + + break; + case BluetoothService.MESSAGE_UNABLE_CONNECT: //ÎÞ·¨Á¬½ÓÉ豸 + Toast.makeText(getApplicationContext(), "Unable to connect device", + Toast.LENGTH_SHORT).show(); + break; + } + } + + }; + + @Override + public void onActivityResult(int requestCode, int resultCode, Intent data) { + super.onActivityResult(requestCode, resultCode, data); + switch (requestCode) { + case REQUEST_ENABLE_BT: //ÇëÇó´ò¿ªÀ¶ÑÀ + if (resultCode == Activity.RESULT_OK) { //À¶ÑÀÒѾ­´ò¿ª + Toast.makeText(this, "Bluetooth open successful", Toast.LENGTH_LONG).show(); + } + break; + case REQUEST_CONNECT_DEVICE: //ÇëÇóÁ¬½ÓijһÀ¶ÑÀÉ豸 + if (resultCode == Activity.RESULT_OK) { //Òѵã»÷ËÑË÷ÁбíÖеÄij¸öÉ豸Ïî + String address = Objects.requireNonNull(data.getExtras()).getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS); //»ñÈ¡ÁбíÏîÖÐÉ豸µÄmacµØÖ· + con_dev = mService.getDevByMac(address); + mService.connect(con_dev); + } + + break; + } + } + + public static class Formatter { + private byte[] mFormat; + + public Formatter() { + // Default: + mFormat = new byte[]{27, 33, 0}; + } + + /** + * Method to get the Build result + * + * @return the format + */ + public byte[] get() { + return mFormat; + } + + public Formatter bold() { + // Apply bold: + mFormat[2] = ((byte) (0x8 | mFormat[2])); + return this; + } + + public Formatter small() { + mFormat[2] = ((byte) (0x1 | mFormat[2])); + return this; + } + + public Formatter height() { + mFormat[2] = ((byte) (0x10 | mFormat[2])); + return this; + } + + public Formatter width() { + mFormat[2] = ((byte) (0x20 | mFormat[2])); + return this; + } + + public Formatter underlined() { + mFormat[2] = ((byte) (0x80 | mFormat[2])); + return this; + } + + public static byte[] rightAlign() { + return new byte[]{0x1B, 'a', 0x02}; + } + + public static byte[] leftAlign() { + return new byte[]{0x1B, 'a', 0x00}; + } + + public static byte[] centerAlign() { + return new byte[]{0x1B, 'a', 0x01}; + } + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + if (id == android.R.id.home) { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + PrinterActivity.this.finish(); + } + + return super.onOptionsItemSelected(item); + } + + @Override + public void onBackPressed() { + super.onBackPressed(); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + PrinterActivity.this.finish(); + } + + + private static final int WHITE = 0xFFFFFFFF; + private static final int BLACK = 0xFF000000; + + private static Bitmap encodeAsBitmap(String contents, BarcodeFormat format, int img_width, int img_height) throws WriterException { + if (contents == null) { + return null; + } + Map hints = null; + String encoding = guessAppropriateEncoding(contents); + if (encoding != null) { + hints = new EnumMap<>(EncodeHintType.class); + hints.put(EncodeHintType.CHARACTER_SET, encoding); + } + MultiFormatWriter writer = new MultiFormatWriter(); + BitMatrix result; + try { + result = writer.encode(contents, format, img_width, img_height, hints); + } catch (IllegalArgumentException iae) { + // Unsupported format + return null; + } + int width = result.getWidth(); + int height = result.getHeight(); + int[] pixels = new int[width * height]; + for (int y = 0; y < height; y++) { + int offset = y * width; + for (int x = 0; x < width; x++) { + pixels[offset + x] = result.get(x, y) ? BLACK : WHITE; + } + } + + Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); + bitmap.setPixels(pixels, 0, width, 0, 0, width, height); + return bitmap; + } + + private static String guessAppropriateEncoding(CharSequence contents) { + // Very crude at the moment + for (int i = 0; i < contents.length(); i++) { + if (contents.charAt(i) > 0xFF) { + return "UTF-8"; + } + } + return null; + } + + //print photo + public void printPhoto(Bitmap bmp) { + try { + //Bitmap bmp = BitmapFactory.decodeResource(getResources(), img); + if (bmp != null) { + byte[] command = Utils.decodeBitmap(bmp); + mService.write(PrinterCommands.ESC_ALIGN_CENTER); + printText(command); + } else { + //test("Print Photo error", "the file isn't exists"); + } + } catch (Exception e) { + e.fillInStackTrace(); + //test("PrintTools", "the file isn't exists"); + } + } + + //print byte[] + private void printText(byte[] msg) { + // Print normal text + mService.write(msg); + printNewLine(); + } + + //print new line + private void printNewLine() { + mService.write(PrinterCommands.FEED_LINE); + + } + + private void print_image(Bitmap bmp) { + BitSet dots = new BitSet(); + mService.write(PrinterCommands.SET_LINE_SPACING_24); + + int offset = 0; + while (offset < bmp.getHeight()) { + mService.write(PrinterCommands.SELECT_BIT_IMAGE_MODE); + for (int x = 0; x < bmp.getWidth(); ++x) { + for (int k = 0; k < 3; ++k) { + byte slice = 0; + for (int b = 0; b < 8; ++b) { + int y = (((offset / 8) + k) * 8) + b; + int i = (y * bmp.getWidth()) + x; + boolean v = false; + if (i < dots.length()) { + v = dots.get(i); + } + slice |= (byte) ((v ? 1 : 0) << (7 - b)); + } + mService.write(new byte[]{slice}); + } + } + + offset += 24; + mService.write(PrinterCommands.FEED_LINE); + mService.write(PrinterCommands.FEED_LINE); + mService.write(PrinterCommands.FEED_LINE); + mService.write(PrinterCommands.FEED_LINE); + mService.write(PrinterCommands.FEED_LINE); + mService.write(PrinterCommands.FEED_LINE); + } + mService.write(PrinterCommands.SET_LINE_SPACING_30); + } + + + void requestBluetooth() { + // Check if the Android version is 12 (S) or above + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + requestMultiplePermissions.launch( + new String[]{ + Manifest.permission.BLUETOOTH_SCAN, + Manifest.permission.BLUETOOTH_CONNECT + } + ); + } else { + Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); + requestEnableBluetooth.launch(enableBtIntent); + } + } + + private final ActivityResultLauncher requestEnableBluetooth = registerForActivityResult( + new ActivityResultContracts.StartActivityForResult(), + result -> { + if (result.getResultCode() == Activity.RESULT_OK) { + // Bluetooth enabling was granted + //test("MyTag", "Granted Bluetooth permission"); + } else { + // Bluetooth enabling was denied + //test("MyTag", "Denied Bluetooth permission"); + } + } + ); + + private final ActivityResultLauncher requestMultiplePermissions = registerForActivityResult( + new ActivityResultContracts.RequestMultiplePermissions(), + permissions -> { + for (Map.Entry entry : permissions.entrySet()) { + //test("MyTag", entry.getKey() + " = " + entry.getValue()); + } + } + ); +} + + diff --git a/app/src/main/java/com/cpm/lorealbaautomation/printer/PrinterCommands.java b/app/src/main/java/com/cpm/lorealbaautomation/printer/PrinterCommands.java new file mode 100644 index 0000000..318305c --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/printer/PrinterCommands.java @@ -0,0 +1,57 @@ +package com.cpm.lorealbaautomation.printer; + +public class PrinterCommands { + public static final byte HT = 0x9; + public static final byte LF = 0x0A; + public static final byte CR = 0x0D; + public static final byte ESC = 0x1B; + public static final byte DLE = 0x10; + public static final byte GS = 0x1D; + public static final byte FS = 0x1C; + public static final byte STX = 0x02; + public static final byte US = 0x1F; + public static final byte CAN = 0x18; + public static final byte CLR = 0x0C; + public static final byte EOT = 0x04; + + public static final byte[] INIT = {27, 64}; + public static byte[] FEED_LINE = {2}; + + public static byte[] SELECT_FONT_A = {20, 33, 0}; + + public static byte[] SET_BAR_CODE_HEIGHT = {29, 104, 100}; + public static byte[] PRINT_BAR_CODE_1 = {29, 107, 2}; + public static byte[] SEND_NULL_BYTE = {0x00}; + + public static byte[] SELECT_PRINT_SHEET = {0x1B, 0x63, 0x30, 0x02}; + public static byte[] FEED_PAPER_AND_CUT = {0x1D, 0x56, 66, 0x00}; + + public static byte[] SELECT_CYRILLIC_CHARACTER_CODE_TABLE = {0x1B, 0x74, 0x11}; + + public static byte[] SELECT_BIT_IMAGE_MODE = {0x1B, 0x2A, 33, (byte) 255, 3}; + public static byte[] SET_LINE_SPACING_24 = {0x1B, 0x33, 24}; + public static byte[] SET_LINE_SPACING_30 = {0x1B, 0x10, 10}; + + public static byte[] TRANSMIT_DLE_PRINTER_STATUS = {0x10, 0x04, 0x01}; + public static byte[] TRANSMIT_DLE_OFFLINE_PRINTER_STATUS = {0x10, 0x04, 0x02}; + public static byte[] TRANSMIT_DLE_ERROR_STATUS = {0x10, 0x04, 0x03}; + public static byte[] TRANSMIT_DLE_ROLL_PAPER_SENSOR_STATUS = {0x10, 0x04, 0x04}; + + public static final byte[] ESC_FONT_COLOR_DEFAULT = new byte[] { 0x1B, 'r',0x00 }; + public static final byte[] FS_FONT_ALIGN = new byte[] { 0x1C, 0x21, 1, 0x1B, + 0x21, 1 }; + public static final byte[] ESC_ALIGN_LEFT = new byte[] { 0x1b, 'a', 0x00 }; + public static final byte[] ESC_ALIGN_RIGHT = new byte[] { 0x1b, 'a', 0x02 }; + public static final byte[] ESC_ALIGN_CENTER = new byte[] { 0x1b, 'a', 0x01 }; + public static final byte[] ESC_CANCEL_BOLD = new byte[] { 0x1B, 0x45, 0 }; + + + /*********************************************/ + public static final byte[] ESC_HORIZONTAL_CENTERS = new byte[] { 0x1B, 0x44, 20, 28, 00}; + public static final byte[] ESC_CANCLE_HORIZONTAL_CENTERS = new byte[] { 0x1B, 0x44, 00 }; + /*********************************************/ + + public static final byte[] ESC_ENTER = new byte[] { 0x1B, 0x4A, 0x40 }; + public static final byte[] PRINTE_TEST = new byte[] { 0x1D, 0x28, 0x41 }; + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/printer/Utils.java b/app/src/main/java/com/cpm/lorealbaautomation/printer/Utils.java new file mode 100644 index 0000000..9d270ac --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/printer/Utils.java @@ -0,0 +1,152 @@ +package com.cpm.lorealbaautomation.printer; + +import android.graphics.Bitmap; + +import java.util.ArrayList; +import java.util.List; + +public class Utils { + + private static String hexStr = "0123456789ABCDEF"; + private static String[] binaryArray = { "0000", "0001", "0010", "0011", + "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", + "1100", "1101", "1110", "1111" }; + + public static byte[] decodeBitmap(Bitmap bmp){ + int bmpWidth = bmp.getWidth(); + int bmpHeight = bmp.getHeight(); + List list = new ArrayList(); //binaryString list + StringBuffer sb; + int zeroCount = bmpWidth % 8; + String zeroStr = ""; + if (zeroCount > 0) { + for (int i = 0; i < (8 - zeroCount); i++) { + zeroStr = zeroStr + "0"; + } + } + + for (int i = 0; i < bmpHeight; i++) { + sb = new StringBuffer(); + for (int j = 0; j < bmpWidth; j++) { + int color = bmp.getPixel(j, i); + + int r = (color >> 16) & 0xff; + int g = (color >> 8) & 0xff; + int b = color & 0xff; + + // if color close to white,bit='0', else bit='1' + if (r > 160 && g > 160 && b > 160) + sb.append("0"); + else + sb.append("1"); + } + if (zeroCount > 0) { + sb.append(zeroStr); + } + list.add(sb.toString()); + } + + List bmpHexList = binaryListToHexStringList(list); + String commandHexString = "1D763000"; + String widthHexString = Integer + .toHexString(bmpWidth % 8 == 0 ? bmpWidth / 8 + : (bmpWidth / 8 + 1)); + if (widthHexString.length() > 2) { + //test("decodeBitmap error", " width is too large"); + return null; + } else if (widthHexString.length() == 1) { + widthHexString = "0" + widthHexString; + } + widthHexString = widthHexString + "00"; + + String heightHexString = Integer.toHexString(bmpHeight); + if (heightHexString.length() > 2) { + //test("decodeBitmap error", " height is too large"); + return null; + } else if (heightHexString.length() == 1) { + heightHexString = "0" + heightHexString; + } + heightHexString = heightHexString + "00"; + + List commandList = new ArrayList(); + commandList.add(commandHexString+widthHexString+heightHexString); + commandList.addAll(bmpHexList); + + return hexList2Byte(commandList); + } + + public static List binaryListToHexStringList(List list) { + List hexList = new ArrayList(); + for (String binaryStr : list) { + StringBuffer sb = new StringBuffer(); + for (int i = 0; i < binaryStr.length(); i += 8) { + String str = binaryStr.substring(i, i + 8); + + String hexString = myBinaryStrToHexString(str); + sb.append(hexString); + } + hexList.add(sb.toString()); + } + return hexList; + + } + + public static String myBinaryStrToHexString(String binaryStr) { + String hex = ""; + String f4 = binaryStr.substring(0, 4); + String b4 = binaryStr.substring(4, 8); + for (int i = 0; i < binaryArray.length; i++) { + if (f4.equals(binaryArray[i])) + hex += hexStr.substring(i, i + 1); + } + for (int i = 0; i < binaryArray.length; i++) { + if (b4.equals(binaryArray[i])) + hex += hexStr.substring(i, i + 1); + } + + return hex; + } + + public static byte[] hexList2Byte(List list) { + List commandList = new ArrayList(); + + for (String hexStr : list) { + commandList.add(hexStringToBytes(hexStr)); + } + byte[] bytes = sysCopy(commandList); + return bytes; + } + + public static byte[] hexStringToBytes(String hexString) { + if (hexString == null || hexString.equals("")) { + return null; + } + hexString = hexString.toUpperCase(); + int length = hexString.length() / 2; + char[] hexChars = hexString.toCharArray(); + byte[] d = new byte[length]; + for (int i = 0; i < length; i++) { + int pos = i * 2; + d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1])); + } + return d; + } + + public static byte[] sysCopy(List srcArrays) { + int len = 0; + for (byte[] srcArray : srcArrays) { + len += srcArray.length; + } + byte[] destArray = new byte[len]; + int destLen = 0; + for (byte[] srcArray : srcArrays) { + System.arraycopy(srcArray, 0, destArray, destLen, srcArray.length); + destLen += srcArray.length; + } + return destArray; + } + + private static byte charToByte(char c) { + return (byte) "0123456789ABCDEF".indexOf(c); + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/progressbar/CircularProgressBar.java b/app/src/main/java/com/cpm/lorealbaautomation/progressbar/CircularProgressBar.java new file mode 100644 index 0000000..88ead96 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/progressbar/CircularProgressBar.java @@ -0,0 +1,273 @@ +package com.cpm.lorealbaautomation.progressbar; + +import android.animation.Animator; +import android.animation.Animator.AnimatorListener; +import android.animation.ObjectAnimator; +import android.animation.ValueAnimator; +import android.animation.ValueAnimator.AnimatorUpdateListener; +import android.content.Context; +import android.content.res.Resources; +import android.content.res.TypedArray; +import android.graphics.Canvas; +import android.graphics.Color; +import android.graphics.Paint; +import android.graphics.Paint.Style; +import android.graphics.RectF; +import android.graphics.Typeface; +import android.text.TextUtils; +import android.util.AttributeSet; +import android.view.View; +import android.view.animation.LinearInterpolator; +import android.widget.ProgressBar; + +import com.cpm.lorealbaautomation.R; + + +public class CircularProgressBar extends ProgressBar { + private static final String TAG = "CircularProgressBar"; + + private static final int STROKE_WIDTH = 20; + + private String mTitle = ""; + private String mSubTitle = ""; + + private int mStrokeWidth = STROKE_WIDTH; + + private final RectF mCircleBounds = new RectF(); + + private final Paint mProgressColorPaint = new Paint(); + private final Paint mBackgroundColorPaint = new Paint(); + private final Paint mTitlePaint = new Paint(); + private final Paint mSubtitlePaint = new Paint(); + + private boolean mHasShadow = true; + private int mShadowColor = Color.BLACK; + + public interface ProgressAnimationListener{ + public void onAnimationStart(); + public void onAnimationFinish(); + public void onAnimationProgress(int progress); + } + + public CircularProgressBar(Context context) { + super(context); + init(null, 0); + } + + public CircularProgressBar(Context context, AttributeSet attrs) { + super(context, attrs); + init(attrs, 0); + } + + public CircularProgressBar(Context context, AttributeSet attrs, int defStyle) { + super(context, attrs, defStyle); + init(attrs, defStyle); + } + + public void init(AttributeSet attrs, int style){ + //so that shadow shows up properly for lines and arcs + setLayerType(View.LAYER_TYPE_SOFTWARE, null); + + TypedArray a = getContext().obtainStyledAttributes(attrs, + R.styleable.CircularProgressBar, style, 0); + + String color; + Resources res = getResources(); + + this.mHasShadow = a.getBoolean(R.styleable.CircularProgressBar_cpb_hasShadow, true); + + color = a.getString(R.styleable.CircularProgressBar_cpb_progressColor); + if(color==null) + mProgressColorPaint.setColor(res.getColor(R.color.circular_progress_default_progress)); + else + mProgressColorPaint.setColor(Color.parseColor(color)); + + color = a.getString(R.styleable.CircularProgressBar_cpb_backgroundColor); + if(color==null) + mBackgroundColorPaint.setColor(res.getColor(R.color.circular_progress_default_background)); + else + mBackgroundColorPaint.setColor(Color.parseColor(color)); + + color = a.getString(R.styleable.CircularProgressBar_cpb_titleColor); + if(color==null) + mTitlePaint.setColor(res.getColor(R.color.circular_progress_default_title)); + else + mTitlePaint.setColor(Color.parseColor(color)); + + color = a.getString(R.styleable.CircularProgressBar_cpb_subtitleColor); + if(color==null) + mSubtitlePaint.setColor(res.getColor(R.color.circular_progress_default_subtitle)); + else + mSubtitlePaint.setColor(Color.parseColor(color)); + + + String t = a.getString(R.styleable.CircularProgressBar_cpb_title); + if(t!=null) + mTitle = t; + + t = a.getString(R.styleable.CircularProgressBar_cpb_subtitle); + if(t!=null) + mSubTitle = t; + + mStrokeWidth = a.getInt(R.styleable.CircularProgressBar_cpb_strokeWidth, STROKE_WIDTH); + + a.recycle(); + + + mProgressColorPaint.setAntiAlias(true); + mProgressColorPaint.setStyle(Style.STROKE); + mProgressColorPaint.setStrokeWidth(mStrokeWidth); + + mBackgroundColorPaint.setAntiAlias(true); + mBackgroundColorPaint.setStyle(Style.STROKE); + mBackgroundColorPaint.setStrokeWidth(mStrokeWidth); + + mTitlePaint.setTextSize(60); + mTitlePaint.setStyle(Style.FILL); + mTitlePaint.setAntiAlias(true); + mTitlePaint.setTypeface(Typeface.create("Roboto-Thin", Typeface.NORMAL)); + mTitlePaint.setShadowLayer(0.1f, 0, 1, Color.GRAY); + + mSubtitlePaint.setTextSize(20); + mSubtitlePaint.setStyle(Style.FILL); + mSubtitlePaint.setAntiAlias(true); + mSubtitlePaint.setTypeface(Typeface.create("Roboto-Thin", Typeface.BOLD)); + // mSubtitlePaint.setShadowLayer(0.1f, 0, 1, Color.GRAY); + } + + @Override + protected synchronized void onDraw(Canvas canvas) { + canvas.drawArc(mCircleBounds, 0, 360 , false, mBackgroundColorPaint); + + int prog = getProgress(); + float scale = getMax() > 0 ? (float)prog/getMax() *360: 0; + + if(mHasShadow) + mProgressColorPaint.setShadowLayer( 3, 0, 1, mShadowColor); + canvas.drawArc(mCircleBounds, 270, scale , false, mProgressColorPaint); + + + if(!TextUtils.isEmpty(mTitle)){ + int xPos = (int)(getMeasuredWidth()/2 - mTitlePaint.measureText(mTitle) / 2); + int yPos = (int) (getMeasuredHeight()/2); + + float titleHeight = Math.abs(mTitlePaint.descent() + mTitlePaint.ascent()); + if(TextUtils.isEmpty(mSubTitle)){ + yPos += titleHeight/2; + } + canvas.drawText(mTitle, xPos, yPos, mTitlePaint); + + yPos += titleHeight; + xPos = (int)(getMeasuredWidth()/2 - mSubtitlePaint.measureText(mSubTitle) / 2); + + canvas.drawText(mSubTitle, xPos, yPos, mSubtitlePaint); + } + + super.onDraw(canvas); + } + + @Override + protected void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec) { + final int height = getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec); + final int width = getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec); + final int min = Math.min(width, height); + setMeasuredDimension(min+2*STROKE_WIDTH, min+2*STROKE_WIDTH); + + mCircleBounds.set(STROKE_WIDTH, STROKE_WIDTH, min+STROKE_WIDTH, min+STROKE_WIDTH); + } + + @Override + public synchronized void setProgress(int progress) { + super.setProgress(progress); + + // the setProgress super will not change the details of the progress bar + // anymore so we need to force an update to redraw the progress bar + invalidate(); + } + + public void animateProgressTo(final int start, final int end, final ProgressAnimationListener listener){ + if(start!=0) + setProgress(start); + + //check + final ObjectAnimator progressBarAnimator = ObjectAnimator.ofFloat(this, TRANSLATION_X, start, end); + progressBarAnimator.setDuration(1500); + // progressBarAnimator.setInterpolator(new AnticipateOvershootInterpolator(2f, 1.5f)); + progressBarAnimator.setInterpolator(new LinearInterpolator()); + + progressBarAnimator.addListener(new AnimatorListener() { + @Override + public void onAnimationCancel(final Animator animation) { + } + + @Override + public void onAnimationEnd(final Animator animation) { + CircularProgressBar.this.setProgress(end); + if(listener!=null) + listener.onAnimationFinish(); + } + + @Override + public void onAnimationRepeat(final Animator animation) { + } + + @Override + public void onAnimationStart(final Animator animation) { + if(listener!=null) + listener.onAnimationStart(); + } + }); + + progressBarAnimator.addUpdateListener(new AnimatorUpdateListener() { + @Override + public void onAnimationUpdate(final ValueAnimator animation) { + int progress = ((Float) animation.getAnimatedValue()).intValue(); + if(progress!=CircularProgressBar.this.getProgress()){ + //test(TAG, progress + ""); + CircularProgressBar.this.setProgress(progress); + if(listener!=null) + listener.onAnimationProgress(progress); + } + } + }); + progressBarAnimator.start(); + } + + public synchronized void setTitle(String title){ + this.mTitle = title; + invalidate(); + } + + public synchronized void setSubTitle(String subtitle){ + this.mSubTitle = subtitle; + invalidate(); + } + + public synchronized void setSubTitleColor(int color){ + mSubtitlePaint.setColor(color); + invalidate(); + } + + public synchronized void setTitleColor(int color){ + mTitlePaint.setColor(color); + invalidate(); + } + + public synchronized void setHasShadow(boolean flag){ + this.mHasShadow = flag; + invalidate(); + } + + public synchronized void setShadow(int color){ + this.mShadowColor = color; + invalidate(); + } + + public String getTitle(){ + return mTitle; + } + + public boolean getHasShadow(){ + return mHasShadow; + } +} \ No newline at end of file diff --git a/app/src/main/java/com/cpm/lorealbaautomation/promooffer/PromoOfferDetailsActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/promooffer/PromoOfferDetailsActivity.java new file mode 100644 index 0000000..f5e6098 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/promooffer/PromoOfferDetailsActivity.java @@ -0,0 +1,116 @@ +package com.cpm.lorealbaautomation.promooffer; + +import android.content.Context; +import android.content.SharedPreferences; +import android.graphics.Bitmap; +import android.graphics.BitmapFactory; + +import androidx.appcompat.app.AppCompatActivity; +import android.os.Bundle; + +import androidx.appcompat.widget.Toolbar; +import android.view.MenuItem; +import android.widget.ImageView; +import android.widget.TextView; + +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.constant.CommonFunctions; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterPromoOffer; + +import java.io.File; + +public class PromoOfferDetailsActivity extends AppCompatActivity { + MasterPromoOffer object = new MasterPromoOffer(); + TextView promostart_txt, promoend_txt, promo_description; + ImageView image; + String visit_date, username, promoId = ""; + private SharedPreferences preferences; + private SharedPreferences.Editor editor = null; + Lorealba_Database db; + Context context; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_promo_offer_details); + + context = this; + db = new Lorealba_Database(context); + db.open(); + Toolbar toolbar = findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + getSupportActionBar().setHomeButtonEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + + if (!CommonFunctions.isTablet(context)) { + toolbar.setTitleTextAppearance(context, R.style.changestext_sizefor_mobile); + } + + + if (getIntent().getStringExtra(CommonString.KEY_PROMO_ID) != null) { + promoId = getIntent().getStringExtra(CommonString.KEY_PROMO_ID); + } + + + iduserinterface(); + setTitle("Promo Offers - " + username); + } + + private void iduserinterface() { + preferences = PrefHelper.getPrefs(context); + editor = preferences.edit(); + username = preferences.getString(CommonString.KEY_USERNAME, ""); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + promostart_txt = (TextView) findViewById(R.id.promostart_txt); + promoend_txt = (TextView) findViewById(R.id.promoend_txt); + promo_description = (TextView) findViewById(R.id.promo_description); + image = (ImageView) findViewById(R.id.image); + db.open(); + + object = db.getmaterPromoOffersbypromoId(promoId); + + if (object != null && object.getPromoId() != null) { + if (CommonFunctions.isTablet(context)) { + String path = CommonString.getPromosFolder(context) + object.getPromoOfferTab(); + File dir = new File(path); + if (dir.exists()) { + Bitmap myBitmap = BitmapFactory.decodeFile(dir.getAbsolutePath()); + image.setImageBitmap(myBitmap); + } + } else { + String path = CommonString.getPromosFolder(context) + object.getPromoOfferMobile(); + File dir = new File(path); + if (dir.exists()) { + Bitmap myBitmap = BitmapFactory.decodeFile(dir.getAbsolutePath()); + image.setImageBitmap(myBitmap); + } + } + } + + promostart_txt.setText(object.getStartDate()); + promoend_txt.setText(object.getEndDate()); + promo_description.setText(object.getDescription()); + + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // as you specify a parent activity in AndroidManifest.xml. + if (item.getItemId() == android.R.id.home) { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + PromoOfferDetailsActivity.this.finish(); + } + + return super.onOptionsItemSelected(item); + } + + @Override + public void onBackPressed() { + super.onBackPressed(); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + PromoOfferDetailsActivity.this.finish(); + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/promooffer/PromoOffersActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/promooffer/PromoOffersActivity.java new file mode 100644 index 0000000..0cb781e --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/promooffer/PromoOffersActivity.java @@ -0,0 +1,172 @@ +package com.cpm.lorealbaautomation.promooffer; + +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.graphics.Bitmap; +import android.graphics.BitmapFactory; + +import androidx.annotation.NonNull; +import androidx.appcompat.app.AppCompatActivity; +import android.os.Bundle; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; +import androidx.appcompat.widget.Toolbar; +import android.view.LayoutInflater; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; +import android.widget.ImageView; + +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.constant.CommonFunctions; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterPromoOffer; + + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + + +public class PromoOffersActivity extends AppCompatActivity { + String visit_date, username; + private SharedPreferences preferences; + private SharedPreferences.Editor editor = null; + RecyclerView recycl_promooffers; + Lorealba_Database db; + Context context; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_promo_offers); + + context = this; + db = new Lorealba_Database(context); + db.open(); + Toolbar toolbar = findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + getSupportActionBar().setHomeButtonEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + + if (!CommonFunctions.isTablet(context)) { + toolbar.setTitleTextAppearance(context, R.style.changestext_sizefor_mobile); + } + + iduserinterface(); + setTitle("Promo Offers - " + username); + } + + private void iduserinterface() { + preferences = PrefHelper.getPrefs(context); + editor = preferences.edit(); + username = preferences.getString(CommonString.KEY_USERNAME, ""); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + recycl_promooffers = (RecyclerView) findViewById(R.id.recycl_promooffers); + db.open(); + final ArrayList[] masterPromoOffers = new ArrayList[]{new ArrayList<>()}; + final ArrayList[] finalPromoOffers = new ArrayList[]{new ArrayList<>()}; + + masterPromoOffers[0] = db.getmaterPromoOffers(); + if (!masterPromoOffers[0].isEmpty()) { + finalPromoOffers[0] = new ArrayList<>(); + for (int k = 0; k < masterPromoOffers[0].size(); k++) { + if (CommonFunctions.isTablet(context)) { + String path = CommonString.getPromosFolder(context) + masterPromoOffers[0].get(k).getPromoOfferTab(); + File dir = new File(path); + if (dir.exists()) { + finalPromoOffers[0].add(masterPromoOffers[0].get(k)); + } + } else { + String path = CommonString.getPromosFolder(context) + masterPromoOffers[0].get(k).getPromoOfferMobile(); + File dir = new File(path); + if (dir.exists()) { + finalPromoOffers[0].add(masterPromoOffers[0].get(k)); + } + } + } + } + + + recycl_promooffers.setAdapter(new ValueAdapter(context, finalPromoOffers[0])); + recycl_promooffers.setLayoutManager(new LinearLayoutManager(context)); + } + + private class ValueAdapter extends RecyclerView.Adapter { + LayoutInflater inflator; + List data; + + public ValueAdapter(Context context, List data) { + inflator = LayoutInflater.from(context); + this.data = data; + } + + + @NonNull + @Override + public ValueAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) { + View view = inflator.inflate(R.layout.linear_layout_promo, parent, false); + return new ValueAdapter.MyViewHolder(view); + } + + @Override + public void onBindViewHolder(@NonNull final ValueAdapter.MyViewHolder holder, final int position) { + final MasterPromoOffer object = data.get(position); + if (CommonFunctions.isTablet(context)) { + String path = CommonString.getPromosFolder(context) + object.getPromoOfferTab(); + File dir = new File(path); + if (dir.exists()) { + Bitmap myBitmap = BitmapFactory.decodeFile(dir.getAbsolutePath()); + holder.imageView.setImageBitmap(myBitmap); + } + } else { + String path = CommonString.getPromosFolder(context) + object.getPromoOfferMobile(); + File dir = new File(path); + if (dir.exists()) { + Bitmap myBitmap = BitmapFactory.decodeFile(dir.getAbsolutePath()); + holder.imageView.setImageBitmap(myBitmap); + } + } + + holder.imageView.setOnClickListener(view -> { + startActivity(new Intent(context, PromoOfferDetailsActivity.class).putExtra(CommonString.KEY_PROMO_ID, object.getPromoId())); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + }); + } + + @Override + public int getItemCount() { + return data.size(); + } + + class MyViewHolder extends RecyclerView.ViewHolder { + ImageView imageView; + + public MyViewHolder(View itemView) { + super(itemView); + imageView = (ImageView) itemView.findViewById(R.id.image); + } + } + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // as you specify a parent activity in AndroidManifest.xml. + if (item.getItemId() == android.R.id.home) { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + PromoOffersActivity.this.finish(); + } + + return super.onOptionsItemSelected(item); + } + + @Override + public void onBackPressed() { + super.onBackPressed(); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + PromoOffersActivity.this.finish(); + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/promooffer/VerticalViewPager.java b/app/src/main/java/com/cpm/lorealbaautomation/promooffer/VerticalViewPager.java new file mode 100644 index 0000000..d198618 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/promooffer/VerticalViewPager.java @@ -0,0 +1,83 @@ +package com.cpm.lorealbaautomation.promooffer; + +import android.content.Context; +import androidx.viewpager.widget.ViewPager; +import android.util.AttributeSet; +import android.view.MotionEvent; +import android.view.View; + +/** + * Uses a combination of a PageTransformer and swapping X & Y coordinates + * of touch events to create the illusion of a vertically scrolling ViewPager. + * + * Requires API 11+ + * + */ +public class VerticalViewPager extends ViewPager { + + public VerticalViewPager(Context context) { + super(context); + init(); + } + + public VerticalViewPager(Context context, AttributeSet attrs) { + super(context, attrs); + init(); + } + + private void init() { + // The majority of the magic happens here + setPageTransformer(true, new VerticalPageTransformer()); + // The easiest way to get rid of the overscroll drawing that happens on the left and right + setOverScrollMode(OVER_SCROLL_NEVER); + } + + private class VerticalPageTransformer implements ViewPager.PageTransformer { + + @Override + public void transformPage(View view, float position) { + if (position < -1) { // [-Infinity,-1) + // This page is way off-screen to the left. + view.setAlpha(0); + } else if (position <= 1) { // [-1,1] + view.setAlpha(1); + // Counteract the default slide transition + view.setTranslationX(view.getWidth() * -position); + //set Y position to swipe in from top + float yPosition = position * view.getHeight(); + view.setTranslationY(yPosition); + } else { // (1,+Infinity] + // This page is way off-screen to the right. + view.setAlpha(0); + } + } + } + + /** + * Swaps the X and Y coordinates of your touch event. + */ + private MotionEvent swapXY(MotionEvent ev) { + float width = getWidth(); + float height = getHeight(); + + float newX = (ev.getY() / height) * width; + float newY = (ev.getX() / width) * height; + + ev.setLocation(newX, newY); + + return ev; + } + + @Override + public boolean onInterceptTouchEvent(MotionEvent ev){ + boolean intercepted = super.onInterceptTouchEvent(swapXY(ev)); + swapXY(ev); // return touch coordinates to original reference frame for any child views + return intercepted; + } + + @Override + public boolean onTouchEvent(MotionEvent ev) { + return super.onTouchEvent(swapXY(ev)); + } + +} \ No newline at end of file diff --git a/app/src/main/java/com/cpm/lorealbaautomation/reportGetterSetter/AppDashboardIncentive.java b/app/src/main/java/com/cpm/lorealbaautomation/reportGetterSetter/AppDashboardIncentive.java new file mode 100644 index 0000000..c1e5ec6 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/reportGetterSetter/AppDashboardIncentive.java @@ -0,0 +1,134 @@ +package com.cpm.lorealbaautomation.reportGetterSetter; + +import com.google.gson.annotations.SerializedName; + +public class AppDashboardIncentive { + @SerializedName("KPI") + private String kpi; + @SerializedName("CounterId") + private Integer counterId; + @SerializedName("UserId") + private String userId; + @SerializedName("ChannelName") + private String channelName; + @SerializedName("Tier") + private String tier; + @SerializedName("Offtake") + private Double offtake; + @SerializedName("LY_AVG_Sale") + private Double lYAVGSale; + @SerializedName("MJF_AVG_Sale") + private Double mJFAVGSale; + @SerializedName("SL_Incentive") + private Double sLIncentive; + @SerializedName("Flat_Incentive") + private Double flatIncentive; + @SerializedName("ToatlIncentive") + private Double toatlIncentive; + @SerializedName("MaximumIncentive") + private Double maximumIncentive; + @SerializedName("Per") + private Double per; + + public Double getPer() { + return per; + } + public void setPer(Double per) { + this.per = per; + } + public String getKpi() { + return kpi; + } + + public void setKpi(String kpi) { + this.kpi = kpi; + } + + public Integer getCounterId() { + return counterId; + } + + public void setCounterId(Integer counterId) { + this.counterId = counterId; + } + + public String getUserId() { + return userId; + } + + public void setUserId(String userId) { + this.userId = userId; + } + + public String getChannelName() { + return channelName; + } + + public void setChannelName(String channelName) { + this.channelName = channelName; + } + + public String getTier() { + return tier; + } + + public void setTier(String tier) { + this.tier = tier; + } + + public Double getOfftake() { + return offtake; + } + + public void setOfftake(Double offtake) { + this.offtake = offtake; + } + + public Double getLYAVGSale() { + return lYAVGSale; + } + + public void setLYAVGSale(Double lYAVGSale) { + this.lYAVGSale = lYAVGSale; + } + + public Double getMJFAVGSale() { + return mJFAVGSale; + } + + public void setMJFAVGSale(Double mJFAVGSale) { + this.mJFAVGSale = mJFAVGSale; + } + + public Double getSLIncentive() { + return sLIncentive; + } + + public void setSLIncentive(Double sLIncentive) { + this.sLIncentive = sLIncentive; + } + + public Double getFlatIncentive() { + return flatIncentive; + } + + public void setFlatIncentive(Double flatIncentive) { + this.flatIncentive = flatIncentive; + } + + public Double getToatlIncentive() { + return toatlIncentive; + } + + public void setToatlIncentive(Double toatlIncentive) { + this.toatlIncentive = toatlIncentive; + } + + public Double getMaximumIncentive() { + return maximumIncentive; + } + + public void setMaximumIncentive(Double maximumIncentive) { + this.maximumIncentive = maximumIncentive; + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/reportGetterSetter/AppDashboardLeaderBoard.java b/app/src/main/java/com/cpm/lorealbaautomation/reportGetterSetter/AppDashboardLeaderBoard.java new file mode 100644 index 0000000..05dd14b --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/reportGetterSetter/AppDashboardLeaderBoard.java @@ -0,0 +1,115 @@ +package com.cpm.lorealbaautomation.reportGetterSetter; + +import com.google.gson.annotations.SerializedName; + +public class AppDashboardLeaderBoard { + @SerializedName("CounterId") + private Integer counterId; + @SerializedName("CounterCode") + private String counterCode; + @SerializedName("CounterName") + private String counterName; + @SerializedName("KPI") + private String kpi; + @SerializedName("Graph") + private String graph; + @SerializedName("EmpId") + private Integer empId; + @SerializedName("EmpCode") + private String empCode; + @SerializedName("EmpName") + private String empName; + @SerializedName("Target") + private Double target; + @SerializedName("TotalSale") + private Integer totalSale; + @SerializedName("Per") + private Double per; + public String getKpi() { + return kpi; + } + public void setKpi(String kpi) { + this.kpi = kpi; + } + + public String getGraph() { + return graph; + } + + public void setGraph(String graph) { + this.graph = graph; + } + + public Integer getEmpId() { + return empId; + } + + public void setEmpId(Integer empId) { + this.empId = empId; + } + + public String getEmpCode() { + return empCode; + } + + public void setEmpCode(String empCode) { + this.empCode = empCode; + } + + public String getEmpName() { + return empName; + } + + public void setEmpName(String empName) { + this.empName = empName; + } + + public Double getTarget() { + return target; + } + + public void setTarget(Double target) { + this.target = target; + } + + public Integer getTotalSale() { + return totalSale; + } + + public void setTotalSale(Integer totalSale) { + this.totalSale = totalSale; + } + + public Double getPer() { + return per; + } + + public void setPer(Double per) { + this.per = per; + } + public Integer getCounterId() { + return counterId; + } + + public void setCounterId(Integer counterId) { + this.counterId = counterId; + } + + public String getCounterCode() { + return counterCode; + } + + public void setCounterCode(String counterCode) { + this.counterCode = counterCode; + } + + public String getCounterName() { + return counterName; + } + + public void setCounterName(String counterName) { + this.counterName = counterName; + } + + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/reportGetterSetter/ReportAttendanceDetail.java b/app/src/main/java/com/cpm/lorealbaautomation/reportGetterSetter/ReportAttendanceDetail.java new file mode 100644 index 0000000..94915f5 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/reportGetterSetter/ReportAttendanceDetail.java @@ -0,0 +1,53 @@ +package com.cpm.lorealbaautomation.reportGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class ReportAttendanceDetail { + + @SerializedName("BAName") + @Expose + private String bAName; + @SerializedName("BAUserId") + @Expose + private String bAUserId; + @SerializedName("AttDate") + @Expose + private String attDate; + @SerializedName("Attendance") + @Expose + private String attendance; + + public String getBAName() { + return bAName; + } + + public void setBAName(String bAName) { + this.bAName = bAName; + } + + public String getBAUserId() { + return bAUserId; + } + + public void setBAUserId(String bAUserId) { + this.bAUserId = bAUserId; + } + + public String getAttDate() { + return attDate; + } + + public void setAttDate(String attDate) { + this.attDate = attDate; + } + + public String getAttendance() { + return attendance; + } + + public void setAttendance(String attendance) { + this.attendance = attendance; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/reportGetterSetter/ReportAttendanceSummary.java b/app/src/main/java/com/cpm/lorealbaautomation/reportGetterSetter/ReportAttendanceSummary.java new file mode 100644 index 0000000..543ca1d --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/reportGetterSetter/ReportAttendanceSummary.java @@ -0,0 +1,43 @@ +package com.cpm.lorealbaautomation.reportGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class ReportAttendanceSummary { + + @SerializedName("AttendanceStatus") + @Expose + private String attendanceStatus; + @SerializedName("MTD") + @Expose + private Integer mTD; + + public Integer getLastMonth() { + return LastMonth; + } + + public void setLastMonth(Integer lastMonth) { + LastMonth = lastMonth; + } + + @SerializedName("LastMonth") + @Expose + private Integer LastMonth; + + public String getAttendanceStatus() { + return attendanceStatus; + } + + public void setAttendanceStatus(String attendanceStatus) { + this.attendanceStatus = attendanceStatus; + } + + public Integer getMTD() { + return mTD; + } + + public void setMTD(Integer mTD) { + this.mTD = mTD; + } + +} \ No newline at end of file diff --git a/app/src/main/java/com/cpm/lorealbaautomation/reportGetterSetter/ReportAvgBillValue.java b/app/src/main/java/com/cpm/lorealbaautomation/reportGetterSetter/ReportAvgBillValue.java new file mode 100644 index 0000000..b777a9a --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/reportGetterSetter/ReportAvgBillValue.java @@ -0,0 +1,77 @@ +package com.cpm.lorealbaautomation.reportGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class ReportAvgBillValue { + + @SerializedName("CounterId") + @Expose + private Integer counterId; + @SerializedName("KPI") + @Expose + private String kPI; + @SerializedName("MTDTg") + @Expose + private Double mTDTg; + @SerializedName("MTDAch") + @Expose + private Double mTDAch; + @SerializedName("AchPer") + @Expose + private Double achPer; + @SerializedName("Pending") + @Expose + private Double pending; + + public Integer getCounterId() { + return counterId; + } + + public void setCounterId(Integer counterId) { + this.counterId = counterId; + } + + public String getKPI() { + return kPI; + } + + public void setKPI(String kPI) { + this.kPI = kPI; + } + + public Double getMTDTg() { + return mTDTg; + } + + public void setMTDTg(Double mTDTg) { + this.mTDTg = mTDTg; + } + + public Double getMTDAch() { + return mTDAch; + } + + public void setMTDAch(Double mTDAch) { + this.mTDAch = mTDAch; + } + + public Double getAchPer() { + return achPer; + } + + public void setAchPer(Double achPer) { + this.achPer = achPer; + } + + public Double getPending() { + return pending; + } + + public void setPending(Double pending) { + this.pending = pending; + } + +} + + diff --git a/app/src/main/java/com/cpm/lorealbaautomation/reportGetterSetter/ReportAvgLinPerBill.java b/app/src/main/java/com/cpm/lorealbaautomation/reportGetterSetter/ReportAvgLinPerBill.java new file mode 100644 index 0000000..24bc801 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/reportGetterSetter/ReportAvgLinPerBill.java @@ -0,0 +1,75 @@ +package com.cpm.lorealbaautomation.reportGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class ReportAvgLinPerBill { + + @SerializedName("CounterId") + @Expose + private Integer counterId; + @SerializedName("KPI") + @Expose + private String kPI; + @SerializedName("MTDTg") + @Expose + private Integer mTDTg; + @SerializedName("MTDAch") + @Expose + private Double mTDAch; + @SerializedName("AchPer") + @Expose + private Double achPer; + @SerializedName("Pending") + @Expose + private Double pending; + + public Integer getCounterId() { + return counterId; + } + + public void setCounterId(Integer counterId) { + this.counterId = counterId; + } + + public String getKPI() { + return kPI; + } + + public void setKPI(String kPI) { + this.kPI = kPI; + } + + public Integer getMTDTg() { + return mTDTg; + } + + public void setMTDTg(Integer mTDTg) { + this.mTDTg = mTDTg; + } + + public Double getMTDAch() { + return mTDAch; + } + + public void setMTDAch(Double mTDAch) { + this.mTDAch = mTDAch; + } + + public Double getAchPer() { + return achPer; + } + + public void setAchPer(Double achPer) { + this.achPer = achPer; + } + + public Double getPending() { + return pending; + } + + public void setPending(Double pending) { + this.pending = pending; + } + +} \ No newline at end of file diff --git a/app/src/main/java/com/cpm/lorealbaautomation/reportGetterSetter/ReportAvgTransactionPerDay.java b/app/src/main/java/com/cpm/lorealbaautomation/reportGetterSetter/ReportAvgTransactionPerDay.java new file mode 100644 index 0000000..23696fe --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/reportGetterSetter/ReportAvgTransactionPerDay.java @@ -0,0 +1,75 @@ +package com.cpm.lorealbaautomation.reportGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class ReportAvgTransactionPerDay { + + @SerializedName("CounterId") + @Expose + private Integer counterId; + @SerializedName("KPI") + @Expose + private String kPI; + @SerializedName("MTDTg") + @Expose + private Integer mTDTg; + @SerializedName("MTDAch") + @Expose + private Integer mTDAch; + @SerializedName("AchPer") + @Expose + private Double achPer; + @SerializedName("Pending") + @Expose + private Double pending; + + public Integer getCounterId() { + return counterId; + } + + public void setCounterId(Integer counterId) { + this.counterId = counterId; + } + + public String getKPI() { + return kPI; + } + + public void setKPI(String kPI) { + this.kPI = kPI; + } + + public Integer getMTDTg() { + return mTDTg; + } + + public void setMTDTg(Integer mTDTg) { + this.mTDTg = mTDTg; + } + + public Integer getMTDAch() { + return mTDAch; + } + + public void setMTDAch(Integer mTDAch) { + this.mTDAch = mTDAch; + } + + public Double getAchPer() { + return achPer; + } + + public void setAchPer(Double achPer) { + this.achPer = achPer; + } + + public Double getPending() { + return pending; + } + + public void setPending(Double pending) { + this.pending = pending; + } + +} \ No newline at end of file diff --git a/app/src/main/java/com/cpm/lorealbaautomation/reportGetterSetter/ReportAvgUnitsPerBill.java b/app/src/main/java/com/cpm/lorealbaautomation/reportGetterSetter/ReportAvgUnitsPerBill.java new file mode 100644 index 0000000..7841c75 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/reportGetterSetter/ReportAvgUnitsPerBill.java @@ -0,0 +1,85 @@ +package com.cpm.lorealbaautomation.reportGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class ReportAvgUnitsPerBill { + + @SerializedName("CounterId") + @Expose + private Integer counterId; + @SerializedName("KPI") + @Expose + private String kPI; + @SerializedName("MTDTg") + @Expose + private Double mTDTg; + @SerializedName("MTDAch") + @Expose + private Double mTDAch; + @SerializedName("AchPer") + @Expose + private Double achPer; + @SerializedName("Pending") + @Expose + private Double pending; + + public Integer getCounterId() { + return counterId; + } + + public void setCounterId(Integer counterId) { + this.counterId = counterId; + } + + public String getKPI() { + return kPI; + } + + public void setKPI(String kPI) { + this.kPI = kPI; + } + + public Double getMTDTg() { + return mTDTg; + } + + public void setMTDTg(Double mTDTg) { + this.mTDTg = mTDTg; + } + + public Double getMTDAch() { + return mTDAch; + } + + public void setMTDAch(Double mTDAch) { + this.mTDAch = mTDAch; + } + + public Double getAchPer() { + return achPer; + } + + public void setAchPer(Double achPer) { + this.achPer = achPer; + } + + public Double getPending() { + return pending; + } + + public void setPending(Double pending) { + this.pending = pending; + } + + public int getRunRate() { + return runRate; + } + + public void setRunRate(int runRate) { + this.runRate = runRate; + } + + int runRate=0; + +} \ No newline at end of file diff --git a/app/src/main/java/com/cpm/lorealbaautomation/reportGetterSetter/ReportBAAvailability.java b/app/src/main/java/com/cpm/lorealbaautomation/reportGetterSetter/ReportBAAvailability.java new file mode 100644 index 0000000..95b48d9 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/reportGetterSetter/ReportBAAvailability.java @@ -0,0 +1,53 @@ +package com.cpm.lorealbaautomation.reportGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class ReportBAAvailability { + + @SerializedName("Date") + @Expose + private String date; + @SerializedName("BudgetedMandays") + @Expose + private Integer budgetedMandays; + @SerializedName("AchievedMandays") + @Expose + private Integer achievedMandays; + @SerializedName("TotalTime") + @Expose + private Integer totalTime; + + public String getDate() { + return date; + } + + public void setDate(String date) { + this.date = date; + } + + public Integer getBudgetedMandays() { + return budgetedMandays; + } + + public void setBudgetedMandays(Integer budgetedMandays) { + this.budgetedMandays = budgetedMandays; + } + + public Integer getAchievedMandays() { + return achievedMandays; + } + + public void setAchievedMandays(Integer achievedMandays) { + this.achievedMandays = achievedMandays; + } + + public Integer getTotalTime() { + return totalTime; + } + + public void setTotalTime(Integer totalTime) { + this.totalTime = totalTime; + } + +} \ No newline at end of file diff --git a/app/src/main/java/com/cpm/lorealbaautomation/reportGetterSetter/ReportInwardStockSummary.java b/app/src/main/java/com/cpm/lorealbaautomation/reportGetterSetter/ReportInwardStockSummary.java new file mode 100644 index 0000000..ef7b4a9 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/reportGetterSetter/ReportInwardStockSummary.java @@ -0,0 +1,98 @@ +package com.cpm.lorealbaautomation.reportGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class ReportInwardStockSummary { + + @SerializedName("InvoiceNo") + @Expose + private String invoiceNo; + @SerializedName("InvoiceDate") + @Expose + private String invoiceDate; + @SerializedName("InvoiceType") + @Expose + private String invoiceType; + @SerializedName("Source") + @Expose + private String source; + @SerializedName("InvoiceValue") + @Expose + private Double invoiceValue; + @SerializedName("TotalLine") + @Expose + private Integer totalLine; + @SerializedName("ConfirmLine") + @Expose + private Integer confirmLine; + @SerializedName("PendingLine") + @Expose + private Integer pendingLine; + + public String getInvoiceNo() { + return invoiceNo; + } + + public void setInvoiceNo(String invoiceNo) { + this.invoiceNo = invoiceNo; + } + + public String getInvoiceDate() { + return invoiceDate; + } + + public void setInvoiceDate(String invoiceDate) { + this.invoiceDate = invoiceDate; + } + + public String getInvoiceType() { + return invoiceType; + } + + public void setInvoiceType(String invoiceType) { + this.invoiceType = invoiceType; + } + + public String getSource() { + return source; + } + + public void setSource(String source) { + this.source = source; + } + + public Double getInvoiceValue() { + return invoiceValue; + } + + public void setInvoiceValue(Double invoiceValue) { + this.invoiceValue = invoiceValue; + } + + public Integer getTotalLine() { + return totalLine; + } + + public void setTotalLine(Integer totalLine) { + this.totalLine = totalLine; + } + + public Integer getConfirmLine() { + return confirmLine; + } + + public void setConfirmLine(Integer confirmLine) { + this.confirmLine = confirmLine; + } + + public Integer getPendingLine() { + return pendingLine; + } + + public void setPendingLine(Integer pendingLine) { + this.pendingLine = pendingLine; + } + +} + diff --git a/app/src/main/java/com/cpm/lorealbaautomation/reportGetterSetter/ReportSalesValue.java b/app/src/main/java/com/cpm/lorealbaautomation/reportGetterSetter/ReportSalesValue.java new file mode 100644 index 0000000..327d427 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/reportGetterSetter/ReportSalesValue.java @@ -0,0 +1,86 @@ +package com.cpm.lorealbaautomation.reportGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class ReportSalesValue { + + @SerializedName("CounterId") + @Expose + private Integer counterId; + @SerializedName("KPI") + @Expose + private String kPI; + @SerializedName("MTDTg") + @Expose + private Double mTDTg; + @SerializedName("MTDAch") + @Expose + private Double mTDAch; + @SerializedName("AchPer") + @Expose + private Double achPer; + @SerializedName("Pending") + @Expose + private Double pending; + @SerializedName("RunRate") + @Expose + private Double runRate; + + public Integer getCounterId() { + return counterId; + } + + public void setCounterId(Integer counterId) { + this.counterId = counterId; + } + + public String getKPI() { + return kPI; + } + + public void setKPI(String kPI) { + this.kPI = kPI; + } + + public Double getMTDTg() { + return mTDTg; + } + + public void setMTDTg(Double mTDTg) { + this.mTDTg = mTDTg; + } + + public Double getMTDAch() { + return mTDAch; + } + + public void setMTDAch(Double mTDAch) { + this.mTDAch = mTDAch; + } + + public Double getAchPer() { + return achPer; + } + + public void setAchPer(Double achPer) { + this.achPer = achPer; + } + + public Double getPending() { + return pending; + } + + public void setPending(Double pending) { + this.pending = pending; + } + + public Double getRunRate() { + return runRate; + } + + public void setRunRate(Double runRate) { + this.runRate = runRate; + } + +} \ No newline at end of file diff --git a/app/src/main/java/com/cpm/lorealbaautomation/reportGetterSetter/ReportSellingPrice.java b/app/src/main/java/com/cpm/lorealbaautomation/reportGetterSetter/ReportSellingPrice.java new file mode 100644 index 0000000..49e8d75 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/reportGetterSetter/ReportSellingPrice.java @@ -0,0 +1,76 @@ +package com.cpm.lorealbaautomation.reportGetterSetter; + + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class ReportSellingPrice { + + @SerializedName("CounterId") + @Expose + private Integer counterId; + @SerializedName("KPI") + @Expose + private String kPI; + @SerializedName("MTDTg") + @Expose + private Double mTDTg; + @SerializedName("MTDAch") + @Expose + private Double mTDAch; + @SerializedName("AchPer") + @Expose + private Double achPer; + @SerializedName("Pending") + @Expose + private Double pending; + + public Integer getCounterId() { + return counterId; + } + + public void setCounterId(Integer counterId) { + this.counterId = counterId; + } + + public String getKPI() { + return kPI; + } + + public void setKPI(String kPI) { + this.kPI = kPI; + } + + public Double getMTDTg() { + return mTDTg; + } + + public void setMTDTg(Double mTDTg) { + this.mTDTg = mTDTg; + } + + public Double getMTDAch() { + return mTDAch; + } + + public void setMTDAch(Double mTDAch) { + this.mTDAch = mTDAch; + } + + public Double getAchPer() { + return achPer; + } + + public void setAchPer(Double achPer) { + this.achPer = achPer; + } + + public Double getPending() { + return pending; + } + + public void setPending(Double pending) { + this.pending = pending; + } + +} \ No newline at end of file diff --git a/app/src/main/java/com/cpm/lorealbaautomation/reportGetterSetter/ReportTop10Value.java b/app/src/main/java/com/cpm/lorealbaautomation/reportGetterSetter/ReportTop10Value.java new file mode 100644 index 0000000..feacf04 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/reportGetterSetter/ReportTop10Value.java @@ -0,0 +1,118 @@ +package com.cpm.lorealbaautomation.reportGetterSetter; + + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class ReportTop10Value { + + @SerializedName("CounterId") + @Expose + private Integer counterId; + @SerializedName("BrandName") + @Expose + private String brandName; + @SerializedName("SubBrandName") + @Expose + private String subBrandName; + @SerializedName("ReferenceName") + @Expose + private String referenceName; + @SerializedName("EanCode") + @Expose + private String eanCode; + @SerializedName("ProductName") + @Expose + private String productName; + @SerializedName("MTDValue") + @Expose + private Double mTDValue; + @SerializedName("AvgPerDayValue") + @Expose + private Double avgPerDayValue; + + public int getDrawble_code() { + return drawble_code; + } + + public void setDrawble_code(int drawble_code) { + this.drawble_code = drawble_code; + } + + int drawble_code; + + public Integer getCounterId() { + return counterId; + } + + public void setCounterId(Integer counterId) { + this.counterId = counterId; + } + + public String getBrandName() { + return brandName; + } + + public void setBrandName(String brandName) { + this.brandName = brandName; + } + + public String getSubBrandName() { + return subBrandName; + } + + public void setSubBrandName(String subBrandName) { + this.subBrandName = subBrandName; + } + + public String getReferenceName() { + return referenceName; + } + + public void setReferenceName(String referenceName) { + this.referenceName = referenceName; + } + + public String getEanCode() { + return eanCode; + } + + public void setEanCode(String eanCode) { + this.eanCode = eanCode; + } + + public String getProductName() { + return productName; + } + + public void setProductName(String productName) { + this.productName = productName; + } + + public Double getMTDValue() { + return mTDValue; + } + + public void setMTDValue(Double mTDValue) { + this.mTDValue = mTDValue; + } + + public Double getAvgPerDayValue() { + return avgPerDayValue; + } + + public void setAvgPerDayValue(Double avgPerDayValue) { + this.avgPerDayValue = avgPerDayValue; + } + + public int getColor_code() { + return color_code; + } + + public void setColor_code(int color_code) { + this.color_code = color_code; + } + + public int color_code=000; + +} \ No newline at end of file diff --git a/app/src/main/java/com/cpm/lorealbaautomation/reportGetterSetter/ReportTop10Volume.java b/app/src/main/java/com/cpm/lorealbaautomation/reportGetterSetter/ReportTop10Volume.java new file mode 100644 index 0000000..76b7a3d --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/reportGetterSetter/ReportTop10Volume.java @@ -0,0 +1,97 @@ +package com.cpm.lorealbaautomation.reportGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class ReportTop10Volume { + + @SerializedName("CounterId") + @Expose + private Integer counterId; + @SerializedName("BrandName") + @Expose + private String brandName; + @SerializedName("SubBrandName") + @Expose + private String subBrandName; + @SerializedName("ReferenceName") + @Expose + private String referenceName; + @SerializedName("EanCode") + @Expose + private String eanCode; + @SerializedName("ProductName") + @Expose + private String productName; + @SerializedName("MTDVolume") + @Expose + private Integer mTDVolume; + @SerializedName("AvgPerDayVolume") + @Expose + private Integer avgPerDayVolume; + + public Integer getCounterId() { + return counterId; + } + + public void setCounterId(Integer counterId) { + this.counterId = counterId; + } + + public String getBrandName() { + return brandName; + } + + public void setBrandName(String brandName) { + this.brandName = brandName; + } + + public String getSubBrandName() { + return subBrandName; + } + + public void setSubBrandName(String subBrandName) { + this.subBrandName = subBrandName; + } + + public String getReferenceName() { + return referenceName; + } + + public void setReferenceName(String referenceName) { + this.referenceName = referenceName; + } + + public String getEanCode() { + return eanCode; + } + + public void setEanCode(String eanCode) { + this.eanCode = eanCode; + } + + public String getProductName() { + return productName; + } + + public void setProductName(String productName) { + this.productName = productName; + } + + public Integer getMTDVolume() { + return mTDVolume; + } + + public void setMTDVolume(Integer mTDVolume) { + this.mTDVolume = mTDVolume; + } + + public Integer getAvgPerDayVolume() { + return avgPerDayVolume; + } + + public void setAvgPerDayVolume(Integer avgPerDayVolume) { + this.avgPerDayVolume = avgPerDayVolume; + } + +} \ No newline at end of file diff --git a/app/src/main/java/com/cpm/lorealbaautomation/reportGetterSetter/SkinGeniusUrl.java b/app/src/main/java/com/cpm/lorealbaautomation/reportGetterSetter/SkinGeniusUrl.java new file mode 100644 index 0000000..5ba220e --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/reportGetterSetter/SkinGeniusUrl.java @@ -0,0 +1,20 @@ +package com.cpm.lorealbaautomation.reportGetterSetter; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class SkinGeniusUrl { + @SerializedName("SkinGeniusUrl") + @Expose + private String skinGeniusUrl; + public String getSkinGeniusUrl() { + return skinGeniusUrl; + } + @SerializedName("maybellineUrl") + @Expose + private String maybellineUrl; + public String getMaybellineUrl() { + return maybellineUrl; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/reports/DamagedStockHistory.java b/app/src/main/java/com/cpm/lorealbaautomation/reports/DamagedStockHistory.java new file mode 100644 index 0000000..ba02701 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/reports/DamagedStockHistory.java @@ -0,0 +1,319 @@ +package com.cpm.lorealbaautomation.reports; + +import static com.cpm.lorealbaautomation.constant.CommonFunctions.getFilters; + +import android.annotation.SuppressLint; +import android.app.ProgressDialog; +import android.content.Context; +import android.content.SharedPreferences; +import android.os.Bundle; + +import androidx.annotation.NonNull; +import androidx.appcompat.app.AppCompatActivity; +import androidx.cardview.widget.CardView; +import androidx.recyclerview.widget.GridLayoutManager; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; +import androidx.appcompat.widget.Toolbar; + +import android.view.LayoutInflater; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; +import android.widget.TextView; + +import com.google.gson.Gson; +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.adapter.SubAxeValueAdapter; +import com.cpm.lorealbaautomation.constant.CommonFunctions; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.gsonGetterSetter.ReportDamageStockHistory; +import com.cpm.lorealbaautomation.gsonGetterSetter.ResponseResult; +import com.cpm.lorealbaautomation.retrofit.PostApi; + +import org.json.JSONException; +import org.json.JSONObject; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.TimeUnit; + +import okhttp3.MediaType; +import okhttp3.OkHttpClient; +import okhttp3.RequestBody; +import okhttp3.ResponseBody; +import retrofit2.Call; +import retrofit2.Callback; +import retrofit2.Response; +import retrofit2.Retrofit; +import retrofit2.converter.gson.GsonConverterFactory; + +public class DamagedStockHistory extends AppCompatActivity { + public ArrayList reportsList = new ArrayList<>(); + String counter_Id, visit_date, username; + private SharedPreferences preferences; + RecyclerView recycle_reports; + ProgressDialog loading; + Lorealba_Database db; + Context context; + + @SuppressLint("SetTextI18n") + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_reports_damaged_stock); + context = this; + db = new Lorealba_Database(context); + db.open(); + Toolbar toolbar = findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + Objects.requireNonNull(getSupportActionBar()).setHomeButtonEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + iduserinterface(); + String couter_code = preferences.getString(CommonString.KEY_COUNTER_CODE, ""); + TextView txt_counter_code = (TextView) findViewById(R.id.txt_counter_code); + txt_counter_code.setText("Counter Code - " + couter_code + " / Id - " + counter_Id); + } + + private void iduserinterface() { + preferences = PrefHelper.getPrefs(context); + counter_Id = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + username = preferences.getString(CommonString.KEY_USERNAME, ""); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + recycle_reports = (RecyclerView) findViewById(R.id.recycle_reports); + setTitle("Reports Damaged Stock - " + visit_date); + db = new Lorealba_Database(context); + db.open(); + + validatefilterui(); + call_adapter(context); + if (CommonFunctions.checkNetIsAvailable(context)) { + download_report(context); + } + } + + @Override + protected void onResume() { + super.onResume(); + db.open(); + } + + private void call_adapter(Context context) { + db.open(); + reportsList = db.getdamagestockhistory(counter_Id); + if (!reportsList.isEmpty()) { + recycle_reports.setAdapter(new ReportsAdapter(context, reportsList)); + recycle_reports.setLayoutManager(new LinearLayoutManager(context)); + } + } + + private static class ReportsAdapter extends RecyclerView.Adapter { + LayoutInflater inflator; + List data; + + public ReportsAdapter(Context context, List data) { + inflator = LayoutInflater.from(context); + this.data = data; + } + + @NonNull + @Override + public ReportsAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) { + + View view = inflator.inflate(R.layout.row_report_damagedstock, parent, false); + return new ReportsAdapter.MyViewHolder(view); + } + + @SuppressLint("SetTextI18n") + @Override + public void onBindViewHolder(final ReportsAdapter.MyViewHolder holder, final int position) { + final ReportDamageStockHistory current = data.get(position); + + holder.d_verifydate.setText(current.getVerifyDate()); + holder.d_verifydate.setId(position); + + holder.dverify.setText(current.getVerify()); + holder.dverify.setId(position); + + holder.ddamgeQTY.setText("" + current.getDamageQty()); + holder.ddamgeQTY.setId(position); + + holder.dmrp.setText("" + current.getMrp()); + holder.dmrp.setId(position); + + holder.dean_code.setText(current.getEanCode()); + holder.dean_code.setId(position); + + holder.dproduct_name.setText(current.getProductName()); + holder.dproduct_name.setId(position); + + holder.dproduct_code.setText(current.getProductCode()); + holder.dproduct_code.setId(position); + holder.dvisit_date.setText(current.getVisitDate()); + holder.dvisit_date.setId(position); + } + + @Override + public int getItemCount() { + return data.size(); + } + + class MyViewHolder extends RecyclerView.ViewHolder { + TextView d_verifydate, dverify, ddamgeQTY, dmrp, dean_code, dproduct_name, dproduct_code, dvisit_date; + CardView sale_card; + + public MyViewHolder(View itemView) { + super(itemView); + d_verifydate = (TextView) itemView.findViewById(R.id.d_verifydate); + dverify = (TextView) itemView.findViewById(R.id.dverify); + ddamgeQTY = (TextView) itemView.findViewById(R.id.ddamgeQTY); + dmrp = (TextView) itemView.findViewById(R.id.dmrp); + dean_code = (TextView) itemView.findViewById(R.id.dean_code); + dproduct_name = (TextView) itemView.findViewById(R.id.dproduct_name); + dproduct_code = (TextView) itemView.findViewById(R.id.dproduct_code); + dvisit_date = (TextView) itemView.findViewById(R.id.dvisit_date); + sale_card = (CardView) itemView.findViewById(R.id.sale_card); + } + } + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + if (id == android.R.id.home) { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + DamagedStockHistory.this.finish(); + + } + + + return super.onOptionsItemSelected(item); + } + + @Override + public void onBackPressed() { + super.onBackPressed(); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + DamagedStockHistory.this.finish(); + + } + + + private void download_report(final Context context) { + try { + String download_key = "Report_DamageStockHistory"; + JSONObject jsonObject = new JSONObject(); + jsonObject.put("Downloadtype", download_key); + jsonObject.put("Username", username); + jsonObject.put("Param1", counter_Id); + jsonObject.put("Param2", ""); + String jsonString = jsonObject.toString(); + try { + + loading = ProgressDialog.show(context, "Processing", "Please wait...", false, true); + OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, + TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build(); + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsonString); + Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build(); + PostApi api = adapter.create(PostApi.class); + Call call = api.getTabjournePlan(jsonData); + call.enqueue(new Callback() { + @Override + public void onResponse(@NonNull Call call, @NonNull Response response) { + ResponseBody responseBody = response.body(); + String data = null; + if (responseBody != null && response.isSuccessful()) { + try { + loading.dismiss(); + assert response.body() != null; + data = response.body().string(); + data = data.substring(1, data.length() - 1).replace("\\", ""); + if (data.equalsIgnoreCase(CommonString.KEY_FAILURE)) { + if (loading != null && loading.isShowing()) { + loading.dismiss(); + } + ///caling adapter + call_adapter(context); + } else if (!data.contains("No Data")) { + if (loading != null && loading.isShowing()) { + loading.dismiss(); + } + ResponseResult reportsaleDatewiseObject = new Gson().fromJson(data, ResponseResult.class); + if (reportsaleDatewiseObject != null) { + db.open(); + if (db.insertdamagestockhistory(reportsaleDatewiseObject)) { + call_adapter(context); + } + } + } else { + loading.dismiss(); + if (loading != null && loading.isShowing()) { + loading.dismiss(); + } + db.open(); + db.delete_table_data("Report_DamageStockHistory"); + ///caling adapter + call_adapter(context); + } + + } catch (Exception e) { + loading.dismiss(); + if (loading != null && loading.isShowing()) { + loading.dismiss(); + } + ///caling adapter + call_adapter(context); + } + } else { + loading.dismiss(); + if (loading != null && loading.isShowing()) { + loading.dismiss(); + } + ///caling adapter + call_adapter(context); + } + } + + @Override + public void onFailure(@NonNull Call call, @NonNull Throwable t) { + loading.dismiss(); + if (loading != null && loading.isShowing()) { + loading.dismiss(); + } + ///caling adapter + call_adapter(context); + } + }); + + } catch (Exception e) { + loading.dismiss(); + if (loading != null && loading.isShowing()) { + loading.dismiss(); + } + ///caling adapter + call_adapter(context); + + } + + } catch (JSONException e) { + loading.dismiss(); + if (loading != null && loading.isShowing()) { + loading.dismiss(); + } + ///caling adapter + call_adapter(context); + } + } + + @SuppressLint("NotifyDataSetChanged") + private void validatefilterui() { + RecyclerView rec_subaxe = (RecyclerView) findViewById(R.id.rec_subaxe); + rec_subaxe.setLayoutManager(new GridLayoutManager(context, 3)); + rec_subaxe.setAdapter(new SubAxeValueAdapter(context, getFilters(), "Sub Axe", true, false, (filterText, placeHolder) -> { + })); + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/reports/DashbordOffTakeReportActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/reports/DashbordOffTakeReportActivity.java new file mode 100644 index 0000000..788db68 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/reports/DashbordOffTakeReportActivity.java @@ -0,0 +1,391 @@ +package com.cpm.lorealbaautomation.reports; + +import static com.cpm.lorealbaautomation.constant.CommonFunctions.getFilters; + +import android.annotation.SuppressLint; +import android.app.Dialog; +import android.app.ProgressDialog; +import android.content.Context; +import android.content.SharedPreferences; +import android.graphics.Color; +import android.graphics.drawable.ColorDrawable; +import android.os.Bundle; +import android.view.LayoutInflater; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; +import android.view.Window; +import android.widget.LinearLayout; +import android.widget.TextView; + +import androidx.annotation.NonNull; +import androidx.appcompat.app.AppCompatActivity; +import androidx.appcompat.widget.Toolbar; +import androidx.core.content.ContextCompat; +import androidx.recyclerview.widget.GridLayoutManager; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; + +import com.google.android.material.appbar.AppBarLayout; +import com.google.gson.Gson; +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.adapter.SubAxeValueAdapter; +import com.cpm.lorealbaautomation.constant.CommonFunctions; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.databinding.CounterGrowthDetailBinding; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.gsonGetterSetter.ResponseResult; +import com.cpm.lorealbaautomation.reports.offtakemodels.SalesGrowthSubAxe; +import com.cpm.lorealbaautomation.retrofit.PostApi; + +import org.json.JSONException; +import org.json.JSONObject; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.TimeUnit; + +import okhttp3.MediaType; +import okhttp3.OkHttpClient; +import okhttp3.RequestBody; +import okhttp3.ResponseBody; +import retrofit2.Call; +import retrofit2.Callback; +import retrofit2.Response; +import retrofit2.Retrofit; +import retrofit2.converter.gson.GsonConverterFactory; + +public class DashbordOffTakeReportActivity extends AppCompatActivity { + ArrayList salesGrowthSubAxes = new ArrayList<>(); + RecyclerView recyclSalesGrowthCounter, recyclSalesGrowthDetails; + String counter_Id, visit_date, username, default_type = "Axe"; + LinearLayout rlSalesGrowthCounter, rlSalesGSubAxe; + TextView tvKPICounter, tvKPISubAxe, tvParamCode, + tvParamName; + AppBarLayout appBarLayout; + private SharedPreferences preferences; + Lorealba_Database db; + Context context; + + @SuppressLint("SetTextI18n") + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_dash_offtake); + context = this; + db = new Lorealba_Database(context); + db.open(); + Toolbar toolbar = findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + Objects.requireNonNull(getSupportActionBar()).setHomeButtonEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + iduserinterface(); + String couter_code = preferences.getString(CommonString.KEY_COUNTER_CODE, ""); + TextView txt_counter_code = (TextView) findViewById(R.id.txt_counter_code); + txt_counter_code.setText("Counter Code - " + couter_code + " / Id - " + counter_Id); + counterSalesGrowth(); + OffTakeTesterUsageDetails(default_type, null); + validatefilterui(); + } + + private void iduserinterface() { + preferences = PrefHelper.getPrefs(context); + counter_Id = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + username = preferences.getString(CommonString.KEY_USERNAME, ""); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + //////// + recyclSalesGrowthCounter = findViewById(R.id.recyclSalesGrowthCounter); + rlSalesGrowthCounter = findViewById(R.id.rlSalesGrowthCounter); + tvKPICounter = findViewById(R.id.tvKPICounter); + recyclSalesGrowthDetails = findViewById(R.id.recyclSalesGSubAxe); + rlSalesGSubAxe = findViewById(R.id.rlSalesGSubAxe); + tvKPISubAxe = findViewById(R.id.tvKPISubAxe); + tvParamCode = (TextView) findViewById(R.id.tvParamCode); + tvParamName = (TextView) findViewById(R.id.tvParamName); + appBarLayout = findViewById(R.id.appBarLayout); + setTitle(getIntent().getStringExtra(CommonString.Brand) + " Report " + " - " + visit_date); + db = new Lorealba_Database(context); + db.open(); + } + + private class OffTakeAdapter extends RecyclerView.Adapter { + LayoutInflater inflator; + List data; + String param; + boolean details; + + public OffTakeAdapter(Context context, List data, String param, boolean details) { + inflator = LayoutInflater.from(context); + this.details = details; + this.param = param; + this.data = data; + } + + @NonNull + @Override + public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) { + View view = inflator.inflate(R.layout.row_offtake, parent, false); + return new MyViewHolder(view); + } + + @SuppressLint({"SetTextI18n", "DefaultLocale"}) + @Override + public void onBindViewHolder(@NonNull final MyViewHolder holder, final int position) { + final SalesGrowthSubAxe current = data.get(position); + if (details) { + holder.tvParamName.setText(CommonFunctions.capitalizeFirstLetter(current.getParamName())); + holder.tvParamCode.setText(current.getParamCode()); + holder.rlRowSalesGSubAxe.setVisibility(View.VISIBLE); + holder.rlRSalesGrowthCounter.setVisibility(View.GONE); + holder.rlRSalesGrowthCounter.setId(position); + holder.rlRowSalesGSubAxe.setId(position); + holder.tvParamName.setId(position); + holder.tvParamCode.setId(position); + } else { + holder.rlRSalesGrowthCounter.setVisibility(View.VISIBLE); + holder.rlRowSalesGSubAxe.setVisibility(View.GONE); + holder.rlRSalesGrowthCounter.setId(position); + holder.rlRowSalesGSubAxe.setId(position); + } + + holder.rlParent.setOnLongClickListener(v -> { + new DetailsDailog((AppCompatActivity) context, current, param, details).show(); + return false; + }); + + setText(details ? holder.tvLSTYSameMoSaleSubAxe : holder.tvLSTYSameMoSale, position, String.format("%.0f", current.getLastYearSameMonthSale()), false); + setText(details ? holder.tvL3M_AvgSaleSubAxe : holder.tvL3M_AvgSale, position, String.format("%.0f", current.getL3MAvgSale()), false); + setText(details ? holder.tvCurrentMonthSaleSubAxe : holder.tvCurrentMonthSale, position, String.format("%.0f", current.getCurrentMonthSale()), false); + setText(details ? holder.tvGrowthoverLSTYearPerSubAxe : holder.tvGrowthoverLSTYearPer, position, current.getGrowthOverLastYearPer().toString() + "%", true); + setText(details ? holder.tvGrowthoverL3MPerSubAxe : holder.tvGrowthoverL3MPer, position, current.getGrowthOverL3MPer().toString() + "%", true); + setText(details ? holder.tvClsStkLSTMonthSubAxe : holder.tvClsStkLSTMonth, position, String.format("%.0f", current.getClosingStockLastMonth()), false); + setText(details ? holder.tvNODSubAxe : holder.tvNOD, position, current.getNod().toString() + "%", false); + } + + @Override + public int getItemCount() { + return data.size(); + } + + class MyViewHolder extends RecyclerView.ViewHolder { + LinearLayout rlRSalesGrowthCounter, rlRowSalesGSubAxe, rlParent; + TextView tvLSTYSameMoSale, tvL3M_AvgSale, tvCurrentMonthSale, tvGrowthoverLSTYearPer, tvGrowthoverL3MPer, tvClsStkLSTMonth, tvNOD, + tvLSTYSameMoSaleSubAxe, tvL3M_AvgSaleSubAxe, tvCurrentMonthSaleSubAxe, + tvGrowthoverLSTYearPerSubAxe, tvGrowthoverL3MPerSubAxe, tvClsStkLSTMonthSubAxe, tvNODSubAxe, + tvParamCode, tvParamName; + + public MyViewHolder(View itemView) { + super(itemView); + rlParent = (LinearLayout) itemView.findViewById(R.id.rlParent); + rlRSalesGrowthCounter = (LinearLayout) itemView.findViewById(R.id.rlRSalesGrowthCounter); + tvLSTYSameMoSale = (TextView) itemView.findViewById(R.id.tvLSTYSameMoSale); + tvL3M_AvgSale = (TextView) itemView.findViewById(R.id.tvL3M_AvgSale); + tvCurrentMonthSale = (TextView) itemView.findViewById(R.id.tvCurrentMonthSale); + tvGrowthoverLSTYearPer = (TextView) itemView.findViewById(R.id.tvGrowthoverLSTYearPer); + tvGrowthoverL3MPer = (TextView) itemView.findViewById(R.id.tvGrowthoverL3MPer); + tvClsStkLSTMonth = (TextView) itemView.findViewById(R.id.tvClsStkLSTMonth); + tvNOD = (TextView) itemView.findViewById(R.id.tvNOD); + rlRowSalesGSubAxe = (LinearLayout) itemView.findViewById(R.id.rlRowSalesGSubAxe); + tvParamCode = (TextView) itemView.findViewById(R.id.tvParamCode); + tvParamName = (TextView) itemView.findViewById(R.id.tvParamName); + tvLSTYSameMoSaleSubAxe = (TextView) itemView.findViewById(R.id.tvLSTYSameMoSaleSubAxe); + tvL3M_AvgSaleSubAxe = (TextView) itemView.findViewById(R.id.tvL3M_AvgSaleSubAxe); + tvCurrentMonthSaleSubAxe = (TextView) itemView.findViewById(R.id.tvCurrentMonthSaleSubAxe); + tvGrowthoverLSTYearPerSubAxe = (TextView) itemView.findViewById(R.id.tvGrowthoverLSTYearPerSubAxe); + tvGrowthoverL3MPerSubAxe = (TextView) itemView.findViewById(R.id.tvGrowthoverL3MPerSubAxe); + tvClsStkLSTMonthSubAxe = (TextView) itemView.findViewById(R.id.tvClsStkLSTMonthSubAxe); + tvNODSubAxe = (TextView) itemView.findViewById(R.id.tvNODSubAxe); + } + } + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + if (id == android.R.id.home) { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + this.finish(); + } + return super.onOptionsItemSelected(item); + } + + @Override + public void onBackPressed() { + super.onBackPressed(); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + this.finish(); + } + + private void counterSalesGrowth() { + db.open(); + //Counter Growth + salesGrowthSubAxes = db.getSalesGrowthReport(counter_Id, false); + if (!salesGrowthSubAxes.isEmpty()) { + recyclSalesGrowthCounter.setAdapter(new OffTakeAdapter(context, salesGrowthSubAxes, null, false)); + recyclSalesGrowthCounter.setLayoutManager(new LinearLayoutManager(context)); + rlSalesGrowthCounter.setVisibility(View.VISIBLE); + } + } + + @SuppressLint("DefaultLocale") + private void setText(TextView tv, int pos, String value, boolean checkValue) { + if (checkValue && (value.substring(0, 1).contains("-") || value.substring(0, 1).contains("0"))) { + tv.setTextColor(ContextCompat.getColor(context, R.color.light_red)); + } else { + tv.setTextColor(ContextCompat.getColor(context, R.color.black)); + } + tv.setText(value); + tv.setId(pos); + } + + private class DetailsDailog extends Dialog { + private final SalesGrowthSubAxe object; + private final boolean detail; + String param; + + public DetailsDailog(AppCompatActivity activity, SalesGrowthSubAxe object, String param, boolean details) { + super(activity); + this.param = param; + this.detail = details; + this.object = object; + } + + @SuppressLint({"SetTextI18n", "DefaultLocale"}) + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + requestWindowFeature(Window.FEATURE_NO_TITLE); + com.cpm.lorealbaautomation.databinding.CounterGrowthDetailBinding binding = CounterGrowthDetailBinding.inflate(getLayoutInflater()); + setContentView(binding.getRoot()); + Objects.requireNonNull(getWindow()).setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); + binding.imgClose.setOnClickListener(v -> dismiss()); + + if (detail && param != null) { + assert binding.rlParamCode != null; + binding.rlParamCode.setVisibility(View.VISIBLE); + assert binding.rlParamName != null; + binding.rlParamName.setVisibility(View.VISIBLE); + + assert binding.tvParamCodePlaceHolder != null; + binding.tvParamCodePlaceHolder.setText(param + " Code"); + assert binding.tvParamCode != null; + binding.tvParamCode.setText(object.getParamCode()); + assert binding.tvParamNamePlaceHolder != null; + binding.tvParamNamePlaceHolder.setText(param + " Name"); + assert binding.tvParamName != null; + binding.tvParamName.setText(object.getParamName()); + } + + if ((object.getGrowthOverLastYearPer().toString().substring(0, 1).contains("-") || object.getGrowthOverLastYearPer().toString().substring(0, 1).contains("0"))) { + binding.tvGrowthOverLastYearPer.setTextColor(ContextCompat.getColor(getContext(), R.color.light_red)); + } else + binding.tvGrowthOverLastYearPer.setTextColor(ContextCompat.getColor(getContext(), R.color.black)); + if ((object.getGrowthOverL3MPer().toString().substring(0, 1).contains("-") || object.getGrowthOverL3MPer().toString().substring(0, 1).contains("0"))) { + binding.TvGrowthOverL3MPer.setTextColor(ContextCompat.getColor(getContext(), R.color.light_red)); + } else + binding.TvGrowthOverL3MPer.setTextColor(ContextCompat.getColor(getContext(), R.color.black)); + + binding.tvLastYearSameMonthSale.setText(getString(R.string.Rs) + " " + String.format("%.0f", object.getLastYearSameMonthSale())); + binding.tvL3MAvgSale.setText(getString(R.string.Rs) + " " + String.format("%.0f", object.getL3MAvgSale())); + binding.tvCurrentMonthSale.setText(getString(R.string.Rs) + " " + String.format("%.0f", object.getCurrentMonthSale())); + binding.tvGrowthOverLastYearPer.setText(object.getGrowthOverLastYearPer().toString() + "%"); + binding.TvGrowthOverL3MPer.setText(object.getGrowthOverL3MPer().toString() + "%"); + binding.tvClosingStockLastMonth.setText(String.format("%.0f", object.getClosingStockLastMonth())); + binding.tvNOD.setText(object.getNod().toString() + "%"); + } + + @SuppressLint("SetTextI18n") + @Override + protected void onStart() { + super.onStart(); + setCancelable(true); + } + } + + @SuppressLint("NotifyDataSetChanged") + private void validatefilterui() { + RecyclerView rec_subaxe = (RecyclerView) findViewById(R.id.rec_subaxe); + rec_subaxe.setLayoutManager(new GridLayoutManager(context, 3)); + rec_subaxe.setAdapter(new SubAxeValueAdapter(context, getFilters(), default_type, false, true, (filterText, placeHolder) -> download_report(context, filterText))); + } + + private void download_report(final Context context, String param) { + ProgressDialog loading = null; + try { + String cParam = param; + cParam = cParam.replaceAll(" ", "") + "Name"; + JSONObject jsonObject = new JSONObject(); + jsonObject.put("Downloadtype", "Report_SalesGrowth_CounterDetail"); + jsonObject.put("Username", username); + jsonObject.put("Param1", counter_Id); + jsonObject.put("Param2", cParam); + String jsonString = jsonObject.toString(); + try { + loading = ProgressDialog.show(context, "Processing", "Please wait...", false, true); + OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build(); + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsonString); + Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build(); + PostApi api = adapter.create(PostApi.class); + Call call = api.getTabjournePlan(jsonData); + ProgressDialog finalLoading = loading; + call.enqueue(new Callback() { + @Override + public void onResponse(@NonNull Call call, @NonNull Response response) { + ResponseBody responseBody = response.body(); + String data = null; + if (responseBody != null && response.isSuccessful()) { + try { + finalLoading.dismiss(); + assert response.body() != null; + data = response.body().string(); + data = data.substring(1, data.length() - 1).replace("\\", ""); + if (data.contains("No Data") || data.equalsIgnoreCase(CommonString.KEY_FAILURE) || data.contains("Failure;Cannot find table 0.")) { + OffTakeTesterUsageDetails(param, finalLoading); + } else { + ResponseResult salesGrowthSubAxe = new Gson().fromJson(data, ResponseResult.class); + if (salesGrowthSubAxe != null) { + db.open(); + db.insertSalesGrowthCounterSubAxe(salesGrowthSubAxe); + OffTakeTesterUsageDetails(param, finalLoading); + } + } + } catch (Exception e) { + OffTakeTesterUsageDetails(param, finalLoading); + } + } else { + OffTakeTesterUsageDetails(param, finalLoading); + } + } + + @Override + public void onFailure(@NonNull Call call, @NonNull Throwable t) { + OffTakeTesterUsageDetails(param, finalLoading); + } + }); + } catch (Exception e) { + OffTakeTesterUsageDetails(param, null); + } + + } catch (JSONException e) { + OffTakeTesterUsageDetails(param, null); + } + } + + @SuppressLint("SetTextI18n") + private void OffTakeTesterUsageDetails(String param, ProgressDialog dialog) { + salesGrowthSubAxes = db.getSalesGrowthReport(counter_Id, true); + if (!salesGrowthSubAxes.isEmpty()) { + tvParamCode.setText(param + " Code"); + tvParamName.setText(param + " Name"); + recyclSalesGrowthDetails.setAdapter(new OffTakeAdapter(context, salesGrowthSubAxes, param, true)); + recyclSalesGrowthDetails.setLayoutManager(new LinearLayoutManager(context)); + rlSalesGSubAxe.setVisibility(View.VISIBLE); + if (dialog != null && dialog.isShowing()) { + dialog.dismiss(); + } + } + } +} \ No newline at end of file diff --git a/app/src/main/java/com/cpm/lorealbaautomation/reports/KPITrackerActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/reports/KPITrackerActivity.java new file mode 100644 index 0000000..2f389be --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/reports/KPITrackerActivity.java @@ -0,0 +1,156 @@ +package com.cpm.lorealbaautomation.reports; + +import static com.cpm.lorealbaautomation.constant.CommonFunctions.getFilters; + +import android.annotation.SuppressLint; +import android.content.Context; +import android.content.SharedPreferences; +import android.os.Bundle; +import android.view.LayoutInflater; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; +import android.widget.TextView; + +import androidx.annotation.NonNull; +import androidx.appcompat.app.AppCompatActivity; +import androidx.appcompat.widget.Toolbar; +import androidx.recyclerview.widget.GridLayoutManager; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; + +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.adapter.SubAxeValueAdapter; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.reportGetterSetter.ReportAvgUnitsPerBill; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +public class KPITrackerActivity extends AppCompatActivity { + ArrayList dashReportList = new ArrayList<>(); + String counter_Id, visit_date, username; + private SharedPreferences preferences; + RecyclerView recycle_reports; + Lorealba_Database db; + Context context; + + @SuppressLint("SetTextI18n") + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_kpi_tracker); + context = this; + db = new Lorealba_Database(context); + db.open(); + Toolbar toolbar = findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + Objects.requireNonNull(getSupportActionBar()).setHomeButtonEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + iduserinterface(); + validatefilterui(); + } + + @SuppressLint("SetTextI18n") + private void iduserinterface() { + preferences = PrefHelper.getPrefs(context); + counter_Id = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + username = preferences.getString(CommonString.KEY_USERNAME, ""); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + recycle_reports = (RecyclerView) findViewById(R.id.recycle_reports); + setTitle(getIntent().getStringExtra(CommonString.Brand) + " Report " + " - " + visit_date); + String couter_code = preferences.getString(CommonString.KEY_COUNTER_CODE, ""); + TextView txt_counter_code = (TextView) findViewById(R.id.txt_counter_code); + txt_counter_code.setText("Counter Code - " + couter_code + " / Id - " + counter_Id); + db = new Lorealba_Database(context); + db.open(); + dashReportList = db.getDashboardReport(counter_Id); + if (!dashReportList.isEmpty()) { + recycle_reports.setAdapter(new KPITrackerAdapter(context, dashReportList)); + recycle_reports.setLayoutManager(new LinearLayoutManager(context)); + } + } + + private static class KPITrackerAdapter extends RecyclerView.Adapter { + LayoutInflater inflator; + List data; + + public KPITrackerAdapter(Context context, List data) { + inflator = LayoutInflater.from(context); + this.data = data; + } + + @NonNull + @Override + public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) { + View view = inflator.inflate(R.layout.row_kpi_tracker, parent, false); + return new MyViewHolder(view); + } + + @SuppressLint({"SetTextI18n", "DefaultLocale"}) + @Override + public void onBindViewHolder(@NonNull final MyViewHolder holder, final int position) { + final ReportAvgUnitsPerBill current = data.get(position); + //holder.tvRunRate.setText("KPI - (Run Rate - " + current.getRunRate() + " )"); + holder.tvKpiName.setText(current.getKPI()); + holder.tvKpiName.setId(position); + holder.tvMTDACH.setText(String.format("%.0f", current.getMTDAch())); + holder.tvMTDACH.setId(position); + holder.tvAchPer.setText(String.format("%.0f", current.getAchPer()) + "%"); + holder.tvAchPer.setId(position); + holder.tvMTDTGT.setText(String.format("%.0f", current.getMTDTg())); + holder.tvMTDTGT.setId(position); + holder.tvPendingPer.setText(String.format("%.0f", current.getPending()) + "%"); + holder.tvPendingPer.setId(position); + } + + @Override + public int getItemCount() { + return data.size(); + } + + private static class MyViewHolder extends RecyclerView.ViewHolder { + TextView tvKpiName, tvMTDACH, tvAchPer, tvMTDTGT, tvPendingPer; + + + public MyViewHolder(View itemView) { + super(itemView); + tvKpiName = (TextView) itemView.findViewById(R.id.tvKpiName); + tvMTDACH = (TextView) itemView.findViewById(R.id.tvMTDACH); + tvAchPer = (TextView) itemView.findViewById(R.id.tvAchPer); + tvMTDTGT = (TextView) itemView.findViewById(R.id.tvMTDTGT); + tvPendingPer = (TextView) itemView.findViewById(R.id.tvPendingPer); + } + } + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + if (id == android.R.id.home) { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + KPITrackerActivity.this.finish(); + } + return super.onOptionsItemSelected(item); + } + + @Override + public void onBackPressed() { + super.onBackPressed(); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + KPITrackerActivity.this.finish(); + } + + @SuppressLint("NotifyDataSetChanged") + private void validatefilterui() { + RecyclerView rec_subaxe = (RecyclerView) findViewById(R.id.rec_subaxe); + rec_subaxe.setLayoutManager(new GridLayoutManager(context, 3)); + rec_subaxe.setAdapter(new SubAxeValueAdapter(context, getFilters(), "Sub Axe", true,false, (filterText, placeHolder) -> { + + })); + } +} \ No newline at end of file diff --git a/app/src/main/java/com/cpm/lorealbaautomation/reports/MeSaleReport.java b/app/src/main/java/com/cpm/lorealbaautomation/reports/MeSaleReport.java new file mode 100644 index 0000000..d91ea73 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/reports/MeSaleReport.java @@ -0,0 +1,152 @@ +package com.cpm.lorealbaautomation.reports; + +import androidx.annotation.NonNull; +import androidx.appcompat.app.AppCompatActivity; +import androidx.appcompat.widget.Toolbar; +import androidx.cardview.widget.CardView; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; + +import android.annotation.SuppressLint; +import android.content.Context; +import android.content.SharedPreferences; +import android.os.Bundle; +import android.view.LayoutInflater; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; +import android.widget.TextView; + +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.gsonGetterSetter.ReportMESale; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +public class MeSaleReport extends AppCompatActivity { + public ArrayList meSaleReportArrayList = new ArrayList<>(); + String counter_Id, visit_date, username, report_name = ""; + private SharedPreferences preferences; + RecyclerView recycle_reports; + Lorealba_Database db; + Context context; + + @SuppressLint("SetTextI18n") + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_me_sale_report); + context = this; + db = new Lorealba_Database(context); + db.open(); + Toolbar toolbar = findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + Objects.requireNonNull(getSupportActionBar()).setHomeButtonEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + iduserinterface(); + + String couter_code = preferences.getString(CommonString.KEY_COUNTER_CODE, ""); + TextView txt_counter_code = (TextView) findViewById(R.id.txt_counter_code); + txt_counter_code.setText("Counter Code - " + couter_code + " / Id - " + counter_Id); + } + + private void iduserinterface() { + preferences = PrefHelper.getPrefs(context); + counter_Id = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + username = preferences.getString(CommonString.KEY_USERNAME, ""); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + recycle_reports = (RecyclerView) findViewById(R.id.recycle_reports); + report_name = getIntent().getStringExtra(CommonString.Brand); + setTitle("ME_Sale Report " + " - " + visit_date); + db = new Lorealba_Database(context); + db.open(); + meSaleReportArrayList = db.getreportMeSale(); + + if (meSaleReportArrayList.size()>0){ + recycle_reports.setAdapter(new ReportsAdapter(context, meSaleReportArrayList)); + recycle_reports.setLayoutManager(new LinearLayoutManager(context)); + } + } + + public class ReportsAdapter extends RecyclerView.Adapter { + LayoutInflater inflator; + List data; + + public ReportsAdapter(Context context, List data) { + inflator = LayoutInflater.from(context); + this.data = data; + } + + @NonNull + @Override + public ReportsAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) { + View view = inflator.inflate(R.layout.row_reports_me_sale, parent, false); + return new MyViewHolder(view); + } + + @SuppressLint({"SetTextI18n", "DefaultLocale"}) + @Override + public void onBindViewHolder(final ReportsAdapter.MyViewHolder holder, final int position) { + final ReportMESale current = data.get(position); + + + + holder.date_txt.setText(current.getVisitDate()); + holder.date_txt.setId(position); + + holder.contercodeTV.setText(current.getCounterCode()); + holder.contercodeTV.setId(position); + + holder.conternameTV.setText(current.getCounterName()); + holder.conternameTV.setId(position); + + holder.totalsaleTV.setText(String.format("%.2f", current.getTotalsale())); + holder.totalsaleTV.setId(position); + + holder.totalunitsaleTV.setText(String.valueOf(current.getTotalunitsale())); + holder.totalunitsaleTV.setId(position); + } + + @Override + public int getItemCount() { + return data.size(); + } + + class MyViewHolder extends RecyclerView.ViewHolder { + TextView date_txt, contercodeTV, conternameTV,totalunitsaleTV,totalsaleTV; + CardView sale_card; + + public MyViewHolder(View itemView) { + super(itemView); + date_txt = (TextView) itemView.findViewById(R.id.date_txt); + contercodeTV = (TextView) itemView.findViewById(R.id.contercodeTV); + conternameTV = (TextView) itemView.findViewById(R.id.conternameTV); + totalunitsaleTV = (TextView) itemView.findViewById(R.id.totalunitsaleTV); + totalsaleTV = (TextView) itemView.findViewById(R.id.totalsaleTV); + sale_card = (CardView) itemView.findViewById(R.id.sale_card); + } + } + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + if (id == android.R.id.home) { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + MeSaleReport.this.finish(); + } + return super.onOptionsItemSelected(item); + } + + @Override + public void onBackPressed() { + super.onBackPressed(); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + MeSaleReport.this.finish(); + } +} \ No newline at end of file diff --git a/app/src/main/java/com/cpm/lorealbaautomation/reports/MyLibraryActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/reports/MyLibraryActivity.java new file mode 100644 index 0000000..8b6a853 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/reports/MyLibraryActivity.java @@ -0,0 +1,257 @@ +package com.cpm.lorealbaautomation.reports; + +import android.annotation.SuppressLint; +import android.content.ActivityNotFoundException; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.graphics.Bitmap; +import android.net.Uri; +import android.os.Build; +import android.os.Bundle; + +import androidx.annotation.RequiresApi; +import androidx.appcompat.app.AppCompatActivity; +import androidx.appcompat.widget.Toolbar; +import android.view.MenuItem; +import android.view.View; +import android.webkit.DownloadListener; +import android.webkit.ValueCallback; +import android.webkit.WebChromeClient; +import android.webkit.WebSettings; +import android.webkit.WebView; +import android.webkit.WebViewClient; +import android.widget.LinearLayout; +import android.widget.Toast; + +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.constant.CommonFunctions; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.delegates.PrefHelper; + +import im.delight.android.webview.AdvancedWebView; + +public class MyLibraryActivity extends AppCompatActivity implements AdvancedWebView.Listener { + String counter_id, visit_date, username, intent_value, skingeniusurl = ""; + private SharedPreferences preferences; + private Lorealba_Database db; + LinearLayout rl_no_internet; + private AdvancedWebView webView; + String url; + Context context; + private ValueCallback mUploadMessage; + public ValueCallback uploadMessage; + public static final int REQUEST_SELECT_FILE = 100; + private final static int FILECHOOSER_RESULTCODE = 1; + WebSettings mWebSettings; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_my_library); + context = this; + db = new Lorealba_Database(context); + db.open(); + Toolbar toolbar = findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + getSupportActionBar().setHomeButtonEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + preferences = PrefHelper.getPrefs(context); + counter_id = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + username = preferences.getString(CommonString.KEY_USERNAME, ""); + skingeniusurl = preferences.getString(CommonString.KEY_SKIN_GENIUS_URL, ""); + webView = findViewById(R.id.webview); + rl_no_internet = (LinearLayout) findViewById(R.id.rl_no_internet); + intent_value = getIntent().getStringExtra(CommonString.KEY_BODY); + if (intent_value != null) { + if (!intent_value.equals("") && intent_value.equals("1")) { + setTitle("Training - " + username); + url = CommonString.KEY_MY_KNOWLEDGE_URL + counter_id; + } else { + setTitle("Skin Genius - " + username); + url = skingeniusurl; + } + } + + webView.setListener(this, this); + call_upload_photos(); + } + + @Override + protected void onPause() { + webView.onPause(); + // ... + super.onPause(); + } + + @Override + protected void onResume() { + super.onResume(); + webView.onResume(); + // ... + } + + @Override + public void onPageStarted(String url, Bitmap favicon) { + + } + + @Override + public void onPageFinished(String url) { + + } + + @Override + public void onPageError(int errorCode, String description, String failingUrl) { + + } + + @Override + public void onDownloadRequested(String url, String suggestedFilename, String mimeType, long contentLength, String contentDisposition, String userAgent) { + + } + + @Override + public void onExternalPageRequest(String url) { + + } + + private class MyWebViewClient extends WebViewClient { + @Override + public boolean shouldOverrideUrlLoading(WebView view, String url) { + view.loadUrl(url); + return true; + } + + @Override + public void onPageFinished(WebView view, String url) { + super.onPageFinished(view, url); + view.clearCache(true); + } + + @Override + public void onPageStarted(WebView view, String url, Bitmap favicon) { + super.onPageStarted(view, url, favicon); + } + } + + @Override + public void onBackPressed() { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + this.finish(); + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + if (id == android.R.id.home) { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + this.finish(); + } + return super.onOptionsItemSelected(item); + } + + + @SuppressLint("SetJavaScriptEnabled") + private void call_upload_photos() { + webView.setWebViewClient(new MyWebViewClient()); + webView.getSettings().setJavaScriptEnabled(true); + //webView.getSettings().setAppCacheEnabled(false); + webView.clearCache(true); + webView.getSettings().setSupportZoom(true); + webView.getSettings().setJavaScriptEnabled(true); + webView.getSettings().setUseWideViewPort(true); + webView.getSettings().setAllowFileAccess(true); + webView.getSettings().setAllowFileAccess(true); + webView.getSettings().setAllowContentAccess(true); + webView.setLongClickable(true); + mWebSettings = webView.getSettings(); + + webView.setWebChromeClient(new WebChromeClient() { + // For 3.0+ Devices (Start) + // onActivityResult attached before constructor + private void openFileChooser(ValueCallback uploadMsg, String acceptType) { + mUploadMessage = uploadMsg; + Intent i = new Intent(Intent.ACTION_GET_CONTENT); + i.addCategory(Intent.CATEGORY_OPENABLE); + i.setType("image/*"); + startActivityForResult(Intent.createChooser(i, "File Browser"), FILECHOOSER_RESULTCODE); + } + + + // For Lollipop 5.0+ Devices + @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) + public boolean onShowFileChooser(WebView mWebView, ValueCallback filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) { + if (uploadMessage != null) { + uploadMessage.onReceiveValue(null); + uploadMessage = null; + } + + uploadMessage = filePathCallback; + Intent intent = fileChooserParams.createIntent(); + try { + startActivityForResult(intent, REQUEST_SELECT_FILE); + } catch (ActivityNotFoundException e) { + uploadMessage = null; + Toast.makeText(context, "Cannot Open File Chooser", Toast.LENGTH_LONG).show(); + return false; + } + + return true; + } + + }); + + webView.setDownloadListener(new DownloadListener() { + public void onDownloadStart(String url, String userAgent, + String contentDisposition, String mimetype, + long contentLength) { + Intent i = new Intent(Intent.ACTION_VIEW); + i.setData(Uri.parse(url)); + startActivity(i); + } + }); + + if (CommonFunctions.checkNetIsAvailable(context)) { + //load notice board url + rl_no_internet.setVisibility(View.GONE); + webView.setVisibility(View.VISIBLE); + webView.setWebViewClient(new MyWebViewClient()); + webView.getSettings().setJavaScriptEnabled(true); + webView.getSettings().setBuiltInZoomControls(true); + if (url != null && !url.equals("")) { + webView.loadUrl(url); + } + } else { + rl_no_internet.setVisibility(View.VISIBLE); + webView.setVisibility(View.GONE); + } + + } + + @Override + public void onActivityResult(int requestCode, int resultCode, Intent intent) { + super.onActivityResult(requestCode, resultCode, intent); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { + if (requestCode == REQUEST_SELECT_FILE) { + if (uploadMessage == null) + return; + uploadMessage.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, intent)); + uploadMessage = null; + } + } else if (requestCode == FILECHOOSER_RESULTCODE) { + if (null == mUploadMessage) + return; + // Use MainActivity.RESULT_OK if you're implementing WebView inside Fragment + // Use RESULT_OK only if you're implementing WebView inside an Activity + Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData(); + mUploadMessage.onReceiveValue(result); + mUploadMessage = null; + } else + Toast.makeText(context, "Failed to Upload Image", Toast.LENGTH_LONG).show(); + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/reports/PerformanceHistoryActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/reports/PerformanceHistoryActivity.java new file mode 100644 index 0000000..5173d4f --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/reports/PerformanceHistoryActivity.java @@ -0,0 +1,109 @@ +package com.cpm.lorealbaautomation.reports; + +import androidx.appcompat.app.AppCompatActivity; +import androidx.appcompat.widget.Toolbar; + +import android.content.Context; +import android.content.SharedPreferences; +import android.graphics.Bitmap; +import android.os.Bundle; +import android.view.MenuItem; +import android.view.View; +import android.webkit.WebSettings; +import android.webkit.WebView; +import android.webkit.WebViewClient; +import android.widget.TextView; + +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.delegates.PrefHelper; + +public class PerformanceHistoryActivity extends AppCompatActivity { + private SharedPreferences preferences; + private SharedPreferences.Editor editor = null; + String counter_Id, visit_date, username = ""; + Lorealba_Database db; + Context context; + private WebView webView; + String url; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_performance_history); + context = this; + db = new Lorealba_Database(context); + db.open(); + iduserinterface(); + + String couter_code = preferences.getString(CommonString.KEY_COUNTER_CODE, ""); + TextView txt_counter_code = (TextView) findViewById(R.id.txt_counter_code); + txt_counter_code.setText("Counter Code - " + couter_code + " / Id - " + counter_Id); + + Toolbar toolbar = findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + getSupportActionBar().setHomeButtonEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + webView = findViewById(R.id.webview); + url = "https://dle.parinaam.in/Content/lba/perf.html"; + + webView.setWebViewClient(new MyWebViewClient()); + webView.getSettings().setUseWideViewPort(true); + + WebSettings webSettings = webView.getSettings(); + webSettings.setJavaScriptEnabled(true); + + webView.loadUrl(url); + } + + private void iduserinterface() { + preferences = PrefHelper.getPrefs(context); + editor = preferences.edit(); + counter_Id = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + username = preferences.getString(CommonString.KEY_USERNAME, ""); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + + setTitle("Performance History " + " - " + visit_date); + + } + + private class MyWebViewClient extends WebViewClient { + @Override + public boolean shouldOverrideUrlLoading(WebView view, String url) { + view.loadUrl("url"); + return true; + } + + @Override + public void onPageFinished(WebView view, String url) { + webView.setVisibility(View.VISIBLE); + super.onPageFinished(view, url); + view.clearCache(true); + } + + @Override + public void onPageStarted(WebView view, String url, Bitmap favicon) { + super.onPageStarted(view, url, favicon); + } + + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + if (id == android.R.id.home) { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + PerformanceHistoryActivity.this.finish(); + } + return super.onOptionsItemSelected(item); + } + + @Override + public void onBackPressed() { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + PerformanceHistoryActivity.this.finish(); + } + +} \ No newline at end of file diff --git a/app/src/main/java/com/cpm/lorealbaautomation/reports/ReportAttendanceSummaryActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/reports/ReportAttendanceSummaryActivity.java new file mode 100644 index 0000000..4feafee --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/reports/ReportAttendanceSummaryActivity.java @@ -0,0 +1,197 @@ +package com.cpm.lorealbaautomation.reports; + +import android.content.Context; +import android.content.SharedPreferences; + +import androidx.appcompat.app.AppCompatActivity; +import android.os.Bundle; +import androidx.cardview.widget.CardView; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; +import androidx.appcompat.widget.Toolbar; +import android.view.LayoutInflater; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; +import android.widget.TextView; + +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.reportGetterSetter.ReportAttendanceDetail; +import com.cpm.lorealbaautomation.reportGetterSetter.ReportAttendanceSummary; + +import java.util.ArrayList; +import java.util.List; + +public class ReportAttendanceSummaryActivity extends AppCompatActivity { + public ArrayList reportatt_summaryList = new ArrayList<>(); + ArrayList report_att_detailList = new ArrayList<>(); + String counter_Id, visit_date, username; + private SharedPreferences preferences; private SharedPreferences.Editor editor = null; + RecyclerView recycle_reports_att_summary, recycle_reports_details; + Lorealba_Database db; + Context context; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_report_attendance_summary); + context = this; + db = new Lorealba_Database(context); + db.open(); + Toolbar toolbar = findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + getSupportActionBar().setHomeButtonEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + iduserinterface(); + + String couter_code = preferences.getString(CommonString.KEY_COUNTER_CODE, ""); + TextView txt_counter_code = (TextView) findViewById(R.id.txt_counter_code); + txt_counter_code.setText("Counter Code - " + couter_code + " / Id - " + counter_Id); + } + + private void iduserinterface() { + preferences = PrefHelper.getPrefs(context); + editor = preferences.edit(); + counter_Id = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + username = preferences.getString(CommonString.KEY_USERNAME, ""); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + recycle_reports_att_summary = (RecyclerView) findViewById(R.id.recycle_reports_att_summary); + recycle_reports_details = (RecyclerView) findViewById(R.id.recycle_reports_details); + + setTitle("Attendance Reports - " + visit_date); + db = new Lorealba_Database(context); + db.open(); + reportatt_summaryList = db.getAttendanceSummary(); + if (reportatt_summaryList.size() > 0) { + recycle_reports_att_summary.setAdapter(new ReportsAttSummaryAdapter(context, reportatt_summaryList)); + recycle_reports_att_summary.setLayoutManager(new LinearLayoutManager(context)); + } + db.open(); + report_att_detailList = db.getAttendanceDetails(); + if (report_att_detailList.size() > 0) { + recycle_reports_details.setAdapter(new ReportsAttDetailsAdapter(context, report_att_detailList)); + recycle_reports_details.setLayoutManager(new LinearLayoutManager(context)); + } + } + + public class ReportsAttSummaryAdapter extends RecyclerView.Adapter { + private LayoutInflater inflator; + List data; + + public ReportsAttSummaryAdapter(Context context, List data) { + inflator = LayoutInflater.from(context); + this.data = data; + } + + @Override + public ReportsAttSummaryAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int i) { + View view = inflator.inflate(R.layout.row_report_att_summary, parent, false); + return new ReportsAttSummaryAdapter.MyViewHolder(view); + } + + @Override + public void onBindViewHolder(final ReportsAttSummaryAdapter.MyViewHolder holder, final int position) { + final ReportAttendanceSummary current = data.get(position); + + holder.att_status.setText("" + current.getAttendanceStatus()); + holder.att_status.setId(position); + + holder.last_month_txt.setText("" + current.getLastMonth().toString()); + holder.last_month_txt.setId(position); + + holder.mtd_txt.setText("" + current.getMTD().toString()); + holder.mtd_txt.setId(position); + } + + @Override + public int getItemCount() { + return data.size(); + } + + class MyViewHolder extends RecyclerView.ViewHolder { + TextView att_status, last_month_txt, mtd_txt; + CardView sale_card; + + public MyViewHolder(View itemView) { + super(itemView); + att_status = (TextView) itemView.findViewById(R.id.att_status); + last_month_txt = (TextView) itemView.findViewById(R.id.last_month_txt); + mtd_txt = (TextView) itemView.findViewById(R.id.mtd_txt); + sale_card = (CardView) itemView.findViewById(R.id.sale_card); + } + } + } + + public class ReportsAttDetailsAdapter extends RecyclerView.Adapter { + private LayoutInflater inflator; + List data; + + public ReportsAttDetailsAdapter(Context context, List data) { + inflator = LayoutInflater.from(context); + this.data = data; + } + + @Override + public ReportsAttDetailsAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int i) { + View view = inflator.inflate(R.layout.row_report_att_details, parent, false); + return new ReportsAttDetailsAdapter.MyViewHolder(view); + } + + @Override + public void onBindViewHolder(final MyViewHolder holder, final int position) { + final ReportAttendanceDetail current = data.get(position); + holder.att_ba_name_txt.setText("" + current.getBAName()); + holder.att_ba_name_txt.setId(position); + + holder.att_date.setText("" + current.getAttDate()); + holder.att_date.setId(position); + + holder.attendance_txt.setText("" + current.getAttendance()); + holder.attendance_txt.setId(position); + } + + @Override + public int getItemCount() { + return data.size(); + } + + class MyViewHolder extends RecyclerView.ViewHolder { + TextView att_ba_name_txt, att_date, attendance_txt; + CardView sale_card; + + public MyViewHolder(View itemView) { + super(itemView); + att_ba_name_txt = (TextView) itemView.findViewById(R.id.att_ba_name_txt); + att_date = (TextView) itemView.findViewById(R.id.att_date); + attendance_txt = (TextView) itemView.findViewById(R.id.attendance_txt); + sale_card = (CardView) itemView.findViewById(R.id.sale_card); + } + } + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + if (id == android.R.id.home) { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + ReportAttendanceSummaryActivity.this.finish(); + + } + + + return super.onOptionsItemSelected(item); + } + + @Override + public void onBackPressed() { + super.onBackPressed(); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + ReportAttendanceSummaryActivity.this.finish(); + + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/reports/ReportBaAvailability.java b/app/src/main/java/com/cpm/lorealbaautomation/reports/ReportBaAvailability.java new file mode 100644 index 0000000..8a99e83 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/reports/ReportBaAvailability.java @@ -0,0 +1,155 @@ +package com.cpm.lorealbaautomation.reports; + +import android.annotation.SuppressLint; +import android.content.Context; +import android.content.SharedPreferences; + +import androidx.annotation.NonNull; +import androidx.appcompat.app.AppCompatActivity; + +import android.os.Bundle; + +import androidx.cardview.widget.CardView; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; +import androidx.appcompat.widget.Toolbar; + +import android.view.LayoutInflater; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; +import android.widget.TextView; + +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.reportGetterSetter.ReportBAAvailability; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +public class ReportBaAvailability extends AppCompatActivity { + public ArrayList reportsList = new ArrayList<>(); + String counter_Id, visit_date, username, report_name = ""; + private SharedPreferences preferences; + private SharedPreferences.Editor editor = null; + RecyclerView recycle_reports; + Lorealba_Database db; + Context context; + + @SuppressLint("SetTextI18n") + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_report_ba_availability); + context = this; + db = new Lorealba_Database(context); + db.open(); + Toolbar toolbar = findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + Objects.requireNonNull(getSupportActionBar()).setHomeButtonEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + iduserinterface(); + + String couter_code = preferences.getString(CommonString.KEY_COUNTER_CODE, ""); + TextView txt_counter_code = (TextView) findViewById(R.id.txt_counter_code); + txt_counter_code.setText("Counter Code - " + couter_code + " / Id - " + counter_Id); + } + + private void iduserinterface() { + preferences = PrefHelper.getPrefs(context); + editor = preferences.edit(); + counter_Id = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + username = preferences.getString(CommonString.KEY_USERNAME, ""); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + recycle_reports = (RecyclerView) findViewById(R.id.recycle_reports); + report_name = getIntent().getStringExtra(CommonString.Brand); + setTitle("Reports " + report_name + " - " + visit_date); + db = new Lorealba_Database(context); + db.open(); + reportsList = db.getreport_ba_availability(); + if (!reportsList.isEmpty()) { + recycle_reports.setAdapter(new ReportsAdapter(context, reportsList)); + recycle_reports.setLayoutManager(new LinearLayoutManager(context)); + } + } + + private class ReportsAdapter extends RecyclerView.Adapter { + LayoutInflater inflator; + List data; + + public ReportsAdapter(Context context, List data) { + inflator = LayoutInflater.from(context); + this.data = data; + + } + + @NonNull + @Override + public ReportsAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) { + View view = inflator.inflate(R.layout.row_reports_ba_avialability, parent, false); + return new ReportsAdapter.MyViewHolder(view); + } + + @SuppressLint("SetTextI18n") + @Override + public void onBindViewHolder(final ReportsAdapter.MyViewHolder holder, final int position) { + final ReportBAAvailability current = data.get(position); + + holder.date_txt.setText(current.getDate()); + holder.date_txt.setId(position); + + holder.AchievedMandays.setText("" + current.getAchievedMandays()); + holder.AchievedMandays.setId(position); + + holder.BudgetedMandays.setText(current.getBudgetedMandays().toString()); + holder.BudgetedMandays.setId(position); + + holder.TotalTime.setText(current.getTotalTime().toString()); + holder.TotalTime.setId(position); + } + + @Override + public int getItemCount() { + return data.size(); + } + + class MyViewHolder extends RecyclerView.ViewHolder { + TextView date_txt, BudgetedMandays, AchievedMandays, TotalTime; + CardView sale_card; + + public MyViewHolder(View itemView) { + super(itemView); + date_txt = (TextView) itemView.findViewById(R.id.date_txt); + BudgetedMandays = (TextView) itemView.findViewById(R.id.BudgetedMandays); + AchievedMandays = (TextView) itemView.findViewById(R.id.AchievedMandays); + TotalTime = (TextView) itemView.findViewById(R.id.TotalTime); + sale_card = (CardView) itemView.findViewById(R.id.sale_card); + } + } + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + if (id == android.R.id.home) { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + ReportBaAvailability.this.finish(); + + } + + + return super.onOptionsItemSelected(item); + } + + @Override + public void onBackPressed() { + super.onBackPressed(); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + ReportBaAvailability.this.finish(); + + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/reports/ReportConsumerProductWiseActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/reports/ReportConsumerProductWiseActivity.java new file mode 100644 index 0000000..e6f1505 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/reports/ReportConsumerProductWiseActivity.java @@ -0,0 +1,171 @@ +package com.cpm.lorealbaautomation.reports; + +import static com.cpm.lorealbaautomation.constant.CommonFunctions.getFilters; + +import android.annotation.SuppressLint; +import android.content.Context; +import android.content.SharedPreferences; +import android.os.Bundle; + +import androidx.annotation.NonNull; +import androidx.appcompat.app.AppCompatActivity; +import androidx.cardview.widget.CardView; +import androidx.recyclerview.widget.GridLayoutManager; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; +import androidx.appcompat.widget.Toolbar; + +import android.view.LayoutInflater; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; +import android.widget.TextView; + +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.adapter.SubAxeValueAdapter; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.gsonGetterSetter.ReportSalesConsumerProductwise; +import com.cpm.lorealbaautomation.gsonGetterSetter.ReportSalesConsumerWise; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +public class ReportConsumerProductWiseActivity extends AppCompatActivity { + public ArrayList reportsList = new ArrayList<>(); + ReportSalesConsumerWise consumerObject = new ReportSalesConsumerWise(); + String counter_Id, visit_date, username, report_name = ""; + private SharedPreferences preferences; + RecyclerView recycle_reports; + TextView consumer_name; + Context context; + + @SuppressLint("SetTextI18n") + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_reports_consumerproductwise); + context = this; + Toolbar toolbar = findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + Objects.requireNonNull(getSupportActionBar()).setHomeButtonEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + iduserinterface(); + + String couter_code = preferences.getString(CommonString.KEY_COUNTER_CODE, ""); + TextView txt_counter_code = (TextView) findViewById(R.id.txt_counter_code); + txt_counter_code.setText("Counter Code - " + couter_code + " / Id - " + counter_Id); + } + + @SuppressLint("SetTextI18n") + private void iduserinterface() { + preferences = PrefHelper.getPrefs(context); + counter_Id = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + username = preferences.getString(CommonString.KEY_USERNAME, ""); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + recycle_reports = (RecyclerView) findViewById(R.id.recycle_reports); + consumer_name = (TextView) findViewById(R.id.consumer_name); + report_name = getIntent().getStringExtra(CommonString.Brand); + setTitle("Reports Consumer Product Wise - " + visit_date); + + if (getIntent().getSerializableExtra(CommonString.TAG_OBJECT) != null) { + reportsList = (ArrayList) getIntent().getSerializableExtra(CommonString.TAG_OBJECT); + } + if (getIntent().getSerializableExtra(CommonString.KEY_Consumer_Object) != null) { + consumerObject = (ReportSalesConsumerWise) getIntent().getSerializableExtra(CommonString.KEY_Consumer_Object); + if (consumerObject != null && consumerObject.getConsumerName() != null) { + consumer_name.setVisibility(View.VISIBLE); + consumer_name.setText("Consumer Name : " + consumerObject.getConsumerName() + " - " + consumerObject.getMobileNumber()); + } + } else { + consumer_name.setVisibility(View.GONE); + } + + if (!reportsList.isEmpty()) { + validatefilterui(); + recycle_reports.setAdapter(new ReportsAdapter(context, reportsList)); + recycle_reports.setLayoutManager(new LinearLayoutManager(context)); + } + } + + private class ReportsAdapter extends RecyclerView.Adapter { + LayoutInflater inflator; + List data; + + public ReportsAdapter(Context context, List data) { + inflator = LayoutInflater.from(context); + this.data = data; + } + + @NonNull + @Override + public ReportsAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) { + View view = inflator.inflate(R.layout.row_report_consumer_product_wise, parent, false); + return new ReportsAdapter.MyViewHolder(view); + } + + @SuppressLint("SetTextI18n") + @Override + public void onBindViewHolder(final ReportsAdapter.MyViewHolder holder, final int position) { + final ReportSalesConsumerProductwise current = data.get(position); + + holder.datewith_day.setText(current.getVisitDate() + " - " + current.getWeekDay()); + holder.datewith_day.setId(position); + + holder.product_name.setText(current.getProductName()); + holder.product_name.setId(position); + + holder.txt_qty.setText(String.valueOf(current.getQty())); + holder.txt_qty.setId(position); + + holder.txt_salevalue.setText(String.valueOf(current.getSalesValue())); + holder.txt_salevalue.setId(position); + } + + @Override + public int getItemCount() { + return data.size(); + } + + class MyViewHolder extends RecyclerView.ViewHolder { + TextView datewith_day, product_name, txt_qty, txt_salevalue; + CardView sale_card; + + public MyViewHolder(View itemView) { + super(itemView); + datewith_day = (TextView) itemView.findViewById(R.id.datewith_day); + product_name = (TextView) itemView.findViewById(R.id.product_name); + txt_qty = (TextView) itemView.findViewById(R.id.txt_qty); + txt_salevalue = (TextView) itemView.findViewById(R.id.txt_salevalue); + sale_card = (CardView) itemView.findViewById(R.id.sale_card); + } + } + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + if (id == android.R.id.home) { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + ReportConsumerProductWiseActivity.this.finish(); + } + + return super.onOptionsItemSelected(item); + } + + @Override + public void onBackPressed() { + super.onBackPressed(); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + ReportConsumerProductWiseActivity.this.finish(); + } + + @SuppressLint("NotifyDataSetChanged") + private void validatefilterui() { + RecyclerView rec_subaxe = (RecyclerView) findViewById(R.id.rec_subaxe); + rec_subaxe.setLayoutManager(new GridLayoutManager(context, 3)); + rec_subaxe.setAdapter(new SubAxeValueAdapter(context, getFilters(), "Sub Axe", true,false, (filterText, placeHolder) -> {})); + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/reports/ReportConsumerWiseActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/reports/ReportConsumerWiseActivity.java new file mode 100644 index 0000000..cf3b748 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/reports/ReportConsumerWiseActivity.java @@ -0,0 +1,255 @@ +package com.cpm.lorealbaautomation.reports; + +import static com.cpm.lorealbaautomation.constant.CommonFunctions.getFilters; + +import android.annotation.SuppressLint; +import android.app.Activity; +import android.app.ProgressDialog; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.os.Bundle; + +import androidx.annotation.NonNull; +import androidx.appcompat.app.AppCompatActivity; +import androidx.cardview.widget.CardView; +import androidx.recyclerview.widget.GridLayoutManager; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; +import androidx.appcompat.widget.Toolbar; + +import android.view.LayoutInflater; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; +import android.widget.TextView; + +import com.google.gson.Gson; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.adapter.SubAxeValueAdapter; +import com.cpm.lorealbaautomation.constant.AlertandMessages; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.gsonGetterSetter.BADeviceLoginGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.ReportSalesConsumerWise; +import com.cpm.lorealbaautomation.retrofit.PostApi; + +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.TimeUnit; + +import okhttp3.MediaType; +import okhttp3.OkHttpClient; +import okhttp3.RequestBody; +import retrofit2.Call; +import retrofit2.Callback; +import retrofit2.Response; +import retrofit2.Retrofit; +import retrofit2.converter.gson.GsonConverterFactory; + +public class ReportConsumerWiseActivity extends AppCompatActivity { + public ArrayList reportsList = new ArrayList<>(); + String counter_Id, visit_date, username, report_name = "", userType; + private SharedPreferences preferences; + RecyclerView recycle_reports; + ProgressDialog loading; + Context context; + + @SuppressLint("SetTextI18n") + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_reports_consumerwise); + context = this; + Toolbar toolbar = findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + userType = getIntent().getStringExtra(CommonString.KEY_USER_TYPE); + Objects.requireNonNull(getSupportActionBar()).setHomeButtonEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + iduserinterface(); + + String couter_code = preferences.getString(CommonString.KEY_COUNTER_CODE, ""); + TextView txt_counter_code = (TextView) findViewById(R.id.txt_counter_code); + txt_counter_code.setText("Counter Code - " + couter_code + " / Id - " + counter_Id); + } + + private void iduserinterface() { + preferences = PrefHelper.getPrefs(context); + counter_Id = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + username = preferences.getString(CommonString.KEY_USERNAME, ""); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + recycle_reports = (RecyclerView) findViewById(R.id.recycle_reports); + report_name = getIntent().getStringExtra(CommonString.Brand); + setTitle("Reports Consumer Wise - " + visit_date); + if (getIntent().getSerializableExtra(CommonString.TAG_OBJECT) != null) { + reportsList = (ArrayList) getIntent().getSerializableExtra(CommonString.TAG_OBJECT); + } + + assert reportsList != null; + if (!reportsList.isEmpty()) { + validatefilterui(); + recycle_reports.setAdapter(new ReportsAdapter(context, reportsList)); + recycle_reports.setLayoutManager(new LinearLayoutManager(context)); + } + } + + private class ReportsAdapter extends RecyclerView.Adapter { + LayoutInflater inflator; + List data; + + public ReportsAdapter(Context context, List data) { + inflator = LayoutInflater.from(context); + this.data = data; + } + + @NonNull + @Override + public ReportsAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) { + View view = inflator.inflate(R.layout.row_report_consumerwise, parent, false); + return new ReportsAdapter.MyViewHolder(view); + } + + @SuppressLint("SetTextI18n") + @Override + public void onBindViewHolder(final ReportsAdapter.MyViewHolder holder, final int position) { + final ReportSalesConsumerWise current = data.get(position); + + holder.datewith_day.setText(current.getVisitDate() + " - " + current.getWeekDays()); + holder.datewith_day.setId(position); + + holder.consumer_name.setText(current.getConsumerName()); + holder.consumer_name.setId(position); + + holder.mobile_no.setText(current.getMobileNumber()); + holder.mobile_no.setId(position); + + holder.txt_qty.setText(String.valueOf(current.getQty())); + holder.txt_qty.setId(position); + + holder.txt_salevalue.setText(String.valueOf(current.getSalesValue())); + holder.txt_salevalue.setId(position); + + holder.consumer_name.setOnClickListener(view -> downloadreportConsumerWise(current)); + } + + @Override + public int getItemCount() { + return data.size(); + } + + class MyViewHolder extends RecyclerView.ViewHolder { + TextView datewith_day, consumer_name, mobile_no, txt_qty, txt_salevalue; + CardView sale_card; + + public MyViewHolder(View itemView) { + super(itemView); + datewith_day = (TextView) itemView.findViewById(R.id.datewith_day); + consumer_name = (TextView) itemView.findViewById(R.id.consumer_name); + mobile_no = (TextView) itemView.findViewById(R.id.mobile_no); + txt_qty = (TextView) itemView.findViewById(R.id.txt_qty); + txt_salevalue = (TextView) itemView.findViewById(R.id.txt_salevalue); + sale_card = (CardView) itemView.findViewById(R.id.sale_card); + } + } + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + if (id == android.R.id.home) { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + ReportConsumerWiseActivity.this.finish(); + + } + + + return super.onOptionsItemSelected(item); + } + + @Override + public void onBackPressed() { + super.onBackPressed(); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + ReportConsumerWiseActivity.this.finish(); + } + + private void downloadreportConsumerWise(final ReportSalesConsumerWise current) { + try { + + JSONObject obj = new JSONObject(); + obj.put("Downloadtype", userType != null && userType.equalsIgnoreCase(CommonString.TAG_FROM_ME) ? + "Report_SalesConsumerProductwiseME" : "Report_SalesConsumerProductwise"); + obj.put("Username", username); + obj.put("Param1", current.getCounterId()); + obj.put("Param2", current.getTId()); + loading = ProgressDialog.show(context, "Processing", "Please wait...", false, false); + final OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, + TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build(); + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), obj.toString()); + Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build(); + PostApi api = adapter.create(PostApi.class); + Call call_login_tym = api.getDownloadAll(jsonData); + call_login_tym.enqueue(new Callback() { + @Override + public void onResponse(@NonNull Call call, @NonNull Response response) { + String responseBody = response.body(); + String data_consumer_wise = null; + if (responseBody != null && response.isSuccessful()) { + try { + loading.dismiss(); + data_consumer_wise = response.body(); + assert data_consumer_wise != null; + if (!data_consumer_wise.equals("")) { + BADeviceLoginGetterSetter consumerwiseSaleObject = null; + if (!data_consumer_wise.contains("No Data")) { + consumerwiseSaleObject = new Gson().fromJson(data_consumer_wise, BADeviceLoginGetterSetter.class); + if (consumerwiseSaleObject != null) { + startActivity(new Intent(context, ReportConsumerProductWiseActivity.class). + putExtra(CommonString.TAG_OBJECT, userType != null && userType.equalsIgnoreCase(CommonString.TAG_FROM_ME) + ? (Serializable) consumerwiseSaleObject.getReportSalesConsumerProductwiseMe() + : (Serializable) consumerwiseSaleObject.getReportSalesConsumerProductwise()) + .putExtra(CommonString.KEY_Consumer_Object, current)); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + } + } else { + AlertandMessages.showToastMsg(context, "Consumer Wise Sale Report Not found"); + } + } + } catch (Exception e) { + e.fillInStackTrace(); + loading.dismiss(); + AlertandMessages.showAlertlogin((Activity) context, CommonString.MESSAGE_SOCKETEXCEPTION + " - " + e.toString()); + } + } else { + loading.dismiss(); + AlertandMessages.showAlertlogin((Activity) context, CommonString.MESSAGE_NO_RESPONSE_SERVER); + } + } + + @Override + public void onFailure(@NonNull Call call, @NonNull Throwable t) { + loading.dismiss(); + AlertandMessages.showAlertlogin((Activity) context, CommonString.MESSAGE_SOCKETEXCEPTION); + } + }); + + } catch (JSONException e) { + e.fillInStackTrace(); + loading.dismiss(); + AlertandMessages.showAlertlogin((Activity) context, CommonString.MESSAGE_INVALID_JSON); + } + } + + @SuppressLint("NotifyDataSetChanged") + private void validatefilterui() { + RecyclerView rec_subaxe = (RecyclerView) findViewById(R.id.rec_subaxe); + rec_subaxe.setLayoutManager(new GridLayoutManager(context, 3)); + rec_subaxe.setAdapter(new SubAxeValueAdapter(context, getFilters(), "Sub Axe", true,false, (filterText, placeHolder) -> {})); + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/reports/ReportDayWiseActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/reports/ReportDayWiseActivity.java new file mode 100644 index 0000000..38ff443 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/reports/ReportDayWiseActivity.java @@ -0,0 +1,419 @@ +package com.cpm.lorealbaautomation.reports; + +import static com.cpm.lorealbaautomation.constant.CommonFunctions.getFilters; + +import android.annotation.SuppressLint; +import android.app.ProgressDialog; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.os.Bundle; + +import androidx.annotation.NonNull; +import androidx.appcompat.app.AppCompatActivity; +import androidx.recyclerview.widget.GridLayoutManager; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; +import androidx.appcompat.widget.Toolbar; + +import android.text.Html; +import android.view.LayoutInflater; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; +import android.widget.LinearLayout; +import android.widget.TextView; + +import com.google.gson.Gson; +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.adapter.SubAxeValueAdapter; +import com.cpm.lorealbaautomation.constant.AlertandMessages; +import com.cpm.lorealbaautomation.constant.CommonFunctions; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.gsonGetterSetter.BADeviceLoginGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.ReportSalesDateWise; +import com.cpm.lorealbaautomation.gsonGetterSetter.ReportSalesL3MValue; +import com.cpm.lorealbaautomation.gsonGetterSetter.ResponseResult; +import com.cpm.lorealbaautomation.retrofit.PostApi; + +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.TimeUnit; + +import okhttp3.MediaType; +import okhttp3.OkHttpClient; +import okhttp3.RequestBody; +import okhttp3.ResponseBody; +import retrofit2.Call; +import retrofit2.Callback; +import retrofit2.Response; +import retrofit2.Retrofit; +import retrofit2.converter.gson.GsonConverterFactory; + +public class ReportDayWiseActivity extends AppCompatActivity { + ArrayList reportsList = new ArrayList<>(); + String counter_Id, visit_date, username, userType; + SharedPreferences preferences; + RecyclerView recycle_reports, threemonth_salesRecycle; + ArrayList salesL3MValues = new ArrayList<>(); + LinearLayout rl_threemonthsales; + ProgressDialog loading; + Lorealba_Database db; + Context context; + + @SuppressLint("SetTextI18n") + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_reports_daywise); + context = this; + db = new Lorealba_Database(context); + db.open(); + Toolbar toolbar = findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + userType = getIntent().getStringExtra(CommonString.KEY_USER_TYPE); + Objects.requireNonNull(getSupportActionBar()).setHomeButtonEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + iduserinterface(); + String couter_code = preferences.getString(CommonString.KEY_COUNTER_CODE, ""); + TextView txt_counter_code = (TextView) findViewById(R.id.txt_counter_code); + txt_counter_code.setText("Counter Code - " + couter_code + " / Id - " + counter_Id); + validatefilterui(); + } + + private void iduserinterface() { + preferences = PrefHelper.getPrefs(context); + counter_Id = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + username = preferences.getString(CommonString.KEY_USERNAME, ""); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + recycle_reports = (RecyclerView) findViewById(R.id.recycle_reports); + rl_threemonthsales = (LinearLayout) findViewById(R.id.rl_threemonthsales); + threemonth_salesRecycle = (RecyclerView) findViewById(R.id.threemonth_salesRecycle); + setTitle("Reports DayWise - " + visit_date); + db = new Lorealba_Database(context); + db.open(); + salesL3MValues = db.getreportthreemonthsalevalue(userType); + if (!salesL3MValues.isEmpty()) { + rl_threemonthsales.setVisibility(View.VISIBLE); + threemonth_salesRecycle.setAdapter(new SalesValueAdapter(context, salesL3MValues)); + threemonth_salesRecycle.setLayoutManager(new LinearLayoutManager(context)); + } else { + rl_threemonthsales.setVisibility(View.GONE); + } + if (CommonFunctions.checkNetIsAvailable(context)) { + download_report(context); + } else { + call_adapter(context); + } + } + + @Override + protected void onResume() { + super.onResume(); + call_adapter(context); + } + + private void call_adapter(Context context) { + db.open(); + reportsList = db.getreportdaywisesale(counter_Id, userType); + if (!reportsList.isEmpty()) { + recycle_reports.setAdapter(new ReportsAdapter(context, reportsList)); + recycle_reports.setLayoutManager(new LinearLayoutManager(context)); + } + } + + private class ReportsAdapter extends RecyclerView.Adapter { + LayoutInflater inflator; + List data; + + public ReportsAdapter(Context context, List data) { + inflator = LayoutInflater.from(context); + this.data = data; + } + + @NonNull + @Override + public ReportsAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) { + View view = inflator.inflate(R.layout.row_report_daywise, parent, false); + return new ReportsAdapter.MyViewHolder(view); + } + + @SuppressLint("SetTextI18n") + @Override + public void onBindViewHolder(final ReportsAdapter.MyViewHolder holder, final int position) { + final ReportSalesDateWise current = data.get(position); + holder.datewith_day.setText(Html.fromHtml(current.getVisitDate() + " - " + current.getWeekDays())); + holder.datewith_day.setId(position); + + holder.txt_qty.setText(String.valueOf(current.getQty())); + holder.txt_qty.setId(position); + + holder.txt_salevalue.setText(String.valueOf(current.getSalesValue())); + holder.txt_salevalue.setId(position); + + holder.datewith_day.setOnClickListener(view -> { + if (CommonFunctions.checkNetIsAvailable(context)) { + downloadreportConsumerWise(current); + } else { + AlertandMessages.showToastMsg(context, getString(R.string.nonetwork) + ". For viewing consumer wise report"); + } + }); + + } + + @Override + public int getItemCount() { + return data.size(); + } + + class MyViewHolder extends RecyclerView.ViewHolder { + TextView datewith_day, txt_qty, txt_salevalue; + + public MyViewHolder(View itemView) { + super(itemView); + datewith_day = (TextView) itemView.findViewById(R.id.datewith_day); + txt_qty = (TextView) itemView.findViewById(R.id.txt_qty); + txt_salevalue = (TextView) itemView.findViewById(R.id.txt_salevalue); + } + } + } + + + private static class SalesValueAdapter extends RecyclerView.Adapter { + LayoutInflater inflator; + ArrayList data; + + public SalesValueAdapter(Context context, ArrayList data) { + inflator = LayoutInflater.from(context); + this.data = data; + } + + @NonNull + @Override + public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) { + View view = inflator.inflate(R.layout.row_report_three_months, parent, false); + return new MyViewHolder(view); + } + + @SuppressLint("SetTextI18n") + @Override + public void onBindViewHolder(final MyViewHolder holder, final int position) { + final ReportSalesL3MValue current = data.get(position); + + holder.sales_months.setText(current.getMonth()); + holder.sales_months.setId(position); + + holder.txt_qty.setText(String.valueOf(current.getQty())); + holder.txt_qty.setId(position); + + holder.txt_salevalue.setText(String.valueOf(current.getSalesValue())); + holder.txt_salevalue.setId(position); + + } + + @Override + public int getItemCount() { + return data.size(); + } + + private static class MyViewHolder extends RecyclerView.ViewHolder { + TextView sales_months, txt_qty, txt_salevalue; + + public MyViewHolder(View itemView) { + super(itemView); + sales_months = (TextView) itemView.findViewById(R.id.sales_months); + txt_qty = (TextView) itemView.findViewById(R.id.txt_qty); + txt_salevalue = (TextView) itemView.findViewById(R.id.txt_salevalue); + } + } + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + if (id == android.R.id.home) { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + ReportDayWiseActivity.this.finish(); + } + + return super.onOptionsItemSelected(item); + } + + @Override + public void onBackPressed() { + super.onBackPressed(); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + ReportDayWiseActivity.this.finish(); + + } + + private void downloadreportConsumerWise(ReportSalesDateWise current) { + try { + JSONObject obj = new JSONObject(); + obj.put("Downloadtype", userType != null && userType.equalsIgnoreCase(CommonString.TAG_FROM_ME) ? "Report_SalesConsumerWiseME" : "Report_SalesConsumerWise"); + obj.put("Username", username); + obj.put("Param1", current.getCounterId()); + obj.put("Param2", current.getVisitDate()); + loading = ProgressDialog.show(context, "Processing", "Please wait...", false, true); + OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, + TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build(); + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), obj.toString()); + Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build(); + PostApi api = adapter.create(PostApi.class); + Call call_login_tym = api.getDownloadAll(jsonData); + call_login_tym.enqueue(new Callback() { + @Override + public void onResponse(@NonNull Call call, @NonNull Response response) { + String responseBody = response.body(); + String data_consumer_wise = null; + if (responseBody != null && response.isSuccessful()) { + loading.dismiss(); + if (loading != null && loading.isShowing()) { + loading.dismiss(); + } + try { + data_consumer_wise = response.body(); + assert data_consumer_wise != null; + if (!data_consumer_wise.isEmpty()) { + BADeviceLoginGetterSetter consumerwiseSaleObject = null; + if (!data_consumer_wise.contains("No Data")) { + consumerwiseSaleObject = new Gson().fromJson(data_consumer_wise, BADeviceLoginGetterSetter.class); + if (consumerwiseSaleObject != null) { + startActivity(new Intent(context, ReportConsumerWiseActivity.class) + .putExtra(CommonString.TAG_OBJECT, + userType != null && userType.equalsIgnoreCase(CommonString.TAG_FROM_ME) ? + (Serializable) consumerwiseSaleObject.getReportSalesConsumerWiseMe() : + (Serializable) consumerwiseSaleObject + .getReportSalesConsumerWise()).putExtra(CommonString.KEY_USER_TYPE, userType)); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + } + } else { + AlertandMessages.showToastMsg(context, "Day Wise Sale Report Not found"); + } + } + } catch (Exception e) { + e.fillInStackTrace(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_SOCKETEXCEPTION + " - " + e.toString()); + loading.dismiss(); + } + } else { + loading.dismiss(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_NO_RESPONSE_SERVER); + } + } + + @Override + public void onFailure(@NonNull Call call, @NonNull Throwable t) { + loading.dismiss(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_SOCKETEXCEPTION); + } + }); + + } catch (JSONException e) { + e.fillInStackTrace(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INVALID_JSON); + } + } + + + private void download_report(final Context context) { + try { + JSONObject jsonObject = new JSONObject(); + jsonObject.put("Downloadtype", userType != null && userType.equalsIgnoreCase(CommonString.TAG_FROM_ME) ? "Report_SalesConsumerWiseME" : "Report_SalesConsumerWise"); + jsonObject.put("Username", username); + jsonObject.put("Param1", counter_Id); + jsonObject.put("Param2", ""); + String jsonString = jsonObject.toString(); + + loading = ProgressDialog.show(context, "Processing", "Please wait...", false, true); + OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, + TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build(); + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsonString); + Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build(); + PostApi api = adapter.create(PostApi.class); + Call call = api.getTabjournePlan(jsonData); + call.enqueue(new Callback() { + @Override + public void onResponse(@NonNull Call call, @NonNull Response response) { + ResponseBody responseBody = response.body(); + String data = null; + if (responseBody != null && response.isSuccessful()) { + try { + loading.dismiss(); + assert response.body() != null; + data = response.body().string(); + data = data.substring(1, data.length() - 1).replace("\\", ""); + if (data.equalsIgnoreCase(CommonString.KEY_FAILURE)) { + if (loading != null && loading.isShowing()) { + loading.dismiss(); + } + + call_adapter(context); + } else if (!data.contains("No Data")) { + if (loading != null && loading.isShowing()) { + loading.dismiss(); + } + + ResponseResult reportsaleDatewiseObject = new Gson().fromJson(data, ResponseResult.class); + if (reportsaleDatewiseObject != null) { + db.open(); + db.insertReportDaywiseSale(reportsaleDatewiseObject, userType != null && userType.equalsIgnoreCase(CommonString.TAG_FROM_ME)); + } + + call_adapter(context); + + + } else { + if (loading != null && loading.isShowing()) { + loading.dismiss(); + } + db.open(); + db.delete_table_data(userType != null && userType.equalsIgnoreCase(CommonString.TAG_FROM_ME) ? "Report_SalesConsumerWiseME" : "Report_SalesConsumerWise"); + call_adapter(context); + } + } catch (Exception e) { + if (loading != null && loading.isShowing()) { + loading.dismiss(); + } + call_adapter(context); + } + } else { + if (loading != null && loading.isShowing()) { + loading.dismiss(); + } + + call_adapter(context); + } + } + + @Override + public void onFailure(@NonNull Call call, @NonNull Throwable t) { + if (loading != null && loading.isShowing()) { + loading.dismiss(); + } + call_adapter(context); + } + }); + } catch (Exception e) { + if (loading != null && loading.isShowing()) { + loading.dismiss(); + } + call_adapter(context); + } + } + + @SuppressLint("NotifyDataSetChanged") + private void validatefilterui() { + RecyclerView rec_subaxe = (RecyclerView) findViewById(R.id.rec_subaxe); + rec_subaxe.setLayoutManager(new GridLayoutManager(context, 3)); + rec_subaxe.setAdapter(new SubAxeValueAdapter(context, getFilters(), "Sub Axe", true,false, (filterText, placeHolder) -> {})); + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/reports/ReportsActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/reports/ReportsActivity.java new file mode 100644 index 0000000..0d4bb45 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/reports/ReportsActivity.java @@ -0,0 +1,357 @@ +package com.cpm.lorealbaautomation.reports; + +import android.annotation.SuppressLint; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; + +import androidx.annotation.NonNull; +import androidx.appcompat.app.AppCompatActivity; + +import android.os.Bundle; + +import androidx.cardview.widget.CardView; +import androidx.recyclerview.widget.GridLayoutManager; +import androidx.recyclerview.widget.RecyclerView; +import androidx.appcompat.widget.Toolbar; + +import android.view.LayoutInflater; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; +import android.widget.ImageView; +import android.widget.TextView; + +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.constant.CommonFunctions; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.reportGetterSetter.ReportTop10Value; +import com.cpm.lorealbaautomation.reports.countervaluevolume.CounterValueVolumeDetailActivity; +import com.cpm.lorealbaautomation.reports.dailyTva.DailyTVAActivity; +import com.cpm.lorealbaautomation.reports.inwarddetails.CounterInwordDetailActivity; +import com.cpm.lorealbaautomation.reports.testerdetails.TesterUsageReportActivity; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +public class ReportsActivity extends AppCompatActivity { + public ArrayList reportsList = new ArrayList<>(); + ReportTop10Value object = new ReportTop10Value(); + String counter_Id, visit_date, username; + private SharedPreferences preferences; + RecyclerView recycle_reports; + String userType = ""; + Lorealba_Database db; + Context context; + + @SuppressLint("SetTextI18n") + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_reports); + context = this; + db = new Lorealba_Database(context); + db.open(); + Toolbar toolbar = findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + userType = getIntent().getStringExtra("from"); + Objects.requireNonNull(getSupportActionBar()).setHomeButtonEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + iduserinterface(); + setTitle("Reports List - " + visit_date); + + String couter_code = preferences.getString(CommonString.KEY_COUNTER_CODE, ""); + TextView txt_counter_code = (TextView) findViewById(R.id.txt_counter_code); + txt_counter_code.setText("Counter Code - " + couter_code + " / Id - " + counter_Id); + } + + private void iduserinterface() { + preferences = PrefHelper.getPrefs(context); + counter_Id = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + username = preferences.getString(CommonString.KEY_USERNAME, ""); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + recycle_reports = (RecyclerView) findViewById(R.id.recycle_reports); + int count = 2; + if (CommonFunctions.isTablet(context)) { + count = 3; + } + recycle_reports.setAdapter(new ReportListAdapter(context, addNames())); + recycle_reports.setLayoutManager(new GridLayoutManager(this, count)); + } + + private ArrayList addNames() { + if (!userType.isEmpty() && userType.equalsIgnoreCase(CommonString.TAG_FROM_ME)) { + object = new ReportTop10Value(); + object.setBrandName("Counter Coverage"); + object.setColor_code(getResources().getColor(R.color.white)); + object.setDrawble_code(R.mipmap.stock_check); + reportsList.add(object); + + object = new ReportTop10Value(); + object.setBrandName("Sale Reports"); + object.setColor_code(getResources().getColor(R.color.white)); + object.setDrawble_code(R.mipmap.salesreport); + reportsList.add(object); + + object = new ReportTop10Value(); + object.setBrandName("Sale Reports Day Wise"); + object.setColor_code(getResources().getColor(R.color.white)); + object.setDrawble_code(R.mipmap.daywise_report); + reportsList.add(object); + + } else { + object = new ReportTop10Value(); + object.setBrandName("Stock Ledger Detail"); + object.setColor_code(getResources().getColor(R.color.white)); + object.setDrawble_code(R.mipmap.stock_ledger); + reportsList.add(object); + + object = new ReportTop10Value(); + object.setBrandName("Counter Inward Stock Detail"); + object.setColor_code(getResources().getColor(R.color.white)); + object.setDrawble_code(R.mipmap.inward_stock_detail); + reportsList.add(object); + + object = new ReportTop10Value(); + object.setBrandName("Counter Value Detail"); + object.setColor_code(getResources().getColor(R.color.white)); + object.setDrawble_code(R.mipmap.value_detail); + reportsList.add(object); + + object = new ReportTop10Value(); + object.setBrandName("Counter Volume Detail"); + object.setColor_code(getResources().getColor(R.color.white)); + object.setDrawble_code(R.mipmap.volume_detail); + reportsList.add(object); + + object = new ReportTop10Value(); + object.setBrandName("Tester Usage Detail"); + object.setColor_code(getResources().getColor(R.color.white)); + object.setDrawble_code(R.mipmap.tester_usage_detail); + reportsList.add(object); + + object = new ReportTop10Value(); + object.setBrandName("L3M OffTake"); + object.setColor_code(getResources().getColor(R.color.white)); + object.setDrawble_code(R.mipmap.sale_growth); + reportsList.add(object); + + object = new ReportTop10Value(); + object.setBrandName("Daily TVA"); + object.setColor_code(getResources().getColor(R.color.white)); + object.setDrawble_code(R.mipmap.daily_tva); + reportsList.add(object); + + object = new ReportTop10Value(); + object.setBrandName("KPI Tracker"); + object.setColor_code(getResources().getColor(R.color.white)); + object.setDrawble_code(R.mipmap.kpi_tracker); + reportsList.add(object); + + /* + old report of top 10 value and volume + object = new ReportTop10Value(); + object.setBrandName("Top 10 Value"); + object.setColor_code(getResources().getColor(R.color.white)); + object.setDrawble_code(R.mipmap.report_value); + reportsList.add(object); + + object = new ReportTop10Value(); + object.setBrandName("Top 10 Volume"); + object.setColor_code(getResources().getColor(R.color.white)); + object.setDrawble_code(R.mipmap.report_volume); + reportsList.add(object);*/ + + object = new ReportTop10Value(); + object.setBrandName("Attendance Reports"); + object.setColor_code(getResources().getColor(R.color.white)); + object.setDrawble_code(R.mipmap.report_attendance); + reportsList.add(object); + + object = new ReportTop10Value(); + object.setBrandName("BA Availability"); + object.setColor_code(getResources().getColor(R.color.white)); + object.setDrawble_code(R.mipmap.report_baa); + reportsList.add(object); + + object = new ReportTop10Value(); + object.setBrandName("Inward Lines Summary"); + object.setColor_code(getResources().getColor(R.color.white)); + object.setDrawble_code(R.mipmap.report_inword); + reportsList.add(object); + + object = new ReportTop10Value(); + object.setBrandName("Tester Stock Summary"); + object.setColor_code(getResources().getColor(R.color.white)); + object.setDrawble_code(R.mipmap.report_tester); + reportsList.add(object); + + object = new ReportTop10Value(); + object.setBrandName("Damaged Stock Summary"); + object.setColor_code(getResources().getColor(R.color.white)); + object.setDrawble_code(R.mipmap.report_damage); + reportsList.add(object); + + object = new ReportTop10Value(); + object.setBrandName("Sale Reports"); + object.setColor_code(getResources().getColor(R.color.white)); + object.setDrawble_code(R.mipmap.salesreport); + reportsList.add(object); + + object = new ReportTop10Value(); + object.setBrandName("Sale Reports Day Wise"); + object.setColor_code(getResources().getColor(R.color.white)); + object.setDrawble_code(R.mipmap.daywise_report); + reportsList.add(object); + + object = new ReportTop10Value(); + object.setBrandName("Stock Check Reports"); + object.setColor_code(getResources().getColor(R.color.white)); + object.setDrawble_code(R.mipmap.stock_check); + reportsList.add(object); + } + + return reportsList; + } + + private class ReportListAdapter extends RecyclerView.Adapter { + LayoutInflater inflator; + List data; + + public ReportListAdapter(Context context, List data) { + inflator = LayoutInflater.from(context); + this.data = data; + } + + @NonNull + @Override + public ReportListAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) { + View view = inflator.inflate(R.layout.row_reports, parent, false); + return new ReportListAdapter.MyViewHolder(view); + } + + @SuppressLint("SetTextI18n") + @Override + public void onBindViewHolder(final ReportListAdapter.MyViewHolder holder, final int position) { + final ReportTop10Value current = data.get(position); + holder.img_icon.setImageResource(current.getDrawble_code()); + holder.img_icon.setId(position); + + holder.report_name_txt.setText(current.getBrandName()); + holder.report_name_txt.setId(position); + + holder.sale_card.setCardBackgroundColor(current.getColor_code()); + holder.sale_card.setId(position); + + holder.sale_card.setOnClickListener(view -> { + switch (current.getBrandName()) { + /* case "Top 10 Value": + case "Top 10 Volume": + startActivity(new Intent(context, ReportsTop10Value.class).putExtra(CommonString.Brand, current.getBrandName())); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + break;*/ + case "Inward Lines Summary": + startActivity(new Intent(context, ReportsInwordStock.class).putExtra(CommonString.Brand, current.getBrandName())); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + break; + case "Attendance Reports": + startActivity(new Intent(context, ReportAttendanceSummaryActivity.class)); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + break; + case "Tester Stock Summary": + case "Stock Check Reports": + case "Counter Coverage": + startActivity(new Intent(context, TesterReportActivity.class).putExtra(CommonString.Brand, current.getBrandName())); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + break; + case "Damaged Stock Summary": + startActivity(new Intent(context, DamagedStockHistory.class)); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + break; + case "BA Availability": + startActivity(new Intent(context, ReportBaAvailability.class).putExtra(CommonString.Brand, current.getBrandName())); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + break; + case "Sale Reports": + startActivity(new Intent(context, SalesReportsActivity.class).putExtra(CommonString.KEY_USER_TYPE, userType)); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + break; + case "Sale Reports Day Wise": + startActivity(new Intent(context, ReportDayWiseActivity.class).putExtra(CommonString.KEY_USER_TYPE, userType)); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + break; + case "KPI Tracker": + startActivity(new Intent(context, KPITrackerActivity.class).putExtra(CommonString.Brand, current.getBrandName())); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + break; + case "L3M OffTake": + startActivity(new Intent(context, DashbordOffTakeReportActivity.class).putExtra(CommonString.Brand, current.getBrandName())); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + break; + case "Daily TVA": + startActivity(new Intent(context, DailyTVAActivity.class).putExtra(CommonString.Brand, current.getBrandName())); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + break; + case "Tester Usage Detail": + startActivity(new Intent(context, TesterUsageReportActivity.class).putExtra(CommonString.Brand, current.getBrandName())); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + break; + + case "Counter Value Detail": + case "Counter Volume Detail": + startActivity(new Intent(context, CounterValueVolumeDetailActivity.class).putExtra(CommonString.Brand, current.getBrandName())); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + break; + case "Counter Inward Stock Detail": + case "Stock Ledger Detail": + startActivity(new Intent(context, CounterInwordDetailActivity.class).putExtra(CommonString.Brand, current.getBrandName())); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + break; + } + }); + } + + @Override + public int getItemCount() { + return data.size(); + } + + class MyViewHolder extends RecyclerView.ViewHolder { + TextView report_name_txt; + CardView sale_card; + ImageView img_icon; + + public MyViewHolder(View itemView) { + super(itemView); + report_name_txt = (TextView) itemView.findViewById(R.id.report_name_txt); + img_icon = (ImageView) itemView.findViewById(R.id.img_icon); + sale_card = (CardView) itemView.findViewById(R.id.sale_card); + } + } + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + if (id == android.R.id.home) { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + ReportsActivity.this.finish(); + + } + + return super.onOptionsItemSelected(item); + } + + @Override + public void onBackPressed() { + super.onBackPressed(); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + ReportsActivity.this.finish(); + + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/reports/ReportsInwordStock.java b/app/src/main/java/com/cpm/lorealbaautomation/reports/ReportsInwordStock.java new file mode 100644 index 0000000..5c137ce --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/reports/ReportsInwordStock.java @@ -0,0 +1,325 @@ +package com.cpm.lorealbaautomation.reports; + +import static com.cpm.lorealbaautomation.constant.CommonFunctions.getFilters; + +import android.annotation.SuppressLint; +import android.app.ProgressDialog; +import android.content.Context; +import android.content.SharedPreferences; + +import androidx.annotation.NonNull; +import androidx.appcompat.app.AppCompatActivity; + +import android.os.Bundle; + +import androidx.recyclerview.widget.GridLayoutManager; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; +import androidx.appcompat.widget.Toolbar; + +import android.view.LayoutInflater; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; +import android.widget.TextView; + +import com.google.gson.Gson; +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.adapter.SubAxeValueAdapter; +import com.cpm.lorealbaautomation.constant.CommonFunctions; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterBAProfileGetterSetter; +import com.cpm.lorealbaautomation.reportGetterSetter.ReportInwardStockSummary; +import com.cpm.lorealbaautomation.retrofit.PostApi; + +import org.json.JSONException; +import org.json.JSONObject; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.TimeUnit; + +import okhttp3.MediaType; +import okhttp3.OkHttpClient; +import okhttp3.RequestBody; +import okhttp3.ResponseBody; +import retrofit2.Call; +import retrofit2.Callback; +import retrofit2.Response; +import retrofit2.Retrofit; +import retrofit2.converter.gson.GsonConverterFactory; + +public class ReportsInwordStock extends AppCompatActivity { + public ArrayList reportsList = new ArrayList<>(); + String counter_Id, visit_date, username, report_name = ""; + private SharedPreferences preferences; + RecyclerView recycle_reports; + ProgressDialog loading = null; + Lorealba_Database db; + Context context; + + @SuppressLint("SetTextI18n") + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_reports_inword_stock); + context = this; + db = new Lorealba_Database(context); + db.open(); + Toolbar toolbar = findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + Objects.requireNonNull(getSupportActionBar()).setHomeButtonEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + iduserinterface(); + String couter_code = preferences.getString(CommonString.KEY_COUNTER_CODE, ""); + TextView txt_counter_code = (TextView) findViewById(R.id.txt_counter_code); + txt_counter_code.setText("Counter Code - " + couter_code + " / Id - " + counter_Id); + validatefilterui(); + } + + private void iduserinterface() { + preferences = PrefHelper.getPrefs(context); + counter_Id = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + username = preferences.getString(CommonString.KEY_USERNAME, ""); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + recycle_reports = (RecyclerView) findViewById(R.id.recycle_reports); + report_name = getIntent().getStringExtra(CommonString.Brand); + setTitle("Reports " + report_name + "- " + visit_date); + db = new Lorealba_Database(context); + db.open(); + if (CommonFunctions.checkNetIsAvailable(context)) { + download_report(context); + } else { + call_adapter(context); + } + } + + + @Override + protected void onResume() { + super.onResume(); + call_adapter(context); + } + + private void call_adapter(Context context) { + db.open(); + reportsList = db.getinwordStockSummary(counter_Id); + if (!reportsList.isEmpty()) { + recycle_reports.setAdapter(new ReportsAdapter(context, reportsList)); + recycle_reports.setLayoutManager(new LinearLayoutManager(context)); + } + } + + private static class ReportsAdapter extends RecyclerView.Adapter { + LayoutInflater inflator; + List data; + + public ReportsAdapter(Context context, List data) { + inflator = LayoutInflater.from(context); + this.data = data; + } + + @NonNull + @Override + public ReportsAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) { + View view = inflator.inflate(R.layout.row_report_inword_stock, parent, false); + return new MyViewHolder(view); + } + + @SuppressLint("SetTextI18n") + @Override + public void onBindViewHolder(final ReportsAdapter.MyViewHolder holder, final int position) { + final ReportInwardStockSummary current = data.get(position); + + holder.invoice_no_txt.setText(current.getInvoiceNo()); + holder.invoice_no_txt.setId(position); + + holder.invoice_date_txt.setText(current.getInvoiceDate()); + holder.invoice_date_txt.setId(position); + + holder.invoice_type_txt.setText(current.getInvoiceType()); + holder.invoice_type_txt.setId(position); + + holder.source_txt.setText(current.getSource()); + holder.source_txt.setId(position); + + holder.invoice_value_txt.setText(current.getInvoiceValue().toString()); + holder.invoice_value_txt.setId(position); + + holder.total_line_txt.setText(current.getTotalLine().toString()); + holder.total_line_txt.setId(position); + + holder.confrm_line_txt.setText(current.getConfirmLine().toString()); + holder.confrm_line_txt.setId(position); + + holder.pending_line_txt.setText(current.getPendingLine().toString()); + holder.pending_line_txt.setId(position); + + + } + + @Override + public int getItemCount() { + return data.size(); + } + + static class MyViewHolder extends RecyclerView.ViewHolder { + TextView invoice_no_txt, invoice_date_txt, invoice_type_txt, source_txt, invoice_value_txt, total_line_txt, confrm_line_txt, pending_line_txt; + + public MyViewHolder(View itemView) { + super(itemView); + invoice_no_txt = (TextView) itemView.findViewById(R.id.invoice_no_txt); + invoice_date_txt = (TextView) itemView.findViewById(R.id.invoice_date_txt); + invoice_type_txt = (TextView) itemView.findViewById(R.id.invoice_type_txt); + source_txt = (TextView) itemView.findViewById(R.id.source_txt); + invoice_value_txt = (TextView) itemView.findViewById(R.id.invoice_value_txt); + total_line_txt = (TextView) itemView.findViewById(R.id.total_line_txt); + confrm_line_txt = (TextView) itemView.findViewById(R.id.confrm_line_txt); + pending_line_txt = (TextView) itemView.findViewById(R.id.pending_line_txt); + } + } + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + if (id == android.R.id.home) { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + this.finish(); + } + + return super.onOptionsItemSelected(item); + } + + @Override + public void onBackPressed() { + super.onBackPressed(); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + this.finish(); + + } + + private void download_report(final Context context) { + try { + String download_key = "Report_InwardStockSummary"; + JSONObject jsonObject = new JSONObject(); + jsonObject.put("Downloadtype", download_key); + jsonObject.put("Username", username); + jsonObject.put("Param1", counter_Id); + jsonObject.put("Param2", ""); + String jsonString = jsonObject.toString(); + try { + loading = ProgressDialog.show(context, "Processing", "Please wait...", false, true); + OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, + TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build(); + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsonString); + Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build(); + PostApi api = adapter.create(PostApi.class); + Call call = api.getTabjournePlan(jsonData); + call.enqueue(new Callback() { + @Override + public void onResponse(@NonNull Call call, @NonNull Response response) { + ResponseBody responseBody = response.body(); + String data = null; + if (responseBody != null && response.isSuccessful()) { + try { + loading.dismiss(); + assert response.body() != null; + data = response.body().string(); + data = data.substring(1, data.length() - 1).replace("\\", ""); + if (data.equalsIgnoreCase(CommonString.KEY_FAILURE)) { + if (loading != null && loading.isShowing()) { + loading.dismiss(); + } + ///caling adapter + call_adapter(context); + } else if (!data.contains("No Data")) { + if (loading != null && loading.isShowing()) { + loading.dismiss(); + } + MasterBAProfileGetterSetter reportInwordStockSummeryGetterSetter = new Gson().fromJson(data, MasterBAProfileGetterSetter.class); + if (reportInwordStockSummeryGetterSetter != null) { + db.open(); + db.insertreport_inword_stock_summery(reportInwordStockSummeryGetterSetter); + } + ///caling adapter + call_adapter(context); + } else { + loading.dismiss(); + if (loading != null && loading.isShowing()) { + loading.dismiss(); + } + db.open(); + db.delete_table_data("Report_InwardStockSummary"); + ///caling adapter + call_adapter(context); + } + + } catch (Exception e) { + loading.dismiss(); + if (loading != null && loading.isShowing()) { + loading.dismiss(); + } + ///caling adapter + call_adapter(context); + } + } else { + loading.dismiss(); + if (loading != null && loading.isShowing()) { + loading.dismiss(); + } + ///caling adapter + call_adapter(context); + } + } + + @Override + public void onFailure(@NonNull Call call, @NonNull Throwable t) { + loading.dismiss(); + if (loading != null && loading.isShowing()) { + loading.dismiss(); + } + ///caling adapter + call_adapter(context); + } + }); + + } catch (Exception e) { + loading.dismiss(); + if (loading != null && loading.isShowing()) { + loading.dismiss(); + } + ///caling adapter + call_adapter(context); + } + + } catch (JSONException e) { + loading.dismiss(); + if (loading != null && loading.isShowing()) { + loading.dismiss(); + } + ///caling adapter + call_adapter(context); + } + } + + @Override + protected void onDestroy() { + if (loading != null && loading.isShowing()) { + loading.dismiss(); + } + + super.onDestroy(); + } + + @SuppressLint("NotifyDataSetChanged") + private void validatefilterui() { + RecyclerView rec_subaxe = (RecyclerView) findViewById(R.id.rec_subaxe); + rec_subaxe.setLayoutManager(new GridLayoutManager(context, 3)); + rec_subaxe.setAdapter(new SubAxeValueAdapter(context, getFilters(), "Sub Axe", true,false, (filterText, placeHolder) -> {})); + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/reports/ReportsTop10Value.java b/app/src/main/java/com/cpm/lorealbaautomation/reports/ReportsTop10Value.java new file mode 100644 index 0000000..b8002c0 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/reports/ReportsTop10Value.java @@ -0,0 +1,396 @@ +package com.cpm.lorealbaautomation.reports; + +import static com.cpm.lorealbaautomation.constant.CommonFunctions.getFilters; + +import android.annotation.SuppressLint; +import android.app.ProgressDialog; +import android.content.Context; +import android.content.SharedPreferences; + +import androidx.annotation.NonNull; +import androidx.appcompat.app.AppCompatActivity; + +import android.os.Bundle; + +import androidx.cardview.widget.CardView; +import androidx.recyclerview.widget.GridLayoutManager; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; +import androidx.appcompat.widget.Toolbar; + +import android.view.LayoutInflater; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; +import android.widget.TextView; + +import com.google.gson.Gson; +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.adapter.SubAxeValueAdapter; +import com.cpm.lorealbaautomation.constant.CommonFunctions; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterProfileQuestionGetterSetter; +import com.cpm.lorealbaautomation.reportGetterSetter.ReportTop10Value; +import com.cpm.lorealbaautomation.retrofit.PostApi; + +import org.json.JSONException; +import org.json.JSONObject; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.TimeUnit; + +import okhttp3.MediaType; +import okhttp3.OkHttpClient; +import okhttp3.RequestBody; +import okhttp3.ResponseBody; +import retrofit2.Call; +import retrofit2.Callback; +import retrofit2.Response; +import retrofit2.Retrofit; +import retrofit2.converter.gson.GsonConverterFactory; + +public class ReportsTop10Value extends AppCompatActivity { + public ArrayList reportsList = new ArrayList<>(); + TextView str_mtd_valume, str_avgperday_calume; + String counter_Id, visit_date, username, report_name = ""; + private SharedPreferences preferences; + private ProgressDialog loading = null; + RecyclerView recycle_reports; + Lorealba_Database db; + Context context; + + @SuppressLint("SetTextI18n") + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_reports_name_list); + context = this; + db = new Lorealba_Database(context); + db.open(); + Toolbar toolbar = findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + Objects.requireNonNull(getSupportActionBar()).setHomeButtonEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + iduserinterface(); + + String couter_code = preferences.getString(CommonString.KEY_COUNTER_CODE, ""); + TextView txt_counter_code = (TextView) findViewById(R.id.txt_counter_code); + txt_counter_code.setText("Counter Code - " + couter_code + " / Id - " + counter_Id); + + } + + + private void iduserinterface() { + preferences = PrefHelper.getPrefs(context); + counter_Id = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + username = preferences.getString(CommonString.KEY_USERNAME, ""); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + recycle_reports = (RecyclerView) findViewById(R.id.recycle_reports); + + str_mtd_valume = (TextView) findViewById(R.id.str_mtd_valume); + str_avgperday_calume = (TextView) findViewById(R.id.str_avgperday_calume); + report_name = getIntent().getStringExtra(CommonString.Brand); + setTitle("Reports " + report_name + "- " + visit_date); + db = new Lorealba_Database(context); + db.open(); + validatefilterui(); + if (report_name.equals("Top 10 Value")) { + str_mtd_valume.setText(getString(R.string.mtd_value)); + str_avgperday_calume.setText(getString(R.string.avg_perday_value)); + if (CommonFunctions.checkNetIsAvailable(context)) { + download_report(context, true); + } else { + calculatedatafor_tp10Value("0"); + } + } else { + str_mtd_valume.setText(getString(R.string.mtd_valuume)); + str_avgperday_calume.setText(getString(R.string.avg_perday_volume)); + if (CommonFunctions.checkNetIsAvailable(context)) { + download_report(context, false); + } else { + calculatedatafor_tp10Value("1"); + } + } + } + + + private void calculatedatafor_tp10Value(String value) { + if (value != null && value.equals("0")) { + db.open(); + reportsList = db.gettop10Value(counter_Id); + } else if (value != null && value.equals("1")) { + db.open(); + reportsList = db.gettop10Valume(counter_Id); + } + + if (!reportsList.isEmpty()) { + recycle_reports.setAdapter(new ReportsAdapter(context, reportsList, value)); + recycle_reports.setLayoutManager(new LinearLayoutManager(context)); + } + + } + + + private class ReportsAdapter extends RecyclerView.Adapter { + LayoutInflater inflator; + List data; + String value; + + public ReportsAdapter(Context context, List data, String value) { + inflator = LayoutInflater.from(context); + this.data = data; + this.value = value; + } + + @NonNull + @Override + public ReportsAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) { + View view = inflator.inflate(R.layout.row_reports_list, parent, false); + return new ReportsAdapter.MyViewHolder(view); + } + + @SuppressLint("SetTextI18n") + @Override + public void onBindViewHolder(final ReportsAdapter.MyViewHolder holder, final int position) { + final ReportTop10Value current = data.get(position); + + holder.brand_name_txt.setText(current.getBrandName()); + holder.brand_name_txt.setId(position); + + holder.ean_code.setText(current.getEanCode()); + holder.ean_code.setId(position); + + holder.product_name.setText(current.getProductName()); + holder.product_name.setId(position); + + if (value.equals("0")) { + holder.mtd_valume.setText(current.getMTDValue().toString()); + holder.mtd_valume.setId(position); + holder.avgperday_calume.setText(current.getAvgPerDayValue().toString()); + holder.avgperday_calume.setId(position); + } else { + holder.mtd_valume.setText(current.getMTDValue().toString()); + holder.mtd_valume.setId(position); + holder.avgperday_calume.setText(current.getAvgPerDayValue().toString()); + holder.avgperday_calume.setId(position); + } + + } + + @Override + public int getItemCount() { + return data.size(); + } + + class MyViewHolder extends RecyclerView.ViewHolder { + TextView brand_name_txt, ean_code, product_name, mtd_valume, avgperday_calume; + CardView sale_card; + + public MyViewHolder(View itemView) { + super(itemView); + brand_name_txt = (TextView) itemView.findViewById(R.id.brand_name_txt); + ean_code = (TextView) itemView.findViewById(R.id.promo_ean_code); + product_name = (TextView) itemView.findViewById(R.id.product_name); + mtd_valume = (TextView) itemView.findViewById(R.id.mtd_valume); + avgperday_calume = (TextView) itemView.findViewById(R.id.avgperday_calume); + sale_card = (CardView) itemView.findViewById(R.id.sale_card); + } + } + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + if (id == android.R.id.home) { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + ReportsTop10Value.this.finish(); + + } + + + return super.onOptionsItemSelected(item); + } + + @Override + public void onBackPressed() { + super.onBackPressed(); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + ReportsTop10Value.this.finish(); + + } + + + private void download_report(final Context context, final boolean flagfor_top10_value) { + try { + String download_key = "Report_Top10Volume"; + if (flagfor_top10_value) { + download_key = "Report_Top10Value"; + } + JSONObject jsonObject = new JSONObject(); + jsonObject.put("Downloadtype", download_key); + jsonObject.put("Username", username); + jsonObject.put("Param1", counter_Id); + jsonObject.put("Param2", ""); + String jsonString = jsonObject.toString(); + try { + + loading = ProgressDialog.show(context, "Processing", "Please wait...", false, true); + OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, + TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build(); + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsonString); + Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build(); + PostApi api = adapter.create(PostApi.class); + Call call = api.getTabjournePlan(jsonData); + call.enqueue(new Callback() { + @Override + public void onResponse(@NonNull Call call, @NonNull Response response) { + ResponseBody responseBody = response.body(); + String data = null; + if (responseBody != null && response.isSuccessful()) { + try { + loading.dismiss(); + assert response.body() != null; + data = response.body().string(); + data = data.substring(1, data.length() - 1).replace("\\", ""); + if (data.equalsIgnoreCase(CommonString.KEY_FAILURE)) { + if (loading != null && loading.isShowing()) { + loading.dismiss(); + } + if (flagfor_top10_value) { + calculatedatafor_tp10Value("0"); + } else { + calculatedatafor_tp10Value("1"); + } + } else if (!data.contains("No Data")) { + if (loading != null && loading.isShowing()) { + loading.dismiss(); + } + if (flagfor_top10_value) { + MasterProfileQuestionGetterSetter reportTop10ValueObject = new Gson().fromJson(data, MasterProfileQuestionGetterSetter.class); + if (reportTop10ValueObject != null) { + db.open(); + db.insertReportTop10Value(reportTop10ValueObject); + } + + } else { + MasterProfileQuestionGetterSetter reportTop10VolumeObject = new Gson().fromJson(data, MasterProfileQuestionGetterSetter.class); + if (reportTop10VolumeObject != null) { + db.open(); + db.insertReportTop10Volume(reportTop10VolumeObject); + } + } + ///caling adapter + if (flagfor_top10_value) { + calculatedatafor_tp10Value("0"); + } else { + calculatedatafor_tp10Value("1"); + } + } else { + loading.dismiss(); + if (loading != null && loading.isShowing()) { + loading.dismiss(); + } + if (flagfor_top10_value) { + db.open(); + db.delete_table_data("Report_Top10Value"); + } else { + db.open(); + db.delete_table_data("Report_Top10Volume"); + } + + ///caling adapter + if (flagfor_top10_value) { + calculatedatafor_tp10Value("0"); + } else { + calculatedatafor_tp10Value("1"); + } + } + } catch (Exception e) { + loading.dismiss(); + if (loading != null && loading.isShowing()) { + loading.dismiss(); + } + ///caling adapter + if (flagfor_top10_value) { + calculatedatafor_tp10Value("0"); + } else { + calculatedatafor_tp10Value("1"); + } + } + } else { + loading.dismiss(); + if (loading != null && loading.isShowing()) { + loading.dismiss(); + } + ///caling adapter + if (flagfor_top10_value) { + calculatedatafor_tp10Value("0"); + } else { + calculatedatafor_tp10Value("1"); + } + } + } + + @Override + public void onFailure(@NonNull Call call, @NonNull Throwable t) { + loading.dismiss(); + if (loading != null && loading.isShowing()) { + loading.dismiss(); + } + ///caling adapter + if (flagfor_top10_value) { + calculatedatafor_tp10Value("0"); + } else { + calculatedatafor_tp10Value("1"); + } + } + }); + + } catch (Exception e) { + loading.dismiss(); + if (loading != null && loading.isShowing()) { + loading.dismiss(); + } + ///caling adapter + if (flagfor_top10_value) { + calculatedatafor_tp10Value("0"); + } else { + calculatedatafor_tp10Value("1"); + } + + } + + } catch (JSONException e) { + loading.dismiss(); + if (loading != null && loading.isShowing()) { + loading.dismiss(); + } + ///caling adapter + if (flagfor_top10_value) { + calculatedatafor_tp10Value("0"); + } else { + calculatedatafor_tp10Value("1"); + } + } + } + + @Override + protected void onDestroy() { + if (loading != null && loading.isShowing()) { + loading.dismiss(); + } + super.onDestroy(); + } + + @SuppressLint("NotifyDataSetChanged") + private void validatefilterui() { + RecyclerView rec_subaxe = (RecyclerView) findViewById(R.id.rec_subaxe); + rec_subaxe.setLayoutManager(new GridLayoutManager(context, 3)); + rec_subaxe.setAdapter(new SubAxeValueAdapter(context, getFilters(), "Axe", true, false, (filterText, placeHolder) ->{} )); + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/reports/SalesReportsActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/reports/SalesReportsActivity.java new file mode 100644 index 0000000..a1772ce --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/reports/SalesReportsActivity.java @@ -0,0 +1,395 @@ +package com.cpm.lorealbaautomation.reports; + +import android.annotation.SuppressLint; +import android.app.ProgressDialog; +import android.content.Context; +import android.content.SharedPreferences; + +import androidx.annotation.NonNull; +import androidx.appcompat.app.AppCompatActivity; + +import android.os.Bundle; + +import androidx.cardview.widget.CardView; +import androidx.recyclerview.widget.GridLayoutManager; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; +import androidx.appcompat.widget.Toolbar; + +import android.view.LayoutInflater; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; +import android.widget.TextView; + +import com.google.gson.Gson; +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.constant.CommonFunctions; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterProfileQuestionGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.ProductMaster; +import com.cpm.lorealbaautomation.retrofit.PostApi; + +import org.json.JSONException; +import org.json.JSONObject; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.TimeUnit; + +import okhttp3.MediaType; +import okhttp3.OkHttpClient; +import okhttp3.RequestBody; +import okhttp3.ResponseBody; +import retrofit2.Call; +import retrofit2.Callback; +import retrofit2.Response; +import retrofit2.Retrofit; +import retrofit2.converter.gson.GsonConverterFactory; + +public class SalesReportsActivity extends AppCompatActivity { + String counter_Id, visit_date, username, report_name = ""; + ArrayList salereportList = new ArrayList<>(); + SharedPreferences preferences; + RecyclerView recycle_reports, recSubAxe; + String selectedSubAxe = "Axe"; + SubAxeValueAdapter subAxeValueAdapter; + ArrayList listSubAxe; + SaleReportsAdapter saleReportsAdapter; + ProgressDialog loading = null; + String userType = ""; + TextView product_name; + Lorealba_Database db; + Context context; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_sales_reports); + context = this; + db = new Lorealba_Database(context); + db.open(); + Toolbar toolbar = findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + userType = getIntent().getStringExtra(CommonString.KEY_USER_TYPE); + Objects.requireNonNull(getSupportActionBar()).setHomeButtonEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + iduserinterface(); + } + + @SuppressLint("SetTextI18n") + private void iduserinterface() { + preferences = PrefHelper.getPrefs(context); + counter_Id = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + username = preferences.getString(CommonString.KEY_USERNAME, ""); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + recycle_reports = (RecyclerView) findViewById(R.id.recycle_reports); + recSubAxe = (RecyclerView) findViewById(R.id.rec_subaxe); + product_name = (TextView) findViewById(R.id.product_name); + + report_name = getIntent().getStringExtra(CommonString.Brand); + setTitle("Sale Reports - " + visit_date); + db = new Lorealba_Database(context); + db.open(); + validatefilterui(); + if (CommonFunctions.checkNetIsAvailable(context)) { + download_report(context); + } else { + call_adapter(context); + } + + String couter_code = preferences.getString(CommonString.KEY_COUNTER_CODE, ""); + TextView txt_counter_code = (TextView) findViewById(R.id.txt_counter_code); + txt_counter_code.setText("Counter Code - " + couter_code + " / Id - " + counter_Id); + } + + @SuppressLint("NotifyDataSetChanged") + private void call_adapter(Context context) { + db.open(); + salereportList = db.getsalesReports(selectedSubAxe, userType); + if (!salereportList.isEmpty()) { + saleReportsAdapter = new SaleReportsAdapter(context, salereportList); + recycle_reports.setAdapter(saleReportsAdapter); + recycle_reports.setLayoutManager(new LinearLayoutManager(context)); + saleReportsAdapter.notifyDataSetChanged(); + } + } + + + @SuppressLint("NotifyDataSetChanged") + private void validatefilterui() { + listSubAxe = new ArrayList<>(); + ProductMaster obj = new ProductMaster(); + obj.setSubAxeName("Axe"); + listSubAxe.add(obj); + + obj = new ProductMaster(); + obj.setSubAxeName("Sub Axe"); + listSubAxe.add(obj); + + obj = new ProductMaster(); + obj.setSubAxeName("Signature"); + listSubAxe.add(obj); + + obj = new ProductMaster(); + obj.setSubAxeName("Sub Brand"); + listSubAxe.add(obj); + + obj = new ProductMaster(); + obj.setSubAxeName("Brand"); + listSubAxe.add(obj); + + + obj = new ProductMaster(); + obj.setSubAxeName("Product"); + listSubAxe.add(obj); + + recSubAxe.setLayoutManager(new GridLayoutManager(context, 3)); + subAxeValueAdapter = new SubAxeValueAdapter(context, listSubAxe); + recSubAxe.setAdapter(subAxeValueAdapter); + subAxeValueAdapter.notifyDataSetChanged(); + } + + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // Handle action bar item clicks here. The action bar will + // automatically handle clicks on the Home/Up button, so long + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + if (id == android.R.id.home) { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + SalesReportsActivity.this.finish(); + } + + return super.onOptionsItemSelected(item); + } + + + private class SubAxeValueAdapter extends RecyclerView.Adapter { + LayoutInflater inflator; + List data; + + public SubAxeValueAdapter(Context context, List data) { + inflator = LayoutInflater.from(context); + this.data = data; + } + + @NonNull + @Override + public SubAxeValueAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) { + View view = inflator.inflate(R.layout.item_filter, parent, false); + return new SubAxeValueAdapter.MyViewHolder(view); + } + + + @SuppressLint({"SetTextI18n", "NotifyDataSetChanged"}) + @Override + public void onBindViewHolder(final SubAxeValueAdapter.MyViewHolder holder, final int position) { + final ProductMaster current = data.get(position); + holder.tv_item.setText(current.getSubAxeName()); + holder.tv_item.setId(position); + + if (userType != null && !userType.equalsIgnoreCase(CommonString.TAG_FROM_ME)) { + holder.tv_item.setOnClickListener(v -> { + selectedSubAxe = current.getSubAxeName(); + if (selectedSubAxe.equalsIgnoreCase("Product")) { + product_name.setText("Product Name"); + } else if (selectedSubAxe.equalsIgnoreCase("Axe")) { + product_name.setText("Axe Name"); + } else if (selectedSubAxe.equalsIgnoreCase("Sub Axe")) { + product_name.setText("Sub Axe Name"); + } else if (selectedSubAxe.equalsIgnoreCase("Signature")) { + product_name.setText("Signature Name"); + } else if (selectedSubAxe.equalsIgnoreCase("Sub Brand")) { + product_name.setText("Sub Brand Name"); + } else if (selectedSubAxe.equalsIgnoreCase("Brand")) { + product_name.setText("Brand Name"); + } + db.open(); + saleReportsAdapter = new SaleReportsAdapter(context, db.getsalesReports(selectedSubAxe, userType)); + recycle_reports.setAdapter(saleReportsAdapter); + recycle_reports.setLayoutManager(new LinearLayoutManager(context)); + saleReportsAdapter.notifyDataSetChanged(); + current.setSelected(true); + subAxeValueAdapter.notifyDataSetChanged(); + }); + } + if (userType != null && !userType.equalsIgnoreCase(CommonString.TAG_FROM_ME)) { + holder.tv_item.setTextColor(inflator.getContext().getResources().getColor(R.color.white)); + holder.tv_item.setId(position); + if (current.getSubAxeName().equalsIgnoreCase(selectedSubAxe)) { + holder.card.setCardBackgroundColor(inflator.getContext().getResources().getColor(R.color.dashboard_ach)); + holder.card.setId(position); + } else { + holder.card.setCardBackgroundColor(inflator.getContext().getResources().getColor(R.color.grey_dark_background)); + holder.card.setId(position); + } + } else { + holder.card.setCardBackgroundColor(inflator.getContext().getResources().getColor(R.color.circular_progress_default_background)); + holder.card.setId(position); + + holder.tv_item.setTextColor(inflator.getContext().getResources().getColor(R.color.disable_txt_color)); + holder.tv_item.setId(position); + } + } + + @Override + public int getItemCount() { + return data.size(); + } + + class MyViewHolder extends RecyclerView.ViewHolder { + TextView tv_item; + CardView card; + + public MyViewHolder(View itemView) { + super(itemView); + tv_item = (TextView) itemView.findViewById(R.id.tv_item); + card = (CardView) itemView.findViewById(R.id.item_card); + + } + } + } + + + private class SaleReportsAdapter extends RecyclerView.Adapter { + LayoutInflater inflator; + List data; + + public SaleReportsAdapter(Context context, List data) { + inflator = LayoutInflater.from(context); + this.data = data; + + } + + @NonNull + @Override + public SaleReportsAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) { + View view = inflator.inflate(R.layout.row_sale_report, parent, false); + return new SaleReportsAdapter.MyViewHolder(view); + } + + @SuppressLint("SetTextI18n") + @Override + public void onBindViewHolder(final SaleReportsAdapter.MyViewHolder holder, final int position) { + final ProductMaster current = data.get(position); + + holder.txt_product_name.setText(current.getProductName()); + holder.txt_product_name.setId(position); + + holder.txtValue.setText(String.valueOf(current.getSaleValue())); + holder.txtValue.setId(position); + + holder.txt_QTY.setText(current.getActualQty()); + holder.txt_QTY.setId(position); + } + + @Override + public int getItemCount() { + return data.size(); + } + + + class MyViewHolder extends RecyclerView.ViewHolder { + TextView txt_product_name, txt_QTY, txtValue; + + public MyViewHolder(View itemView) { + super(itemView); + txt_product_name = (TextView) itemView.findViewById(R.id.txt_product_name); + txt_QTY = (TextView) itemView.findViewById(R.id.txt_QTY); + txtValue = (TextView) itemView.findViewById(R.id.txtValue); + } + } + } + + private void download_report(final Context context) { + try { + JSONObject jsonObject = new JSONObject(); + jsonObject.put("Downloadtype", userType != null && userType.equalsIgnoreCase(CommonString.TAG_FROM_ME) ? "Report_Sales_DetailME" : "Report_Sales_Detail"); + jsonObject.put("Username", username); + jsonObject.put("Param1", counter_Id); + jsonObject.put("Param2", ""); + String jsonString = jsonObject.toString(); + try { + loading = ProgressDialog.show(context, "Processing", "Please wait...", false, true); + OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build(); + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsonString); + Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build(); + PostApi api = adapter.create(PostApi.class); + Call call = api.getTabjournePlan(jsonData); + call.enqueue(new Callback() { + @Override + public void onResponse(@NonNull Call call, @NonNull Response response) { + ResponseBody responseBody = response.body(); + String data = null; + if (responseBody != null && response.isSuccessful()) { + try { + assert response.body() != null; + data = response.body().string(); + data = data.substring(1, data.length() - 1).replace("\\", ""); + if (data.equalsIgnoreCase(CommonString.KEY_FAILURE)) { + if (loading != null && loading.isShowing()) loading.dismiss(); + + call_adapter(context); + + } else if (!data.contains("No Data")) { + if (loading != null && loading.isShowing()) loading.dismiss(); + + MasterProfileQuestionGetterSetter reportSaleDetailsObject = new Gson().fromJson(data, MasterProfileQuestionGetterSetter.class); + if (reportSaleDetailsObject != null) { + db.open(); + db.insertReportSaleDetails(reportSaleDetailsObject, userType != null && userType.equalsIgnoreCase(CommonString.TAG_FROM_ME)); + } + call_adapter(context); + + + } else { + if (loading != null && loading.isShowing()) loading.dismiss(); + + db.open(); + db.delete_table_data(userType != null && userType.equalsIgnoreCase(CommonString.TAG_FROM_ME) ? "Report_Sales_DetailME" : "Report_Sales_Detail"); + + call_adapter(context); + } + + } catch (Exception e) { + if (loading != null && loading.isShowing()) loading.dismiss(); + + call_adapter(context); + } + } else { + if (loading != null && loading.isShowing()) loading.dismiss(); + + call_adapter(context); + + } + } + + @Override + public void onFailure(@NonNull Call call, @NonNull Throwable t) { + if (loading != null && loading.isShowing()) loading.dismiss(); + + call_adapter(context); + } + }); + + } catch (Exception e) { + if (loading != null && loading.isShowing()) loading.dismiss(); + + call_adapter(context); + + } + + } catch (JSONException e) { + if (loading != null && loading.isShowing()) loading.dismiss(); + + call_adapter(context); + } + } + + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/reports/TargetAchievementActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/reports/TargetAchievementActivity.java new file mode 100644 index 0000000..4065b7b --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/reports/TargetAchievementActivity.java @@ -0,0 +1,445 @@ +package com.cpm.lorealbaautomation.reports; + +import static com.cpm.lorealbaautomation.constant.CommonFunctions.capitalizeFirstLetter; + +import android.annotation.SuppressLint; +import android.content.Context; +import android.content.SharedPreferences; +import android.content.res.Resources; +import android.graphics.Color; +import android.os.Bundle; + +import androidx.annotation.NonNull; +import androidx.appcompat.app.AppCompatActivity; +import androidx.cardview.widget.CardView; +import androidx.core.content.ContextCompat; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; +import androidx.appcompat.widget.Toolbar; + +import android.view.LayoutInflater; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; +import android.widget.LinearLayout; +import android.widget.TextView; + +import com.github.mikephil.charting.charts.CombinedChart; +import com.github.mikephil.charting.components.XAxis; +import com.github.mikephil.charting.components.YAxis; +import com.github.mikephil.charting.data.BarData; +import com.github.mikephil.charting.data.BarDataSet; +import com.github.mikephil.charting.data.BarEntry; +import com.github.mikephil.charting.data.CombinedData; +import com.github.mikephil.charting.data.LineData; +import com.github.mikephil.charting.data.LineDataSet; +import com.github.mikephil.charting.formatter.IndexAxisValueFormatter; +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.constant.CommonFunctions; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.gsonGetterSetter.AppDashboardTVADrillDown; +import com.cpm.lorealbaautomation.reportGetterSetter.AppDashboardIncentive; +import com.cpm.lorealbaautomation.utils.BarChartCustomRenderer; +import com.cpm.lorealbaautomation.utils.RoundedBarChart; +import com.cpm.lorealbaautomation.utils.VerticalValueFormatter; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +public class TargetAchievementActivity extends AppCompatActivity { + private ArrayList downs = new ArrayList<>(); + private LinearLayout rlIncentiveDetail, rlLeaderBInfo, rlTVADetails; + private TextView tvEIncentive, tvMaxIncentive, + tvSaleLinkedIncentive, tvFlatIncentive, tvTotalIncentive, tvNodata; + String counter_Id, visit_date, username, kPI; + private SharedPreferences preferences; + RecyclerView recycle_reports; + Lorealba_Database db; + Context context; + RoundedBarChart barChart; + CombinedChart combinedChart; + ArrayList barEntries, targetBarEntries; + String[] productsgroupnames; + long _totalsales = 0, totalTarget = 0; + List entries; + + @SuppressLint("SetTextI18n") + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_reports_sale_details); + context = this; + db = new Lorealba_Database(context); + db.open(); + combinedChart = (CombinedChart) findViewById(R.id.combinedChart); + barChart = findViewById(R.id.idBarChart); + Toolbar toolbar = findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + kPI = getIntent().getStringExtra("kpi"); + Objects.requireNonNull(getSupportActionBar()).setHomeButtonEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + iduserinterface(); + String couter_code = preferences.getString(CommonString.KEY_COUNTER_CODE, ""); + TextView txt_counter_code = (TextView) findViewById(R.id.txt_counter_code); + txt_counter_code.setText("Counter Code - " + couter_code + " / Id - " + counter_Id); + calculateRequiredData(); + } + + + private void calculateRequiredData() { + if (kPI != null && kPI.equals("LeaderBoard")) { + db.open(); + downs = db.getLeaderDashboards(); + if (!downs.isEmpty()) { + rlLeaderBInfo.setVisibility(View.VISIBLE); + rlIncentiveDetail.setVisibility(View.GONE); + Adapter(findViewById(R.id.recycleLeaderb)); + rlTVADetails.setVisibility(View.GONE); + } else tvNodata.setVisibility(View.GONE); + } else if (kPI != null && kPI.equals("Incentive")) { + incentiveDetail(); + } else + TVAdeTail(); + } + + private void Adapter(RecyclerView recyclerView) { + recyclerView.setAdapter(new DashTVADrillDownAdapter(context, downs)); + recyclerView.setLayoutManager(new LinearLayoutManager(context)); + } + + private void barChart() { + try { + barChart.setVisibility(View.VISIBLE); + combinedChart.setVisibility(View.GONE); + barChart.setScaleEnabled(false); + BarDataSet set = new BarDataSet(entries, ""); + set.setColors(ContextCompat.getColor(context, R.color.achievement), ContextCompat.getColor(context, R.color.target_color)); + set.setStackLabels(new String[]{getString(R.string.achievement), getString(R.string.targets)}); + set.setDrawIcons(false); + set.setDrawValues(false); // Enable value drawing + if (CommonFunctions.isTablet(context)) { + set.setValueTextSize(15f); // Set the text size for the values + } else { + set.setValueTextSize(10f); // Set the text size for the values + } + set.setValueTextColor(Color.WHITE); + BarData data = new BarData(set); + barChart.setDrawValueAboveBar(false); + barChart.setDrawBarShadow(false); + barChart.setDrawGridBackground(false); + ///decrease width for 3 column + if (downs.size() == 1) { + data.setBarWidth(0.2f); + } else if (downs.size() > 1 && downs.size() <= 3) { + data.setBarWidth(0.5f); + } + barChart.setData(data); + + XAxis xAxis = barChart.getXAxis(); + xAxis.setValueFormatter(new IndexAxisValueFormatter(productsgroupnames)); + barChart.setVisibleXRangeMaximum(productsgroupnames.length); + xAxis.setGranularity(1f); + xAxis.setPosition(XAxis.XAxisPosition.BOTTOM); + /////YAxisLeft + YAxis yAxisLeft = barChart.getAxisLeft(); + yAxisLeft.setAxisMinimum(5f); + yAxisLeft.setDrawGridLines(false); + xAxis.setPosition(XAxis.XAxisPosition.BOTTOM); + // yAxisLeft.setPosition(YAxis.YAxisLabelPosition.INSIDE_CHART); + yAxisLeft.setEnabled(true); + yAxisLeft.setDrawZeroLine(true); + //remove left border + yAxisLeft.setDrawAxisLine(true); + yAxisLeft.setTextColor(R.color.text_grey_color); + + YAxis yAxisRight = barChart.getAxisRight(); + //remove right border + yAxisRight.setAxisMinimum(5f); + yAxisRight.setDrawGridLines(false); + //remove left border + yAxisRight.setDrawAxisLine(false); + yAxisRight.setPosition(YAxis.YAxisLabelPosition.INSIDE_CHART); + yAxisRight.setEnabled(false); + + barChart.getXAxis().setDrawGridLines(false); + barChart.getDescription().setEnabled(false); + //remove top border + barChart.getXAxis().setDrawAxisLine(false); + BarChartCustomRenderer barChartCustomRenderer + = new BarChartCustomRenderer(barChart, barChart.getAnimator(), barChart.getViewPortHandler()); + barChart.setRenderer(barChartCustomRenderer); + barChart.getLegend().setEnabled(false); + barChart.invalidate(); + + } catch (Resources.NotFoundException e) { + throw new RuntimeException(e); + } + } + + private void iduserinterface() { + preferences = PrefHelper.getPrefs(context); + counter_Id = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + username = preferences.getString(CommonString.KEY_USERNAME, ""); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + recycle_reports = (RecyclerView) findViewById(R.id.recycle_reports); + rlIncentiveDetail = (LinearLayout) findViewById(R.id.rlIncentiveDetail); + rlLeaderBInfo = (LinearLayout) findViewById(R.id.rlLeaderBInfo); + rlTVADetails = (LinearLayout) findViewById(R.id.rlTVADetails); + /////////////////// + tvEIncentive = (TextView) findViewById(R.id.tvEIncentive); + tvMaxIncentive = (TextView) findViewById(R.id.tvMaxIncentive); + tvSaleLinkedIncentive = (TextView) findViewById(R.id.tvSaleLinkedIncentive); + tvTotalIncentive = (TextView) findViewById(R.id.tvTotalIncentive); + tvFlatIncentive = (TextView) findViewById(R.id.tvFlatIncentive); + ////For no data view + tvNodata = (TextView) findViewById(R.id.tvNodata); + + if (kPI != null && kPI.equals("Incentive")) { + setTitle("Incentive Details - " + visit_date); + } else { + setTitle((kPI != null && kPI.equals("LeaderBoard")) ? "Leader Board Details - " + visit_date : "Target vs Achievement - " + visit_date); + } + db = new Lorealba_Database(context); + db.open(); + } + + + private class DashTVADrillDownAdapter extends RecyclerView.Adapter { + LayoutInflater inflator; + List data; + + public DashTVADrillDownAdapter(Context context, List data) { + inflator = LayoutInflater.from(context); + this.data = data; + } + + @NonNull + @Override + public DashTVADrillDownAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) { + View view = inflator.inflate((kPI != null && kPI.equals("LeaderBoard")) ? R.layout.row_leaderboard_info : R.layout.row_tva_drill_down, parent, false); + return new DashTVADrillDownAdapter.MyViewHolder(view); + } + + @SuppressLint({"SetTextI18n", "DefaultLocale"}) + @Override + public void onBindViewHolder(@NonNull final MyViewHolder viewholder, final int position) { + final AppDashboardTVADrillDown current = data.get(position); + if (kPI != null && kPI.equals("LeaderBoard")) { + viewholder.tvProductGroup.setText(capitalizeFirstLetter(current.getProductGroupName())); + viewholder.tvProductGroup.setId(position); + + viewholder.tvTotalSales.setText(current.getGraph()); + viewholder.tvTotalSales.setId(position); + + viewholder.tvAchPer.setText(current.getPer().toString() + "%"); + viewholder.tvAchPer.setId(position); + + } else { + viewholder.tvProductGroup.setText(capitalizeFirstLetter(current.getProductGroupName())); + viewholder.tvProductGroup.setId(position); + viewholder.tvTargets.setText(String.format("%.0f", current.getTarget())); + viewholder.tvTargets.setId(position); + viewholder.tvTotalSales.setText(String.format("%.0f", current.getTotalSale())); + viewholder.tvTotalSales.setId(position); + viewholder.tvAchPer.setText(current.getPer().toString() + "%"); + viewholder.tvAchPer.setId(position); + if (position == data.size() - 1) { + viewholder.cardtotalValues.setVisibility(View.VISIBLE); + viewholder.cardtotalValues.setId(position); + viewholder.tvCalculatedSales.setText(String.valueOf(_totalsales)); + viewholder.tvCalculatedSales.setId(position); + viewholder.tvtotalTargets.setText(String.valueOf(totalTarget)); + viewholder.tvtotalTargets.setId(position); + } else { + viewholder.cardtotalValues.setVisibility(View.GONE); + viewholder.cardtotalValues.setId(position); + } + } + } + + @Override + public int getItemCount() { + return data.size(); + } + + class MyViewHolder extends RecyclerView.ViewHolder { + TextView tvProductGroup, tvTargets, tvTotalSales, tvAchPer, tvtotalTargets, tvCalculatedSales; + CardView cardtotalValues; + + public MyViewHolder(View itemView) { + super(itemView); + if (kPI != null && kPI.equals("LeaderBoard")) { + tvProductGroup = (TextView) itemView.findViewById(R.id.tvProductGroup); + tvTotalSales = (TextView) itemView.findViewById(R.id.tvTotalSales); + tvAchPer = (TextView) itemView.findViewById(R.id.tvAchPer); + } else { + tvProductGroup = (TextView) itemView.findViewById(R.id.tvProductGroup); + tvTargets = (TextView) itemView.findViewById(R.id.tvTargets); + tvTotalSales = (TextView) itemView.findViewById(R.id.tvTotalSales); + tvAchPer = (TextView) itemView.findViewById(R.id.tvAchPer); + + cardtotalValues = (CardView) itemView.findViewById(R.id.cardtotalValues); + tvtotalTargets = (TextView) itemView.findViewById(R.id.tvtotalTargets); + tvCalculatedSales = (TextView) itemView.findViewById(R.id.tvCalculatedSales); + } + } + } + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + if (id == android.R.id.home) { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + this.finish(); + } + + return super.onOptionsItemSelected(item); + } + + @Override + public void onBackPressed() { + super.onBackPressed(); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + this.finish(); + } + + private void combinedChart() { + try { + // initializing variable for bar chart. + barChart.setVisibility(View.GONE); + combinedChart.setVisibility(View.VISIBLE); + combinedChart.getDescription().setEnabled(false); + + BarDataSet barDataSet = new BarDataSet(targetBarEntries, getString(R.string.targets)); + barDataSet.setColor(context.getResources().getColor(R.color.target_color)); + barDataSet.setDrawIcons(false); + BarData barData = new BarData(barDataSet); + barData.setDrawValues(false); // Enable value drawing + + if (CommonFunctions.isTablet(context)) { + barData.setValueTextSize(15f); // Set the text size for the values + } else { + barData.setValueTextSize(10f); // Set the text size for the values + } + barData.setValueTextColor(Color.BLUE); + // Use the custom VerticalValueFormatter + barDataSet.setValueFormatter(new VerticalValueFormatter()); + + LineDataSet lineDataSet = new LineDataSet(barEntries, getString(R.string.achievement)); + lineDataSet.setColor(context.getResources().getColor(R.color.achievement)); + lineDataSet.setLineWidth(2.5f); + lineDataSet.setCircleColor(context.getResources().getColor(R.color.achievement)); + lineDataSet.setCircleRadius(4f); + lineDataSet.setFillColor(context.getResources().getColor(R.color.achievement)); + lineDataSet.setDrawValues(false); + lineDataSet.setDrawIcons(false); + if (CommonFunctions.isTablet(context)) { + lineDataSet.setValueTextSize(15f); // Set the text size for the values + } else { + lineDataSet.setValueTextSize(10f); // Set the text size for the values + } + + lineDataSet.setValueTextColor(Color.GREEN); + lineDataSet.setMode(LineDataSet.Mode.STEPPED); + LineData lineData = new LineData(lineDataSet); + // Combine the data sets + CombinedData combinedData = new CombinedData(); + combinedData.setData(barData); + combinedData.setData(lineData); + // Set data to the chart + combinedChart.setData(combinedData); + // Customize X-axis + XAxis xAxis = combinedChart.getXAxis(); + xAxis.setValueFormatter(new IndexAxisValueFormatter(productsgroupnames)); + combinedChart.setVisibleXRangeMaximum(productsgroupnames.length); + xAxis.setGranularity(1f); + xAxis.setPosition(XAxis.XAxisPosition.BOTTOM); + /////YAxisLeft + YAxis yAxisLeft = combinedChart.getAxisLeft(); + yAxisLeft.setAxisMinimum(5f); + yAxisLeft.setDrawGridLines(false); + //remove left border + yAxisLeft.setDrawAxisLine(false); + yAxisLeft.setPosition(YAxis.YAxisLabelPosition.INSIDE_CHART); + yAxisLeft.setEnabled(false); + + YAxis yAxisRight = combinedChart.getAxisRight(); + //remove right border + yAxisRight.setAxisMinimum(1f); + yAxisRight.setDrawGridLines(false); + //remove left border + yAxisRight.setDrawAxisLine(false); + yAxisRight.setPosition(YAxis.YAxisLabelPosition.INSIDE_CHART); + yAxisRight.setEnabled(false); + + combinedChart.getXAxis().setDrawGridLines(false); + combinedChart.getDescription().setEnabled(false); + //remove top border + combinedChart.getXAxis().setDrawAxisLine(false); + combinedChart.getLegend().setEnabled(false); + combinedChart.setScaleEnabled(false); + combinedChart.invalidate(); + } catch (Resources.NotFoundException e) { + throw new RuntimeException(e); + } + } + + @SuppressLint("SetTextI18n") + private void incentiveDetail() { + db.open(); + AppDashboardIncentive incentive = db.getDashboardIncentiveDetail(counter_Id, username); + if (incentive != null) { + rlLeaderBInfo.setVisibility(View.GONE); + try { + rlIncentiveDetail.setVisibility(View.VISIBLE); + tvEIncentive.setText(context.getString(R.string.Rs) + " " + incentive.getToatlIncentive().intValue()); + tvMaxIncentive.setText(context.getString(R.string.Rs) + " " + incentive.getMaximumIncentive().intValue()); + tvSaleLinkedIncentive.setText(context.getString(R.string.Rs) + " " + incentive.getSLIncentive().intValue()); + tvFlatIncentive.setText(context.getString(R.string.Rs) + " " + incentive.getFlatIncentive().intValue()); + tvTotalIncentive.setText(context.getString(R.string.Rs) + " " + incentive.getToatlIncentive().intValue()); + rlTVADetails.setVisibility(View.GONE); + } catch (Exception e) { + e.fillInStackTrace(); + } + } else tvNodata.setVisibility(View.VISIBLE); + } + + private void TVAdeTail() { + db.open(); + downs = db.getDashboardTVADrillDown(counter_Id); + if (!downs.isEmpty()) { + ArrayList names = new ArrayList<>(); + rlIncentiveDetail.setVisibility(View.GONE); + rlTVADetails.setVisibility(View.VISIBLE); + rlLeaderBInfo.setVisibility(View.GONE); + targetBarEntries = new ArrayList<>(); + barEntries = new ArrayList<>(); + entries = new ArrayList<>(); + + for (int k = 0; k < downs.size(); k++) { + _totalsales += downs.get(k).getTotalSale().intValue(); + totalTarget += downs.get(k).getTarget().intValue(); + names.add(capitalizeFirstLetter(downs.get(k).getProductGroupName())); + entries.add(new BarEntry(k, new float[]{downs.get(k).getTotalSale(). + intValue(), downs.get(k).getTarget().intValue()})); + targetBarEntries.add(new BarEntry(k, + downs.get(k).getTarget().intValue())); + barEntries.add(new BarEntry(k, + downs.get(k).getTotalSale().intValue())); + } + productsgroupnames = names.toArray(new String[0]); + /*if (appDashboardTVADrillDowns.get(0).getGraph().equals("Bar Chart")) { + barChart(); + } else { + combinedChart(); + }*/ + barChart(); + Adapter(recycle_reports); + } else tvNodata.setVisibility(View.VISIBLE); + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/reports/TesterReportActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/reports/TesterReportActivity.java new file mode 100644 index 0000000..60edc40 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/reports/TesterReportActivity.java @@ -0,0 +1,284 @@ +package com.cpm.lorealbaautomation.reports; + +import static com.cpm.lorealbaautomation.constant.CommonFunctions.getFilters; + +import android.annotation.SuppressLint; +import android.content.Context; +import android.content.SharedPreferences; + +import androidx.annotation.NonNull; +import androidx.appcompat.app.AppCompatActivity; + +import android.os.Bundle; + +import androidx.recyclerview.widget.GridLayoutManager; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; +import androidx.appcompat.widget.Toolbar; + +import android.view.LayoutInflater; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; +import android.widget.LinearLayout; +import android.widget.TextView; + +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.adapter.SubAxeValueAdapter; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.gsonGetterSetter.TStockSummary; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +public class TesterReportActivity extends AppCompatActivity { + ArrayList reportsList = new ArrayList<>(); + String counter_Id, visit_date, username, report_name = "", default_type = "Axe"; + TextView brand_name, testername_txt, unit_of_testertxt; + SharedPreferences preferences; + RecyclerView recycle_reports; + Lorealba_Database db; + Context context; + LinearLayout card_total_salestock, rlTester, rlOthers; + TextView total_sales_qty, sale_value_total, tvTesterName, tvUnit_of_tester; + + @SuppressLint("SetTextI18n") + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_tester_report); + context = this; + db = new Lorealba_Database(context); + db.open(); + Toolbar toolbar = findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + Objects.requireNonNull(getSupportActionBar()).setHomeButtonEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + iduserinterface(); + + String couter_code = preferences.getString(CommonString.KEY_COUNTER_CODE, ""); + TextView txt_counter_code = (TextView) findViewById(R.id.txt_counter_code); + txt_counter_code.setText("Counter Code - " + couter_code + " / Id - " + counter_Id); + } + + + @SuppressLint("SetTextI18n") + private void iduserinterface() { + preferences = PrefHelper.getPrefs(context); + counter_Id = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + username = preferences.getString(CommonString.KEY_USERNAME, ""); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + recycle_reports = (RecyclerView) findViewById(R.id.recycle_reports); + brand_name = (TextView) findViewById(R.id.brand_name); + testername_txt = (TextView) findViewById(R.id.testername_txt); + unit_of_testertxt = (TextView) findViewById(R.id.unit_of_testertxt); + card_total_salestock = (LinearLayout) findViewById(R.id.card_total_salestock); + rlTester = (LinearLayout) findViewById(R.id.rlTester); + rlOthers = (LinearLayout) findViewById(R.id.rlOthers); + total_sales_qty = (TextView) findViewById(R.id.total_sales_qty); + sale_value_total = (TextView) findViewById(R.id.sale_value_total); + tvTesterName = (TextView) findViewById(R.id.tvTesterName); + tvUnit_of_tester = (TextView) findViewById(R.id.tvUnit_of_tester); + report_name = getIntent().getStringExtra(CommonString.Brand); + setTitle("Reports " + report_name + "- " + visit_date); + db = new Lorealba_Database(context); + db.open(); + if (report_name.equalsIgnoreCase("Tester Stock Summary")) { + tvTesterName.setText(default_type + " Name"); + tvUnit_of_tester.setText(getString(R.string.tester_availebility)); + reportsList = db.getreport_tester_stock(counter_Id, default_type + "Name"); + total_stock_calculate(true, reportsList); + rlTester.setVisibility(View.VISIBLE); + rlOthers.setVisibility(View.GONE); + } else if (report_name.equalsIgnoreCase("Counter Coverage")) { + db.open(); + brand_name.setText(getString(R.string.visitdate)); + testername_txt.setText(getString(R.string.counter_name)); + unit_of_testertxt.setText(getString(R.string.counter_code)); + reportsList = db.getStockCheckReport(visit_date, counter_Id, true, default_type + "Name"); + total_stock_calculate(true, reportsList); + rlTester.setVisibility(View.GONE); + rlOthers.setVisibility(View.VISIBLE); + } else { + db.open(); + rlTester.setVisibility(View.GONE); + rlOthers.setVisibility(View.VISIBLE); + brand_name.setText(default_type + " Name"); + setTitle(report_name + " - " + visit_date); + testername_txt.setText(getString(R.string.stock_qty)); + unit_of_testertxt.setText(getString(R.string.stock_value)); + reportsList = db.getStockCheckReport(visit_date, counter_Id, false, default_type + "Name"); + total_stock_calculate(false, reportsList); + } + + if (!reportsList.isEmpty()) { + validatefilterui(); + recycle_reports.setAdapter(new ReportsAdapter(context, reportsList)); + recycle_reports.setLayoutManager(new LinearLayoutManager(context)); + } + } + + @SuppressLint("SetTextI18n") + private void total_stock_calculate(boolean flag_tester, ArrayList reportsList) { + try { + if (flag_tester) { + db.open(); + TStockSummary testStocksummery = db.gettesterstock(counter_Id); + if (!reportsList.isEmpty() && testStocksummery != null) { + card_total_salestock.setVisibility(View.VISIBLE); + total_sales_qty.setText(""); + sale_value_total.setText("Total " + getString(R.string.tester_availebility) + "\n" + testStocksummery.getTesterBalance()); + } else { + card_total_salestock.setVisibility(View.GONE); + total_sales_qty.setText(""); + sale_value_total.setText(""); + } + } else { + db.open(); + TStockSummary stockSummary = db.getStockCheckTotalStockWithQty(visit_date, counter_Id); + if (!reportsList.isEmpty() && stockSummary != null) { + card_total_salestock.setVisibility(View.VISIBLE); + total_sales_qty.setText("Total Stock QTY \n" + stockSummary.getStock()); + sale_value_total.setText("Total Stock Value \n" + stockSummary.getMrp()); + } else { + card_total_salestock.setVisibility(View.GONE); + total_sales_qty.setText(""); + sale_value_total.setText(""); + } + } + + } catch (Exception e) { + e.fillInStackTrace(); + } + } + + private class ReportsAdapter extends RecyclerView.Adapter { + final LayoutInflater inflator; + List data; + + public ReportsAdapter(Context context, List data) { + inflator = LayoutInflater.from(context); + this.data = data; + } + + @NonNull + @Override + public ReportsAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) { + View view = inflator.inflate(R.layout.row_reports_tester, parent, false); + return new ReportsAdapter.MyViewHolder(view); + } + + @SuppressLint("SetTextI18n") + @Override + public void onBindViewHolder(@NonNull final ReportsAdapter.MyViewHolder holder, final int position) { + final TStockSummary current = data.get(position); + if (report_name.equalsIgnoreCase("Tester Stock Summary")) { + holder.itemRLTester.setVisibility(View.VISIBLE); + holder.itemRLTester.setId(position); + holder.itemRLOther.setVisibility(View.GONE); + holder.itemRLOther.setId(position); + + holder.tvTesterName.setText(current.getProductName()); + holder.tvTesterName.setId(position); + holder.tvTesterBalances.setText(current.getTesterBalance().toString()); + holder.tvTesterBalances.setId(position); + } else if (report_name.equalsIgnoreCase("Counter Coverage")) { + holder.itemRLTester.setVisibility(View.GONE); + holder.itemRLTester.setId(position); + holder.itemRLOther.setVisibility(View.VISIBLE); + holder.itemRLOther.setId(position); + + holder.product_name.setText(current.getProductName()); + holder.product_name.setId(position); + holder.tester_balance.setText(current.getGwpStatus()); + holder.tester_balance.setId(position); + holder.brand_name_txt.setText(current.getBrand_name()); + holder.brand_name_txt.setId(position); + } else { + holder.itemRLTester.setVisibility(View.GONE); + holder.itemRLTester.setId(position); + holder.itemRLOther.setVisibility(View.VISIBLE); + holder.itemRLOther.setId(position); + holder.brand_name_txt.setText(current.getBrand_name()); + holder.brand_name_txt.setId(position); + holder.product_name.setText(String.valueOf(current.getStock())); + holder.product_name.setId(position); + holder.tester_balance.setText(String.valueOf(current.getMrp())); + holder.tester_balance.setId(position); + } + } + + @Override + public int getItemCount() { + return data.size(); + } + + class MyViewHolder extends RecyclerView.ViewHolder { + LinearLayout itemRLOther, itemRLTester; + TextView brand_name_txt, tester_balance, product_name, + tvTesterName, tvTesterBalances; + + public MyViewHolder(View itemView) { + super(itemView); + itemRLTester = (LinearLayout) itemView.findViewById(R.id.itemRLTester); + itemRLOther = (LinearLayout) itemView.findViewById(R.id.itemRLOther); + brand_name_txt = (TextView) itemView.findViewById(R.id.brand_name_txt); + tester_balance = (TextView) itemView.findViewById(R.id.tester_balance); + product_name = (TextView) itemView.findViewById(R.id.product_name); + ////for tester + tvTesterName = (TextView) itemView.findViewById(R.id.tvTesterName); + tvTesterBalances = (TextView) itemView.findViewById(R.id.tvTesterBalances); + } + } + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + if (id == android.R.id.home) { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + this.finish(); + + } + + + return super.onOptionsItemSelected(item); + } + + @Override + public void onBackPressed() { + super.onBackPressed(); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + this.finish(); + } + + @SuppressLint("NotifyDataSetChanged") + private void validatefilterui() { + RecyclerView rec_subaxe = (RecyclerView) findViewById(R.id.rec_subaxe); + rec_subaxe.setLayoutManager(new GridLayoutManager(context, 3)); + rec_subaxe.setAdapter(new SubAxeValueAdapter(context, getFilters(), default_type, report_name.equals("Counter Coverage"), false, this::callAdapter)); + } + private void callAdapter(String column_name, String place_holder) { + String compColumn = column_name.replaceAll(" ", ""); + compColumn += "Name"; + if (report_name.equalsIgnoreCase("Tester Stock Summary")) { + tvTesterName.setText(place_holder); + reportsList = db.getreport_tester_stock(counter_Id, compColumn); + } else if (report_name.equalsIgnoreCase("Counter Coverage")) { + brand_name.setText(getString(R.string.visitdate)); + reportsList = db.getStockCheckReport(visit_date, counter_Id, true, compColumn); + } else { + brand_name.setText(place_holder); + reportsList = db.getStockCheckReport(visit_date, counter_Id, false, compColumn); + } + + if (!reportsList.isEmpty()) { + recycle_reports.setAdapter(new ReportsAdapter(context, reportsList)); + recycle_reports.setLayoutManager(new LinearLayoutManager(context)); + } + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/reports/countervaluevolume/CounterValueVolumeDetailActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/reports/countervaluevolume/CounterValueVolumeDetailActivity.java new file mode 100644 index 0000000..e93a59e --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/reports/countervaluevolume/CounterValueVolumeDetailActivity.java @@ -0,0 +1,243 @@ +package com.cpm.lorealbaautomation.reports.countervaluevolume; + +import static com.cpm.lorealbaautomation.constant.CommonFunctions.getFilters; + +import android.annotation.SuppressLint; +import android.app.ProgressDialog; +import android.content.Context; +import android.content.SharedPreferences; +import android.os.Bundle; +import android.view.MenuItem; +import android.view.View; +import android.widget.LinearLayout; +import android.widget.TextView; + +import androidx.annotation.NonNull; +import androidx.appcompat.app.AppCompatActivity; +import androidx.appcompat.widget.Toolbar; +import androidx.recyclerview.widget.GridLayoutManager; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; + +import com.google.gson.Gson; +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.adapter.SubAxeValueAdapter; +import com.cpm.lorealbaautomation.adapter.VolumeDetailAdapter; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.databinding.DetailTesterUsageBinding; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.gsonGetterSetter.ResponseResult; +import com.cpm.lorealbaautomation.gsonGetterSetter.countervolune.ReportCounterVolume; +import com.cpm.lorealbaautomation.gsonGetterSetter.countervolune.ReportCounterVolumeDetail; +import com.cpm.lorealbaautomation.retrofit.PostApi; + +import org.json.JSONException; +import org.json.JSONObject; + +import java.util.ArrayList; +import java.util.Objects; +import java.util.concurrent.TimeUnit; + +import okhttp3.MediaType; +import okhttp3.OkHttpClient; +import okhttp3.RequestBody; +import okhttp3.ResponseBody; +import retrofit2.Call; +import retrofit2.Callback; +import retrofit2.Response; +import retrofit2.Retrofit; +import retrofit2.converter.gson.GsonConverterFactory; + +public class CounterValueVolumeDetailActivity extends AppCompatActivity { + TextView tvCounterValue, tvMTDVolumePlaceholder, AvgPerDayVolumePlaceholder, tvMTDVolume, AvgPerDayVolume, + tvCounterVolumeDetail, tvParamCode, tvParamName, tvMTDVolumeDetail, tvAvgPerDayVolumeDetail; + ArrayList volumeDetails = new ArrayList<>(); + String counter_Id, visit_date, username, default_type = "Axe", reportName = ""; + LinearLayout rlCounterVolume, rlCounterVolumeDetails; + RecyclerView recyclCounterVolumeDetail; + private SharedPreferences preferences; + boolean value_flag = false; + Lorealba_Database db; + Context context; + + @SuppressLint("SetTextI18n") + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_counter_value); + context = this; + db = new Lorealba_Database(context); + db.open(); + Toolbar toolbar = findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + Objects.requireNonNull(getSupportActionBar()).setHomeButtonEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + iduserinterface(); + String couter_code = preferences.getString(CommonString.KEY_COUNTER_CODE, ""); + TextView txt_counter_code = (TextView) findViewById(R.id.txt_counter_code); + txt_counter_code.setText("Counter Code - " + couter_code + " / Id - " + counter_Id); + validatefilterui(); + } + + @SuppressLint("SetTextI18n") + private void iduserinterface() { + preferences = PrefHelper.getPrefs(context); + counter_Id = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + username = preferences.getString(CommonString.KEY_USERNAME, ""); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + + tvCounterValue = (TextView) findViewById(R.id.tvCounterValue); + tvMTDVolumePlaceholder = (TextView) findViewById(R.id.tvMTDVolumePlaceholder); + AvgPerDayVolumePlaceholder = (TextView) findViewById(R.id.AvgPerDayVolumePlaceholder); + tvMTDVolume = (TextView) findViewById(R.id.tvMTDVolume); + AvgPerDayVolume = (TextView) findViewById(R.id.AvgPerDayVolume); + //////details + tvCounterVolumeDetail = (TextView) findViewById(R.id.tvCounterVolumeDetail); + tvParamCode = (TextView) findViewById(R.id.tvParamCode); + tvParamName = (TextView) findViewById(R.id.tvParamName); + tvMTDVolumeDetail = (TextView) findViewById(R.id.tvMTDVolumeDetail); + tvAvgPerDayVolumeDetail = (TextView) findViewById(R.id.tvAvgPerDayVolumeDetail); + + rlCounterVolume = (LinearLayout) findViewById(R.id.rlCounterVolume); + recyclCounterVolumeDetail = (RecyclerView) findViewById(R.id.recyclCounterVolumeDetail); + rlCounterVolumeDetails = (LinearLayout) findViewById(R.id.rlCounterVolumeDetails); + if (getIntent().getStringExtra(CommonString.Brand) != null) { + reportName = getIntent().getStringExtra(CommonString.Brand); + } + assert reportName != null; + db.open(); + ReportCounterVolume counterVolume = db.getCounterVolume(counter_Id, false); + if (reportName.equalsIgnoreCase("Counter Value Detail")) { + db.open(); + value_flag = true; + counterVolume = db.getCounterVolume(counter_Id, true); + AvgPerDayVolumePlaceholder.setText("AvgPer Day Value"); + tvCounterValue.setText("Counter Top 10 Value"); + tvMTDVolumePlaceholder.setText("MTD Value"); + tvCounterVolumeDetail.setText("Counter Top 10 Value Details"); + tvAvgPerDayVolumeDetail.setText("AvgPer Day Value"); + tvMTDVolumeDetail.setText("MTD Value"); + } + + if (counterVolume != null) { + tvMTDVolume.setText(counterVolume.getMTDVolume() != null ? counterVolume.getMTDVolume().toString() : "0"); + AvgPerDayVolume.setText(counterVolume.getAvgPerDayVolume() != null ? counterVolume.getAvgPerDayVolume().toString() : "0"); + } + + counterVolumeDetails(default_type, null); + setTitle(reportName + " Report " + " - " + visit_date); + db = new Lorealba_Database(context); + db.open(); + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + if (id == android.R.id.home) { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + this.finish(); + } + return super.onOptionsItemSelected(item); + } + + @Override + public void onBackPressed() { + super.onBackPressed(); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + this.finish(); + } + + @SuppressLint("SetTextI18n") + private void counterVolumeDetails(String param, ProgressDialog dialog) { + //details + volumeDetails = db.getCounterVolumeDetails(counter_Id, value_flag); + if (!volumeDetails.isEmpty()) { + tvParamCode.setText(param + " Code"); + tvParamName.setText(param + " Name"); + recyclCounterVolumeDetail.setAdapter(new VolumeDetailAdapter(context, volumeDetails)); + recyclCounterVolumeDetail.setLayoutManager(new LinearLayoutManager(context)); + rlCounterVolumeDetails.setVisibility(View.VISIBLE); + if (dialog != null && dialog.isShowing()) { + dialog.dismiss(); + } + } + } + + @SuppressLint("NotifyDataSetChanged") + private void validatefilterui() { + RecyclerView rec_subaxe = (RecyclerView) findViewById(R.id.rec_subaxe); + rec_subaxe.setLayoutManager(new GridLayoutManager(context, 3)); + rec_subaxe.setAdapter(new SubAxeValueAdapter(context, getFilters(), default_type, false, true, (filterText, placeHolder) -> download_report(context, filterText))); + } + + private void download_report(final Context context, String param) { + ProgressDialog loading = null; + try { + String cParam = param; + cParam = cParam.replaceAll(" ", "") + "Name"; + String download_key = value_flag ? "Report_ConterValueDetail" : "Report_CounterVolumeDetail"; + JSONObject jsonObject = new JSONObject(); + jsonObject.put("Downloadtype", download_key); + jsonObject.put("Username", username); + jsonObject.put("Param1", counter_Id); + jsonObject.put("Param2", cParam); + String jsonString = jsonObject.toString(); + try { + loading = ProgressDialog.show(context, "Processing", "Please wait...", false, true); + OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build(); + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsonString); + Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build(); + PostApi api = adapter.create(PostApi.class); + Call call = api.getTabjournePlan(jsonData); + ProgressDialog finalLoading = loading; + call.enqueue(new Callback() { + @Override + public void onResponse(@NonNull Call call, @NonNull Response response) { + ResponseBody responseBody = response.body(); + String data = null; + if (responseBody != null && response.isSuccessful()) { + try { + finalLoading.dismiss(); + assert response.body() != null; + data = response.body().string(); + data = data.substring(1, data.length() - 1).replace("\\", ""); + if (data.contains("No Data") || data.equalsIgnoreCase(CommonString.KEY_FAILURE) || data.contains("Failure;Cannot find table 0.")) { + counterVolumeDetails(param, finalLoading); + } else { + ResponseResult counterVolumeDetail = new Gson().fromJson(data, ResponseResult.class); + if (counterVolumeDetail != null) { + if (value_flag) { + db.open(); + db.insertCounterValueDetail(counterVolumeDetail); + } else { + db.open(); + db.insertCounterVolumeDetail(counterVolumeDetail); + } + + counterVolumeDetails(param, finalLoading); + } + } + } catch (Exception e) { + counterVolumeDetails(param, finalLoading); + } + } else { + counterVolumeDetails(param, finalLoading); + } + } + + @Override + public void onFailure(@NonNull Call call, @NonNull Throwable t) { + counterVolumeDetails(param, finalLoading); + } + }); + } catch (Exception e) { + counterVolumeDetails(param, null); + } + } catch (JSONException e) { + counterVolumeDetails(param, null); + } + } + +} \ No newline at end of file diff --git a/app/src/main/java/com/cpm/lorealbaautomation/reports/dailyTva/DailyTVA.java b/app/src/main/java/com/cpm/lorealbaautomation/reports/dailyTva/DailyTVA.java new file mode 100644 index 0000000..af90263 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/reports/dailyTva/DailyTVA.java @@ -0,0 +1,76 @@ +package com.cpm.lorealbaautomation.reports.dailyTva; + +import com.google.gson.annotations.SerializedName; + +public class DailyTVA { + @SerializedName("KPI") + private String kpi; + @SerializedName("CounterId") + private Integer counterId; + @SerializedName("VisitDate") + private String visitDate; + @SerializedName("UserId") + private String userId; + @SerializedName("Target") + private Double target; + @SerializedName("TotalSale") + private Integer totalSale; + @SerializedName("Per") + private Double per; + + public String getKpi() { + return kpi; + } + + public void setKpi(String kpi) { + this.kpi = kpi; + } + + public Integer getCounterId() { + return counterId; + } + + public void setCounterId(Integer counterId) { + this.counterId = counterId; + } + + public String getUserId() { + return userId; + } + + public void setUserId(String userId) { + this.userId = userId; + } + + public Double getTarget() { + return target; + } + + public void setTarget(Double target) { + this.target = target; + } + + public Integer getTotalSale() { + return totalSale; + } + + public void setTotalSale(Integer totalSale) { + this.totalSale = totalSale; + } + + public Double getPer() { + return per; + } + + public void setPer(Double per) { + this.per = per; + } + + public String getVisitDate() { + return visitDate; + } + + public void setVisitDate(String visitDate) { + this.visitDate = visitDate; + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/reports/dailyTva/DailyTVAActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/reports/dailyTva/DailyTVAActivity.java new file mode 100644 index 0000000..b4bad84 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/reports/dailyTva/DailyTVAActivity.java @@ -0,0 +1,164 @@ +package com.cpm.lorealbaautomation.reports.dailyTva; + +import static com.cpm.lorealbaautomation.constant.CommonFunctions.getFilters; + +import android.annotation.SuppressLint; +import android.content.Context; +import android.content.SharedPreferences; +import android.os.Bundle; +import android.view.LayoutInflater; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; +import android.widget.TextView; + +import androidx.annotation.NonNull; +import androidx.appcompat.app.AppCompatActivity; +import androidx.appcompat.widget.Toolbar; +import androidx.recyclerview.widget.GridLayoutManager; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; + +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.adapter.SubAxeValueAdapter; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.delegates.PrefHelper; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +public class DailyTVAActivity extends AppCompatActivity { + TextView tvtotalTargets, tvTotalSales, tvKPI, tvTotalAch; + ArrayList dailyTVAS = new ArrayList<>(); + String counter_Id, visit_date, username; + private SharedPreferences preferences; + RecyclerView recyclDailyTVa; + DailyTVA dailyTVA = null; + Lorealba_Database db; + Context context; + + @SuppressLint("SetTextI18n") + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_daily_tva); + context = this; + db = new Lorealba_Database(context); + db.open(); + Toolbar toolbar = findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + Objects.requireNonNull(getSupportActionBar()).setHomeButtonEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + iduserinterface(); + String couter_code = preferences.getString(CommonString.KEY_COUNTER_CODE, ""); + TextView txt_counter_code = (TextView) findViewById(R.id.txt_counter_code); + txt_counter_code.setText("Counter Code - " + couter_code + " / Id - " + counter_Id); + validatefilterui(); + dailyTVA(); + } + + private void iduserinterface() { + preferences = PrefHelper.getPrefs(context); + counter_Id = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + username = preferences.getString(CommonString.KEY_USERNAME, ""); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + recyclDailyTVa = findViewById(R.id.recyclDailyTVa); + tvtotalTargets = findViewById(R.id.tvtotalTargets); + tvTotalSales = findViewById(R.id.tvTotalSales); + tvTotalAch = findViewById(R.id.tvTotalAch); + tvKPI = findViewById(R.id.tvKPI); + + setTitle(getIntent().getStringExtra(CommonString.Brand) + " Report " + " - " + visit_date); + db = new Lorealba_Database(context); + db.open(); + } + + private class DailyTvaAdapter extends RecyclerView.Adapter { + LayoutInflater inflator; + List data; + + public DailyTvaAdapter(Context context, List data) { + inflator = LayoutInflater.from(context); + this.data = data; + } + + @NonNull + @Override + public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) { + View view = inflator.inflate(R.layout.row_daily_tva, parent, false); + return new MyViewHolder(view); + } + + @SuppressLint({"SetTextI18n", "DefaultLocale"}) + @Override + public void onBindViewHolder(@NonNull final MyViewHolder holder, final int position) { + final DailyTVA current = data.get(position); + holder.tvVisitedDate.setText(current.getVisitDate()); + holder.tvVisitedDate.setId(position); + holder.tvAchPer.setText(current.getPer().toString() + "%"); + holder.tvAchPer.setId(position); + holder.tvTarget.setText(String.format("%.0f", current.getTarget())); + holder.tvTarget.setId(position); + holder.tvTotalSale.setText(current.getTotalSale().toString()); + holder.tvTotalSale.setId(position); + } + + @Override + public int getItemCount() { + return data.size(); + } + + class MyViewHolder extends RecyclerView.ViewHolder { + TextView tvVisitedDate, tvTarget, tvTotalSale, tvAchPer; + + public MyViewHolder(View itemView) { + super(itemView); + tvVisitedDate = (TextView) itemView.findViewById(R.id.tvVisitedDate); + tvTotalSale = (TextView) itemView.findViewById(R.id.tvTotalSale); + tvTarget = (TextView) itemView.findViewById(R.id.tvTarget); + tvAchPer = (TextView) itemView.findViewById(R.id.tvAchPer); + } + } + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + if (id == android.R.id.home) { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + DailyTVAActivity.this.finish(); + } + return super.onOptionsItemSelected(item); + } + + @Override + public void onBackPressed() { + super.onBackPressed(); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + DailyTVAActivity.this.finish(); + } + + @SuppressLint({"SetTextI18n", "DefaultLocale"}) + private void dailyTVA() { + db.open(); + dailyTVAS = db.getDailyTVAReport(counter_Id, username); + dailyTVA = db.getTotalDailyTVA(counter_Id, username); + if (!dailyTVAS.isEmpty() && dailyTVA != null) { + tvtotalTargets.setText(getString(R.string.Rs) + " " + String.format("%.0f", dailyTVA.getTarget())); + tvTotalSales.setText(getString(R.string.Rs) + " " + dailyTVA.getTotalSale()); + tvTotalAch.setText(String.format("%.2f", dailyTVA.getPer()) + "%"); + recyclDailyTVa.setAdapter(new DailyTvaAdapter(context, dailyTVAS)); + recyclDailyTVa.setLayoutManager(new LinearLayoutManager(context)); + } + } + + @SuppressLint("NotifyDataSetChanged") + private void validatefilterui() { + RecyclerView rec_subaxe = (RecyclerView) findViewById(R.id.rec_subaxe); + rec_subaxe.setLayoutManager(new GridLayoutManager(context, 3)); + rec_subaxe.setAdapter(new SubAxeValueAdapter(context, getFilters(), "Sub Axe", true, false,(filterText, placeHolder) -> {})); + } +} \ No newline at end of file diff --git a/app/src/main/java/com/cpm/lorealbaautomation/reports/inwarddetails/CounterInwordDetailActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/reports/inwarddetails/CounterInwordDetailActivity.java new file mode 100644 index 0000000..c5b19ba --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/reports/inwarddetails/CounterInwordDetailActivity.java @@ -0,0 +1,261 @@ +package com.cpm.lorealbaautomation.reports.inwarddetails; + +import static com.cpm.lorealbaautomation.constant.CommonFunctions.getFilters; + +import android.annotation.SuppressLint; +import android.app.ProgressDialog; +import android.content.Context; +import android.content.SharedPreferences; +import android.os.Bundle; +import android.view.MenuItem; +import android.view.View; +import android.widget.LinearLayout; +import android.widget.TextView; + +import androidx.annotation.NonNull; +import androidx.appcompat.app.AppCompatActivity; +import androidx.appcompat.widget.Toolbar; +import androidx.recyclerview.widget.GridLayoutManager; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; + +import com.google.gson.Gson; +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.adapter.InwardStkDetailAdapter; +import com.cpm.lorealbaautomation.adapter.SubAxeValueAdapter; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.gsonGetterSetter.ResponseResult; +import com.cpm.lorealbaautomation.gsonGetterSetter.inwordDetail.ReportCounterInwardStock; +import com.cpm.lorealbaautomation.gsonGetterSetter.inwordDetail.ReportCounterInwardStockDetail; +import com.cpm.lorealbaautomation.retrofit.PostApi; + +import org.json.JSONException; +import org.json.JSONObject; + +import java.util.ArrayList; +import java.util.Objects; +import java.util.concurrent.TimeUnit; + +import okhttp3.MediaType; +import okhttp3.OkHttpClient; +import okhttp3.RequestBody; +import okhttp3.ResponseBody; +import retrofit2.Call; +import retrofit2.Callback; +import retrofit2.Response; +import retrofit2.Retrofit; +import retrofit2.converter.gson.GsonConverterFactory; + +public class CounterInwordDetailActivity extends AppCompatActivity { + TextView tvInvoiceQty, tvActualQty, + tvDamageQty, tvMissingQTY, tvParamCode, tvParamName; + TextView headerStk, tvPlaceInvoice, tvPlaceActual, tvPlaceDamage, tvPlaceMissing, + headerStkDetail, tvPlaceInvoiceDetail, tvPlaceActualDetail, tvPlaceDamageDetail, tvPlaceMissingDetail; + ArrayList inwardStockDetails = new ArrayList<>(); + String counter_Id, visit_date, username, default_type = "Axe", reportName = ""; + LinearLayout rlCounterInwordStk, rlCounterInwordStkDetails; + RecyclerView recyclCounterInwordStkDetail; + private SharedPreferences preferences; + private boolean inward_detail = true; + Lorealba_Database db; + Context context; + + @SuppressLint("SetTextI18n") + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_counter_inword_detail); + context = this; + db = new Lorealba_Database(context); + db.open(); + headerStk = findViewById(R.id.headerStk); + tvPlaceInvoice = findViewById(R.id.tvPlaceInvoice); + tvPlaceActual = findViewById(R.id.tvPlaceActual); + tvPlaceDamage = findViewById(R.id.tvPlaceDamage); + tvPlaceMissing = findViewById(R.id.tvPlaceMissing); + ///Details place holder Ids + headerStkDetail = findViewById(R.id.headerStkDetail); + tvPlaceInvoiceDetail = findViewById(R.id.tvPlaceInvoiceDetail); + tvPlaceActualDetail = findViewById(R.id.tvPlaceActualDetail); + tvPlaceDamageDetail = findViewById(R.id.tvPlaceDamageDetail); + tvPlaceMissingDetail = findViewById(R.id.tvPlaceMissingDetail); + Toolbar toolbar = findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + Objects.requireNonNull(getSupportActionBar()).setHomeButtonEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + iduserinterface(); + String couter_code = preferences.getString(CommonString.KEY_COUNTER_CODE, ""); + TextView txt_counter_code = (TextView) findViewById(R.id.txt_counter_code); + txt_counter_code.setText("Counter Code - " + couter_code + " / Id - " + counter_Id); + validatefilterui(); + } + + @SuppressLint("SetTextI18n") + private void iduserinterface() { + preferences = PrefHelper.getPrefs(context); + counter_Id = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + username = preferences.getString(CommonString.KEY_USERNAME, ""); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + tvInvoiceQty = (TextView) findViewById(R.id.tvInvoiceQty); + tvActualQty = (TextView) findViewById(R.id.tvActualQty); + //////details + tvDamageQty = (TextView) findViewById(R.id.tvDamageQty); + tvMissingQTY = (TextView) findViewById(R.id.tvMissingQTY); + tvParamCode = (TextView) findViewById(R.id.tvParamCode); + tvParamName = (TextView) findViewById(R.id.tvParamName); + + rlCounterInwordStk = (LinearLayout) findViewById(R.id.rlCounterInwordStk); + recyclCounterInwordStkDetail = (RecyclerView) findViewById(R.id.recyclCounterInwordStkDetail); + rlCounterInwordStkDetails = (LinearLayout) findViewById(R.id.rlCounterInwordStkDetails); + if (getIntent().getStringExtra(CommonString.Brand) != null) { + reportName = getIntent().getStringExtra(CommonString.Brand); + } + assert reportName != null; + if (reportName.equalsIgnoreCase("Stock Ledger Detail")) { + inward_detail = false; + } + + + db.open(); + setPlaceholderText(); + ReportCounterInwardStock inwordStk = db.getCounterInwordStk(counter_Id, inward_detail); + if (inwordStk != null) { + tvInvoiceQty.setText(inwordStk.getInvoiceQty() != null ? inwordStk.getInvoiceQty().toString() : "0"); + tvActualQty.setText(inwordStk.getActualQty() != null ? inwordStk.getActualQty().toString() : "0"); + tvDamageQty.setText(inwordStk.getDamageQty() != null ? inwordStk.getDamageQty().toString() : "0"); + tvMissingQTY.setText(inwordStk.getMissedQty() != null ? inwordStk.getMissedQty().toString() : "0"); + } + + counterInwordStkDetails(default_type, null); + setTitle(reportName + " Report " + " - " + visit_date); + db = new Lorealba_Database(context); + db.open(); + } + + @SuppressLint("SetTextI18n") + private void setPlaceholderText() { + if (!inward_detail) { + headerStk.setText("Counter Stock Ledger"); + tvPlaceInvoice.setText("Opening Stock"); + tvPlaceInvoiceDetail.setText("Opening Stock"); + tvPlaceActual.setText("Stock-In"); + tvPlaceActualDetail.setText("Stock-In"); + tvPlaceDamage.setText("Sale-Out"); + tvPlaceDamageDetail.setText("Sale-Out"); + tvPlaceMissing.setText("Saleable Balance"); + tvPlaceMissingDetail.setText("Saleable Balance"); + headerStkDetail.setText("Counter Stock Ledger Detail"); + + } + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + if (id == android.R.id.home) { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + this.finish(); + } + return super.onOptionsItemSelected(item); + } + + @Override + public void onBackPressed() { + super.onBackPressed(); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + this.finish(); + } + + @SuppressLint("SetTextI18n") + private void counterInwordStkDetails(String param, ProgressDialog dialog) { + //details + inwardStockDetails = db.getCounterInwordStkDetails(counter_Id, inward_detail); + if (!inwardStockDetails.isEmpty()) { + tvParamCode.setText(param + " Code"); + tvParamName.setText(param + " Name"); + recyclCounterInwordStkDetail.setAdapter(new InwardStkDetailAdapter(context, inwardStockDetails)); + recyclCounterInwordStkDetail.setLayoutManager(new LinearLayoutManager(context)); + rlCounterInwordStkDetails.setVisibility(View.VISIBLE); + if (dialog != null && dialog.isShowing()) { + dialog.dismiss(); + } + } + } + + @SuppressLint("NotifyDataSetChanged") + private void validatefilterui() { + RecyclerView rec_subaxe = (RecyclerView) findViewById(R.id.rec_subaxe); + rec_subaxe.setLayoutManager(new GridLayoutManager(context, 3)); + rec_subaxe.setAdapter(new SubAxeValueAdapter(context, getFilters(), default_type, false, true, (filterText, placeHolder) -> download_report(context, filterText))); + } + + private void download_report(final Context context, String param) { + ProgressDialog loading = null; + try { + String cParam = param; + cParam = cParam.replaceAll(" ", "") + "Name"; + JSONObject jsonObject = new JSONObject(); + jsonObject.put("Downloadtype", inward_detail ? "Report_CounterInwardStockDetail" : "Report_CounterStockLedgerDetail"); + jsonObject.put("Username", username); + jsonObject.put("Param1", counter_Id); + jsonObject.put("Param2", cParam); + String jsonString = jsonObject.toString(); + try { + loading = ProgressDialog.show(context, "Processing", "Please wait...", false, true); + OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build(); + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsonString); + Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build(); + PostApi api = adapter.create(PostApi.class); + Call call = api.getTabjournePlan(jsonData); + ProgressDialog finalLoading = loading; + call.enqueue(new Callback() { + @Override + public void onResponse(@NonNull Call call, @NonNull Response response) { + ResponseBody responseBody = response.body(); + String data = null; + if (responseBody != null && response.isSuccessful()) { + try { + finalLoading.dismiss(); + assert response.body() != null; + data = response.body().string(); + data = data.substring(1, data.length() - 1).replace("\\", ""); + if (data.contains("No Data") || data.equalsIgnoreCase(CommonString.KEY_FAILURE) || data.contains("Failure;Cannot find table 0.")) { + counterInwordStkDetails(param, finalLoading); + } else { + ResponseResult counterVolumeDetail = new Gson().fromJson(data, ResponseResult.class); + if (counterVolumeDetail != null) { + db.open(); + if (inward_detail) { + db.insertCounterInwardStockDetail(counterVolumeDetail); + } else { + db.insertCounterStockLedgerDetail(counterVolumeDetail); + } + counterInwordStkDetails(param, finalLoading); + } + } + } catch (Exception e) { + counterInwordStkDetails(param, finalLoading); + } + } else { + counterInwordStkDetails(param, finalLoading); + } + } + + @Override + public void onFailure(@NonNull Call call, @NonNull Throwable t) { + counterInwordStkDetails(param, finalLoading); + } + }); + } catch (Exception e) { + counterInwordStkDetails(param, null); + } + + } catch (JSONException e) { + counterInwordStkDetails(param, null); + } + } + +} \ No newline at end of file diff --git a/app/src/main/java/com/cpm/lorealbaautomation/reports/offtakemodels/L3MOffTakeCounter.java b/app/src/main/java/com/cpm/lorealbaautomation/reports/offtakemodels/L3MOffTakeCounter.java new file mode 100644 index 0000000..4ae1496 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/reports/offtakemodels/L3MOffTakeCounter.java @@ -0,0 +1,34 @@ +package com.cpm.lorealbaautomation.reports.offtakemodels; + +import com.google.gson.annotations.SerializedName; + +public class L3MOffTakeCounter { + @SerializedName("KPI") + private String kpi; + @SerializedName("CounterId") + private Integer counterId; + @SerializedName("Data") + private OffTakeData data; + public String getKpi() { + return kpi; + } + public void setKpi(String kpi) { + this.kpi = kpi; + } + + public Integer getCounterId() { + return counterId; + } + + public void setCounterId(Integer counterId) { + this.counterId = counterId; + } + + public OffTakeData getData() { + return data; + } + public void setData(OffTakeData data) { + this.data = data; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/reports/offtakemodels/L3MOffTakeNuance.java b/app/src/main/java/com/cpm/lorealbaautomation/reports/offtakemodels/L3MOffTakeNuance.java new file mode 100644 index 0000000..1866d4e --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/reports/offtakemodels/L3MOffTakeNuance.java @@ -0,0 +1,67 @@ +package com.cpm.lorealbaautomation.reports.offtakemodels; + +import com.google.gson.annotations.SerializedName; + +public class L3MOffTakeNuance { + @SerializedName("KPI") + private String kpi; + @SerializedName("CounterId") + private Integer counterId; + @SerializedName("NuanceId") + private Integer nuanceId; + @SerializedName("NuanceName") + private String nuanceName; + @SerializedName("Month_Year") + private String monthYear; + @SerializedName("OffTake") + private String offTake; + + public String getKpi() { + return kpi; + } + + public void setKpi(String kpi) { + this.kpi = kpi; + } + + public Integer getCounterId() { + return counterId; + } + + public void setCounterId(Integer counterId) { + this.counterId = counterId; + } + + public Integer getNuanceId() { + return nuanceId; + } + + public void setNuanceId(Integer nuanceId) { + this.nuanceId = nuanceId; + } + + public String getNuanceName() { + return nuanceName; + } + + public void setNuanceName(String nuanceName) { + this.nuanceName = nuanceName; + } + + public String getMonthYear() { + return monthYear; + } + + public void setMonthYear(String monthYear) { + this.monthYear = monthYear; + } + + public String getOffTake() { + return offTake; + } + + public void setOffTake(String offTake) { + this.offTake = offTake; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/reports/offtakemodels/L3MOffTakeSubAxe.java b/app/src/main/java/com/cpm/lorealbaautomation/reports/offtakemodels/L3MOffTakeSubAxe.java new file mode 100644 index 0000000..588c1aa --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/reports/offtakemodels/L3MOffTakeSubAxe.java @@ -0,0 +1,66 @@ +package com.cpm.lorealbaautomation.reports.offtakemodels; + +import com.google.gson.annotations.SerializedName; + +public class L3MOffTakeSubAxe { + @SerializedName("KPI") + private String kpi; + @SerializedName("CounterId") + private Integer counterId; + @SerializedName("SubAxeId") + private Integer subAxeId; + @SerializedName("SubAxeName") + private String subAxeName; + @SerializedName("Month_Year") + private String monthYear; + @SerializedName("OffTake") + private String offTake; + + public String getKpi() { + return kpi; + } + + public void setKpi(String kpi) { + this.kpi = kpi; + } + + public Integer getCounterId() { + return counterId; + } + + public void setCounterId(Integer counterId) { + this.counterId = counterId; + } + + public Integer getSubAxeId() { + return subAxeId; + } + + public void setSubAxeId(Integer subAxeId) { + this.subAxeId = subAxeId; + } + + public String getSubAxeName() { + return subAxeName; + } + + public void setSubAxeName(String subAxeName) { + this.subAxeName = subAxeName; + } + + public String getMonthYear() { + return monthYear; + } + + public void setMonthYear(String monthYear) { + this.monthYear = monthYear; + } + + public String getOffTake() { + return offTake; + } + + public void setOffTake(String offTake) { + this.offTake = offTake; + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/reports/offtakemodels/OffTakeData.java b/app/src/main/java/com/cpm/lorealbaautomation/reports/offtakemodels/OffTakeData.java new file mode 100644 index 0000000..1a23219 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/reports/offtakemodels/OffTakeData.java @@ -0,0 +1,16 @@ +package com.cpm.lorealbaautomation.reports.offtakemodels; + +import com.google.gson.annotations.SerializedName; + +import java.util.List; + +public class OffTakeData { + @SerializedName("DATA") + private List data; + public List getData() { + return data; + } + public void setData(List data) { + this.data = data; + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/reports/offtakemodels/OffTakeDataItem.java b/app/src/main/java/com/cpm/lorealbaautomation/reports/offtakemodels/OffTakeDataItem.java new file mode 100644 index 0000000..378eeb8 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/reports/offtakemodels/OffTakeDataItem.java @@ -0,0 +1,24 @@ +package com.cpm.lorealbaautomation.reports.offtakemodels; + +import com.google.gson.annotations.SerializedName; + +public class OffTakeDataItem { + @SerializedName("Month_Year") + private String monthYear; + @SerializedName("OffTake") + private String offTake; + public String getMonthYear() { + return monthYear; + } + public void setMonthYear(String monthYear) { + this.monthYear = monthYear; + } + + public String getOffTake() { + return offTake; + } + + public void setOffTake(String offTake) { + this.offTake = offTake; + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/reports/offtakemodels/SalesGrowthCounter.java b/app/src/main/java/com/cpm/lorealbaautomation/reports/offtakemodels/SalesGrowthCounter.java new file mode 100644 index 0000000..46acafd --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/reports/offtakemodels/SalesGrowthCounter.java @@ -0,0 +1,96 @@ +package com.cpm.lorealbaautomation.reports.offtakemodels; + +import com.google.gson.annotations.SerializedName; + +public class SalesGrowthCounter { + @SerializedName("KPI") + private String kpi; + @SerializedName("CounterId") + private Integer counterId; + @SerializedName("Last_Year_SameMonthSale") + private Double lastYearSameMonthSale; + @SerializedName("L3M_Avg_Sale") + private Double l3MAvgSale; + @SerializedName("Current_Month_Sale") + private Double currentMonthSale; + @SerializedName("Growth_over_Last_Year_Per") + private Double growthOverLastYearPer; + @SerializedName("Growth_over_L3M_Per") + private Double growthOverL3MPer; + @SerializedName("Closing_Stock_LastMonth") + private Double closingStockLastMonth; + @SerializedName("NOD") + private Double nod; + + public String getKpi() { + return kpi; + } + + public void setKpi(String kpi) { + this.kpi = kpi; + } + + public Integer getCounterId() { + return counterId; + } + + public void setCounterId(Integer counterId) { + this.counterId = counterId; + } + + public Double getLastYearSameMonthSale() { + return lastYearSameMonthSale; + } + + public void setLastYearSameMonthSale(Double lastYearSameMonthSale) { + this.lastYearSameMonthSale = lastYearSameMonthSale; + } + + public Double getL3MAvgSale() { + return l3MAvgSale; + } + + public void setL3MAvgSale(Double l3MAvgSale) { + this.l3MAvgSale = l3MAvgSale; + } + + public Double getCurrentMonthSale() { + return currentMonthSale; + } + + public void setCurrentMonthSale(Double currentMonthSale) { + this.currentMonthSale = currentMonthSale; + } + + public Double getGrowthOverLastYearPer() { + return growthOverLastYearPer; + } + + public void setGrowthOverLastYearPer(Double growthOverLastYearPer) { + this.growthOverLastYearPer = growthOverLastYearPer; + } + + public Double getGrowthOverL3MPer() { + return growthOverL3MPer; + } + + public void setGrowthOverL3MPer(Double growthOverL3MPer) { + this.growthOverL3MPer = growthOverL3MPer; + } + + public Double getClosingStockLastMonth() { + return closingStockLastMonth; + } + + public void setClosingStockLastMonth(Double closingStockLastMonth) { + this.closingStockLastMonth = closingStockLastMonth; + } + + public Double getNod() { + return nod; + } + + public void setNod(Double nod) { + this.nod = nod; + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/reports/offtakemodels/SalesGrowthSubAxe.java b/app/src/main/java/com/cpm/lorealbaautomation/reports/offtakemodels/SalesGrowthSubAxe.java new file mode 100644 index 0000000..8db4b94 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/reports/offtakemodels/SalesGrowthSubAxe.java @@ -0,0 +1,136 @@ +package com.cpm.lorealbaautomation.reports.offtakemodels; + +import com.google.gson.annotations.SerializedName; + +public class SalesGrowthSubAxe { + @SerializedName("KPI") + private String kpi; + @SerializedName("CounterId") + private Integer counterId; + @SerializedName("CounterCode") + private String counterCode; + @SerializedName("CounterName") + private String counterName; + @SerializedName("ParamCode") + private String paramCode; + @SerializedName("ParamName") + private String paramName; + @SerializedName("Last_Year_SameMonthSale") + private Double lastYearSameMonthSale; + @SerializedName("L3M_Avg_Sale") + private Double l3MAvgSale; + @SerializedName("Current_Month_Sale") + private Double currentMonthSale; + @SerializedName("Growth_over_Last_Year_Per") + private Double growthOverLastYearPer; + @SerializedName("Growth_over_L3M_Per") + private Double growthOverL3MPer; + @SerializedName("Closing_Stock_LastMonth") + private Double closingStockLastMonth; + @SerializedName("NOD") + private Double nod; + + public String getKpi() { + return kpi; + } + + public void setKpi(String kpi) { + this.kpi = kpi; + } + + public Integer getCounterId() { + return counterId; + } + + public void setCounterId(Integer counterId) { + this.counterId = counterId; + } + + public String getCounterCode() { + return counterCode; + } + + public void setCounterCode(String counterCode) { + this.counterCode = counterCode; + } + + public String getCounterName() { + return counterName; + } + + public void setCounterName(String counterName) { + this.counterName = counterName; + } + + public String getParamCode() { + return paramCode; + } + + public void setParamCode(String paramCode) { + this.paramCode = paramCode; + } + + public String getParamName() { + return paramName; + } + + public void setParamName(String paramName) { + this.paramName = paramName; + } + + public Double getLastYearSameMonthSale() { + return lastYearSameMonthSale; + } + + public void setLastYearSameMonthSale(Double lastYearSameMonthSale) { + this.lastYearSameMonthSale = lastYearSameMonthSale; + } + + public Double getL3MAvgSale() { + return l3MAvgSale; + } + + public void setL3MAvgSale(Double l3MAvgSale) { + this.l3MAvgSale = l3MAvgSale; + } + + public Double getCurrentMonthSale() { + return currentMonthSale; + } + + public void setCurrentMonthSale(Double currentMonthSale) { + this.currentMonthSale = currentMonthSale; + } + + public Double getGrowthOverLastYearPer() { + return growthOverLastYearPer; + } + + public void setGrowthOverLastYearPer(Double growthOverLastYearPer) { + this.growthOverLastYearPer = growthOverLastYearPer; + } + + public Double getGrowthOverL3MPer() { + return growthOverL3MPer; + } + + public void setGrowthOverL3MPer(Double growthOverL3MPer) { + this.growthOverL3MPer = growthOverL3MPer; + } + + public Double getClosingStockLastMonth() { + return closingStockLastMonth; + } + + public void setClosingStockLastMonth(Double closingStockLastMonth) { + this.closingStockLastMonth = closingStockLastMonth; + } + + public Double getNod() { + return nod; + } + + public void setNod(Double nod) { + this.nod = nod; + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/reports/testerdetails/ReportTesterCounterDetail.java b/app/src/main/java/com/cpm/lorealbaautomation/reports/testerdetails/ReportTesterCounterDetail.java new file mode 100644 index 0000000..bac22b7 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/reports/testerdetails/ReportTesterCounterDetail.java @@ -0,0 +1,146 @@ +package com.cpm.lorealbaautomation.reports.testerdetails; +import com.google.gson.annotations.SerializedName; + +public class ReportTesterCounterDetail { + @SerializedName("KPI") + private String kpi; + @SerializedName("CounterId") + private Integer counterId; + @SerializedName("CounterCode") + + private String counterCode; + @SerializedName("CounterName") + + private String counterName; + @SerializedName("ParamId") + + private Integer paramId; + @SerializedName("ParamCode") + + private String paramCode; + @SerializedName("ParamName") + + private String paramName; + @SerializedName("OpeningStock") + + private Integer openingStock; + @SerializedName("InvoicedQty") + + private Integer invoicedQty; + @SerializedName("ReceivedQty") + + private Integer receivedQty; + @SerializedName("TesterStockAvailable") + + private Integer testerStockAvailable; + @SerializedName("TesterUsed") + + private Integer testerUsed; + @SerializedName("TesterUsedPer") + + private Double testerUsedPer; + + public String getKpi() { + return kpi; + } + + public void setKpi(String kpi) { + this.kpi = kpi; + } + + public Integer getCounterId() { + return counterId; + } + + public void setCounterId(Integer counterId) { + this.counterId = counterId; + } + + public String getCounterCode() { + return counterCode; + } + + public void setCounterCode(String counterCode) { + this.counterCode = counterCode; + } + + public String getCounterName() { + return counterName; + } + + public void setCounterName(String counterName) { + this.counterName = counterName; + } + + public Integer getParamId() { + return paramId; + } + + public void setParamId(Integer paramId) { + this.paramId = paramId; + } + + public String getParamCode() { + return paramCode; + } + + public void setParamCode(String paramCode) { + this.paramCode = paramCode; + } + + public String getParamName() { + return paramName; + } + + public void setParamName(String paramName) { + this.paramName = paramName; + } + + public Integer getOpeningStock() { + return openingStock; + } + + public void setOpeningStock(Integer openingStock) { + this.openingStock = openingStock; + } + + public Integer getInvoicedQty() { + return invoicedQty; + } + + public void setInvoicedQty(Integer invoicedQty) { + this.invoicedQty = invoicedQty; + } + + public Integer getReceivedQty() { + return receivedQty; + } + + public void setReceivedQty(Integer receivedQty) { + this.receivedQty = receivedQty; + } + + public Integer getTesterStockAvailable() { + return testerStockAvailable; + } + + public void setTesterStockAvailable(Integer testerStockAvailable) { + this.testerStockAvailable = testerStockAvailable; + } + + public Integer getTesterUsed() { + return testerUsed; + } + + public void setTesterUsed(Integer testerUsed) { + this.testerUsed = testerUsed; + } + + public Double getTesterUsedPer() { + return testerUsedPer; + } + + public void setTesterUsedPer(Double testerUsedPer) { + this.testerUsedPer = testerUsedPer; + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/reports/testerdetails/TesterUsageReportActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/reports/testerdetails/TesterUsageReportActivity.java new file mode 100644 index 0000000..f8bd236 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/reports/testerdetails/TesterUsageReportActivity.java @@ -0,0 +1,364 @@ +package com.cpm.lorealbaautomation.reports.testerdetails; + +import static com.cpm.lorealbaautomation.constant.CommonFunctions.getFilters; + +import android.annotation.SuppressLint; +import android.app.Dialog; +import android.app.ProgressDialog; +import android.content.Context; +import android.content.SharedPreferences; +import android.graphics.Color; +import android.graphics.drawable.ColorDrawable; +import android.os.Bundle; +import android.view.LayoutInflater; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; +import android.view.Window; +import android.widget.LinearLayout; +import android.widget.TextView; + +import androidx.annotation.NonNull; +import androidx.appcompat.app.AppCompatActivity; +import androidx.appcompat.widget.Toolbar; +import androidx.core.content.ContextCompat; +import androidx.recyclerview.widget.GridLayoutManager; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; + +import com.google.gson.Gson; +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.adapter.SubAxeValueAdapter; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.databinding.CounterGrowthDetailBinding; +import com.cpm.lorealbaautomation.databinding.DetailTesterUsageBinding; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.gsonGetterSetter.ResponseResult; +import com.cpm.lorealbaautomation.retrofit.PostApi; + +import org.json.JSONException; +import org.json.JSONObject; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.TimeUnit; + +import okhttp3.MediaType; +import okhttp3.OkHttpClient; +import okhttp3.RequestBody; +import okhttp3.ResponseBody; +import retrofit2.Call; +import retrofit2.Callback; +import retrofit2.Response; +import retrofit2.Retrofit; +import retrofit2.converter.gson.GsonConverterFactory; + +public class TesterUsageReportActivity extends AppCompatActivity { + ArrayList testerUsageCounter = new ArrayList<>(); + String counter_Id, visit_date, username, default_type = "Axe"; + RecyclerView recyclTesterCounter, recyclTesterUsageDetail; + LinearLayout rlTesterUsage, rlTesterUsageDetails; + TextView tvKPICounter, tvParamCode, tvParamName; + private SharedPreferences preferences; + Lorealba_Database db; + Context context; + + @SuppressLint("SetTextI18n") + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_tester_usage_report); + context = this; + db = new Lorealba_Database(context); + db.open(); + Toolbar toolbar = findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + Objects.requireNonNull(getSupportActionBar()).setHomeButtonEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + iduserinterface(); + String couter_code = preferences.getString(CommonString.KEY_COUNTER_CODE, ""); + TextView txt_counter_code = (TextView) findViewById(R.id.txt_counter_code); + txt_counter_code.setText("Counter Code - " + couter_code + " / Id - " + counter_Id); + validatefilterui(); + testerCounterUsageReport(); + } + + private void iduserinterface() { + preferences = PrefHelper.getPrefs(context); + counter_Id = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + username = preferences.getString(CommonString.KEY_USERNAME, ""); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + //////// + recyclTesterCounter = findViewById(R.id.recyclTesterCounter); + rlTesterUsage = findViewById(R.id.rlTesterUsage); + tvKPICounter = findViewById(R.id.tvKPICounter); + recyclTesterUsageDetail = findViewById(R.id.recyclTesterUsageDetail); + rlTesterUsageDetails = findViewById(R.id.rlTesterUsageDetails); + tvParamCode = findViewById(R.id.tvParamCode); + tvParamName = findViewById(R.id.tvParamName); + setTitle(getIntent().getStringExtra(CommonString.Brand) + " Report " + " - " + visit_date); + db = new Lorealba_Database(context); + db.open(); + } + + private class TesterUsageAdapter extends RecyclerView.Adapter { + LayoutInflater inflator; + List data; + String param; + boolean detail; + + public TesterUsageAdapter(Context context, List data, boolean detail, String param) { + inflator = LayoutInflater.from(context); + this.param = param; + this.detail = detail; + this.data = data; + } + + @NonNull + @Override + public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) { + View view = inflator.inflate(R.layout.row_tester_usage, parent, false); + return new MyViewHolder(view); + } + + @SuppressLint({"SetTextI18n", "DefaultLocale"}) + @Override + public void onBindViewHolder(@NonNull final MyViewHolder holder, final int position) { + final ReportTesterCounterDetail current = data.get(position); + if (detail) { + holder.tvRowParamName.setText(current.getParamName()); + holder.rlTesterUsageDetail.setVisibility(View.VISIBLE); + holder.tvParamCode.setText(current.getParamCode()); + holder.rlTesterCounter.setVisibility(View.GONE); + holder.rlTesterUsageDetail.setId(position); + holder.rlTesterCounter.setId(position); + holder.tvRowParamName.setId(position); + holder.tvParamCode.setId(position); + } else { + holder.rlTesterCounter.setVisibility(View.VISIBLE); + holder.rlTesterUsageDetail.setVisibility(View.GONE); + holder.rlTesterUsageDetail.setId(position); + holder.rlTesterCounter.setId(position); + } + + holder.rlParent.setOnLongClickListener(v -> { + new DetailsDailog((AppCompatActivity) context, current, param, detail).show(); + return false; + }); + + setText(detail ? holder.tvOPSSTKDetail : holder.tvOPSSTK, position, current.getOpeningStock().toString()); + setText(detail ? holder.tvInvQTYDetail : holder.tvInvQTY, position, current.getInvoicedQty().toString()); + + setText(detail ? holder.tvRCVDQTYDetail : holder.tvRCVDQTY, position, current.getReceivedQty().toString()); + setText(detail ? holder.tvTesterSTKAVAILDetail : holder.tvTesterSTKAVAIL, position, current.getTesterStockAvailable().toString()); + setText(detail ? holder.tvTesterUsedDetail : holder.tvTesterUsed, position, current.getTesterUsed().toString()); + setText(detail ? holder.tvTesterUsedPerDetail : holder.tvTesterUsedPer, position, current.getTesterUsedPer().toString() + "%"); + } + + @Override + public int getItemCount() { + return data.size(); + } + + class MyViewHolder extends RecyclerView.ViewHolder { + LinearLayout rlTesterCounter, rlTesterUsageDetail, rlParent; + TextView tvOPSSTK, tvInvQTY, tvRCVDQTY, tvTesterSTKAVAIL, tvTesterUsed, tvTesterUsedPer, tvParamCode, tvRowParamName, tvOPSSTKDetail, tvInvQTYDetail, tvRCVDQTYDetail, tvTesterSTKAVAILDetail, tvTesterUsedDetail, tvTesterUsedPerDetail; + + public MyViewHolder(View itemView) { + super(itemView); + rlParent = (LinearLayout) itemView.findViewById(R.id.rlParent); + rlTesterCounter = (LinearLayout) itemView.findViewById(R.id.rlTesterCounter); + tvOPSSTK = (TextView) itemView.findViewById(R.id.tvOPSSTK); + tvInvQTY = (TextView) itemView.findViewById(R.id.tvInvQTY); + tvRCVDQTY = (TextView) itemView.findViewById(R.id.tvRCVDQTY); + tvTesterSTKAVAIL = (TextView) itemView.findViewById(R.id.tvTesterSTKAVAIL); + tvTesterUsed = (TextView) itemView.findViewById(R.id.tvTesterUsed); + tvTesterUsedPer = (TextView) itemView.findViewById(R.id.tvTesterUsedPer); + ///details IDS + rlTesterUsageDetail = (LinearLayout) itemView.findViewById(R.id.rlTesterUsageDetail); + tvParamCode = (TextView) itemView.findViewById(R.id.tvParamCode); + tvRowParamName = (TextView) itemView.findViewById(R.id.tvRowParamName); + tvOPSSTKDetail = (TextView) itemView.findViewById(R.id.tvOPSSTKDetail); + tvInvQTYDetail = (TextView) itemView.findViewById(R.id.tvInvQTYDetail); + tvRCVDQTYDetail = (TextView) itemView.findViewById(R.id.tvRCVDQTYDetail); + tvTesterSTKAVAILDetail = (TextView) itemView.findViewById(R.id.tvTesterSTKAVAILDetail); + tvTesterUsedDetail = (TextView) itemView.findViewById(R.id.tvTesterUsedDetail); + tvTesterUsedPerDetail = (TextView) itemView.findViewById(R.id.tvTesterUsedPerDetail); + } + } + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + if (id == android.R.id.home) { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + this.finish(); + } + return super.onOptionsItemSelected(item); + } + + @Override + public void onBackPressed() { + super.onBackPressed(); + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + this.finish(); + } + + @SuppressLint("SetTextI18n") + private void testerCounterUsageReport() { + db.open(); + //Counter Tester Usage + testerUsageCounter = db.getTesterCounterUsageReport(counter_Id, false); + if (!testerUsageCounter.isEmpty()) { + recyclTesterCounter.setAdapter(new TesterUsageAdapter(context, testerUsageCounter, false, null)); + recyclTesterCounter.setLayoutManager(new LinearLayoutManager(context)); + rlTesterUsage.setVisibility(View.VISIBLE); + } + + testerCounterUsageDetail(default_type, null); + } + + @SuppressLint("SetTextI18n") + private void testerCounterUsageDetail(String param, ProgressDialog dialog) { + //details + testerUsageCounter = db.getTesterCounterUsageReport(counter_Id, true); + if (!testerUsageCounter.isEmpty()) { + tvParamCode.setText(param + " Code"); + tvParamName.setText(param + " Name"); + recyclTesterUsageDetail.setAdapter(new TesterUsageAdapter(context, testerUsageCounter, true, param)); + recyclTesterUsageDetail.setLayoutManager(new LinearLayoutManager(context)); + rlTesterUsageDetails.setVisibility(View.VISIBLE); + if (dialog != null && dialog.isShowing()) { + dialog.dismiss(); + } + } + } + + @SuppressLint("DefaultLocale") + private void setText(TextView tv, int pos, String value) { + tv.setTextColor(ContextCompat.getColor(context, R.color.black)); + tv.setText(value); + tv.setId(pos); + } + + private static class DetailsDailog extends Dialog { + private final ReportTesterCounterDetail object; + String param; + boolean detail; + + public DetailsDailog(AppCompatActivity activity, ReportTesterCounterDetail object, String param, boolean detail) { + super(activity); + this.detail = detail; + this.param = param; + this.object = object; + } + + @SuppressLint({"SetTextI18n", "DefaultLocale"}) + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + requestWindowFeature(Window.FEATURE_NO_TITLE); + DetailTesterUsageBinding binding = DetailTesterUsageBinding.inflate(getLayoutInflater()); + setContentView(binding.getRoot()); + Objects.requireNonNull(getWindow()).setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); + binding.imgClose.setOnClickListener(v -> dismiss()); + + if (detail) { + binding.rlParamCode.setVisibility(View.VISIBLE); + binding.rlParamName.setVisibility(View.VISIBLE); + } + + binding.tvParamCodePlaceHolder.setText(param + " Code"); + binding.tvParamCode.setText(object.getParamCode()); + binding.tvParamNamePlaceHolder.setText(param + " Name"); + binding.tvParamName.setText(object.getParamName()); + binding.tvOPSSTK.setText(object.getOpeningStock().toString()); + binding.tvInvQTY.setText(object.getInvoicedQty().toString()); + binding.tvTeserUsed.setText(object.getTesterUsed().toString()); + binding.tvRecievedqty.setText(object.getReceivedQty().toString()); + binding.tvTesterUsedPer.setText(object.getTesterUsedPer().toString() + "%"); + binding.tvTesterSTKAVAIL.setText(object.getTesterStockAvailable().toString()); + } + + @SuppressLint("SetTextI18n") + @Override + protected void onStart() { + super.onStart(); + setCancelable(true); + } + } + + @SuppressLint("NotifyDataSetChanged") + private void validatefilterui() { + RecyclerView rec_subaxe = (RecyclerView) findViewById(R.id.rec_subaxe); + rec_subaxe.setLayoutManager(new GridLayoutManager(context, 3)); + rec_subaxe.setAdapter(new SubAxeValueAdapter(context, getFilters(), default_type, false, true, (filterText, placeHolder) -> download_report(context, filterText))); + } + + private void download_report(final Context context, String param) { + ProgressDialog loading = null; + try { + String cParam = param; + cParam = cParam.replaceAll(" ", "") + "Name"; + String download_key = "Report_TesterCounterDetail"; + JSONObject jsonObject = new JSONObject(); + jsonObject.put("Downloadtype", download_key); + jsonObject.put("Username", username); + jsonObject.put("Param1", counter_Id); + jsonObject.put("Param2", cParam); + String jsonString = jsonObject.toString(); + try { + loading = ProgressDialog.show(context, "Processing", "Please wait...", false, true); + OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build(); + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsonString); + Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build(); + PostApi api = adapter.create(PostApi.class); + Call call = api.getTabjournePlan(jsonData); + ProgressDialog finalLoading = loading; + call.enqueue(new Callback() { + @Override + public void onResponse(@NonNull Call call, @NonNull Response response) { + ResponseBody responseBody = response.body(); + String data = null; + if (responseBody != null && response.isSuccessful()) { + try { + assert response.body() != null; + data = response.body().string(); + data = data.substring(1, data.length() - 1).replace("\\", ""); + if (data.contains("No Data") || data.equalsIgnoreCase(CommonString.KEY_FAILURE) || data.contains("Failure;Cannot find table 0.")) { + testerCounterUsageDetail(param, finalLoading); + } else { + ResponseResult testerCounterDetail = new Gson().fromJson(data, ResponseResult.class); + db.open(); + if (testerCounterDetail != null) { + db.insertTesterCounterDetail(testerCounterDetail); + testerCounterUsageDetail(param, finalLoading); + } + } + } catch (Exception e) { + testerCounterUsageDetail(param, finalLoading); + } + } else { + testerCounterUsageDetail(param, finalLoading); + } + } + + @Override + public void onFailure(@NonNull Call call, @NonNull Throwable t) { + testerCounterUsageDetail(param, finalLoading); + } + }); + } catch (Exception e) { + testerCounterUsageDetail(param, null); + } + + } catch (JSONException e) { + testerCounterUsageDetail(param, null); + } + } + +} \ No newline at end of file diff --git a/app/src/main/java/com/cpm/lorealbaautomation/retrofit/DownloadAllDatawithRetro.java b/app/src/main/java/com/cpm/lorealbaautomation/retrofit/DownloadAllDatawithRetro.java new file mode 100644 index 0000000..cde38bb --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/retrofit/DownloadAllDatawithRetro.java @@ -0,0 +1,2174 @@ +package com.cpm.lorealbaautomation.retrofit; + +import android.annotation.SuppressLint; +import android.app.Activity; +import android.app.ProgressDialog; +import android.content.Context; +import android.content.SharedPreferences; +import android.os.AsyncTask; +import android.util.Log; +import android.view.WindowManager; + +import androidx.annotation.NonNull; + +import com.google.firebase.crashlytics.FirebaseCrashlytics; +import com.google.gson.Gson; +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.constant.AlertandMessages; +import com.cpm.lorealbaautomation.constant.CommonFunctions; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.gettersetter.ReferenceVariablesForDownloadActivity; +import com.cpm.lorealbaautomation.gsonGetterSetter.BaListGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.JCPGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterBAProfileGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterInvoiceTypeGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterNonStockReasonGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterNonVisibilityGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterProfileGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterProfileQuestionGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterPromoOffer; +import com.cpm.lorealbaautomation.gsonGetterSetter.ResponseResult; +import com.cpm.lorealbaautomation.gsonGetterSetter.ServerTimeGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.TCounterInvoiceGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.TStockSummaryGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.TableStructure; +import com.cpm.lorealbaautomation.gsonGetterSetter.TableStructureGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.testerreports.TesterCounter; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.HttpURLConnection; +import java.net.ProtocolException; +import java.net.SocketTimeoutException; +import java.net.URL; +import java.text.DecimalFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Date; +import java.util.List; +import java.util.concurrent.TimeUnit; + +import okhttp3.MediaType; +import okhttp3.OkHttpClient; +import okhttp3.RequestBody; +import okhttp3.ResponseBody; +import retrofit2.Call; +import retrofit2.Callback; +import retrofit2.Response; +import retrofit2.Retrofit; +import retrofit2.converter.gson.GsonConverterFactory; + +/** + * Created by jeevanp on 15-12-2017. + */ + +public class DownloadAllDatawithRetro extends ReferenceVariablesForDownloadActivity { + boolean isvalid; + private Retrofit adapter; + Context context; + public int listSize = 0; + int status = 0; + Lorealba_Database db; + ProgressDialog pd; + SharedPreferences preferences; + SharedPreferences.Editor editor; + String date, counterId = ""; + int from; + + public DownloadAllDatawithRetro(Context context) { + this.context = context; + } + + public DownloadAllDatawithRetro(Context context, Lorealba_Database db, ProgressDialog pd, int from) { + this.context = context; + this.db = db; + this.pd = pd; + preferences = PrefHelper.getPrefs(context); + editor = preferences.edit(); + date = preferences.getString(CommonString.KEY_DATE, ""); + counterId = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + this.from = from; + db.open(); + } + + + public void downloadDataUniversalWithoutWait(final ArrayList jsonStringList, final ArrayList KeyNames, int downloadindex, int type) { + status = 0; + isvalid = false; + final String[] data_global = {""}; + String jsonString = "", KeyName = ""; + int jsonIndex = 0; + if (!jsonStringList.isEmpty()) { + final OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, + TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build(); + jsonString = jsonStringList.get(downloadindex); + KeyName = KeyNames.get(downloadindex); + jsonIndex = downloadindex; + pd.setMessage("Downloading (" + downloadindex + "/" + listSize + ") \n" + KeyName); + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsonString); + adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build(); + PostApi api = adapter.create(PostApi.class); + Call call = api.getDownloadAll(jsonData); + final int[] finalJsonIndex = {jsonIndex}; + final String finalKeyName = KeyName; + + call.enqueue(new Callback() { + @Override + public void onResponse(@NonNull Call call, @NonNull Response response) { + String responseBody = response.body(); + String data = null; + if (responseBody != null && response.isSuccessful()) { + try { + data = response.body(); + assert data != null; + if (data.isEmpty()) { + data_global[0] = ""; + } else { + data_global[0] = data; + if (finalKeyName.equalsIgnoreCase("Table_Structure")) { + editor.putInt(CommonString.KEY_DOWNLOAD_INDEX, finalJsonIndex[0]); + editor.apply(); + tableStructureObj = new Gson().fromJson(data, TableStructureGetterSetter.class); + String isAllTableCreated = createTable(tableStructureObj); + + if (isAllTableCreated != CommonString.KEY_SUCCESS) { + AlertandMessages.showAlert((Activity) context, isAllTableCreated + " not created", true); + pd.dismiss(); + } + } else { + editor.putInt(CommonString.KEY_DOWNLOAD_INDEX, finalJsonIndex[0]); + editor.apply(); + new MyLoader(context, finalKeyName, data).execute(); + } + } + + finalJsonIndex[0]++; + if (finalJsonIndex[0] != KeyNames.size()) { + editor.putInt(CommonString.KEY_DOWNLOAD_INDEX, finalJsonIndex[0]); + editor.apply(); + downloadDataUniversalWithoutWait(jsonStringList, KeyNames, finalJsonIndex[0], CommonString.DOWNLOAD_ALL_SERVICE); + } else { + editor.putInt(CommonString.KEY_DOWNLOAD_INDEX, 0); + editor.apply(); + pd.setMessage("Downloading Images"); + new DownloadImageTask(context, masterPromoOfferObject, baListObject).execute(); + } + } catch (Exception e) { + e.fillInStackTrace(); + editor.putInt(CommonString.KEY_DOWNLOAD_INDEX, finalJsonIndex[0]); + editor.apply(); + pd.dismiss(); + AlertandMessages.showAlert((Activity) context, finalKeyName + " Data not found ", true); + } + } else { + editor.putInt(CommonString.KEY_DOWNLOAD_INDEX, finalJsonIndex[0]); + editor.apply(); + pd.dismiss(); + AlertandMessages.showAlert((Activity) context, "Error in downloading Data at " + finalKeyName, true); + } + } + + @Override + public void onFailure(@NonNull Call call, @NonNull Throwable t) { + isvalid = true; + pd.dismiss(); + AlertandMessages.showAlert((Activity) context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE, true); + } + }); + } else { + editor.putInt(CommonString.KEY_DOWNLOAD_INDEX, 0); + editor.apply(); + pd.setMessage("Downloading Images"); + new DownloadImageTask(context, masterPromoOfferObject, baListObject).execute(); + } + } + + String createTable(TableStructureGetterSetter tableGetSet) { + List tableList = tableGetSet.getTableStructure(); + try { + for (int i = 0; i < tableList.size(); i++) { + String table = tableList.get(i).getSqlText(); + db.open(); + if (db.createtable(table) == 0) { + return table; + } + } + } catch (Exception e) { + e.fillInStackTrace(); + } + + return CommonString.KEY_SUCCESS; + } + + public String downloadDataUniversal(final String jsonString, int type) { + try { + status = 0; + isvalid = false; + final String[] data_global = {""}; + final OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, + TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build(); + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsonString); + adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build(); + PostApi api = adapter.create(PostApi.class); + Call call = null; + if (type == CommonString.CHANGE_PASSWORD_SERVICE) { + call = api.getChangePassword(jsonData); + } else if (type == CommonString.FORGOT_PASSWORD_SERVICE) { + call = api.getResetPassword(jsonData); + } + assert call != null; + call.enqueue(new Callback() { + @Override + public void onResponse(@NonNull Call call, @NonNull Response response) { + ResponseBody responseBody = response.body(); + String data = null; + if (responseBody != null && response.isSuccessful()) { + try { + assert response.body() != null; + data = response.body().string(); + data = data.substring(1, data.length() - 1).replace("\\", ""); + if (data.equalsIgnoreCase(CommonString.KEY_SUCCESS)) { + data_global[0] = data; + isvalid = true; + status = 1; + } else { + data_global[0] = data; + isvalid = true; + status = 1; + } + + } catch (Exception e) { + e.fillInStackTrace(); + isvalid = true; + status = -2; + } + } else { + isvalid = true; + status = -1; + } + } + + @Override + public void onFailure(@NonNull Call call, @NonNull Throwable t) { + isvalid = true; + if (t instanceof SocketTimeoutException) { + status = 3; + } else if (t instanceof IOException) { + status = 3; + } else { + status = 3; + } + } + }); + + while (!isvalid) { + synchronized (this) { + this.wait(25); + } + } + if (isvalid) { + synchronized (this) { + this.notify(); + } + } + if (status == 1) { + return data_global[0]; + } else if (status == 2) { + return CommonString.MESSAGE_NO_RESPONSE_SERVER; + } else if (status == 3) { + return CommonString.MESSAGE_SOCKETEXCEPTION; + } else if (status == -2) { + return CommonString.MESSAGE_INVALID_JSON; + } else { + return CommonString.KEY_FAILURE; + } + } catch (Exception e) { + e.fillInStackTrace(); + return CommonString.KEY_FAILURE; + } + } + + + @SuppressLint("StaticFieldLeak") + private class MyLoader extends AsyncTask { + Context context; + String data, finalKeyName; + + public MyLoader(Context context, String finalKeyName, String data) { + this.context = (context); + this.data = data; + this.finalKeyName = finalKeyName; + } + + @Override + protected String doInBackground(String... strings) { + //perform heavy task here and finally update the UI with result this way - + try { + //test("Json_data", data); + switch (finalKeyName) { + case "BA_List": + if (!data.contains("No Data")) { + baListObject = new Gson().fromJson(data, JCPGetterSetter.class); + db.open(); + if (baListObject != null && !db.insertBalistData(baListObject)) { + AlertandMessages.showToastMsg(context, "Ba List data not saved"); + pd.dismiss(); + } + } else { + throw new java.lang.Exception(); + } + break; + + case "D2D_ARS": + if (!data.contains("No Data")) { + d2DARSGetterSetter = new Gson().fromJson(data, JCPGetterSetter.class); + db.open(); + if (d2DARSGetterSetter != null && !d2DARSGetterSetter.getD2DArsList().isEmpty()) { + editor = preferences.edit(); + editor.putString(CommonString.KEY_D2D_ARS_URL, d2DARSGetterSetter.getD2DArsList().get(0).getD2d_ars_url()); + editor.commit(); + } else { + editor = preferences.edit(); + editor.putString(CommonString.KEY_D2D_ARS_URL, ""); + editor.commit(); + } + } + break; + + case "Mapping_JourneyPlan": + if (!data.contains("No Data")) { + jcpObject = new Gson().fromJson(data, JCPGetterSetter.class); + db.open(); + if (jcpObject != null && !db.insertJCPData(jcpObject)) { + AlertandMessages.showToastMsg(context, "JCP data not saved"); + pd.dismiss(); + } + } else { + throw new java.lang.Exception(); + } + break; + + case "Mapping_CounterGroup_Brand": + if (!data.contains("No Data")) { + mappingCounterGroupBrandObject = new Gson().fromJson(data, JCPGetterSetter.class); + db.open(); + if (mappingCounterGroupBrandObject != null && !db.insertmappingcountergroupBrand(mappingCounterGroupBrandObject)) { + AlertandMessages.showToastMsg(context, "Mapping_CounterGroup_Brand data not saved"); + pd.dismiss(); + } + } else { + db.open(); + db.delete_table_data("Mapping_CounterGroup_Brand"); + } + + break; + + case "Product_Master": + if (!data.contains("No Data")) { + product_masterObject = new Gson().fromJson(data, TableStructureGetterSetter.class); + db.open(); + if (product_masterObject != null && !db.insertproductmasterdata(product_masterObject)) { + AlertandMessages.showToastMsg(context, "Product Master data not saved"); + pd.dismiss(); + } + } else { + throw new java.lang.Exception(); + } + + break; + + case "SkinGeniusUrl": + if (!data.contains("No Data")) { + SkinGeniusUrlObject = new Gson().fromJson(data, TableStructureGetterSetter.class); + db.open(); + if (SkinGeniusUrlObject != null && !SkinGeniusUrlObject.getSkinGeniusUrl().isEmpty()) { + editor = preferences.edit(); + editor.putString(CommonString.KEY_SKIN_GENIUS_URL, SkinGeniusUrlObject.getSkinGeniusUrl().get(0).getSkinGeniusUrl()); + editor.commit(); + } else { + editor = preferences.edit(); + editor.putString(CommonString.KEY_SKIN_GENIUS_URL, ""); + editor.commit(); + } + + if (SkinGeniusUrlObject != null && !SkinGeniusUrlObject.getSkinGeniusUrl().isEmpty()) { + editor = preferences.edit(); + editor.putString(CommonString.KEY_SKIN_MAYBELLINE_URL, SkinGeniusUrlObject.getSkinGeniusUrl().get(0).getMaybellineUrl()); + editor.commit(); + } else { + editor = preferences.edit(); + editor.putString(CommonString.KEY_SKIN_MAYBELLINE_URL, ""); + editor.commit(); + } + } + break; + case "Mapping_Visibility": + if (!data.contains("No Data")) { + mapping_visibilityObject = new Gson().fromJson(data, TableStructureGetterSetter.class); + db.open(); + if (mapping_visibilityObject != null && !db.insertmappingvisibility(mapping_visibilityObject)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Mapping_Visibility data not saved"); + } + } else { + db.open(); + db.delete_table_data("Mapping_Visibility"); + } + + break; + + case "Master_Posm": + if (!data.contains("No Data")) { + posmmasterObject = new Gson().fromJson(data, TableStructureGetterSetter.class); + db.open(); + if (posmmasterObject != null && !db.insertmappingposmdata(posmmasterObject)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Master_Posm data not saved"); + } + } + + break; + + + case "InwardSales_PO": + if (!data.contains("No Data")) { + inwardSales_POObject = new Gson().fromJson(data, TableStructureGetterSetter.class); + db.open(); + if (inwardSales_POObject != null && !db.insertInwordSalesPoData(inwardSales_POObject)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "InwardSales PO Data not saved"); + } + } + + + break; + + + case "ServerTime": + if (!data.contains("No Data")) { + serverTimeObj = new Gson().fromJson(data, ServerTimeGetterSetter.class); + if (serverTimeObj != null && !db.insertServerTimeData(serverTimeObj)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "ServerTime not saved"); + } + } else { + db.open(); + db.delete_table_data("ServerTime"); + } + + break; + + case "StockSummary_Check": + if (!data.contains("No Data")) { + tStockSummaryCheckObj = new Gson().fromJson(data, ServerTimeGetterSetter.class); + if (tStockSummaryCheckObj != null && !db.insertTStockSummaryCheck(tStockSummaryCheckObj)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "StockSummary_Check not saved"); + } + } else { + db.open(); + db.delete_table_data("StockSummary_Check"); + } + break; + + case "T_StockSummary": + if (!data.contains("No Data")) { + try { + tStockSummaryObj = new Gson().fromJson(data, TStockSummaryGetterSetter.class); + if (tStockSummaryObj != null) { + editor = preferences.edit(); + editor.putInt(CommonString.KEY_INCORRECT_TSTOCK_SUMMERY + date, 0); + editor.apply(); + db.open(); + if (!db.insertTStockSummaryData(tStockSummaryObj, counterId, date)) { + db.delete_table_data("T_StockSummary"); + AlertandMessages.showToastMsg(context, "T_StockSummary not saved"); + } else { + throw new java.lang.Exception(); + } + } + } catch (Exception e) { + throw new java.lang.Exception(); + } + } + + break; + + case "T_CounterInvoice": + if (!data.contains("No Data")) { + tCounterInvoiceObj = new Gson().fromJson(data, TCounterInvoiceGetterSetter.class); + db.open(); + if (tCounterInvoiceObj != null && !db.insertTCounterInvoiceData(tCounterInvoiceObj)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "T_CounterInvoice not saved"); + } + } else { + db.open(); + db.delete_table_data("T_CounterInvoice"); + } + + + break; + + case "Master_NonVisibility": + if (!data.contains("No Data")) { + masterNonVisibilityGetterSetter = new Gson().fromJson(data, MasterNonVisibilityGetterSetter.class); + db.open(); + if (masterNonVisibilityGetterSetter != null && !db.insertMasterNonVisibilityData(masterNonVisibilityGetterSetter)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Master_NonVisibility not saved"); + } + } else { + db.open(); + db.delete_table_data("Master_NonVisibility"); + } + + + break; + + + case "Master_NonStockReason": + if (!data.contains("No Data")) { + masterNonStockReasonObj = new Gson().fromJson(data, MasterNonStockReasonGetterSetter.class); + db.open(); + if (masterNonStockReasonObj != null && !db.insertNonStockReasonData(masterNonStockReasonObj)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Master_NonStockReason not saved"); + } + } else { + db.open(); + db.delete_table_data("Master_NonStockReason"); + } + + + break; + //jp + case "Master_SkinType": + if (!data.contains("No Data")) { + masterSkinTypeObject = new Gson().fromJson(data, TableStructureGetterSetter.class); + db.open(); + if (masterSkinTypeObject != null && !db.insertSkinTypeMaster(masterSkinTypeObject)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Master_SkinType not saved"); + } + } else { + throw new java.lang.Exception(); + } + + break; + + case "Master_AgeLimit": + if (!data.contains("No Data")) { + masterAgeLimitObject = new Gson().fromJson(data, TableStructureGetterSetter.class); + db.open(); + if (masterAgeLimitObject != null && !db.insertAgeLimitMaster(masterAgeLimitObject)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Master_AgeLimit not saved"); + } + } else { + throw new java.lang.Exception(); + } + + break; + + case "Master_Profile": + if (!data.contains("No Data")) { + masterProfileGetterSetter = new Gson().fromJson(data, MasterProfileGetterSetter.class); + db.open(); + if (masterProfileGetterSetter != null && !db.insertMasterProfile(masterProfileGetterSetter)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Master_Profile not saved"); + } + } + + + break; + case "Master_ProfileQuestion": + if (!data.contains("No Data")) { + masterProfileQuestionGetterSetter = new Gson().fromJson(data, MasterProfileQuestionGetterSetter.class); + db.open(); + if (masterProfileQuestionGetterSetter != null && !db.insertMasterProfileQuestion(masterProfileQuestionGetterSetter)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Master_AgeLimit not saved"); + } + } else { + throw new java.lang.Exception(); + } + + break; + + case "Master_ReturnReason": + if (!data.contains("No Data")) { + return_ReasonObject = new Gson().fromJson(data, MasterProfileQuestionGetterSetter.class); + db.open(); + if (return_ReasonObject != null && !db.insert_return_reason(return_ReasonObject)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Master_ReturnReason not saved"); + } + } else { + throw new java.lang.Exception(); + } + + + break; + + + case "Master_TermsCondition": + if (!data.contains("No Data")) { + termConditionObject = new Gson().fromJson(data, MasterProfileQuestionGetterSetter.class); + db.open(); + if (termConditionObject != null && !db.inserterm_condition(termConditionObject)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Master_TermsCondition not saved"); + } + } else { + throw new java.lang.Exception(); + } + + break; + + case "Master_InvoiceType": + if (!data.contains("No Data")) { + masterInvoiceTypeObj = new Gson().fromJson(data, MasterInvoiceTypeGetterSetter.class); + db.open(); + if (masterInvoiceTypeObj != null && !db.insertInvoiceTypeMasterData(masterInvoiceTypeObj)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Master_InvoiceType not saved"); + } + } else { + throw new java.lang.Exception(); + } + + + break; + + case "T_LeaveRequest": + if (!data.contains("No Data")) { + LeaveRequestObject = new Gson().fromJson(data, MasterProfileQuestionGetterSetter.class); + db.open(); + if (LeaveRequestObject != null && !db.insertLeaveRequest(LeaveRequestObject)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "T_LeaveRequest not saved"); + } + } else { + db.open(); + db.delete_table_data("T_LeaveRequest"); + } + + + break; + + + case "T_LeaveLedger": + if (!data.contains("No Data")) { + leaveStatusObject = new Gson().fromJson(data, MasterProfileQuestionGetterSetter.class); + db.open(); + if (leaveStatusObject != null && !db.insert_leave_status(leaveStatusObject)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "T_LeaveLedger not saved"); + } + } else { + db.open(); + db.delete_table_data("T_LeaveLedger"); + } + + break; + + case "Master_Break": + if (!data.contains("No Data")) { + masterBreakObject = new Gson().fromJson(data, MasterProfileQuestionGetterSetter.class); + db.open(); + if (masterBreakObject != null && !db.insert_master_break(masterBreakObject)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Master_Break not saved"); + } + } else { + throw new java.lang.Exception(); + } + + + break; + + + ///jp_download Report + case "Report_SalesValue": + if (!data.contains("No Data")) { + editor = preferences.edit(); + editor.putString(CommonString.KEY_DASHBOARD_REFRESH_TIME, CommonFunctions.getCurrentTime_only()); + editor.commit(); + reportSaleValueObject = new Gson().fromJson(data, MasterProfileQuestionGetterSetter.class); + db.open(); + if (reportSaleValueObject != null && !db.insertReportSaleValue(reportSaleValueObject)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Report_SalesValue not saved"); + } + } else { + editor = preferences.edit(); + editor.putString(CommonString.KEY_DASHBOARD_REFRESH_TIME, CommonFunctions.getCurrentTime_only()); + editor.commit(); + db.open(); + db.delete_table_data("Report_SalesValue"); + } + + break; + + ///jp_download Report + case "Report_Sales_Detail": + if (!data.contains("No Data")) { + reportSaleDetailsObject = new Gson().fromJson(data, MasterProfileQuestionGetterSetter.class); + db.open(); + if (reportSaleDetailsObject != null && !db.insertReportSaleDetails(reportSaleDetailsObject, false)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Report_Sales_Detail not saved"); + } + } else { + db.open(); + db.delete_table_data("Report_Sales_Detail"); + } + break; + + case "Report_Sales_DetailME": + if (!data.contains("No Data")) { + reportSaleDetailsObject = new Gson().fromJson(data, MasterProfileQuestionGetterSetter.class); + db.open(); + if (reportSaleDetailsObject != null && !db.insertReportSaleDetails(reportSaleDetailsObject, true)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Report_Sales_DetailME not saved"); + } + } else { + db.open(); + db.delete_table_data("Report_Sales_DetailME"); + } + break; + + case "Report_AvgTransactionPerDay": + if (!data.contains("No Data")) { + reportavGTransationValueObject = new Gson().fromJson(data, MasterProfileQuestionGetterSetter.class); + db.open(); + if (reportavGTransationValueObject != null && !db.insertReportAvgTransationperDay(reportavGTransationValueObject)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Report_AvgTransactionPerDay not saved"); + } + } else { + db.open(); + db.delete_table_data("Report_AvgTransactionPerDay"); + } + + + break; + + case "Report_AvgUnitsPerBill": + if (!data.contains("No Data")) { + reportAvgUnitPerBillObject = new Gson().fromJson(data, MasterProfileQuestionGetterSetter.class); + db.open(); + if (reportAvgUnitPerBillObject != null && !db.insertReportAvgPerBillDay(reportAvgUnitPerBillObject)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Report_AvgUnitsPerBill not saved"); + } + } else { + db.open(); + db.delete_table_data("Report_AvgUnitsPerBill"); + } + + + break; + + case "Report_AvgBillValue": + if (!data.contains("No Data")) { + reportAvgBillUnitObject = new Gson().fromJson(data, MasterProfileQuestionGetterSetter.class); + db.open(); + if (reportAvgBillUnitObject != null && !db.insertReportAvgBillUnit(reportAvgBillUnitObject)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Report_AvgBillValue not saved"); + } + } else { + db.open(); + db.delete_table_data("Report_AvgBillValue"); + } + + + break; + + case "Report_AvgLinPerBill": + if (!data.contains("No Data")) { + reportAvgLinPerBillObject = new Gson().fromJson(data, MasterProfileQuestionGetterSetter.class); + db.open(); + if (reportAvgLinPerBillObject != null && !db.insertReportAvgLinPerBill(reportAvgLinPerBillObject)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Report_AvgLinPerBill not saved"); + } + } else { + db.open(); + db.delete_table_data("Report_AvgLinPerBill"); + } + + + break; + + case "Report_SellingPrice": + if (!data.contains("No Data")) { + reportSalingPrizeObject = new Gson().fromJson(data, MasterProfileQuestionGetterSetter.class); + db.open(); + if (reportSalingPrizeObject != null && !db.insertReportSelingPrice(reportSalingPrizeObject)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Report_SellingPrice not saved"); + } + } else { + db.open(); + db.delete_table_data("Report_SellingPrice"); + } + + + break; + + case "Report_Top10Volume": + if (!data.contains("No Data")) { + reportTop10VolumeObject = new Gson().fromJson(data, MasterProfileQuestionGetterSetter.class); + db.open(); + if (reportTop10VolumeObject != null && !db.insertReportTop10Volume(reportTop10VolumeObject)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Report_Top10Volume not saved"); + } + } else { + db.open(); + db.delete_table_data("Report_Top10Volume"); + } + + + break; + + case "Report_Top10Value": + if (!data.contains("No Data")) { + reportTop10ValueObject = new Gson().fromJson(data, MasterProfileQuestionGetterSetter.class); + db.open(); + if (reportTop10ValueObject != null && !db.insertReportTop10Value(reportTop10ValueObject)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Report_Top10Value not saved"); + } + } else { + db.open(); + db.delete_table_data("Report_Top10Value"); + } + + break; + case "Report_ME_Sale": + if (!data.contains("No Data")) { + reportMeSale = new Gson().fromJson(data, MasterProfileQuestionGetterSetter.class); + db.open(); + if (reportMeSale != null && !db.insertMeSaleReport(reportMeSale)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Report_ME_Sale not saved"); + } + } else { + db.open(); + db.delete_table_data("Report_ME_Sale"); + } + + break; + + case "Master_BAProfile": + if (!data.contains("No Data")) { + masterBAProfileGetterSetter = new Gson().fromJson(data, MasterBAProfileGetterSetter.class); + db.open(); + if (masterBAProfileGetterSetter != null && !db.insertBaProfileValue(masterBAProfileGetterSetter)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Master_BAProfile not saved"); + } + } else { + db.open(); + db.delete_table_data("Master_BAProfile"); + } + + + break; + case "Master_PromoOffers": + if (!data.contains("No Data")) { + masterPromoOfferObject = new Gson().fromJson(data, MasterBAProfileGetterSetter.class); + db.open(); + if (masterPromoOfferObject != null && !db.insertPromoOffers(masterPromoOfferObject)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Master_PromoOffers not saved"); + } + } else { + db.open(); + db.delete_table_data("Master_PromoOffers"); + } + + break; + + case "Report_AttendanceDetail": + if (!data.contains("No Data")) { + reportAttendenceDetailGetterSetter = new Gson().fromJson(data, MasterBAProfileGetterSetter.class); + db.open(); + if (reportAttendenceDetailGetterSetter != null && !db.insertreport_attendence_details(reportAttendenceDetailGetterSetter)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Report_AttendanceDetail not saved"); + } + } else { + db.open(); + db.delete_table_data("Report_AttendanceDetail"); + } + + + break; + case "Report_AttendanceSummary": + if (!data.contains("No Data")) { + reportAttendenceSummeryGetterSetter = new Gson().fromJson(data, MasterBAProfileGetterSetter.class); + db.open(); + if (reportAttendenceSummeryGetterSetter != null && !db.insertreport_attendence_summery(reportAttendenceSummeryGetterSetter)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Report_AttendanceSummary not saved"); + } + } else { + db.open(); + db.delete_table_data("Report_AttendanceSummary"); + } + + break; + + case "Report_InwardStockSummary": + if (!data.contains("No Data")) { + reportInwordStockSummeryGetterSetter = new Gson().fromJson(data, MasterBAProfileGetterSetter.class); + db.open(); + if (reportInwordStockSummeryGetterSetter != null && !db.insertreport_inword_stock_summery(reportInwordStockSummeryGetterSetter)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Report_InwardStockSummary not saved"); + } + } else { + db.open(); + db.delete_table_data("Report_InwardStockSummary"); + } + + + break; + + case "Report_BA_Availability": + if (!data.contains("No Data")) { + reportbaAvailabilityGetterSetter = new Gson().fromJson(data, MasterBAProfileGetterSetter.class); + db.open(); + if (reportbaAvailabilityGetterSetter != null && !db.insert_ba_availability(reportbaAvailabilityGetterSetter)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Report_BA_Availability not saved"); + } + } else { + db.open(); + db.delete_table_data("Report_BA_Availability"); + } + + + break; + + case "Master_Looks": + if (!data.contains("No Data")) { + masterLookObject = new Gson().fromJson(data, MasterBAProfileGetterSetter.class); + db.open(); + if (masterLookObject != null && !db.insert_master_look(masterLookObject)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Master_Looks not saved"); + } + } else { + db.open(); + db.delete_table_data("Master_Looks"); + } + + break; + + case "ME_MEAuditQuestion": + if (!data.contains("No Data")) { + meAuditMasterObject = new Gson().fromJson(data, MasterBAProfileGetterSetter.class); + db.open(); + if (meAuditMasterObject != null && !db.insert_me_audit_question(meAuditMasterObject)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "ME_MEAuditQuestion not saved"); + } + } else { + db.open(); + db.delete_table_data("ME_MEAuditQuestion"); + } + + + break; + + case "ME_MEAuditQuestion_UploadStatus": + if (!data.contains("No Data")) { + meAuditMasterUploadStatusObject = new Gson().fromJson(data, MasterBAProfileGetterSetter.class); + db.open(); + if (meAuditMasterUploadStatusObject != null && !db.insert_me_quizuploadstatus(meAuditMasterUploadStatusObject)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "ME_MEAuditQuestion_UploadStatus not saved"); + } + } else { + db.open(); + db.delete_table_data("ME_MEAuditQuestion_UploadStatus"); + } + + break; + + case "Master_Promotion": + if (!data.contains("No Data")) { + responseResult = new Gson().fromJson(data, ResponseResult.class); + db.open(); + if (responseResult != null && !db.insertPromotionMaster(responseResult)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Master_Promotion not saved"); + } + } else { + db.open(); + db.delete_table_data("Master_Promotion"); + } + + break; + + case "Master_PromotionSetEntityItem": + if (!data.contains("No Data")) { + resultPromotionSetEntityItem = new Gson().fromJson(data, ResponseResult.class); + db.open(); + if (resultPromotionSetEntityItem != null && !db.insertPromotionSetEntityItemMaster(resultPromotionSetEntityItem)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Master_PromotionSetEntityItem not saved"); + } + } else { + db.open(); + db.delete_table_data("Master_PromotionSetEntityItem"); + } + + break; + + case "Master_PromotionGetEntityItem": + if (!data.contains("No Data")) { + resultPromotionGetEntityItem = new Gson().fromJson(data, ResponseResult.class); + db.open(); + if (resultPromotionGetEntityItem != null && !db.insertPromotionGetEntityItemMaster(resultPromotionGetEntityItem)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Master_PromotionGetEntityItem not saved"); + } + } else { + db.open(); + db.delete_table_data("Master_PromotionGetEntityItem"); + } + + break; + + case "Master_PromotionSetProductGroup": + if (!data.contains("No Data")) { + resultPromotionSetProductGroup = new Gson().fromJson(data, ResponseResult.class); + db.open(); + if (resultPromotionSetProductGroup != null && !db.insertPromotionSetProductGroupMaster(resultPromotionSetProductGroup)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Master_PromotionSetProductGroup not saved"); + } + } else { + db.open(); + db.delete_table_data("Master_PromotionSetProductGroup"); + } + + break; + + case "Master_PromotionGetProductGroup": + if (!data.contains("No Data")) { + resultPromotionGetProductGroup = new Gson().fromJson(data, ResponseResult.class); + db.open(); + if (resultPromotionGetProductGroup != null && !db.insertPromotionGetProductGroupMaster(resultPromotionGetProductGroup)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Master_PromotionGetProductGroup not saved"); + } + } else { + db.open(); + db.delete_table_data("Master_PromotionGetProductGroup"); + } + + break; + + case "Master_PromotionSetProductCatalog": + if (!data.contains("No Data")) { + promosetproductCatologObject = new Gson().fromJson(data, ResponseResult.class); + db.open(); + if (promosetproductCatologObject != null && !db.insertMasterPromotionSetProductCatalog(promosetproductCatologObject)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Master_PromotionSetProductCatalog not saved"); + } + } else { + db.open(); + db.delete_table_data("Master_PromotionSetProductCatalog"); + } + + break; + + case "Master_PromotionGetProductCatalog": + if (!data.contains("No Data")) { + promogetproductCatologObject = new Gson().fromJson(data, ResponseResult.class); + db.open(); + if (promogetproductCatologObject != null && !db.insertMasterPromotionGetProductCatalog(promogetproductCatologObject)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Master_PromotionGetProductCatalog not saved"); + } + } else { + db.open(); + db.delete_table_data("Master_PromotionGetProductCatalog"); + } + + break; + + + case "Master_Survey": + if (!data.contains("No Data")) { + masterSurvey = new Gson().fromJson(data, ResponseResult.class); + db.open(); + if (masterSurvey != null && !db.insertMasterSurvey(masterSurvey)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Master_Survey not saved"); + } + } else { + db.open(); + db.delete_table_data("Master_Survey"); + } + + break; + + case "Master_LeaveType": + if (!data.contains("No Data")) { + masterLeaveType = new Gson().fromJson(data, ResponseResult.class); + db.open(); + if (masterLeaveType != null && !db.insertMasterLeaveType(masterLeaveType)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Master_LeaveType not saved"); + } + } else { + db.open(); + db.delete_table_data("Master_LeaveType"); + } + + break; + + + case "Damage_ReturnToDistributor": + if (!data.contains("No Data")) { + damagedReturnToDistributorObject = new Gson().fromJson(data, ResponseResult.class); + db.open(); + if (damagedReturnToDistributorObject != null && !db.insertdamagedReturnToDistributor(damagedReturnToDistributorObject)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Damage_ReturnToDistributor not saved"); + } + } else { + db.open(); + db.delete_table_data("Damage_ReturnToDistributor"); + } + + break; + + case "Master_Survey_UploadStatus": + if (!data.contains("No Data")) { + baorcounterUploadStatusObject = new Gson().fromJson(data, ResponseResult.class); + db.open(); + if (baorcounterUploadStatusObject != null && !db.insertbaservaystusupload(baorcounterUploadStatusObject)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Master_Survey_UploadStatus not saved"); + } + } else { + db.open(); + db.delete_table_data("Master_Survey_UploadStatus"); + } + + break; + + case "Report_ProductGroupWiseSalesValue": + if (!data.contains("No Data")) { + productGroupwiseSaleObject = new Gson().fromJson(data, ResponseResult.class); + db.open(); + if (productGroupwiseSaleObject != null && !db.insertGroupWiseSale(productGroupwiseSaleObject)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Report_ProductGroupWiseSalesValue not saved"); + } + } else { + db.open(); + db.delete_table_data("Report_ProductGroupWiseSalesValue"); + } + + + break; + + case "Report_SalesDateWise": + if (!data.contains("No Data")) { + reportsaleDatewiseObject = new Gson().fromJson(data, ResponseResult.class); + db.open(); + if (reportsaleDatewiseObject != null && !db.insertReportDaywiseSale(reportsaleDatewiseObject, false)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Report_SalesDateWise not saved"); + } + } else { + db.open(); + db.delete_table_data("Report_SalesDateWise"); + } + + break; + + case "Report_SalesDateWiseME": + if (!data.contains("No Data")) { + reportsaleDatewiseObject = new Gson().fromJson(data, ResponseResult.class); + db.open(); + if (reportsaleDatewiseObject != null && !db.insertReportDaywiseSale(reportsaleDatewiseObject, true)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Report_SalesDateWiseME not saved"); + } + } else { + db.open(); + db.delete_table_data("Report_SalesDateWiseME"); + } + + break; + + case "Damage_PreviousPending": + if (!data.contains("No Data")) { + damagedpendingObject = new Gson().fromJson(data, ResponseResult.class); + db.open(); + if (damagedpendingObject != null && !db.insertDamagedPending(damagedpendingObject)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Damage_PreviousPending not saved"); + } + } else { + db.open(); + db.delete_table_data("Damage_PreviousPending"); + } + + + break; + + case "Report_SalesL3MValue": + if (!data.contains("No Data")) { + reportlastmonth = new Gson().fromJson(data, ResponseResult.class); + db.open(); + if (reportlastmonth != null && !db.insertreportsalemonth(reportlastmonth, false)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Report_SalesL3MValue not saved"); + } + } else { + db.open(); + db.delete_table_data("Report_SalesL3MValue"); + } + + break; + + case "Report_SalesL3MValueME": + if (!data.contains("No Data")) { + reportlastmonth = new Gson().fromJson(data, ResponseResult.class); + db.open(); + if (reportlastmonth != null && !db.insertreportsalemonth(reportlastmonth, true)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Report_SalesL3MValueME not saved"); + } + } else { + db.open(); + db.delete_table_data("Report_SalesL3MValueME"); + } + + break; + + case "Report_MTD_WorkingCounterME": + if (!data.contains("No Data")) { + reportlastmonth = new Gson().fromJson(data, ResponseResult.class); + db.open(); + if (reportlastmonth != null && !db.insertMeWorkingcounterDetails(reportlastmonth)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Report_MTD_WorkingCounterME not saved"); + } + } else { + db.open(); + db.delete_table_data("Report_MTD_WorkingCounterME"); + } + + break; + + case "Master_PromotionGetExclusionList": + if (!data.contains("No Data")) { + promogetexclusionlistob = new Gson().fromJson(data, ResponseResult.class); + db.open(); + if (promogetexclusionlistob != null && !db.insertpromogetexclusion(promogetexclusionlistob)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Master_PromotionGetExclusionList not saved"); + } + } else { + db.open(); + db.delete_table_data("Master_PromotionGetExclusionList"); + } + + break; + + case "Master_PromotionSetExclusionList": + if (!data.contains("No Data")) { + promosetexclusionlistob = new Gson().fromJson(data, ResponseResult.class); + db.open(); + if (promosetexclusionlistob != null && !db.insertpromosetExclusion(promosetexclusionlistob)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Master_PromotionSetExclusionList not saved"); + } + } else { + db.open(); + db.delete_table_data("Master_PromotionSetExclusionList"); + } + + break; + + case "Report_DamageStockHistory": + if (!data.contains("No Data")) { + reportdamagehistory = new Gson().fromJson(data, ResponseResult.class); + db.open(); + if (reportdamagehistory != null && !db.insertdamagestockhistory(reportdamagehistory)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Report_DamageStockHistory not saved"); + } + } else { + db.open(); + db.delete_table_data("Report_DamageStockHistory"); + } + + break; + + case "Master_SourcesOfSales": + if (!data.contains("No Data")) { + mastersourceofsales = new Gson().fromJson(data, ResponseResult.class); + db.open(); + if (mastersourceofsales != null && !db.insertsourceofsales(mastersourceofsales)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Master_SourcesOfSales not saved"); + } + } else { + throw new java.lang.Exception(); + } + + break; + + ////Updated by J.P 22/05/22 + case "Master_CompetitonBrandWiseNuance": + if (!data.contains("No Data")) { + masterCompetitonBrandWiseNuance = new Gson().fromJson(data, ResponseResult.class); + db.open(); + if (masterCompetitonBrandWiseNuance != null && !db.insertMasterCompetitonBrandWiseNuance(masterCompetitonBrandWiseNuance)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Master_CompetitonBrandWiseNuance not saved"); + } + } else { + throw new java.lang.Exception(); + } + + break; + + case "Master_CompetitionOfferSet": + if (!data.contains("No Data")) { + masterCompetitionOfferSet = new Gson().fromJson(data, ResponseResult.class); + db.open(); + if (masterCompetitionOfferSet != null && !db.insertMasterCompetitionOfferSet(masterCompetitionOfferSet)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Master_CompetitionOfferSet not saved"); + } + } else { + throw new java.lang.Exception(); + } + + break; + + case "Master_CompetitionOffer": + if (!data.contains("No Data")) { + masterCompetitionOffer = new Gson().fromJson(data, ResponseResult.class); + db.open(); + if (masterCompetitionOffer != null && !db.insertMasterCompetitionOffer(masterCompetitionOffer)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Master_CompetitionOffer not saved"); + } + } else { + throw new java.lang.Exception(); + } + break; + + case "Master_CompetitionOfferSaleRange": + if (!data.contains("No Data")) { + masterCompetitionOfferSaleRange = new Gson().fromJson(data, ResponseResult.class); + db.open(); + if (masterCompetitionOfferSaleRange != null && !db.insertMasterCompetitionOfferSaleRange(masterCompetitionOfferSaleRange)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Master_CompetitionOfferSaleRange not saved"); + } + } else { + throw new java.lang.Exception(); + } + break; + + case "Master_RetailExcellence_Item": + if (!data.contains("No Data")) { + masterRetailExcellence = new Gson().fromJson(data, ResponseResult.class); + db.open(); + if (masterRetailExcellence != null && !db.insertMasterRetailExcellence(masterRetailExcellence)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Master_RetailExcellence_Item not saved"); + } + } else { + throw new java.lang.Exception(); + } + break; + + case "Master_CompetitionOfferGet": + if (!data.contains("No Data")) { + masterCompetitionOfferGet = new Gson().fromJson(data, ResponseResult.class); + db.open(); + if (masterCompetitionOfferGet != null && !db.insertMasterCompetitionOfferGet(masterCompetitionOfferGet)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Master_CompetitionOfferGet not saved"); + } + } else { + throw new java.lang.Exception(); + } + + break; + + case "Master_CompetitionPromoType": + if (!data.contains("No Data")) { + masterCompetitionPromoType = new Gson().fromJson(data, ResponseResult.class); + db.open(); + if (masterCompetitionPromoType != null && !db.insertMasterCompetitionPromoType(masterCompetitionPromoType)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Master_CompetitionPromoType not saved"); + } + } else { + throw new java.lang.Exception(); + } + + break; + + case "Master_CompetitionProductType": + if (!data.contains("No Data")) { + masterCompetitionProductType = new Gson().fromJson(data, ResponseResult.class); + db.open(); + if (masterCompetitionProductType != null && !db.insertMasterCompProductType(masterCompetitionProductType)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Master_CompetitionProductType not saved"); + } + } else { + throw new java.lang.Exception(); + } + + break; + + case "AppDashboard_TVA": + if (!data.contains("No Data")) { + ResponseResult appDashTVA = new Gson().fromJson(data, ResponseResult.class); + db.open(); + if (appDashTVA != null && !db.insertDashTVA(appDashTVA)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "AppDashboard_TVA not saved"); + } + } else { + db.open(); + db.delete_table_data("AppDashboard_TVA"); + } + break; + + case "AppDashboard_TVADrillDown": + if (!data.contains("No Data")) { + ResponseResult appDashTVAdrillDown = new Gson().fromJson(data, ResponseResult.class); + db.open(); + if (appDashTVAdrillDown != null && !db.insertDashTVADrillDown(appDashTVAdrillDown)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "AppDashboard_TVADrillDown not saved"); + } + } else { + db.open(); + db.delete_table_data("AppDashboard_TVADrillDown"); + } + + break; + + case "AppDashboard_LeaderBoard": + if (!data.contains("No Data")) { + ResponseResult leaderBoard = new Gson().fromJson(data, ResponseResult.class); + db.open(); + if (leaderBoard != null && !db.insertDashLeaderBoard(leaderBoard)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "AppDashboard_LeaderBoard not saved"); + } + } else { + db.open(); + db.delete_table_data("AppDashboard_LeaderBoard"); + } + + break; + + case "AppDashboard_Incentive": + if (!data.contains("No Data")) { + ResponseResult incentive = new Gson().fromJson(data, ResponseResult.class); + db.open(); + if (incentive != null && !db.insertDashIncentive(incentive)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "AppDashboard_Incentive not saved"); + } + } else { + db.open(); + db.delete_table_data("AppDashboard_Incentive"); + } + + break; + + case "AppDashboard_L3MOffTake_Counter": + if (!data.contains("No Data")) { + ResponseResult offtakeCounter = new Gson().fromJson(data, ResponseResult.class); + db.open(); + if (offtakeCounter != null && !db.insertDashOffTakeCounter(offtakeCounter)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "L3MOffTake_Counter not saved"); + } + } else { + db.open(); + db.delete_table_data("AppDashboard_L3MOffTake_Counter"); + } + + break; + + case "AppDashboard_L3MOffTake_Nuance": + if (!data.contains("No Data")) { + ResponseResult offtakeNuance = new Gson().fromJson(data, ResponseResult.class); + db.open(); + if (offtakeNuance != null && !db.insertDashOffTakeNuance(offtakeNuance)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "L3MOffTake_Nuance not saved"); + } + } else { + db.open(); + db.delete_table_data("AppDashboard_L3MOffTake_Nuance"); + } + + break; + + case "AppDashboard_L3MOffTake_SubAxe": + if (!data.contains("No Data")) { + ResponseResult offtakeSubAxe = new Gson().fromJson(data, ResponseResult.class); + db.open(); + if (offtakeSubAxe != null && !db.insertDashOffTakeSubAxe(offtakeSubAxe)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "L3MOffTake_SubAxe not saved"); + } + } else { + db.open(); + db.delete_table_data("AppDashboard_L3MOffTake_SubAxe"); + } + + break; + + case "ReportDaily_TVA": + if (!data.contains("No Data")) { + ResponseResult dailyTva = new Gson().fromJson(data, ResponseResult.class); + db.open(); + if (dailyTva != null && !db.insertDailyTVA(dailyTva)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "ReportDaily_TVA not saved"); + } + } else { + db.open(); + db.delete_table_data("ReportDaily_TVA"); + } + + break; + + case "Report_SalesGrowth_Counter": + if (!data.contains("No Data")) { + ResponseResult salesGrowth = new Gson().fromJson(data, ResponseResult.class); + db.open(); + if (salesGrowth != null && !db.insertReportSalesGrowthCounter(salesGrowth)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Report_SalesGrowth_Counter not saved"); + } + } else { + db.open(); + db.delete_table_data("Report_SalesGrowth_Counter"); + } + + break; + + case "Report_SalesGrowth_CounterDetail": + if (!data.contains("No Data")) { + ResponseResult salesGrowthSubAxe = new Gson().fromJson(data, ResponseResult.class); + db.open(); + if (salesGrowthSubAxe != null && !db.insertSalesGrowthCounterSubAxe(salesGrowthSubAxe)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Report_SalesGrowth_CounterDetail not saved"); + } + } else { + db.open(); + db.delete_table_data("Report_SalesGrowth_CounterDetail"); + } + + break; + + case "Report_TesterCounter": + if (!data.contains("No Data")) { + TesterCounter testerCounter = new Gson().fromJson(data, TesterCounter.class); + db.open(); + if (testerCounter != null && testerCounter.getReportTesterCounter()!=null && !db.insertTesterCounter(testerCounter)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Report_TesterCounter not saved"); + } + } else { + db.open(); + db.delete_table_data("Report_TesterCounter"); + } + + break; + + case "Report_TesterCounterDetail": + if (!data.contains("No Data")) { + ResponseResult testerCounterDetail = new Gson().fromJson(data, ResponseResult.class); + db.open(); + if (testerCounterDetail != null && !db.insertTesterCounterDetail(testerCounterDetail)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Report_TesterCounterDetail not saved"); + } + } else { + db.open(); + db.delete_table_data("Report_TesterCounterDetail"); + } + + break; + + case "Report_CounterVolume": + if (!data.contains("No Data")) { + ResponseResult counterVolume = new Gson().fromJson(data, ResponseResult.class); + db.open(); + if (counterVolume != null && !db.insertCounterVolume(counterVolume)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Report_CounterVolume not saved"); + } + } else { + db.open(); + db.delete_table_data("Report_CounterVolume"); + } + + break; + + case "Report_CounterVolumeDetail": + if (!data.contains("No Data")) { + ResponseResult counterVolumeDetail = new Gson().fromJson(data, ResponseResult.class); + db.open(); + if (counterVolumeDetail != null && !db.insertCounterVolumeDetail(counterVolumeDetail)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Report_CounterVolumeDetail not saved"); + } + } else { + db.open(); + db.delete_table_data("Report_CounterVolumeDetail"); + } + + break; + + case "Report_ConterValue": + if (!data.contains("No Data")) { + ResponseResult counterValue = new Gson().fromJson(data, ResponseResult.class); + db.open(); + if (counterValue != null && !db.insertCounterValue(counterValue)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Report_ConterValue not saved"); + } + } else { + db.open(); + db.delete_table_data("Report_ConterValue"); + } + + break; + + case "Report_ConterValueDetail": + if (!data.contains("No Data")) { + ResponseResult counterVolumeDetail = new Gson().fromJson(data, ResponseResult.class); + db.open(); + if (counterVolumeDetail != null && !db.insertCounterValueDetail(counterVolumeDetail)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Report_ConterValueDetail not saved"); + } + } else { + db.open(); + db.delete_table_data("Report_ConterValueDetail"); + } + + break; + + case "Report_CounterInwardStock": + if (!data.contains("No Data")) { + ResponseResult cInwordStk = new Gson().fromJson(data, ResponseResult.class); + db.open(); + if (cInwordStk != null && !db.insertCounterInwardStock(cInwordStk)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Report_CounterInwardStock not saved"); + } + } else { + db.open(); + db.delete_table_data("Report_CounterInwardStock"); + } + + break; + + case "Report_CounterInwardStockDetail": + if (!data.contains("No Data")) { + ResponseResult counterInwDDetail = new Gson().fromJson(data, ResponseResult.class); + db.open(); + if (counterInwDDetail != null && !db.insertCounterInwardStockDetail(counterInwDDetail)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Report_CounterInwardStockDetail not saved"); + } + } else { + db.open(); + db.delete_table_data("Report_CounterInwardStockDetail"); + } + + break; + + case "Report_CounterStockLedger": + if (!data.contains("No Data")) { + ResponseResult cInwordStk = new Gson().fromJson(data, ResponseResult.class); + db.open(); + if (cInwordStk != null && !db.insertCounterStockledger(cInwordStk)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Report_CounterStockLedger not saved"); + } + } else { + db.open(); + db.delete_table_data("Report_CounterStockLedger"); + } + + break; + + case "Report_CounterStockLedgerDetail": + if (!data.contains("No Data")) { + ResponseResult counterInwDDetail = new Gson().fromJson(data, ResponseResult.class); + db.open(); + if (counterInwDDetail != null && !db.insertCounterStockLedgerDetail(counterInwDDetail)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Report_CounterStockLedgerDetail not saved"); + } + } else { + db.open(); + db.delete_table_data("Report_CounterStockLedgerDetail"); + } + + break; + + case "Report_BA_TBASale": + if (!data.contains("No Data")) { + ResponseResult baTbaSales = new Gson().fromJson(data, ResponseResult.class); + db.open(); + if (baTbaSales != null && !db.insertBaTbaSales(baTbaSales)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Report_BA_TBASale not saved"); + } + } else { + db.open(); + db.delete_table_data("Report_BA_TBASale"); + } + + break; + + case "Report_BA_TBAPromoSale": + if (!data.contains("No Data")) { + ResponseResult baTbaPromoSales = new Gson().fromJson(data, ResponseResult.class); + db.open(); + if (baTbaPromoSales != null && !db.insertBaTbaPromoSales(baTbaPromoSales)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Report_BA_TBAPromoSale not saved"); + } + } else { + db.open(); + db.delete_table_data("Report_BA_TBAPromoSale"); + } + + break; + + case "T_LeaveRequestDetail": + if (!data.contains("No Data")) { + ResponseResult leaveRequestDetail = new Gson().fromJson(data, ResponseResult.class); + db.open(); + if (leaveRequestDetail != null && !db.insertLeaveDetails(leaveRequestDetail)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "T_LeaveRequestDetail not saved"); + } + } else { + db.open(); + db.delete_table_data("T_LeaveRequestDetail"); + } + + break; + + case "Master_HolidayList": + if (!data.contains("No Data")) { + ResponseResult holidayList = new Gson().fromJson(data, ResponseResult.class); + db.open(); + if (holidayList != null && !db.insertHolidays(holidayList)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Master_HolidayList not saved"); + } + } else { + db.open(); + db.delete_table_data("Master_HolidayList"); + } + + break; + + case "T_LeaveLedgerSummary": + if (!data.contains("No Data")) { + ResponseResult leaveLedger = new Gson().fromJson(data, ResponseResult.class); + db.open(); + if (leaveLedger != null && !db.insertLeaveLedger(leaveLedger)) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, "T_LeaveLedgerSummary not saved"); + } + } else { + db.open(); + db.delete_table_data("T_LeaveLedgerSummary"); + } + + break; + + case "Mapping_AppRestrictedKPI": + if (!data.contains("No Data")) { + MasterBAProfileGetterSetter mappingAppRestrictedKPIGetterSetter = new Gson().fromJson(data, MasterBAProfileGetterSetter.class); + db.open(); + if (mappingAppRestrictedKPIGetterSetter != null && !db.insertMappingAppRestrictedKPI(mappingAppRestrictedKPIGetterSetter)) { + AlertandMessages.showToastMsg(context, "Mapping_AppRestrictedKPI data not saved"); + pd.dismiss(); + } + } else { + throw new java.lang.Exception(); + } + break; + + + } + } catch (Exception e) { + e.fillInStackTrace(); + } + + return null; + } + } + + @SuppressLint("StaticFieldLeak") + private class DownloadImageTask extends AsyncTask { + Context context; + MasterBAProfileGetterSetter masterPromoOffer; + JCPGetterSetter baListObject; + + DownloadImageTask(Context context, MasterBAProfileGetterSetter masterPromoOffer, JCPGetterSetter baListObject) { + this.masterPromoOffer = masterPromoOffer; + this.context = context; + this.baListObject = baListObject; + } + + @Override + protected String doInBackground(String... strings) { + try { + //insert stock all dats + if (masterPromoOffer != null) { + downloadImages(masterPromoOffer); + } + + if (baListObject != null) { + downloadImagesbaprofile(baListObject); + } + + return CommonString.KEY_SUCCESS; + } catch (IOException ex) { + return CommonString.KEY_FAILURE; + } catch (WindowManager.BadTokenException e) { + //use a log message + return CommonString.KEY_FAILURE; + } + } + + @Override + protected void onPostExecute(String s) { + super.onPostExecute(s); + pd.dismiss(); + db.open(); + if (db.isTStockt(date, counterId) && db.isTStockSummeryCheckNoData(date, counterId)) { + int first_tStockSummery = preferences.getInt(CommonString.KEY_FIRST_DOWNLOAD_TsTOCK + date, 0); + if (first_tStockSummery != 0) { + db.open(); + if (db.isTStockCorrectedinsert(date, counterId)) { + editor = preferences.edit(); + editor.putInt(CommonString.KEY_FIRST_DOWNLOAD_TsTOCK + date, 0); + editor.putInt(CommonString.KEY_INCORRECT_TSTOCK_SUMMERY + date, 1); + editor.apply(); + } else { + db.open(); + db.delete_table_data("T_StockSummary"); + editor = preferences.edit(); + editor.putInt(CommonString.KEY_INCORRECT_TSTOCK_SUMMERY + date, 2); + editor.apply(); + } + } + } else { + editor = preferences.edit(); + editor.putInt(CommonString.KEY_FIRST_DOWNLOAD_TsTOCK + date, 0); + editor.putInt(CommonString.KEY_INCORRECT_TSTOCK_SUMMERY + date, 0); + editor.apply(); + } + + int incorrect_tStockSummery = preferences.getInt(CommonString.KEY_INCORRECT_TSTOCK_SUMMERY + date, 0); + if (incorrect_tStockSummery != 0) { + if (incorrect_tStockSummery == 1) { + AlertandMessages.showAlert((Activity) context, context.getString(R.string.datasyncedcompeletely), true); + } else if (incorrect_tStockSummery == 2) { + AlertandMessages.showAlertfordatanotSyncedcompeletetly((Activity) context, context.getString(R.string.datanotsyncedcompletely), true); + } else { + AlertandMessages.showAlert((Activity) context, context.getString(R.string.datasyncedcompeletely), true); + } + } else { + AlertandMessages.showAlert((Activity) context, context.getString(R.string.datasyncedcompeletely), true); + } + } + } + + + void downloadImages(MasterBAProfileGetterSetter promotion_object) throws IOException { + List data = promotion_object.getMasterPromoOffers(); + try { + File folder = new File(CommonString.getPromosFolder(context)); + if (!folder.isDirectory()) { + folder.mkdir(); + } + /////////Download promotion banner for mobile + if (!data.isEmpty()) { + for (int i = 0; i < data.size(); i++) { + if (data.get(i).getPromoOfferMobile() != null && !data.get(i).getPromoOfferMobile().isEmpty() + && data.get(i).getPromoPath() != null && !data.get(i).getPromoPath().isEmpty()) { + downloadFile(data.get(i).getPromoPath(), data.get(i).getPromoOfferMobile(), folder); + } + } + } + + /////////Download promotion banner for Tablet + List datafor_tab = promotion_object.getMasterPromoOffers(); + if (!datafor_tab.isEmpty()) { + for (int i = 0; i < datafor_tab.size(); i++) { + if (datafor_tab.get(i).getPromoOfferTab() != null && !datafor_tab.get(i).getPromoOfferTab().isEmpty() + && datafor_tab.get(i).getPromoPath() != null && !datafor_tab.get(i).getPromoPath().isEmpty()) { + downloadFile(datafor_tab.get(i).getPromoPath(), datafor_tab.get(i).getPromoOfferTab(), folder); + } + } + } + + } catch (Exception e) { + e.fillInStackTrace(); + } + } + + + public void downloadFile(String fileUrl, String directory, File folder_path) { + try { + URL url = new URL(fileUrl + directory); + HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); + urlConnection.setRequestMethod("GET"); + urlConnection.getResponseCode(); + urlConnection.connect(); + if (urlConnection.getResponseCode() == 200) { + int length = urlConnection.getContentLength(); + String size = new DecimalFormat("##.##").format((double) ((double) length / 1024)) + " KB"; + if (!new File(folder_path.getPath() + directory).exists() && !size.equalsIgnoreCase("0 KB")) { + File outputFile = new File(folder_path, directory); + FileOutputStream fos = new FileOutputStream(outputFile); + InputStream is1 = (InputStream) urlConnection.getInputStream(); + int bytes = 0; + byte[] buffer = new byte[1024]; + int len1 = 0; + + while ((len1 = is1.read(buffer)) != -1) { + bytes = (bytes + len1); + fos.write(buffer, 0, len1); + } + + fos.close(); + is1.close(); + } + } + } catch (ProtocolException e) { + e.fillInStackTrace(); + } catch (IOException e) { + FirebaseCrashlytics.getInstance().recordException(e); + e.fillInStackTrace(); + } + } + + void downloadImagesbaprofile(JCPGetterSetter baprofileObject) throws IOException { + List data = baprofileObject.getBAList(); + try { + File folder = new File(CommonString.getProfileFolder(context)); + if (!folder.isDirectory()) { + folder.mkdir(); + } + for (int i = 0; i < data.size(); i++) { + if (data.get(i).getProfilePic() != null && !data.get(i).getProfilePic().isEmpty() && data.get(i).getProfilePath() != null && !data.get(i).getProfilePath().isEmpty()) { + downloadFile(data.get(i).getProfilePath(), data.get(i).getProfilePic(), folder); + } + } + } catch (Exception e) { + e.fillInStackTrace(); + } + + } + + public void downloadDataUniversalBa(final ArrayList jsonStringList, final ArrayList KeyNames, int downloadindex, int type) { + status = 0; + isvalid = false; + final String[] data_global = {""}; + String jsonString = "", KeyName = ""; + int jsonIndex = 0; + + if (!jsonStringList.isEmpty()) { + final OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, + TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build(); + jsonString = jsonStringList.get(downloadindex); + KeyName = KeyNames.get(downloadindex); + jsonIndex = downloadindex; + + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsonString); + adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build(); + PostApi api = adapter.create(PostApi.class); + Call call = api.getDownloadAll(jsonData); + final int[] finalJsonIndex = {jsonIndex}; + final String finalKeyName = KeyName; + + call.enqueue(new Callback() { + @Override + public void onResponse(@NonNull Call call, @NonNull Response response) { + String responseBody = response.body(); + String data = null; + if (responseBody != null && response.isSuccessful()) { + try { + data = response.body(); + assert data != null; + if (data.isEmpty()) { + data_global[0] = ""; + } else { + data_global[0] = data; + if (finalKeyName.equalsIgnoreCase("Table_Structure")) { + editor.putInt(CommonString.KEY_DOWNLOAD_INDEX, finalJsonIndex[0]); + editor.apply(); + tableStructureObj = new Gson().fromJson(data, TableStructureGetterSetter.class); + String isAllTableCreated = createTable(tableStructureObj); + + if (isAllTableCreated != CommonString.KEY_SUCCESS) { + AlertandMessages.showAlert((Activity) context, isAllTableCreated + " not created", true); + } + } else { + editor.putInt(CommonString.KEY_DOWNLOAD_INDEX, finalJsonIndex[0]); + editor.apply(); + switch (finalKeyName) { + case "BA_List": + if (!data.contains("No Data")) { + baListObject = new Gson().fromJson(data, JCPGetterSetter.class); + db.open(); + if (baListObject != null && !db.insertBalistData(baListObject)) { + AlertandMessages.showSnackbarMsg(context, "Ba List data not saved"); + } + } else { + throw new java.lang.Exception(); + } + break; + + case "Mapping_JourneyPlan": + if (!data.contains("No Data")) { + jcpObject = new Gson().fromJson(data, JCPGetterSetter.class); + db.open(); + if (jcpObject != null && !db.insertJCPData(jcpObject)) { + AlertandMessages.showSnackbarMsg(context, "JCP data not saved"); + } + } + + break; + case "ServerTime": + if (!data.contains("No Data")) { + serverTimeObj = new Gson().fromJson(data, ServerTimeGetterSetter.class); + if (serverTimeObj != null) { + db.open(); + db.insertServerTimeData(serverTimeObj); + try { + String tymStr = calculateTotalDuration(CommonFunctions.setTimeFormat(serverTimeObj.getServerTime().get(0).getServerTime())); + String s[] = tymStr.split(":"); + int t = Integer.parseInt(s[0]); + int t2 = Integer.parseInt(s[1]); + if (t > 0) { + CommonFunctions.show_incurrect_device_tym(context, serverTimeObj.getServerTime().get(0).getServerTime()); + } else if (t2 > 10) { + CommonFunctions.show_incurrect_device_tym(context, serverTimeObj.getServerTime().get(0).getServerTime()); + } + } catch (NumberFormatException e) { + e.fillInStackTrace(); + } + } + } + + break; + + } + } + } + + finalJsonIndex[0]++; + if (finalJsonIndex[0] != KeyNames.size()) { + downloadDataUniversalBa(jsonStringList, KeyNames, finalJsonIndex[0], CommonString.DOWNLOAD_ALL_SERVICE); + } + + } catch (Exception e) { + e.fillInStackTrace(); + editor.putInt(CommonString.KEY_DOWNLOAD_INDEX, finalJsonIndex[0]); + editor.apply(); + } + } else { + editor.putInt(CommonString.KEY_DOWNLOAD_INDEX, finalJsonIndex[0]); + editor.apply(); + } + } + + @Override + public void onFailure(@NonNull Call call, @NonNull Throwable t) { + isvalid = true; + } + }); + } + } + + + private String calculateTotalDuration(String serverTym) { + @SuppressLint("SimpleDateFormat") SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh:mm:ss"); + int days = 0, hours = 0, min = 0; + String str_hours = ""; + try { + Date date1 = simpleDateFormat.parse(serverTym); + Date date2 = simpleDateFormat.parse(getTime()); + assert date2 != null; + assert date1 != null; + long difference = date2.getTime() - date1.getTime(); + days = (int) (difference / (1000 * 60 * 60 * 24)); + hours = (int) ((difference - (1000 * 60 * 60 * 24 * days)) / (1000 * 60 * 60)); + min = (int) (difference - (1000 * 60 * 60 * 24 * days) - (1000 * 60 * 60 * hours)) / (1000 * 60); + hours = (hours < 0 ? -hours : hours); + Log.i("======= Hours", " :: " + hours); + } catch (ParseException e) { + e.fillInStackTrace(); + } + + if (hours != 0 && hours < 10) { + str_hours = "0" + hours; + } else { + str_hours = String.valueOf(hours); + } + + return str_hours + ":" + min; + } + + private String getTime() { + Calendar currnetDateTime = Calendar.getInstance(); + @SuppressLint("SimpleDateFormat") SimpleDateFormat df = new SimpleDateFormat("hh:mm:ss"); + return df.format(currnetDateTime.getTime()); + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/retrofit/Filter.java b/app/src/main/java/com/cpm/lorealbaautomation/retrofit/Filter.java new file mode 100644 index 0000000..3e74761 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/retrofit/Filter.java @@ -0,0 +1,5 @@ +package com.cpm.lorealbaautomation.retrofit; + +interface Filter { + public boolean isMatched(ProductMaster object, String text); +} \ No newline at end of file diff --git a/app/src/main/java/com/cpm/lorealbaautomation/retrofit/PostApi.java b/app/src/main/java/com/cpm/lorealbaautomation/retrofit/PostApi.java new file mode 100644 index 0000000..8deca77 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/retrofit/PostApi.java @@ -0,0 +1,83 @@ +package com.cpm.lorealbaautomation.retrofit; + +import com.google.gson.JsonObject; + +import okhttp3.RequestBody; +import okhttp3.ResponseBody; +import retrofit2.Call; +import retrofit2.http.Body; +import retrofit2.http.POST; + + +public interface PostApi { + // @POST("CounterDeviceLoginWithCode")---Old Method + //Ravi Changes + @POST("CounterInfoDetail") + Call getCounterInfodetail(@Body RequestBody request); + + @POST("CounterDeviceLoginWithCodeAppId") + Call getLogindetail(@Body RequestBody request); + + ///@POST("BADeviceLogin")----Old Ba login Method + @POST("BADeviceLoginAppId") + Call getLoginUserdetail(@Body RequestBody request); + + @POST("GenerateOTP") + Call getLoginUserEmailOtp(@Body RequestBody request); + + @POST("CounterAndBALoginWithIMEIset") + Call getEmailOtpValidate(@Body RequestBody request); + + @POST("DownloadJson") + Call getDownloadAll(@Body RequestBody request); + + @POST("SendOTP") + Call getOTPMethod(@Body RequestBody request); + + @POST("ForgetPassword") + Call getOTPMethodForForgotpass(@Body RequestBody request); + + @POST("UploadJson") + Call getUploadJsonDetail(@Body RequestBody request); + + @POST("Uploadimageswithpath") + retrofit.Call getUploadDataBaseBackup(@Body RequestBody body1); + + @POST("UploadJson") + Call getGeotag(@Body RequestBody request); + + @POST("TokenDetail") + Call uploadTokenDetails(@Body RequestBody request); + + @POST("UploadAttendanceDetail") + Call getAttendanceDetails(@Body RequestBody request); + + @POST("BALogOut") + Call getLogout(@Body RequestBody request); + + //Ravi Changes + @POST("BALogOutResetIMEIDetail") + Call getLogoutResetImei(@Body RequestBody request); + + @POST("BACoverage") + Call getBaCoverage(@Body RequestBody request); + + @POST("CounterCoverage") + Call getCounterCoverage(@Body RequestBody request); + + @POST("TBAJourneyPlan") + Call getTabjourneyCoverage(@Body RequestBody request); + + @POST("DownloadJson") + Call getTabjournePlan(@Body RequestBody request); + + @POST("ChangePassword") + Call getChangePassword(@Body RequestBody request); + + @POST("ResetPasssword") + Call getResetPassword(@Body RequestBody request); + + @POST("LeaveRequest") + Call LeaveRequest(@Body RequestBody request); +} + diff --git a/app/src/main/java/com/cpm/lorealbaautomation/retrofit/PostApiForFile.java b/app/src/main/java/com/cpm/lorealbaautomation/retrofit/PostApiForFile.java new file mode 100644 index 0000000..ea95c97 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/retrofit/PostApiForFile.java @@ -0,0 +1,19 @@ +package com.cpm.lorealbaautomation.retrofit; + +import com.squareup.okhttp.RequestBody; + +import retrofit.Call; +import retrofit.http.Body; +import retrofit.http.POST; + + +/** + * Created by jeevanp on 05-10-2017. + */ + +public interface PostApiForFile { + @POST("Uploadimages") + CallgetUploadImage(@Body RequestBody reqesBody); + + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/retrofit/PostApiForImage.java b/app/src/main/java/com/cpm/lorealbaautomation/retrofit/PostApiForImage.java new file mode 100644 index 0000000..2638f19 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/retrofit/PostApiForImage.java @@ -0,0 +1,13 @@ +package com.cpm.lorealbaautomation.retrofit; + +import retrofit.http.POST; + +/** + * Created by jeevanp on 28-12-2017. + */ + +public interface PostApiForImage { + @POST("Uploadimages") + retrofit.Call getUploadImage(@retrofit.http.Body com.squareup.okhttp.RequestBody reqesBody); + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/retrofit/PostApiForUpload.java b/app/src/main/java/com/cpm/lorealbaautomation/retrofit/PostApiForUpload.java new file mode 100644 index 0000000..e92ebb4 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/retrofit/PostApiForUpload.java @@ -0,0 +1,15 @@ +package com.cpm.lorealbaautomation.retrofit; + +import com.squareup.okhttp.RequestBody; + +import retrofit.http.Body; +import retrofit.http.POST; + +/** + * Created by jeevanp on 5/29/2018. + */ + +public interface PostApiForUpload { + @POST("Uploadimageswithpath") + retrofit.Call getUploadImageRetrofitOne(@Body RequestBody body1); +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/retrofit/RetrofitMethod.java b/app/src/main/java/com/cpm/lorealbaautomation/retrofit/RetrofitMethod.java new file mode 100644 index 0000000..b55baef --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/retrofit/RetrofitMethod.java @@ -0,0 +1,130 @@ +package com.cpm.lorealbaautomation.retrofit; + +import android.app.Activity; +import android.app.ProgressDialog; +import android.content.Context; + +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.constant.AlertandMessages; +import com.cpm.lorealbaautomation.constant.CommonString; + +import java.io.File; +import java.io.IOException; +import java.net.SocketException; +import java.net.SocketTimeoutException; +import okhttp3.RequestBody; +import retrofit.Call; +import retrofit.Callback; +import retrofit.Response; +import retrofit.Retrofit; + +/** + * Created by deepakp on 10/4/2017. + */ + +public class RetrofitMethod { + + RequestBody body1; + PostApi api; + Call call; + private Retrofit adapter; + int status = 0; + int count = 0; + public static int uploadedFiles = 0; + public static int totalFiles = 0; + boolean isvalid = false, statusUpdated = true; + Context context; + String visitDate, userID, uploadStatus; + int storeId = 0; + Lorealba_Database db; + ProgressDialog pd; + public int listSize = 0; + // ArrayList storeList, storeList_deviation; + + public RetrofitMethod(Context context) { + this.context = context; + pd = new ProgressDialog(context); + pd.setCancelable(false); + pd.setTitle("Please wait"); + pd.setMessage("Uploading images"); + pd.show(); + } + + public RetrofitMethod() { + } + + public RetrofitMethod(Context context, String msg) { + this.context = context; + pd = new ProgressDialog(context); + pd.setCancelable(false); + pd.setTitle("Please wait"); + pd.setMessage(msg); + pd.show(); + } + + + public RetrofitMethod(String visitDate, String userId, Context context) { + this.visitDate = visitDate; + this.userID = userId; + this.context = context; + pd = new ProgressDialog(context); + pd.setCancelable(false); + pd.setTitle("Please wait"); + pd.setMessage("Uploading images"); + pd.show(); + } + + + public void UploadBackup(final String filename, String foldername, String folderPath) { + try { + status = 0; + final File finalFile = new File(folderPath + filename); + isvalid = false; + adapter = new Retrofit.Builder() + .baseUrl(CommonString.URL) + .addConverterFactory(new StringConverterFactory()) + .build(); + PostApi api = adapter.create(PostApi.class); + Call call = api.getUploadDataBaseBackup(body1); + call.enqueue(new Callback() { + + @Override + public void onResponse(Response response) { + if (response.isSuccess() && response.body().contains("Success")) { + finalFile.delete(); + pd.dismiss(); + AlertandMessages.showToastMsg(context, context.getString(R.string.data_uploaded_successfully)); + + } else { + pd.dismiss(); + AlertandMessages.showAlert((Activity) context, context.getString(R.string.database_not_uploaded), true); + } + } + + @Override + public void onFailure(Throwable t) { + if (t instanceof IOException || t instanceof SocketTimeoutException || t instanceof SocketException) { + pd.dismiss(); + AlertandMessages.showAlert((Activity) context, CommonString.MESSAGE_SOCKETEXCEPTION, true); + } else { + pd.dismiss(); + AlertandMessages.showAlert((Activity) context, context.getString(R.string.errordatabase_not_uploaded), true); + } + } + }); + } catch (Exception e) { + e.fillInStackTrace(); + pd.dismiss(); + AlertandMessages.showAlert((Activity) context, CommonString.MESSAGE_EXCEPTION, true); + } + } + + String getParsedDate(String filename) { + String testfilename = filename; + testfilename = testfilename.substring(testfilename.indexOf("-") + 1); + testfilename = testfilename.substring(0, testfilename.indexOf("-")); + return testfilename; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/retrofit/StringConverterFactory.java b/app/src/main/java/com/cpm/lorealbaautomation/retrofit/StringConverterFactory.java new file mode 100644 index 0000000..d16f2fa --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/retrofit/StringConverterFactory.java @@ -0,0 +1,51 @@ +package com.cpm.lorealbaautomation.retrofit; + +import com.squareup.okhttp.MediaType; +import com.squareup.okhttp.RequestBody; +import com.squareup.okhttp.ResponseBody; + +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.lang.reflect.Type; + +import retrofit.Converter; + +/** + * Created by jeevanp on 19-05-2017. + */ + +public class StringConverterFactory implements Converter.Factory { + public StringConverterFactory() { + } + @Override + public Converter get(Type type) { + Class cls = (Class) type; + if (String.class.isAssignableFrom(cls)) { + return new StringConverter(); + } + return null; + } +} + +class StringConverter implements Converter { + private static final MediaType PLAIN_TEXT = MediaType.parse("text/plain; charset=UTF-8"); + + @Override + public String fromBody(ResponseBody body) throws IOException { + return new String(body.bytes()); + } + + @Override + public RequestBody toBody(String value) { + return RequestBody.create(PLAIN_TEXT, convertToBytes(value)); + } + + private static byte[] convertToBytes(String string) { + try { + return string.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + throw new RuntimeException(e); + } + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/retrofit/UploadDataWithRetrofit.java b/app/src/main/java/com/cpm/lorealbaautomation/retrofit/UploadDataWithRetrofit.java new file mode 100644 index 0000000..e2ccae7 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/retrofit/UploadDataWithRetrofit.java @@ -0,0 +1,117 @@ +package com.cpm.lorealbaautomation.retrofit; + +import android.content.Context; + +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.gettersetter.ReferenceVariablesForDownloadActivity; + +import java.io.IOException; +import java.net.SocketTimeoutException; +import java.util.concurrent.TimeUnit; + +import okhttp3.MediaType; +import okhttp3.OkHttpClient; +import okhttp3.RequestBody; +import okhttp3.ResponseBody; +import retrofit2.Call; +import retrofit2.Callback; +import retrofit2.Response; +import retrofit2.Retrofit; +import retrofit2.converter.gson.GsonConverterFactory; + + +/** + * Created by on 15/02/2019. + */ + +public class UploadDataWithRetrofit extends ReferenceVariablesForDownloadActivity { + + boolean isvalid; + Context context; + int status = 0; + + public UploadDataWithRetrofit(Context context) { + this.context = context; + } + + + public String uploadDeviceTokenDetails(String jsonString, int type) { + try { + status = 0; + isvalid = false; + final String[] data_global = {""}; + + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsonString); + OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, + TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build(); + Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).addConverterFactory(GsonConverterFactory.create()).client(okHttpClient).build(); + + PostApi api = adapter.create(PostApi.class); + Call call = null; + + if (type == CommonString.UPLOAD_DEVICE_TOKEN_DETAILS) { + call = api.uploadTokenDetails(jsonData); + } + + call.enqueue(new Callback() { + @Override + public void onResponse(Call call, Response response) { + ResponseBody responseBody = response.body(); + String data = null; + if (responseBody != null && response.isSuccessful()) { + try { + data = response.body().string(); + data = data.substring(1, data.length() - 1).replace("\\", ""); + if (data.equalsIgnoreCase("")) { + data_global[0] = ""; + isvalid = true; + status = 1; + } else { + data = data.substring(1, data.length() - 1).replace("\\", ""); + data_global[0] = data; + isvalid = true; + status = 1; + } + + } catch (Exception e) { + e.fillInStackTrace(); + isvalid = true; + status = -2; + } + } else { + isvalid = true; + status = -1; + } + } + + @Override + public void onFailure(Call call, Throwable t) { + isvalid = true; + if (t instanceof SocketTimeoutException) { + status = 3; + } else if (t instanceof IOException) { + status = 3; + } else { + status = 3; + } + + } + }); + + if (status == 1) { + return data_global[0]; + } else if (status == 2) { + return CommonString.MESSAGE_NO_RESPONSE_SERVER; + } else if (status == 3) { + return CommonString.MESSAGE_SOCKETEXCEPTION; + } else if (status == -2) { + return CommonString.MESSAGE_INVALID_JSON; + } else { + return CommonString.KEY_FAILURE; + } + } catch (Exception e) { + e.fillInStackTrace(); + return CommonString.KEY_FAILURE; + } + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/service/BackgroundNotificationService.java b/app/src/main/java/com/cpm/lorealbaautomation/service/BackgroundNotificationService.java new file mode 100644 index 0000000..511678a --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/service/BackgroundNotificationService.java @@ -0,0 +1,141 @@ +package com.cpm.lorealbaautomation.service; + +import android.app.IntentService; +import android.app.NotificationChannel; +import android.app.NotificationManager; +import android.content.Context; +import android.content.Intent; +import android.graphics.Color; +import android.os.Build; +import android.os.Environment; +import androidx.core.app.NotificationCompat; +import androidx.localbroadcastmanager.content.LocalBroadcastManager; + +import com.cpm.lorealbaautomation.DealarBoardActivity; + +import org.json.JSONObject; + +import java.io.BufferedInputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.ArrayList; + +import okhttp3.ResponseBody; + + +public class BackgroundNotificationService extends IntentService { + int downloadindex = 0; + public BackgroundNotificationService() { + super("Service"); + } + private NotificationCompat.Builder notificationBuilder; + private NotificationManager notificationManager; + @Override + protected void onHandleIntent(Intent intent) { + notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + NotificationChannel notificationChannel = new NotificationChannel("id", "an", NotificationManager.IMPORTANCE_HIGH); + notificationChannel.setDescription("no sound"); + notificationChannel.setSound(null, null); + notificationChannel.enableLights(false); + notificationChannel.setLightColor(Color.BLUE); + notificationChannel.enableVibration(false); + notificationManager.createNotificationChannel(notificationChannel); + } + + + notificationBuilder = new NotificationCompat.Builder(this, "id") + .setSmallIcon(android.R.drawable.stat_sys_download) + .setContentTitle("Download") + .setContentText("Downloading Data") + .setDefaults(0) + .setAutoCancel(true); + + notificationManager.notify(0, notificationBuilder.build()); + initRetrofit(); + + } + + private void initRetrofit() { + try { + ArrayList keysList = new ArrayList<>(); + ArrayList jsonList = new ArrayList<>(); + final ArrayList KeyNames = new ArrayList<>(); + KeyNames.clear(); + keysList.clear(); + keysList.add("Table_Structure"); + keysList.add("BA_List"); + keysList.add("Mapping_JourneyPlan"); + keysList.add("Mapping_CounterGroup_Brand"); + keysList.add("Product_Master"); + keysList.add("Mapping_Visibility"); + keysList.add("Master_Posm"); + keysList.add("T_StockSummary"); + keysList.add("ServerTime"); + keysList.add("T_CounterInvoice"); + for (int i = 0; i < keysList.size(); i++) { + JSONObject jsonObject = new JSONObject(); + jsonObject.put("Downloadtype", keysList.get(i)); + jsonObject.put("Username", "testba1"); + jsonObject.put("Param1", "1"); + jsonObject.put("Param2", ""); + jsonList.add(jsonObject.toString()); + KeyNames.add(keysList.get(i)); + } + }catch (Exception e) { + e.fillInStackTrace(); + } + } + private void downloadImage(ResponseBody body) throws IOException { + + int count; + byte data[] = new byte[1024 * 4]; + long fileSize = body.contentLength(); + InputStream inputStream = new BufferedInputStream(body.byteStream(), 1024 * 8); + File outputFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "journaldev-image_icon-downloaded.jpg"); + OutputStream outputStream = new FileOutputStream(outputFile); + long total = 0; + boolean downloadComplete = false; + //int totalFileSize = (int) (fileSize / (Math.pow(1024, 2))); + + while ((count = inputStream.read(data)) != -1) { + + total += count; + int progress = (int) ((double) (total * 100) / (double) fileSize); + + updateNotification(progress); + outputStream.write(data, 0, count); + downloadComplete = true; + } + onDownloadComplete(downloadComplete); + outputStream.flush(); + outputStream.close(); + inputStream.close(); + } + private void updateNotification(int currentProgress) { + notificationBuilder.setProgress(100, currentProgress, false); + notificationBuilder.setContentText("Downloaded: " + currentProgress + "%"); + notificationManager.notify(0, notificationBuilder.build()); + } + + private void sendProgressUpdate(boolean downloadComplete) { + Intent intent = new Intent(DealarBoardActivity.PROGRESS_UPDATE); + intent.putExtra("downloadComplete", downloadComplete); + LocalBroadcastManager.getInstance(BackgroundNotificationService.this).sendBroadcast(intent); + } + private void onDownloadComplete(boolean downloadComplete) { + sendProgressUpdate(downloadComplete); + notificationManager.cancel(0); + notificationBuilder.setProgress(0, 0, false); + notificationBuilder.setContentText("Data Download Complete"); + notificationManager.notify(0, notificationBuilder.build()); + } + @Override + public void onTaskRemoved(Intent rootIntent) { + notificationManager.cancel(0); + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/service/MyFirebaseMessagingService.java b/app/src/main/java/com/cpm/lorealbaautomation/service/MyFirebaseMessagingService.java new file mode 100644 index 0000000..d9bc50a --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/service/MyFirebaseMessagingService.java @@ -0,0 +1,122 @@ +package com.cpm.lorealbaautomation.service; + +import android.app.Notification; +import android.app.NotificationManager; +import android.app.PendingIntent; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.media.RingtoneManager; +import android.net.Uri; +import android.os.Build; + +import androidx.annotation.NonNull; +import androidx.core.app.NotificationCompat; +import androidx.localbroadcastmanager.content.LocalBroadcastManager; + +import com.google.firebase.messaging.FirebaseMessagingService; +import com.google.firebase.messaging.RemoteMessage; +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.DealarBoardActivity; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.dailyactivity.NotificationDetailActivity; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.notification.NotificationUtils; +import static android.app.Notification.DEFAULT_VIBRATE; + +public class MyFirebaseMessagingService extends FirebaseMessagingService { + private static final int DEFAULT_SOUND = 1; + String TAG = "FCM"; + public static int NOTIFICATION_ID = 1; + String body="",path="",title="",type,counter_id=""; + private SharedPreferences preferences; + String visit_date; + long value; + public MyFirebaseMessagingService() { + + } + + @Override + public void onMessageReceived(RemoteMessage remoteMessage) { + + preferences = PrefHelper.getPrefs(this); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + counter_id = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + + body = remoteMessage.getData().get("body"); + title = remoteMessage.getData().get("title"); + path = remoteMessage.getData().get("path"); + type = remoteMessage.getData().get("Mediatype"); + if (!remoteMessage.getData().isEmpty()) { + //test(TAG, "Message data " + remoteMessage.getData()); + Lorealba_Database db = new Lorealba_Database(this); + db.open(); + value = db.insertNotificationData(title,body,path,visit_date,type,counter_id); + } + + // Check if message contains a notification payload. + if (remoteMessage.getNotification() != null) { + showNotification(body, this, title, path, type, value); + } + // Also if you intend on generating your own notifications as a result of a received FCM + // message, here is where that should be initiated. See sendNotification method below. + } + + /** + * Called if InstanceID token is updated. This may occur if the security of + * the previous token had been compromised. Note that this is called when the InstanceID token + * is initially generated so this is where you would retrieve the token. + */ + @Override + public void onNewToken(@NonNull String token) { + //test(TAG, "Refreshed token: " + token); + sendRegistrationToServer(token); + } + + private void sendRegistrationToServer(String token) { + } + + private void showNotification(String body, Context ctx, String title, String path, String type, long value) { + Intent intent = new Intent(this, NotificationDetailActivity.class); + intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); + intent.putExtra(CommonString.KEY_BODY,body); + intent.putExtra("Path",path); + intent.putExtra(CommonString.KEY_TITLE,title); + intent.putExtra("type",type); + intent.putExtra("KEY_ID",value+""); + + NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE); + PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_IMMUTABLE); + + if (Build.VERSION.SDK_INT >= 26) { + NotificationUtils mNotificationUtils = new NotificationUtils(this, pendingIntent); + Notification.Builder nb = mNotificationUtils. + getAndroidChannelNotification(title, body); + mNotificationUtils.getManager().notify(101, nb.build()); + } + else { + Uri sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); + + NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext(), "2") + .setSmallIcon(R.mipmap.image) + .setContentTitle(title) + .setContentText(body) + .setAutoCancel(true) + .setSound(sound) + .setDefaults(DEFAULT_SOUND | DEFAULT_VIBRATE) + .setContentIntent(pendingIntent) + .setVibrate(new long[]{0, 500}) + .setPriority(NotificationManager.IMPORTANCE_HIGH); + + if(NOTIFICATION_ID > 1787258476){ + NOTIFICATION_ID = 0; + } + + notificationManager.notify(NOTIFICATION_ID, mBuilder.build()); + } + + Intent intent1 = new Intent(DealarBoardActivity.PROGRESS_UPDATE); + LocalBroadcastManager.getInstance(MyFirebaseMessagingService.this).sendBroadcast(intent1); + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/tbaleavemodel/Common.java b/app/src/main/java/com/cpm/lorealbaautomation/tbaleavemodel/Common.java new file mode 100644 index 0000000..f10a26d --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/tbaleavemodel/Common.java @@ -0,0 +1,21 @@ +package com.cpm.lorealbaautomation.tbaleavemodel; + +import com.google.gson.annotations.SerializedName; +import java.util.List; +public class Common { + @SerializedName("TBAME_Search") + private List tBAMESearch; + public List getTBAMESearch() { + return tBAMESearch; + } + @SerializedName("LeaveRequest") + private List leaveRequest; + public List getLeaveRequest() { + return leaveRequest; + } + @SerializedName("TBAME_LeaveHistory") + private List tBAMELeaveHistory; + public List getTBAMELeaveHistory() { + return tBAMELeaveHistory; + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/tbaleavemodel/LeaveRequest.java b/app/src/main/java/com/cpm/lorealbaautomation/tbaleavemodel/LeaveRequest.java new file mode 100644 index 0000000..d6a2062 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/tbaleavemodel/LeaveRequest.java @@ -0,0 +1,13 @@ +package com.cpm.lorealbaautomation.tbaleavemodel; +import com.google.gson.annotations.SerializedName; +public class LeaveRequest { + @SerializedName("Result") + private String result; + public String getResult() { + return result; + } + public void setResult(String result) { + this.result = result; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/tbaleavemodel/TBAMELeaveHistory.java b/app/src/main/java/com/cpm/lorealbaautomation/tbaleavemodel/TBAMELeaveHistory.java new file mode 100644 index 0000000..13d8b9f --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/tbaleavemodel/TBAMELeaveHistory.java @@ -0,0 +1,127 @@ +package com.cpm.lorealbaautomation.tbaleavemodel; + +import com.google.gson.annotations.SerializedName; + +public class TBAMELeaveHistory { + @SerializedName("EmpId") + + private Integer empId; + @SerializedName("EmpCode") + + private String empCode; + @SerializedName("Name") + + private String name; + @SerializedName("Designation") + + private String designation; + @SerializedName("ApplyDate") + + private String applyDate; + @SerializedName("LeaveType") + + private String leaveType; + @SerializedName("FromDate") + + private String fromDate; + @SerializedName("ToDate") + + private String toDate; + @SerializedName("NoOfDays") + + private Double noOfDays; + @SerializedName("ApprovedStatus") + + private String approvedStatus; + @SerializedName("RejectRemark") + + private String rejectRemark; + + public Integer getEmpId() { + return empId; + } + + public void setEmpId(Integer empId) { + this.empId = empId; + } + + public String getEmpCode() { + return empCode; + } + + public void setEmpCode(String empCode) { + this.empCode = empCode; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDesignation() { + return designation; + } + + public void setDesignation(String designation) { + this.designation = designation; + } + + public String getApplyDate() { + return applyDate; + } + + public void setApplyDate(String applyDate) { + this.applyDate = applyDate; + } + + public String getLeaveType() { + return leaveType; + } + + public void setLeaveType(String leaveType) { + this.leaveType = leaveType; + } + + public String getFromDate() { + return fromDate; + } + + public void setFromDate(String fromDate) { + this.fromDate = fromDate; + } + + public String getToDate() { + return toDate; + } + + public void setToDate(String toDate) { + this.toDate = toDate; + } + + public Double getNoOfDays() { + return noOfDays; + } + + public void setNoOfDays(Double noOfDays) { + this.noOfDays = noOfDays; + } + + public String getApprovedStatus() { + return approvedStatus; + } + + public void setApprovedStatus(String approvedStatus) { + this.approvedStatus = approvedStatus; + } + + public String getRejectRemark() { + return rejectRemark; + } + + public void setRejectRemark(String rejectRemark) { + this.rejectRemark = rejectRemark; + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/tbaleavemodel/TBAMESearch.java b/app/src/main/java/com/cpm/lorealbaautomation/tbaleavemodel/TBAMESearch.java new file mode 100644 index 0000000..557011a --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/tbaleavemodel/TBAMESearch.java @@ -0,0 +1,46 @@ +package com.cpm.lorealbaautomation.tbaleavemodel; + +import com.google.gson.annotations.SerializedName; + +public class TBAMESearch { + @SerializedName("EmpId") + private Integer empId; + @SerializedName("EmpCode") + private String empCode; + @SerializedName("Name") + private String name; + @SerializedName("Designation") + private String designation; + + public Integer getEmpId() { + return empId; + } + + public void setEmpId(Integer empId) { + this.empId = empId; + } + + public String getEmpCode() { + return empCode; + } + + public void setEmpCode(String empCode) { + this.empCode = empCode; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDesignation() { + return designation; + } + + public void setDesignation(String designation) { + this.designation = designation; + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/timer/GifImageView.java b/app/src/main/java/com/cpm/lorealbaautomation/timer/GifImageView.java new file mode 100644 index 0000000..9d4c331 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/timer/GifImageView.java @@ -0,0 +1,98 @@ +package com.cpm.lorealbaautomation.timer; + +/** + * Created by jeevan on 02/02/2020. + */ + +import android.content.Context; +import android.graphics.Canvas; +import android.graphics.Movie; +import android.net.Uri; +import android.os.SystemClock; +import android.util.AttributeSet; +import android.view.View; + +import java.io.FileNotFoundException; +import java.io.InputStream; + + +public class GifImageView extends View { + + private InputStream mInputStream; + private Movie mMovie; + private int mWidth, mHeight; + private long mStart; + private Context mContext; + + public GifImageView(Context context) { + super(context); + this.mContext = context; + } + + public GifImageView(Context context, AttributeSet attrs) { + this(context, attrs, 0); + } + + public GifImageView(Context context, AttributeSet attrs, int defStyleAttr) { + super(context, attrs, defStyleAttr); + this.mContext = context; + if (attrs.getAttributeName(1).equals("background")) { + int id = Integer.parseInt(attrs.getAttributeValue(1).substring(1)); + setGifImageResource(id); + } + } + + + private void init() { + setFocusable(true); + mMovie = Movie.decodeStream(mInputStream); + mWidth = mMovie.width(); + mHeight = mMovie.height(); + + requestLayout(); + } + + @Override + protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { + setMeasuredDimension(mWidth, mHeight); + } + + @Override + protected void onDraw(Canvas canvas) { + + long now = SystemClock.uptimeMillis(); + + if (mStart == 0) { + mStart = now; + } + + if (mMovie != null) { + + int duration = mMovie.duration(); + if (duration == 0) { + duration = 1000; + } + + int relTime = (int) ((now - mStart) % duration); + + mMovie.setTime(relTime); + + mMovie.draw(canvas, 0, 0); + invalidate(); + } + } + + public void setGifImageResource(int id) { + mInputStream = mContext.getResources().openRawResource(id); + init(); + } + + public void setGifImageUri(Uri uri) { + try { + mInputStream = mContext.getContentResolver().openInputStream(uri); + init(); + } catch (FileNotFoundException e) { + //test("GIfImageView", "File not found"); + } + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/timer/TimerActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/timer/TimerActivity.java new file mode 100644 index 0000000..375525d --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/timer/TimerActivity.java @@ -0,0 +1,245 @@ +package com.cpm.lorealbaautomation.timer; + +import android.app.Activity; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.os.Handler; + +import androidx.annotation.NonNull; +import androidx.appcompat.app.AppCompatActivity; + +import android.os.Bundle; + +import androidx.appcompat.widget.Toolbar; + +import android.widget.Toast; + +import com.google.gson.Gson; +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.DealarBoardActivity; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.constant.AlertandMessages; +import com.cpm.lorealbaautomation.constant.CommonFunctions; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.gsonGetterSetter.JCPGetterSetter; +import com.cpm.lorealbaautomation.retrofit.PostApi; + +import org.json.JSONException; +import org.json.JSONObject; + +import java.util.Timer; +import java.util.TimerTask; +import java.util.concurrent.TimeUnit; + +import okhttp3.MediaType; +import okhttp3.OkHttpClient; +import okhttp3.RequestBody; +import okhttp3.ResponseBody; +import retrofit2.Call; +import retrofit2.Callback; +import retrofit2.Response; +import retrofit2.Retrofit; +import retrofit2.converter.gson.GsonConverterFactory; + + +public class TimerActivity extends AppCompatActivity { + String process_data_Status = "", visit_date, username, counter_id; + SharedPreferences preferences = null; + SharedPreferences.Editor editor = null; + Lorealba_Database db; + Context context; + + Timer timer; + TimerTask timerTask; + //we are going to use a handler to be able to run in our TimerTask + final Handler handler = new Handler(); + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_timer); + context = this; + db = new Lorealba_Database(context); + db.open(); + calculate_ids(); + //calling method first time...... + call_timer(); + checkwait_status(context); + } + + + public void startTimer() { + try { + //set a new Timer + timer = new Timer(); + //initialize the TimerTask's job + initializeTimerTask(); + //schedule the timer, after the first 5000ms the TimerTask will run every 10000ms + // 4 minuts 240,000 + timer.schedule(timerTask, 20000, 240000); + } catch (Exception e) { + e.fillInStackTrace(); + } + } + + public void stoptimertask() { + //stop the timer, if it's not already null + try { + if (timer != null) { + timer.cancel(); + timer = null; + } + } catch (Exception e) { + e.fillInStackTrace(); + } + } + + public void initializeTimerTask() { + timerTask = new TimerTask() { + public void run() { + //use a handler to run a toast that shows the current timestamp + handler.post(() -> { + //get the current timeStamp + int duration = Toast.LENGTH_SHORT; + if (CommonFunctions.checkNetIsAvailable(context)) { + checkwait_status(context); + } else { + call_timer(); + AlertandMessages.showToastMsg(context, getString(R.string.nonetwork)); + } + //show the toast + Toast toast = Toast.makeText(context, "Checking Server Status", duration); + toast.show(); + }); + } + }; + } + + private void call_timer() { + startTimer(); + } + + + private void calculate_ids() { + Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + if (!CommonFunctions.isTablet(context)) { + toolbar.setTitleTextAppearance(context, R.style.changestext_sizefor_mobile); + } + GifImageView gifImageView = (GifImageView) findViewById(R.id.GifImageView); + gifImageView.setGifImageResource(R.drawable.sliding_square_loader_view); + preferences = PrefHelper.getPrefs(context); + counter_id = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + username = preferences.getString(CommonString.KEY_USERNAME, ""); + setTitle("Processing Data - " + username); + } + + private void checkwait_status(Context context) { + db.open(); + if (db.isCheck_Old_Product(visit_date)) { + check_data_managing_status(context, CommonString.Key_Download_Status); + } + } + + + private void check_data_managing_status(final Context context, String service_name) { + try { + JSONObject jsonObject = new JSONObject(); + jsonObject.put("Downloadtype", service_name); + jsonObject.put("Username", ""); + jsonObject.put("Param1", counter_id); + jsonObject.put("Param2", ""); + String jsonString = jsonObject.toString(); + + try { + + OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, + TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build(); + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsonString); + Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build(); + PostApi api = adapter.create(PostApi.class); + Call call = api.getTabjournePlan(jsonData); + call.enqueue(new Callback() { + @Override + public void onResponse(@NonNull Call call, @NonNull Response response) { + ResponseBody responseBody = response.body(); + String data = null; + if (responseBody != null && response.isSuccessful()) { + try { + assert response.body() != null; + data = response.body().string(); + data = data.substring(1, data.length() - 1).replace("\\", ""); + if (data.equalsIgnoreCase(CommonString.KEY_FAILURE)) { + process_data_Status = ""; + AlertandMessages.showToastMsg((Activity) context, CommonString.KEY_FAILURE + " Please try again "); + + } else if (!data.contains("No Data")) { + JCPGetterSetter jcpObject = new Gson().fromJson(data, JCPGetterSetter.class); + if (jcpObject != null && jcpObject.getDownloadStatus() != null) { + process_data_Status = jcpObject.getDownloadStatus().get(0).getDownloadStatus().trim(); + if (process_data_Status.equalsIgnoreCase("Wait")) { + } else { + ///finsh + stoptimertask(); + startActivity(new Intent(context, DealarBoardActivity.class)); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + TimerActivity.this.finish(); + } + } + } else { + process_data_Status = ""; + } + + } catch (Exception e) { + process_data_Status = ""; + e.fillInStackTrace(); + AlertandMessages.showToastMsg((Activity) context, CommonString.MESSAGE_SOCKETEXCEPTION + "(" + e.toString() + ")"); + } + } else { + process_data_Status = ""; + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_NO_RESPONSE_SERVER); + } + } + + @Override + public void onFailure(@NonNull Call call, @NonNull Throwable t) { + process_data_Status = ""; + AlertandMessages.showToastMsg((Activity) context, CommonString.MESSAGE_SOCKETEXCEPTION); + } + }); + + } catch (Exception e) { + process_data_Status = ""; + e.fillInStackTrace(); + AlertandMessages.showAlertlogin((Activity) context, CommonString.MESSAGE_SOCKETEXCEPTION + "(" + e.toString() + ")"); + } + + } catch (JSONException e) { + process_data_Status = ""; + AlertandMessages.showAlertlogin((Activity) context, CommonString.MESSAGE_INVALID_JSON); + } + } + + @Override + protected void onResume() { + super.onResume(); + db.open(); + if (db.isCheck_Old_Product(visit_date)) { + if (process_data_Status != null && !process_data_Status.equals("") && process_data_Status.equalsIgnoreCase("Download")) { + ///finsh + startActivity(new Intent(context, DealarBoardActivity.class)); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + TimerActivity.this.finish(); + } + } + } + + + @Override + public void onBackPressed() { +// super.onBackPressed(); + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/upload/CommonUpload.java b/app/src/main/java/com/cpm/lorealbaautomation/upload/CommonUpload.java new file mode 100644 index 0000000..8c7c82c --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/upload/CommonUpload.java @@ -0,0 +1,921 @@ +package com.cpm.lorealbaautomation.upload; + +import android.app.Activity; +import android.app.ProgressDialog; +import android.content.Context; +import android.content.Intent; +import android.database.sqlite.SQLiteDatabase; +import android.os.Environment; + +import androidx.annotation.NonNull; + +import com.google.gson.JsonObject; +import com.cpm.lorealbaautomation.BuildConfig; +import com.cpm.lorealbaautomation.CounterLoginActivity; +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.constant.AlertandMessages; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.gettersetter.AuditDataGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.GroomingGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.JourneyPlan; +import com.cpm.lorealbaautomation.gsonGetterSetter.MEMEAuditQuestion; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterProfile; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterRetailExcellence; +import com.cpm.lorealbaautomation.gsonGetterSetter.ProductMaster; +import com.cpm.lorealbaautomation.retrofit.PostApi; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.File; +import java.util.ArrayList; +import java.util.concurrent.TimeUnit; + +import okhttp3.MediaType; +import okhttp3.OkHttpClient; +import okhttp3.RequestBody; +import okhttp3.ResponseBody; +import retrofit2.Call; +import retrofit2.Callback; +import retrofit2.Response; +import retrofit2.Retrofit; +import retrofit2.converter.gson.GsonConverterFactory; + +public class CommonUpload { + Context context; + ProgressDialog loading; + Lorealba_Database db; + private double lat = 0.0; + private double lon = 0.0; + String username, counter_id, visit_date; + ArrayList baProfile_ImageList = new ArrayList<>(); + ArrayList counterprofile_imgList = new ArrayList<>(); + ArrayList meQuizList = new ArrayList<>(); + ArrayList masterRetailExcellenceArrayList = new ArrayList<>(); + ArrayList productMasterArrayList = new ArrayList<>(); + ArrayList groomingList = new ArrayList<>(); + ArrayList counterList = new ArrayList<>(); + + public CommonUpload(Context context, Lorealba_Database db, ProgressDialog loading, String counterId, String visit_date, String username, double lat, double lon) { + this.context = context; + this.username = username; + this.counter_id = counterId; + this.visit_date = visit_date; + this.loading = loading; + this.lat = lat; + this.lon = lon; + this.db = db; + + } + + public void CommonUploadwithrecursive(Context context, Lorealba_Database db, boolean previous_date) { + db.open(); + baProfile_ImageList = db.getBaProfileListData(visit_date, counter_id, previous_date); + counterprofile_imgList = db.getCounterProfileListData(visit_date, counter_id, previous_date); + meQuizList = db.getme_quiz_from(visit_date, counter_id, previous_date); + groomingList = db.getgroomingdata(counter_id, visit_date, previous_date); + masterRetailExcellenceArrayList = db.getRetailExcellence_from(visit_date, counter_id, previous_date); + productMasterArrayList = db.getProductMasterMeSale_from(visit_date, counter_id, previous_date); + db.open(); + counterList = db.getba_counterimgList(counter_id, visit_date, previous_date); + loading = ProgressDialog.show(context, "Uploading Data", "Please wait...", false, false); + if (!baProfile_ImageList.isEmpty()) { + UploadBaProfile(loading, db, baProfile_ImageList, 0); + } else if (!counterprofile_imgList.isEmpty()) { + UploadCounterProfile(loading, db, counterprofile_imgList, 0); + } else if (!meQuizList.isEmpty()) { + UploadMeQuiz(loading, db, meQuizList, 0); + } else if (!groomingList.isEmpty()) { + UploadGrooming(loading, db, groomingList, 0); + } else if (!counterList.isEmpty()) { + UploadCounter(loading, db, counterList, 0); + } else if (!masterRetailExcellenceArrayList.isEmpty()) { + UploadRetailExcellence(loading, db, masterRetailExcellenceArrayList, 0); + } else if (!productMasterArrayList.isEmpty()) { + UploadMeSaleData(loading, db, productMasterArrayList, 0); + } + } + + private void UploadMeSaleData(ProgressDialog loading, Lorealba_Database db, ArrayList productMasterArrayListData, int consumerIndex) { + try { + if (!productMasterArrayList.isEmpty()) { + ArrayList productMasterArrayList = db.getMeSaledata(null, productMasterArrayListData.get(consumerIndex).getUser_id(), visit_date, counter_id); + if (!productMasterArrayList.isEmpty()) { + db.open(); + JourneyPlan jcp_Object = db.getBIDfromJCP(productMasterArrayList.get(consumerIndex).getUser_id(), counter_id); + JSONArray consumerUserInfoArray = getJsonArray(productMasterArrayList, jcp_Object); + JSONObject jsonObject = new JSONObject(); + jsonObject.put("MID", jcp_Object.getMID()); + jsonObject.put("Keys", "ME_Sale_Data"); + jsonObject.put("JsonData", consumerUserInfoArray.toString()); + jsonObject.put("UserId", username.toLowerCase()); + upload_ME_Sale_Data(jsonObject.toString(), loading, db, productMasterArrayList.get(consumerIndex), consumerIndex); + } + } + + } catch (JSONException e) { + e.fillInStackTrace(); + } + } + + private @NonNull JSONArray getJsonArray(ArrayList productMasterArrayList, JourneyPlan jcp_Object) throws JSONException { + JSONArray consumerUserInfoArray = new JSONArray(); + for (int k = 0; k < productMasterArrayList.size(); k++) { + if (productMasterArrayList.get(k).getStock() > 0) { + JSONObject obj = new JSONObject(); + obj.put("MID", jcp_Object.getMID()); + obj.put("BID", jcp_Object.getBID()); + obj.put("UserId", username.toLowerCase()); + obj.put("VisiteDate", visit_date); + obj.put("ProductId", productMasterArrayList.get(k).getProductId()); + obj.put("Sale", productMasterArrayList.get(k).getStock()); + consumerUserInfoArray.put(obj); + } + } + return consumerUserInfoArray; + } + + public void upload_ME_Sale_Data(String jsondata, final ProgressDialog loading, final Lorealba_Database db, final ProductMaster object, final int index) { + try { + final int[] finalJsonIndex = {index}; + final OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build(); + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsondata); + Retrofit adapter; + adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build(); + PostApi api = adapter.create(PostApi.class); + Call call = api.getGeotag(jsonData); + call.enqueue(new Callback() { + @Override + public void onResponse(@NonNull Call call, @NonNull Response response) { + String data = null; + if (response.isSuccessful()) { + try { + assert response.body() != null; + data = response.body().get("UploadJsonResult").toString(); + if (!data.isEmpty()) { + data = data.substring(1, data.length() - 1).replace("\\", ""); + if (data.equalsIgnoreCase(CommonString.KEY_SUCCESS)) { + db.open(); + db.update_me_sale(counter_id, object.getUser_id()); + finalJsonIndex[0]++; + if (finalJsonIndex[0] != productMasterArrayList.size()) { + UploadMeSaleData(loading, db, productMasterArrayList, finalJsonIndex[0]); + } else { + Checkout_service(loading, context, lat, lon, username, counter_id, visit_date, db, false); + ////finish activity........... + // loading.dismiss(); + // calling_method(); + } + } else { + loading.dismiss(); + AlertandMessages.showAlert((Activity) context, "Server Not Responding,(Me Sale). Please LogOut Again", false); + } + } + } catch (Exception e) { + e.fillInStackTrace(); + loading.dismiss(); + } + } + } + + @Override + public void onFailure(@NonNull Call call, @NonNull Throwable t) { + AlertandMessages.showAlert((Activity) context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE + " Please LogOut Again", false); + loading.dismiss(); + } + }); + + } catch (Exception e) { + loading.dismiss(); + e.fillInStackTrace(); + } + } + + + private void UploadRetailExcellence(ProgressDialog loading, Lorealba_Database db, ArrayList me_quizList, int consumerIndex) { + try { + if (!me_quizList.isEmpty()) { + ArrayList masterRetailExcellence = db.getRetailExcellencedata(null, masterRetailExcellenceArrayList.get(consumerIndex).getUser_Id(), visit_date, counter_id); + if (!masterRetailExcellence.isEmpty()) { + db.open(); + JourneyPlan jcp_Object = db.getBIDfromJCP(me_quizList.get(consumerIndex).getUser_Id(), counter_id); + JSONObject jsonObject = getJsonObject(masterRetailExcellence, jcp_Object); + // upload_Retail_Excellence_Data(jsonObject.toString(), loading, db, masterRetailExcellence.get(consumerIndex), consumerIndex); + upload_retail_excellence(jsonObject.toString(), loading, db, masterRetailExcellence.get(consumerIndex), consumerIndex); + } + } + } catch (JSONException e) { + e.fillInStackTrace(); + } + } + + private @NonNull JSONObject getJsonObject(ArrayList masterRetailExcellence, JourneyPlan jcp_Object) throws JSONException { + JSONArray consumerUserInfoArray = new JSONArray(); + for (int k = 0; k < masterRetailExcellence.size(); k++) { + JSONObject obj = getJsonObject(masterRetailExcellence, jcp_Object, k); + consumerUserInfoArray.put(obj); + } + JSONObject jsonObject = new JSONObject(); + jsonObject.put("MID", jcp_Object.getMID()); + jsonObject.put("Keys", "Retail_Excellence_Data"); + jsonObject.put("JsonData", consumerUserInfoArray.toString()); + jsonObject.put("UserId", username.toLowerCase()); + return jsonObject; + } + + private @NonNull JSONObject getJsonObject(ArrayList masterRetailExcellence, JourneyPlan jcp_Object, int k) throws JSONException { + JSONObject obj = new JSONObject(); + obj.put("MID", jcp_Object.getMID()); + obj.put("BID", jcp_Object.getBID()); + obj.put("UserId", username.toLowerCase()); + obj.put("VisiteDate", visit_date); + obj.put("ItemCategoryId", masterRetailExcellence.get(k).getItemCatId()); + obj.put("ItemId", masterRetailExcellence.get(k).getItemId()); + if (masterRetailExcellence.get(k).getAnswer().equalsIgnoreCase("Yes")) { + obj.put("Available", 1); + } else { + obj.put("Available", 0); + } + return obj; + } + + public void upload_retail_excellence(String jsondata, final ProgressDialog loading, final Lorealba_Database db, final MasterRetailExcellence object, final int index) { + try { + final int[] finalJsonIndex = {index}; + final OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build(); + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsondata); + Retrofit adapter; + adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build(); + PostApi api = adapter.create(PostApi.class); + Call call = api.getGeotag(jsonData); + call.enqueue(new Callback() { + @Override + public void onResponse(@NonNull Call call, @NonNull Response response) { + String data = null; + if (response.isSuccessful()) { + try { + assert response.body() != null; + data = response.body().get("UploadJsonResult").toString(); + if (!data.isEmpty()) { + data = data.substring(1, data.length() - 1).replace("\\", ""); + if (data.equalsIgnoreCase(CommonString.KEY_SUCCESS)) { + db.open(); + db.update_retail_excellence(counter_id, object.getUser_Id()); + finalJsonIndex[0]++; + if (finalJsonIndex[0] != masterRetailExcellenceArrayList.size()) { + UploadRetailExcellence(loading, db, masterRetailExcellenceArrayList, finalJsonIndex[0]); + } else { + ////finish activity........... + Checkout_service(loading, context, lat, lon, username, counter_id, visit_date, db, false); + } + } else { + loading.dismiss(); + AlertandMessages.showAlert((Activity) context, "Server Not Responding,(Retail Excellence). Please LogOut Again", false); + } + } + } catch (Exception e) { + e.fillInStackTrace(); + loading.dismiss(); + } + } + } + + @Override + public void onFailure(@NonNull Call call, @NonNull Throwable t) { + AlertandMessages.showAlert((Activity) context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE + " Please LogOut Again", false); + loading.dismiss(); + } + }); + + } catch (Exception e) { + loading.dismiss(); + e.fillInStackTrace(); + } + } + + + public static void Checkout_service(ProgressDialog loading, final Context context, double lat, double lon, final String username, String counter_id, String visit_date, final Lorealba_Database db, boolean flag) { + try { + if (flag) { + loading = ProgressDialog.show(context, "Processing", "Please wait...", false, false); + } + + JSONObject jsonObject = new JSONObject(); + //Ravi Changes + jsonObject.put("UserId", username); + jsonObject.put("CounterId", counter_id); + jsonObject.put("Latitude", lat); + jsonObject.put("Longitude", lon); + jsonObject.put("VisitDate", visit_date); + String jsonString = jsonObject.toString(); + try { + final OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, + TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build(); + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsonString); + Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build(); + PostApi api = adapter.create(PostApi.class); + // Call call = api.getLogout(jsonData); + //Ravi Changes + Call call = api.getLogoutResetImei(jsonData); + final ProgressDialog finalLoading = loading; + call.enqueue(new Callback() { + @Override + public void onResponse(@NonNull Call call, @NonNull Response response) { + ResponseBody responseBody = response.body(); + String data = null; + if (responseBody != null && response.isSuccessful()) { + try { + assert response.body() != null; + data = response.body().string(); + data = data.substring(1, data.length() - 1).replace("\\", ""); + if (data.equals("1")) { + finalLoading.dismiss(); + db.open(); + db.updateLoginData(username, "", false); + //Ravi Changes + delete_local_database(context); + Intent intent = new Intent(context, CounterLoginActivity.class); + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); + context.startActivity(intent); + AlertandMessages.showToastMsg(context, "Logout Successfully."); + } else if (data.equalsIgnoreCase(CommonString.KEY_FAILURE)) { + AlertandMessages.showAlertCounterlogin((Activity) context, CommonString.KEY_FAILURE + " Please LogOut Again"); + finalLoading.dismiss(); + } + } catch (Exception e) { + finalLoading.dismiss(); + e.fillInStackTrace(); + AlertandMessages.showAlert((Activity) context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE + " Please LogOut Again", false); + } + } + } + + @Override + public void onFailure(@NonNull Call call, @NonNull Throwable t) { + finalLoading.dismiss(); + AlertandMessages.showAlert((Activity) context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE + " Please LogOut Again", false); + } + }); + + } catch (Exception e) { + loading.dismiss(); + e.fillInStackTrace(); + AlertandMessages.showAlert((Activity) context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE + " Please LogOut Again", false); + } + + } catch (JSONException e) { + loading.dismiss(); + AlertandMessages.showAlert((Activity) context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE + " Please LogOut Again", false); + } + } + + private static boolean delete_local_database(Context context) { + boolean deleted = true; + try { + File datadbfile = Environment.getDataDirectory(); + String currentDBPath = "//data//" + BuildConfig.APPLICATION_ID + "//databases//" + Lorealba_Database.DATABASE_NAME; + File currentDB = new File(datadbfile, currentDBPath); + deleted = SQLiteDatabase.deleteDatabase(currentDB); + if (deleted) { + AlertandMessages.showToastMsg(context, "Database Deleted Successfully"); + } + + Lorealba_Database db = new Lorealba_Database(context); + db.open(); + + } catch (Exception e) { + e.fillInStackTrace(); + } + + return deleted; + } + + private void UploadBaProfile(ProgressDialog loading, Lorealba_Database db, ArrayList baProfile_ImageList, int consumerIndex) { + try { + JSONArray topUpArray = new JSONArray(); + JSONArray storeDetail = new JSONArray(); + ArrayList ba_profile_auditList = db.getAfterSaveAuditQuestionAnswerData(baProfile_ImageList.get(consumerIndex).getUserId(), null); + if (!ba_profile_auditList.isEmpty()) { + for (int j = 0; j < ba_profile_auditList.size(); j++) { + JSONObject obj = new JSONObject(); + obj.put("Category_Id", ba_profile_auditList.get(j).getCATEGORY_ID()); + obj.put("Question_Id", ba_profile_auditList.get(j).getQUESTION_ID()); + obj.put("Question", ba_profile_auditList.get(j).getQUESTION()); + obj.put("Answer_type", ba_profile_auditList.get(j).getANSWER_TYPE()); + obj.put("Answer_Id", ba_profile_auditList.get(j).getANSWER_ID()); + obj.put("Answer", ba_profile_auditList.get(j).getANSWER()); + obj.put("Visit_Date", baProfile_ImageList.get(consumerIndex).getViisitDate()); + db.open(); + obj.put("MID", db.getBIDfromJCP(baProfile_ImageList.get(consumerIndex).getUserId(), counter_id).getMID()); + obj.put("UserId", baProfile_ImageList.get(consumerIndex).getUserId()); + obj.put("Counter_id", counter_id); + topUpArray.put(obj); + } + } + + JSONObject jsonObject = new JSONObject(); + jsonObject.put("Address", baProfile_ImageList.get(consumerIndex).getAddress()); + jsonObject.put("Dob", baProfile_ImageList.get(consumerIndex).getDob()); + jsonObject.put("Mobile_no", baProfile_ImageList.get(consumerIndex).getMobile()); + jsonObject.put("Email_Address", baProfile_ImageList.get(consumerIndex).getEmail()); + jsonObject.put("Instagram_Address", baProfile_ImageList.get(consumerIndex).getInstragramAddress()); + jsonObject.put("Profile_pic", baProfile_ImageList.get(consumerIndex).getProfilePic()); + jsonObject.put("Location", baProfile_ImageList.get(consumerIndex).getLocation()); + jsonObject.put("Landmark", baProfile_ImageList.get(consumerIndex).getLandmark()); + db.open(); + jsonObject.put("MID", db.getBIDfromJCP(baProfile_ImageList.get(consumerIndex).getUserId(), counter_id).getMID()); + jsonObject.put("UserId", baProfile_ImageList.get(consumerIndex).getUserId()); + jsonObject.put("Counter_id", counter_id); + if (!ba_profile_auditList.isEmpty()) { + jsonObject.put("BA_PROFILE_DATA", topUpArray); + } else { + jsonObject.put("BA_PROFILE_DATA", ""); + } + storeDetail.put(jsonObject); + + JSONObject jsonFinalObject = new JSONObject(); + db.open(); + jsonFinalObject.put("MID", db.getBIDfromJCP(baProfile_ImageList.get(consumerIndex).getUserId(), counter_id).getMID()); + jsonFinalObject.put("Keys", "BaProfileData"); + jsonFinalObject.put("JsonData", storeDetail.toString()); + jsonFinalObject.put("UserId", baProfile_ImageList.get(consumerIndex).getUserId()); + upload_BaProfilewithaudit(jsonFinalObject.toString(), loading, baProfile_ImageList.get(consumerIndex), consumerIndex); + } catch (JSONException e) { + e.fillInStackTrace(); + } + } + + public void upload_BaProfilewithaudit(String jsondata, final ProgressDialog loading, final MasterProfile object, final int index) { + try { + final int[] finalJsonIndex = {index}; + final OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, + TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build(); + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsondata); + Retrofit adapter; + adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build(); + PostApi api = adapter.create(PostApi.class); + Call call = api.getGeotag(jsonData); + call.enqueue(new Callback() { + @Override + public void onResponse(@NonNull Call call, @NonNull Response response) { + String data = null; + if (response.isSuccessful()) { + try { + assert response.body() != null; + data = response.body().get("UploadJsonResult").toString(); + if (!data.isEmpty()) { + data = data.substring(1, data.length() - 1).replace("\\", ""); + if (data.equalsIgnoreCase(CommonString.KEY_SUCCESS)) { + db.open(); + db.updateBaProfileStatus(object.getUserId(), object.getViisitDate(), CommonString.KEY_Y); + finalJsonIndex[0]++; + if (finalJsonIndex[0] != baProfile_ImageList.size()) { + UploadBaProfile(loading, db, baProfile_ImageList, finalJsonIndex[0]); + } else if (!counterprofile_imgList.isEmpty()) { + UploadCounterProfile(loading, db, counterprofile_imgList, 0); + } else if (!meQuizList.isEmpty()) { + UploadMeQuiz(loading, db, meQuizList, 0); + } else if (!groomingList.isEmpty()) { + UploadGrooming(loading, db, groomingList, 0); + } else if (!counterList.isEmpty()) { + UploadCounter(loading, db, counterList, 0); + } else { + Checkout_service(loading, context, lat, lon, username, counter_id, visit_date, db, false); + } + } else { + AlertandMessages.showAlert((Activity) context, "Server Not Responding,(Ba Profile). Please LogOut Again", false); + } + } + } catch (Exception e) { + e.fillInStackTrace(); + loading.dismiss(); + } + } + } + + @Override + public void onFailure(@NonNull Call call, @NonNull Throwable t) { + loading.dismiss(); + AlertandMessages.showAlert((Activity) context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE + " Please LogOut Again", false); + } + }); + + } catch (Exception e) { + loading.dismiss(); + e.fillInStackTrace(); + } + } + + private void UploadCounterProfile(ProgressDialog loading, Lorealba_Database db, ArrayList counterimgList, int consumerIndex) { + try { + JSONArray storeDetail = new JSONArray(); + JSONObject jsonObject; + if (!counterimgList.isEmpty()) { + jsonObject = new JSONObject(); + db.open(); + jsonObject.put("MID", db.getBIDfromJCP(counterimgList.get(consumerIndex).getUserId(), counter_id).getMID()); + jsonObject.put("UserId", counterimgList.get(consumerIndex).getUserId()); + jsonObject.put("ProfileImage1", counterimgList.get(consumerIndex).getProfileImage1()); + jsonObject.put("ProfileImage2", counterimgList.get(consumerIndex).getProfileImage2()); + jsonObject.put("Counterlength", counterimgList.get(consumerIndex).getCounterlength()); + jsonObject.put("Counterwidth", counterimgList.get(consumerIndex).getCounterwidth()); + jsonObject.put("SetupDate", counterimgList.get(consumerIndex).getSetupDate()); + jsonObject.put("Visit_Date", visit_date); + jsonObject.put("Counter_id", counter_id); + storeDetail.put(jsonObject); + } + + jsonObject = new JSONObject(); + db.open(); + jsonObject.put("MID", db.getBIDfromJCP(counterimgList.get(consumerIndex).getUserId(), counter_id).getMID()); + jsonObject.put("Keys", "ConterProfileData"); + jsonObject.put("JsonData", storeDetail.toString()); + jsonObject.put("UserId", counterimgList.get(consumerIndex).getUserId()); + upload_CounterProfile(jsonObject.toString(), loading, db, counterimgList.get(consumerIndex), consumerIndex); + + } catch (JSONException e) { + e.fillInStackTrace(); + } + } + + public void upload_CounterProfile(String jsondata, final ProgressDialog loading, final Lorealba_Database db, final JourneyPlan object, final int index) { + try { + final int[] finalJsonIndex = {index}; + final OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, + TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build(); + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsondata); + Retrofit adapter; + adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build(); + PostApi api = adapter.create(PostApi.class); + Call call = api.getGeotag(jsonData); + call.enqueue(new Callback() { + @Override + public void onResponse(@NonNull Call call, @NonNull Response response) { + String data = null; + if (response.isSuccessful()) { + try { + assert response.body() != null; + data = response.body().get("UploadJsonResult").toString(); + if (!data.isEmpty()) { + data = data.substring(1, data.length() - 1).replace("\\", ""); + if (data.equalsIgnoreCase(CommonString.KEY_SUCCESS)) { + db.open(); + db.updateCounterProfileStatus(object.getUserId(), visit_date, CommonString.KEY_Y); + finalJsonIndex[0]++; + if (finalJsonIndex[0] != counterprofile_imgList.size()) { + UploadCounterProfile(loading, db, counterprofile_imgList, finalJsonIndex[0]); + } else if (!meQuizList.isEmpty()) { + UploadMeQuiz(loading, db, meQuizList, 0); + } else if (!groomingList.isEmpty()) { + UploadGrooming(loading, db, groomingList, 0); + } else if (!counterList.isEmpty()) { + UploadCounter(loading, db, counterList, 0); + } else { + Checkout_service(loading, context, lat, lon, username, counter_id, visit_date, db, false); + } + } else { + loading.dismiss(); + AlertandMessages.showAlert((Activity) context, "Server Not Responding,(Counter Profile). Please LogOut Again", false); + } + } + } catch (Exception e) { + e.fillInStackTrace(); + loading.dismiss(); + } + } + } + + @Override + public void onFailure(@NonNull Call call, @NonNull Throwable t) { + AlertandMessages.showAlert((Activity) context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE + " Please LogOut Again", false); + loading.dismiss(); + } + }); + + } catch (Exception e) { + e.fillInStackTrace(); + loading.dismiss(); + } + } + + private void UploadMeQuiz(ProgressDialog loading, Lorealba_Database db, ArrayList me_quizList, int consumerIndex) { + try { + if (!me_quizList.isEmpty()) { + ArrayList specific_meQuizList = db.getme_quiz_from_database(null, me_quizList.get(consumerIndex).getUser_Id(), visit_date, counter_id, null); + if (!specific_meQuizList.isEmpty()) { + JourneyPlan jcp_Object = db.getBIDfromJCP(me_quizList.get(consumerIndex).getUser_Id(), counter_id); + JSONArray consumerUserInfoArray = new JSONArray(); + for (int k = 0; k < me_quizList.size(); k++) { + JSONObject obj = new JSONObject(); + + obj.put("MID", jcp_Object.getMID()); + obj.put("BID", jcp_Object.getBID()); + obj.put("VisiteDate", visit_date); + obj.put("UserId", specific_meQuizList.get(k).getUser_Id()); + obj.put("QuizId", specific_meQuizList.get(k).getQuizId()); + obj.put("Question_Id", specific_meQuizList.get(k).getQuestionId()); + obj.put("Question_Type", specific_meQuizList.get(k).getQuestionType()); + JSONArray compArraymult = new JSONArray(); + JSONObject objmultians = new JSONObject(); + if (specific_meQuizList.get(k).getQuestionType().equalsIgnoreCase("List Single Choice")) { + objmultians.put("Answer", specific_meQuizList.get(k).getAnswer()); + objmultians.put("Answer_Id", specific_meQuizList.get(k).getAnswerId()); + objmultians.put("Answer_Image", specific_meQuizList.get(k).getStr_audit_img()); + compArraymult.put(objmultians); + } else if (!specific_meQuizList.get(k).getQuestionType().equalsIgnoreCase("List Multiple Choice")) { + objmultians.put("Answer", specific_meQuizList.get(k).getAnswer()); + objmultians.put("Answer_Id", 0); + objmultians.put("Answer_Image", ""); + compArraymult.put(objmultians); + } else { + db.open(); + ArrayList multiansList = db.getquiz_answer(specific_meQuizList.get(k).getKeyId()); + if (!multiansList.isEmpty()) { + for (int j2 = 0; j2 < multiansList.size(); j2++) { + objmultians = new JSONObject(); + objmultians.put("Answer", multiansList.get(j2).getAnswer()); + objmultians.put("Answer_Id", multiansList.get(j2).getAnswerId()); + objmultians.put("Answer_Image", ""); + compArraymult.put(objmultians); + } + } + } + obj.put("AnsList", compArraymult); + consumerUserInfoArray.put(obj); + } + + JSONObject jsonObject = new JSONObject(); + db.open(); + jcp_Object = db.getBIDfromJCP(null, counter_id); + jsonObject.put("MID", jcp_Object.getMID()); + jsonObject.put("Keys", "ME_Quiz_Data"); + jsonObject.put("JsonData", consumerUserInfoArray.toString()); + jsonObject.put("UserId", me_quizList.get(consumerIndex).getUser_Id().toLowerCase()); + upload_me_Quiz(jsonObject.toString(), loading, db, me_quizList.get(consumerIndex), consumerIndex); + } + } + } catch (JSONException e) { + e.fillInStackTrace(); + } + } + + public void upload_me_Quiz(String jsondata, final ProgressDialog loading, final Lorealba_Database db, final MEMEAuditQuestion object, final int index) { + try { + final int[] finalJsonIndex = {index}; + + final OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, + TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build(); + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsondata); + Retrofit adapter; + adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build(); + PostApi api = adapter.create(PostApi.class); + Call call = api.getGeotag(jsonData); + call.enqueue(new Callback() { + @Override + public void onResponse(@NonNull Call call, @NonNull Response response) { + String data = null; + if (response.isSuccessful()) { + try { + assert response.body() != null; + data = response.body().get("UploadJsonResult").toString(); + if (!data.isEmpty()) { + data = data.substring(1, data.length() - 1).replace("\\", ""); + if (data.equalsIgnoreCase(CommonString.KEY_SUCCESS)) { + db.open(); + db.update_Me_Quiz(counter_id, object.getUser_Id()); + finalJsonIndex[0]++; + if (finalJsonIndex[0] != meQuizList.size()) { + UploadMeQuiz(loading, db, meQuizList, finalJsonIndex[0]); + } else if (!groomingList.isEmpty()) { + UploadGrooming(loading, db, groomingList, 0); + } else if (!counterList.isEmpty()) { + UploadCounter(loading, db, counterList, 0); + } else { + Checkout_service(loading, context, lat, lon, username, counter_id, visit_date, db, false); + } + } else { + loading.dismiss(); + AlertandMessages.showAlert((Activity) context, "Server Not Responding,(Me Quiz). Please LogOut Again", false); + } + } + } catch (Exception e) { + e.fillInStackTrace(); + loading.dismiss(); + } + } + } + + @Override + public void onFailure(@NonNull Call call, @NonNull Throwable t) { + AlertandMessages.showAlert((Activity) context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE + " Please LogOut Again", false); + loading.dismiss(); + } + }); + + } catch (Exception e) { + loading.dismiss(); + e.fillInStackTrace(); + } + } + + + private void UploadGrooming(ProgressDialog loading, Lorealba_Database db, ArrayList groomingList, int grooming_index) { + try { + if (!groomingList.isEmpty()) { + db.open(); + JourneyPlan jcp_Object = db.getBIDfromJCP(groomingList.get(grooming_index).getUser_Id(), counter_id); + JSONArray consumerUserInfoArray = getJsonArray(groomingList, grooming_index, jcp_Object); + + JSONObject jsonObject = new JSONObject(); + jsonObject.put("MID", jcp_Object.getMID()); + jsonObject.put("Keys", "Groomed_Data"); + jsonObject.put("JsonData", consumerUserInfoArray.toString()); + jsonObject.put("UserId", groomingList.get(grooming_index).getUser_Id()); + upload_grooming(jsonObject.toString(), loading, db, groomingList.get(grooming_index), grooming_index); + } + + + } catch (JSONException e) { + e.fillInStackTrace(); + } + } + + private @NonNull JSONArray getJsonArray(ArrayList groomingList, int grooming_index, JourneyPlan jcp_Object) throws JSONException { + JSONArray consumerUserInfoArray = new JSONArray(); + JSONObject obj = new JSONObject(); + obj.put("MID", jcp_Object.getMID()); + obj.put("BID", jcp_Object.getBID()); + obj.put("VisiteDate", visit_date); + obj.put("UserId", groomingList.get(grooming_index).getUser_Id()); + obj.put("Groomed_Morng_Img", groomingList.get(grooming_index).getMorning_groom_img_str()); + obj.put("Groomed_Morng_Time_Str", groomingList.get(grooming_index).getMorning_groom_time_str()); + obj.put("Groomed_Noon_Img", groomingList.get(grooming_index).getNoon_groom_img_str()); + obj.put("Groomed_Noon_Time_Str", groomingList.get(grooming_index).getNoon_groom_time_str()); + obj.put("Groomed_Eveng_Img", groomingList.get(grooming_index).getEvenning_groom_img_str()); + obj.put("Groomed_Eveng_Time_Str", groomingList.get(grooming_index).getEvenning_groom_time_str()); + + consumerUserInfoArray.put(obj); + return consumerUserInfoArray; + } + + public void upload_grooming(String jsondata, final ProgressDialog loading, final Lorealba_Database db, final GroomingGetterSetter object, final int index) { + try { + final int[] finalJsonIndex = {index}; + + final OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, + TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build(); + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsondata); + Retrofit adapter; + adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build(); + PostApi api = adapter.create(PostApi.class); + Call call = api.getGeotag(jsonData); + call.enqueue(new Callback() { + @Override + public void onResponse(@NonNull Call call, @NonNull Response response) { + String data = null; + if (response.isSuccessful()) { + try { + assert response.body() != null; + data = response.body().get("UploadJsonResult").toString(); + if (!data.isEmpty()) { + data = data.substring(1, data.length() - 1).replace("\\", ""); + if (data.equalsIgnoreCase(CommonString.KEY_SUCCESS)) { + db.open(); + db.update_groomed_img(counter_id, visit_date, object.getUser_Id()); + finalJsonIndex[0]++; + if (finalJsonIndex[0] != groomingList.size()) { + UploadGrooming(loading, db, groomingList, finalJsonIndex[0]); + } else if (!counterList.isEmpty()) { + UploadCounter(loading, db, counterList, 0); + } else { + Checkout_service(loading, context, lat, lon, username, counter_id, visit_date, db, false); + } + + } else { + loading.dismiss(); + AlertandMessages.showAlert((Activity) context, "Server Not Responding,(Grooming). Please LogOut Again", false); + } + } + } catch (Exception e) { + e.fillInStackTrace(); + loading.dismiss(); + } + } + } + + @Override + public void onFailure(@NonNull Call call, @NonNull Throwable t) { + AlertandMessages.showAlert((Activity) context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE + " Please LogOut Again", false); + loading.dismiss(); + } + }); + + } catch (Exception e) { + e.fillInStackTrace(); + loading.dismiss(); + } + } + + private void UploadCounter(ProgressDialog loading, Lorealba_Database db, ArrayList counterList, int counter_index) { + try { + if (!counterList.isEmpty()) { + db.open(); + JourneyPlan jcp_Object = db.getBIDfromJCP(null, counter_id); + JSONArray consumerUserInfoArray = new JSONArray(); + JSONObject obj = new JSONObject(); + String key = ""; + if (counterList.get(counter_index).getUser_type().equalsIgnoreCase(CommonString.TAG_FROM_BA) || counterList.get(counter_index).getUser_type().equalsIgnoreCase(CommonString.TAG_FROM_TBA)) { + key = "Counter_Image_Data"; + obj = new JSONObject(); + consumerUserInfoArray = new JSONArray(); + obj.put("MID", jcp_Object.getMID()); + obj.put("VisitDate", visit_date); + obj.put("UserId", counterList.get(counter_index).getUserId()); + obj.put("Counter_Img_One", counterList.get(counter_index).getCounter_img_onefor_ba()); + obj.put("Counter_Img_Two", counterList.get(counter_index).getCounter_img_two_for_ba()); + consumerUserInfoArray.put(obj); + } else { + key = "ME_Counter_Image_Data"; + obj = new JSONObject(); + consumerUserInfoArray = new JSONArray(); + + obj.put("MID", jcp_Object.getMID()); + obj.put("VisitDate", visit_date); + obj.put("UserId", counterList.get(counter_index).getUserId()); + obj.put("PreSetUpImgOne", counterList.get(counter_index).getPresetup_img_one_str()); + obj.put("PreSetUpImgTwo", counterList.get(counter_index).getPresetup_img_two_str()); + obj.put("PostSetUpImgOne", counterList.get(counter_index).getPostsetup_img_one_str()); + obj.put("PostSetUpImgTwo", counterList.get(counter_index).getPostsetup_img_two_str()); + consumerUserInfoArray.put(obj); + } + + + JSONObject jsonObject = new JSONObject(); + jsonObject.put("MID", jcp_Object.getMID()); + jsonObject.put("Keys", key); + jsonObject.put("JsonData", consumerUserInfoArray.toString()); + jsonObject.put("UserId", counterList.get(counter_index).getUserId()); + upload_counter(jsonObject.toString(), loading, db, counterList.get(counter_index), counter_index); + } + + + } catch (JSONException e) { + e.fillInStackTrace(); + } + } + + public void upload_counter(String jsondata, final ProgressDialog loading, final Lorealba_Database db, final JourneyPlan object, final int index) { + try { + final int[] finalJsonIndex = {index}; + final OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, + TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build(); + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsondata); + Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build(); + PostApi api = adapter.create(PostApi.class); + Call call = api.getGeotag(jsonData); + call.enqueue(new Callback() { + @Override + public void onResponse(@NonNull Call call, @NonNull Response response) { + String data = null; + if (response.isSuccessful()) { + try { + assert response.body() != null; + data = response.body().get("UploadJsonResult").toString(); + if (!data.isEmpty()) { + data = data.substring(1, data.length() - 1).replace("\\", ""); + if (data.equalsIgnoreCase(CommonString.KEY_SUCCESS)) { + db.open(); + db.update_ba_counter_img(counter_id, visit_date, object.getUserId(), object.getTransId()); + finalJsonIndex[0]++; + if (finalJsonIndex[0] != groomingList.size()) { + UploadCounter(loading, db, counterList, finalJsonIndex[0]); + } else { + Checkout_service(loading, context, lat, lon, username, counter_id, visit_date, db, false); + } + } else { + loading.dismiss(); + AlertandMessages.showAlert((Activity) context, "Server Not Responding,(Counter). Please LogOut Again", false); + } + } + } catch (Exception e) { + e.fillInStackTrace(); + loading.dismiss(); + } + } + } + + @Override + public void onFailure(@NonNull Call call, @NonNull Throwable t) { + AlertandMessages.showAlert((Activity) context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE + " Please LogOut Again", false); + loading.dismiss(); + } + }); + + } catch (Exception e) { + e.fillInStackTrace(); + loading.dismiss(); + } + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/upload/ManualUploadActivity.java b/app/src/main/java/com/cpm/lorealbaautomation/upload/ManualUploadActivity.java new file mode 100644 index 0000000..5d32152 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/upload/ManualUploadActivity.java @@ -0,0 +1,2959 @@ +package com.cpm.lorealbaautomation.upload; + +import android.annotation.SuppressLint; +import android.app.Activity; +import android.app.AlertDialog; +import android.app.ProgressDialog; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.os.Environment; + +import androidx.annotation.NonNull; +import androidx.appcompat.app.AppCompatActivity; + +import android.os.Bundle; + +import androidx.appcompat.widget.Toolbar; + +import android.view.KeyEvent; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; +import android.widget.ImageView; +import android.widget.TextView; + +import com.google.gson.Gson; +import com.google.gson.JsonObject; +import com.google.gson.JsonSyntaxException; +import com.cpm.lorealbaautomation.BuildConfig; +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.UserLoginActivity; +import com.cpm.lorealbaautomation.constant.AlertandMessages; +import com.cpm.lorealbaautomation.constant.CommonFunctions; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.gettersetter.AuditDataGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.GroomingGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.InvoiceGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.JourneyPlan; +import com.cpm.lorealbaautomation.gsonGetterSetter.MEMEAuditQuestion; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterBreak; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterCompetitonBrandWiseNuance; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterPosm; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterProfile; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterRetailExcellence; +import com.cpm.lorealbaautomation.gsonGetterSetter.ProductMaster; +import com.cpm.lorealbaautomation.gsonGetterSetter.T_LeaveRequest; +import com.cpm.lorealbaautomation.retrofit.PostApi; +import com.cpm.lorealbaautomation.retrofit.PostApiForUpload; +import com.cpm.lorealbaautomation.retrofit.StringConverterFactory; +import com.squareup.okhttp.MultipartBuilder; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.net.SocketException; +import java.net.SocketTimeoutException; +import java.nio.channels.FileChannel; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Objects; +import java.util.concurrent.TimeUnit; + +import okhttp3.MediaType; +import okhttp3.OkHttpClient; +import okhttp3.RequestBody; +import retrofit2.Call; +import retrofit2.Callback; +import retrofit2.Response; +import retrofit2.Retrofit; +import retrofit2.converter.gson.GsonConverterFactory; + +import static com.cpm.lorealbaautomation.constant.CommonFunctions.saveBitmapToFile; +import static com.cpm.lorealbaautomation.dailyactivity.ServiceActivity.uploadBackup; +import static com.cpm.lorealbaautomation.download.Downloader.convertTym; +import static com.cpm.lorealbaautomation.download.Downloader.getFileNames; + +public class ManualUploadActivity extends AppCompatActivity implements View.OnClickListener { + ArrayList baProfile_ImageList = new ArrayList<>(); + ArrayList counterprofile_imgList = new ArrayList<>(); + ArrayList meQuizList = new ArrayList<>(); + ArrayList masterRetailExcellenceArrayList = new ArrayList<>(); + ArrayList productMasterArrayList = new ArrayList<>(); + ArrayList groomingList = new ArrayList<>(); + ArrayList counterList = new ArrayList<>(); + ImageView img_manual_dataupload, img_manual_imageupload; + ArrayList masterList = new ArrayList<>(); + private SharedPreferences.Editor editor = null; + public static int uploadedFiles = 0; + public static int totalFiles = 0; + ProductMaster obj = new ProductMaster(); + String counter_Id, visit_date, username; + boolean clicked_flag = false; + Lorealba_Database db; + ProgressDialog pd; + Context context; + int value = -1; + + @SuppressLint("SetTextI18n") + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_manual_upload); + context = this; + db = new Lorealba_Database(context); + db.open(); + Toolbar toolbar = findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + Objects.requireNonNull(getSupportActionBar()).setHomeButtonEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + SharedPreferences preferences = PrefHelper.getPrefs(context); + editor = preferences.edit(); + counter_Id = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + username = preferences.getString(CommonString.KEY_USERNAME, ""); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + img_manual_dataupload = (ImageView) findViewById(R.id.img_manual_dataupload); + img_manual_imageupload = (ImageView) findViewById(R.id.img_manual_imageupload); + img_manual_imageupload.setVisibility(View.GONE); + setTitle("Manual Upload - " + username); + value = getIntent().getIntExtra(CommonString.TAG_OBJECT, -1); + db.open(); + masterList = db.getmasterTransaction(visit_date, counter_Id, true); + if (!masterList.isEmpty()) { + clicked_flag = true; + pd = new ProgressDialog(context); + pd.setCancelable(false); + pd.setMessage("Uploading Data" + "(" + "0/" + ")"); + pd.show(); + handleuploaddata_withcase(masterList, 0, pd); + } else if (!CommonFunctions.checkincomplete_upload_data(visit_date, counter_Id, db, true)) { + pd = new ProgressDialog(context); + pd.setCancelable(false); + pd.setMessage("Uploading Data" + "(" + "0/" + ")"); + pd.show(); + CommonUploadwithrecursive(db, true, pd); + } + + ////...............call interface.................. + img_manual_dataupload.setOnClickListener(this); + img_manual_imageupload.setOnClickListener(this); + + String couter_code = preferences.getString(CommonString.KEY_COUNTER_CODE, ""); + TextView txt_counter_code = (TextView) findViewById(R.id.txt_counter_code); + txt_counter_code.setText("Counter Code - " + couter_code + " / Id - " + counter_Id); + } + + @SuppressLint("LongLogTag") + private void handleuploaddata_withcase(ArrayList masterList, int masterfinalindex, ProgressDialog pd) { + if (!masterList.isEmpty()) { + obj = new ProductMaster(); + obj = masterList.get(masterfinalindex); + pd.setMessage("Uploading (" + masterfinalindex + "/" + masterList.size() + ") \n" + obj.getStock_type() + ""); + switch (obj.getStock_type()) { + case CommonString.SALEABLE: + if (obj.getEntry_type().equalsIgnoreCase(CommonString.KEY_DRAFT) || obj.getEntry_type().equalsIgnoreCase(CommonString.KEY_REGULAR)) { + String final_saleable_str = saleablejsonstr(counter_Id, obj); + if (final_saleable_str != null && !final_saleable_str.isEmpty()) { + upload_recursive_Data(final_saleable_str, masterfinalindex, masterList, pd); + //test(CommonString.KEY_JSON + "," + CommonString.SALEABLE, final_saleable_str); + } else { + pd.dismiss(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INVALID_JSON); + } + } else { + db.open(); + ArrayList saleableCompstockList = db.gettransaction_date(obj.getMaster_transaction_id()); + int endIndex = 0; + int startIndex = endIndex; + if (startIndex + 200 < saleableCompstockList.size()) { + endIndex = startIndex + 200; + } else { + endIndex = saleableCompstockList.size(); + } + + UploadStockRecursive(CommonString.KEY_COMPLETE, 0, endIndex, saleableCompstockList, masterList, masterfinalindex, pd); + } + + break; + + case CommonString.TESTER: + if (obj.getEntry_type().equalsIgnoreCase(CommonString.KEY_DRAFT) || obj.getEntry_type().equalsIgnoreCase(CommonString.KEY_REGULAR)) { + String final_saleable_str = saleablejsonstr(counter_Id, obj); + if (final_saleable_str != null && !final_saleable_str.isEmpty()) { + upload_recursive_Data(final_saleable_str, masterfinalindex, masterList, pd); + //test(CommonString.KEY_JSON + "," + CommonString.TESTER, final_saleable_str); + } else { + pd.dismiss(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INVALID_JSON); + } + } else { + db.open(); + ArrayList saleableCompstockList = db.gettransaction_date(obj.getMaster_transaction_id()); + int endIndex = 0; + int startIndex = endIndex; + if (startIndex + 200 < saleableCompstockList.size()) { + endIndex = startIndex + 200; + } else { + endIndex = saleableCompstockList.size(); + } + UploadStockRecursive(CommonString.KEY_COMPLETE, 0, endIndex, saleableCompstockList, masterList, masterfinalindex, pd); + } + + break; + + case CommonString.SAMPLE: + if (obj.getEntry_type().equalsIgnoreCase(CommonString.KEY_DRAFT) || obj.getEntry_type().equalsIgnoreCase(CommonString.KEY_REGULAR)) { + String final_saleable_str = saleablejsonstr(counter_Id, obj); + if (final_saleable_str != null && !final_saleable_str.isEmpty()) { + upload_recursive_Data(final_saleable_str, masterfinalindex, masterList, pd); + //test(CommonString.KEY_JSON + "," + CommonString.SAMPLE, final_saleable_str); + } else { + pd.dismiss(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INVALID_JSON); + } + } else { + db.open(); + ArrayList saleableCompstockList = db.gettransaction_date(obj.getMaster_transaction_id()); + int endIndex = 0; + int startIndex = endIndex; + if (startIndex + 200 < saleableCompstockList.size()) { + endIndex = startIndex + 200; + } else { + endIndex = saleableCompstockList.size(); + } + + UploadStockRecursive(CommonString.KEY_COMPLETE, 0, endIndex, saleableCompstockList, masterList, masterfinalindex, pd); + } + + break; + + case CommonString.GWP: + if (obj.getEntry_type().equalsIgnoreCase(CommonString.KEY_DRAFT) || obj.getEntry_type().equalsIgnoreCase(CommonString.KEY_REGULAR)) { + String final_saleable_str = saleablejsonstr(counter_Id, obj); + if (final_saleable_str != null && !final_saleable_str.equals("")) { + upload_recursive_Data(final_saleable_str, masterfinalindex, masterList, pd); + //test(CommonString.KEY_JSON + "," + CommonString.GWP, final_saleable_str); + } + } else { + db.open(); + ArrayList saleableCompstockList = db.gettransaction_date(obj.getMaster_transaction_id()); + int endIndex = 0; + int startIndex = endIndex; + if (startIndex + 200 < saleableCompstockList.size()) { + endIndex = startIndex + 200; + } else { + endIndex = saleableCompstockList.size(); + } + UploadStockRecursive(CommonString.KEY_COMPLETE, 0, endIndex, saleableCompstockList, masterList, masterfinalindex, pd); + } + + break; + + case CommonString.DAMAGE: + if (obj.getEntry_type().equalsIgnoreCase(CommonString.KEY_REGULAR)) { + String final_saleable_str = saleablejsonstr(counter_Id, obj); + if (final_saleable_str != null && !final_saleable_str.isEmpty()) { + upload_recursive_Data(final_saleable_str, masterfinalindex, masterList, pd); + //test(CommonString.KEY_JSON + "," + CommonString.DAMAGE, final_saleable_str); + } else { + pd.dismiss(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INVALID_JSON); + } + } + + break; + + case CommonString.RETURNTO_DB: + if (obj.getEntry_type().equalsIgnoreCase(CommonString.KEY_REGULAR)) { + String final_saleable_str = saleablejsonstr(counter_Id, obj); + if (final_saleable_str != null && !final_saleable_str.isEmpty()) { + upload_recursive_Data(final_saleable_str, masterfinalindex, masterList, pd); + //test(CommonString.KEY_JSON + "," + CommonString.RETURNTO_DB, final_saleable_str); + } else { + pd.dismiss(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INVALID_JSON); + } + } + + break; + + case CommonString.INWARD_DMS_NEW_SKU: + if (obj.getEntry_type().equalsIgnoreCase(CommonString.KEY_REGULAR)) { + String final_saleable_str = saleablejsonstr(counter_Id, obj); + if (final_saleable_str != null && !final_saleable_str.isEmpty()) { + upload_recursive_Data(final_saleable_str, masterfinalindex, masterList, pd); + //test(CommonString.KEY_JSON + "," + CommonString.INWARD_DMS_NEW_SKU, final_saleable_str); + } else { + pd.dismiss(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INVALID_JSON); + } + } + + break; + + case CommonString.INWARD_DMS: + if (obj.getEntry_type().equalsIgnoreCase(CommonString.KEY_REGULAR)) { + String final_saleable_str = saleablejsonstr(counter_Id, obj); + if (final_saleable_str != null && !final_saleable_str.isEmpty()) { + upload_recursive_Data(final_saleable_str, masterfinalindex, masterList, pd); + //test(CommonString.KEY_JSON + "," + CommonString.INWARD_DMS, final_saleable_str); + } else { + pd.dismiss(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INVALID_JSON); + } + } + + break; + + case CommonString.MANUALINWARD_DMS_NEWPRODUCT: + if (obj.getEntry_type().equalsIgnoreCase(CommonString.KEY_REGULAR)) { + String final_saleable_str = saleablejsonstr(counter_Id, obj); + if (final_saleable_str != null && !final_saleable_str.equals("")) { + upload_recursive_Data(final_saleable_str, masterfinalindex, masterList, pd); + //test(CommonString.KEY_JSON + "," + CommonString.MANUALINWARD_DMS_NEWPRODUCT, final_saleable_str); + } else { + pd.dismiss(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INVALID_JSON); + } + } + + break; + + case CommonString.MANUALINWARD_DMS: + if (obj.getEntry_type().equalsIgnoreCase(CommonString.KEY_REGULAR)) { + String final_saleable_str = saleablejsonstr(counter_Id, obj); + if (final_saleable_str != null && !final_saleable_str.equals("")) { + upload_recursive_Data(final_saleable_str, masterfinalindex, masterList, pd); + //test(CommonString.KEY_JSON + "," + CommonString.MANUALINWARD_DMS, final_saleable_str); + } else { + pd.dismiss(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INVALID_JSON); + } + } + + break; + + case CommonString.CONSUMERSALE: + if (obj.getEntry_type().equalsIgnoreCase(CommonString.KEY_REGULAR)) { + String final_saleable_str = saleablejsonstr(counter_Id, obj); + if (final_saleable_str != null && !final_saleable_str.equals("")) { + upload_recursive_Data(final_saleable_str, masterfinalindex, masterList, pd); + //test(CommonString.KEY_JSON + "," + CommonString.CONSUMERSALE, final_saleable_str); + } else { + pd.dismiss(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INVALID_JSON); + } + } + + break; + + case CommonString.CONSUMERRETURN: + if (obj.getEntry_type().equalsIgnoreCase(CommonString.KEY_REGULAR)) { + String final_saleable_str = saleablejsonstr(counter_Id, obj); + if (final_saleable_str != null && !final_saleable_str.equals("")) { + upload_recursive_Data(final_saleable_str, masterfinalindex, masterList, pd); + //test(CommonString.KEY_JSON + "," + CommonString.CONSUMERRETURN, final_saleable_str); + } else { + pd.dismiss(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INVALID_JSON); + } + } + + break; + + case CommonString.LEAVE_MANAGEMENT: + if (obj.getEntry_type().equalsIgnoreCase(CommonString.KEY_REGULAR)) { + String final_saleable_str = saleablejsonstr(counter_Id, obj); + if (final_saleable_str != null && !final_saleable_str.equals("")) { + upload_recursive_Data(final_saleable_str, masterfinalindex, masterList, pd); + //test(CommonString.KEY_JSON + "," + CommonString.LEAVE_MANAGEMENT, final_saleable_str); + } else { + pd.dismiss(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INVALID_JSON); + } + } + + break; + + case CommonString.BREAK_MANAGEMENT: + if (obj.getEntry_type().equalsIgnoreCase(CommonString.KEY_REGULAR)) { + String final_saleable_str = saleablejsonstr(counter_Id, obj); + if (final_saleable_str != null && !final_saleable_str.equals("")) { + upload_recursive_Data(final_saleable_str, masterfinalindex, masterList, pd); + //test(CommonString.KEY_JSON + "," + CommonString.BREAK_MANAGEMENT, final_saleable_str); + } else { + pd.dismiss(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INVALID_JSON); + } + } + + break; + + case CommonString.VISIBILITY: + if (obj.getEntry_type().equalsIgnoreCase(CommonString.KEY_REGULAR)) { + String final_saleable_str = saleablejsonstr(counter_Id, obj); + if (final_saleable_str != null && !final_saleable_str.equals("")) { + upload_recursive_Data(final_saleable_str, masterfinalindex, masterList, pd); + //test(CommonString.KEY_JSON + "," + CommonString.VISIBILITY, final_saleable_str); + } else { + pd.dismiss(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INVALID_JSON); + } + } + + break; + + case CommonString.MAKEOVER_CAPTURE: + if (obj.getEntry_type().equalsIgnoreCase(CommonString.KEY_REGULAR)) { + String final_saleable_str = saleablejsonstr(counter_Id, obj); + if (final_saleable_str != null && !final_saleable_str.equals("")) { + upload_recursive_Data(final_saleable_str, masterfinalindex, masterList, pd); + //test(CommonString.KEY_JSON + "," + CommonString.MAKEOVER_CAPTURE, final_saleable_str); + } else { + pd.dismiss(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INVALID_JSON); + } + } + + break; + + case CommonString.SKINGENIUS: + if (obj.getEntry_type().equalsIgnoreCase(CommonString.KEY_REGULAR)) { + String final_saleable_str = saleablejsonstr(counter_Id, obj); + if (final_saleable_str != null && !final_saleable_str.equals("")) { + upload_recursive_Data(final_saleable_str, masterfinalindex, masterList, pd); + //test(CommonString.KEY_JSON + "," + CommonString.SKINGENIUS, final_saleable_str); + } else { + pd.dismiss(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INVALID_JSON); + } + } + + break; + + case CommonString.OPEN_SKINGENIUS: + if (obj.getEntry_type().equalsIgnoreCase(CommonString.KEY_REGULAR)) { + String final_saleable_str = saleablejsonstr(counter_Id, obj); + if (final_saleable_str != null && !final_saleable_str.equals("")) { + upload_recursive_Data(final_saleable_str, masterfinalindex, masterList, pd); + //test(CommonString.KEY_JSON + "," + CommonString.OPEN_SKINGENIUS, final_saleable_str); + } else { + pd.dismiss(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INVALID_JSON); + } + } + + break; + + case CommonString.OPEN_MAYBELLINE: + if (obj.getEntry_type().equalsIgnoreCase(CommonString.KEY_REGULAR)) { + String final_saleable_str = saleablejsonstr(counter_Id, obj); + if (final_saleable_str != null && !final_saleable_str.equals("")) { + upload_recursive_Data(final_saleable_str, masterfinalindex, masterList, pd); + //test(CommonString.KEY_JSON + "," + CommonString.OPEN_MAYBELLINE, final_saleable_str); + } else { + pd.dismiss(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INVALID_JSON); + } + } + + break; + + case CommonString.COMP_OFFERS: + if (obj.getEntry_type().equalsIgnoreCase(CommonString.KEY_REGULAR)) { + String final_saleable_str = saleablejsonstr(counter_Id, obj); + if (final_saleable_str != null && !final_saleable_str.equals("")) { + upload_recursive_Data(final_saleable_str, masterfinalindex, masterList, pd); + //test(CommonString.KEY_JSON + "," + CommonString.COMP_OFFERS, final_saleable_str); + } else { + pd.dismiss(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INVALID_JSON); + } + } + + break; + + + default: + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Error in uploading"); + break; + } + } + } + + private String saleablejsonstr(String counter_id, ProductMaster objectcurrent) { + String saleablejson_str = ""; + db.open(); + JourneyPlan jcp_Object = db.getBIDfromJCP(null, counter_id); + db.open(); + ArrayList saleablestockList = db.gettransaction_date(objectcurrent.getMaster_transaction_id()); + try { + + String key = "", complete_json_str = ""; + JSONArray topUpArray = null; + if (objectcurrent.getStock_type().equalsIgnoreCase(CommonString.SALEABLE)) { + if (saleablestockList.size() > 0) { + key = "SaleableFData"; + complete_json_str = ""; + topUpArray = new JSONArray(); + for (int j = 0; j < saleablestockList.size(); j++) { + JSONObject obj = new JSONObject(); + obj.put("ProductId", saleablestockList.get(j).getProductId()); + obj.put("MID", jcp_Object.getMID()); + obj.put("REASON_ID", saleablestockList.get(j).getReasonId()); + obj.put("TranId", saleablestockList.get(j).getTransaction_Id()); + obj.put("UserId", saleablestockList.get(j).getUser_id()); + obj.put("CounterId", counter_id); + //header image + String img = saleablestockList.get(j).getImagePath(); + if (img == null) { + img = ""; + } + + obj.put("Image", img); + int stk = saleablestockList.get(j).getStock(); + if (stk == -1) { + stk = 0; + } + + obj.put("STOCK", stk); + if (objectcurrent.getEntry_type().equalsIgnoreCase(CommonString.KEY_DRAFT)) { + obj.put("Status", saleablestockList.get(j).getEntry_type()); + } else { + key = "SaleableData"; + } + + topUpArray.put(obj); + } + complete_json_str = topUpArray.toString(); + } + } else if (objectcurrent.getStock_type().equalsIgnoreCase(CommonString.TESTER)) { + if (saleablestockList.size() > 0) { + key = "TesterFData"; + complete_json_str = ""; + topUpArray = new JSONArray(); + db.open(); + jcp_Object = db.getBIDfromJCP(null, counter_id); + for (int j = 0; j < saleablestockList.size(); j++) { + JSONObject obj = new JSONObject(); + obj.put("ProductId", saleablestockList.get(j).getProductId()); + obj.put("MID", jcp_Object.getMID()); + obj.put("TranId", saleablestockList.get(j).getTransaction_Id()); + obj.put("UserId", saleablestockList.get(j).getUser_id()); + obj.put("CounterId", counter_id); + int stk = saleablestockList.get(j).getStock(); + if (stk == -1) { + stk = 0; + } + + obj.put("STOCK", stk); + + if (objectcurrent.getEntry_type().equalsIgnoreCase(CommonString.KEY_DRAFT)) { + obj.put("Status", saleablestockList.get(j).getEntry_type()); + } else { + key = "TesterData"; + } + + topUpArray.put(obj); + } + + complete_json_str = topUpArray.toString(); + } + + } else if (objectcurrent.getStock_type().equalsIgnoreCase(CommonString.SAMPLE)) { + if (saleablestockList.size() > 0) { + key = "SampleFData"; + complete_json_str = ""; + topUpArray = new JSONArray(); + db.open(); + jcp_Object = db.getBIDfromJCP(null, counter_id); + for (int j = 0; j < saleablestockList.size(); j++) { + JSONObject obj = new JSONObject(); + obj.put("ProductId", saleablestockList.get(j).getProductId()); + obj.put("MID", jcp_Object.getMID()); + obj.put("TranId", saleablestockList.get(j).getTransaction_Id()); + obj.put("UserId", saleablestockList.get(j).getUser_id()); + obj.put("CounterId", counter_id); + int stk = saleablestockList.get(j).getStock(); + if (stk == -1) { + stk = 0; + } + + obj.put("STOCK", stk); + + if (objectcurrent.getEntry_type().equalsIgnoreCase(CommonString.KEY_DRAFT)) { + obj.put("Status", saleablestockList.get(j).getEntry_type()); + } else { + key = "SampleData"; + } + + topUpArray.put(obj); + } + + complete_json_str = topUpArray.toString(); + } + + } else if (objectcurrent.getStock_type().equalsIgnoreCase(CommonString.GWP)) { + if (saleablestockList.size() > 0) { + key = "GWPFData"; + complete_json_str = ""; + topUpArray = new JSONArray(); + db.open(); + jcp_Object = db.getBIDfromJCP(null, counter_id); + for (int j = 0; j < saleablestockList.size(); j++) { + JSONObject obj = new JSONObject(); + obj.put("ProductId", saleablestockList.get(j).getProductId()); + obj.put("MID", jcp_Object.getMID()); + obj.put("TranId", saleablestockList.get(j).getTransaction_Id()); + obj.put("UserId", saleablestockList.get(j).getUser_id()); + obj.put("CounterId", counter_id); + int stk = saleablestockList.get(j).getStock(); + if (stk == -1) { + stk = 0; + } + obj.put("STOCK", stk); + if (objectcurrent.getEntry_type().equalsIgnoreCase(CommonString.KEY_DRAFT)) { + obj.put("Status", saleablestockList.get(j).getEntry_type()); + } else { + key = "GWPData"; + } + topUpArray.put(obj); + } + + complete_json_str = topUpArray.toString(); + } + } else if (objectcurrent.getStock_type().equalsIgnoreCase(CommonString.ME_SALE)) { + if (saleablestockList.size() > 0) { + key = "ME_SaleFData"; + complete_json_str = ""; + topUpArray = new JSONArray(); + db.open(); + jcp_Object = db.getBIDfromJCP(null, counter_id); + for (int j = 0; j < saleablestockList.size(); j++) { + JSONObject obj = new JSONObject(); + obj.put("ProductId", saleablestockList.get(j).getProductId()); + obj.put("MID", jcp_Object.getMID()); + obj.put("TranId", saleablestockList.get(j).getTransaction_Id()); + obj.put("UserId", saleablestockList.get(j).getUser_id()); + obj.put("CounterId", counter_id); + int stk = saleablestockList.get(j).getStock(); + if (stk == -1) { + stk = 0; + } + + obj.put("STOCK", stk); + + if (objectcurrent.getEntry_type().equalsIgnoreCase(CommonString.KEY_DRAFT)) { + obj.put("Status", saleablestockList.get(j).getEntry_type()); + } else { + key = "ME_SaleData"; + } + + topUpArray.put(obj); + } + + complete_json_str = topUpArray.toString(); + } + } else if (objectcurrent.getStock_type().equalsIgnoreCase(CommonString.DAMAGE)) { + if (saleablestockList.size() > 0) { + key = "DamageData"; + complete_json_str = ""; + topUpArray = new JSONArray(); + db.open(); + jcp_Object = db.getBIDfromJCP(null, counter_id); + for (int j = 0; j < saleablestockList.size(); j++) { + JSONObject obj = new JSONObject(); + obj.put("ProductId", saleablestockList.get(j).getProductId()); + obj.put("MID", jcp_Object.getMID()); + obj.put("TranId", saleablestockList.get(j).getTransaction_Id()); + obj.put("UserId", saleablestockList.get(j).getUser_id()); + obj.put("CounterId", counter_id); + //header image + String img = saleablestockList.get(j).getImagePath(); + if (img == null) { + img = ""; + } + + obj.put("Image", img); + int stk = saleablestockList.get(j).getStock(); + if (stk == -1) { + stk = 0; + } + obj.put("STOCK", stk); + topUpArray.put(obj); + } + + complete_json_str = topUpArray.toString(); + } + } else if (objectcurrent.getStock_type().equalsIgnoreCase(CommonString.RETURNTO_DB)) { + db.open(); + ArrayList damagestockList = db.getreturntodistributor_byUUID(objectcurrent.getTransaction_Id()); + if (damagestockList.size() > 0) { + complete_json_str = ""; + key = "DamageReturnToDistributor"; + topUpArray = new JSONArray(); + db.open(); + jcp_Object = db.getBIDfromJCP(null, counter_id); + for (int j = 0; j < damagestockList.size(); j++) { + JSONObject obj = new JSONObject(); + obj.put("ProductId", damagestockList.get(j).getProductId()); + obj.put("MID", jcp_Object.getMID()); + obj.put("TranId", damagestockList.get(j).getTransaction_Id()); + obj.put("UserId", damagestockList.get(j).getUser_id()); + obj.put("CounterId", counter_id); + int stk = damagestockList.get(j).getStock(); + if (stk == -1) { + stk = 0; + } + obj.put("STOCK", stk); + + topUpArray.put(obj); + } + + complete_json_str = topUpArray.toString(); + } + } else if (objectcurrent.getStock_type().equalsIgnoreCase(CommonString.INWARD_DMS_NEW_SKU)) { + db.open(); + ArrayList dmsList = db.getInwardStockTransactionData(objectcurrent.getTransaction_Id()); + if (dmsList.size() > 0) { + key = "Inward_NewProduct_Stock"; + complete_json_str = ""; + topUpArray = new JSONArray(); + db.open(); + jcp_Object = db.getBIDfromJCP(null, counter_id); + for (int j = 0; j < dmsList.size(); j++) { + JSONObject obj = new JSONObject(); + obj.put("MID", jcp_Object.getMID()); + obj.put("UserId", dmsList.get(j).getUser_id()); + obj.put(CommonString.KEY_VISIT_DATE, dmsList.get(j).getVisit_date()); + obj.put("TranId", dmsList.get(j).getTransaction_Id()); + obj.put(CommonString.KEY_ProductId, dmsList.get(j).getProductId()); + obj.put(CommonString.KEY_INVOICE_ID, dmsList.get(j).getInvId()); + obj.put(CommonString.KEY_INVOICE_STATUS, dmsList.get(j).getInvoice_Status()); + obj.put(CommonString.KEY_INVOICE_NUMBER, dmsList.get(j).getInvoice_number()); + obj.put(CommonString.KEY_INVOICE_TYPE, dmsList.get(j).getInvoice_type()); + obj.put(CommonString.KEY_INVOICE_DATE, dmsList.get(j).getInvoice_date()); + obj.put(CommonString.KEY_INVOICE_QTY, dmsList.get(j).getConsumer_qty()); + obj.put(CommonString.KEY_ACTUAL_QTY, dmsList.get(j).getActualQty()); + obj.put(CommonString.KEY_COUNTER_ID, dmsList.get(j).getCounter_id()); + if (dmsList.get(j).isConfirmChecked()) { + obj.put(CommonString.KEY_COUNTER_CONFIRM, "1"); + } else { + obj.put(CommonString.KEY_COUNTER_CONFIRM, "0"); + } + obj.put(CommonString.KEY_REASON_ID, dmsList.get(j).getReasonId()); + obj.put(CommonString.KEY_SOURCE, dmsList.get(j).getSource()); + + topUpArray.put(obj); + } + + complete_json_str = topUpArray.toString(); + } + } else if (objectcurrent.getStock_type().equalsIgnoreCase(CommonString.INWARD_DMS)) { + db.open(); + ArrayList dmsList = db.getInwardStockTransactionData(objectcurrent.getTransaction_Id()); + if (dmsList.size() > 0) { + key = "Inward_ExistingProduct_Stock"; + complete_json_str = ""; + topUpArray = new JSONArray(); + db.open(); + jcp_Object = db.getBIDfromJCP(null, counter_id); + for (int j = 0; j < dmsList.size(); j++) { + JSONObject obj = new JSONObject(); + obj.put("MID", jcp_Object.getMID()); + obj.put("UserId", dmsList.get(j).getUser_id()); + obj.put(CommonString.KEY_VISIT_DATE, dmsList.get(j).getVisit_date()); + obj.put("TranId", dmsList.get(j).getTransaction_Id()); + obj.put(CommonString.KEY_ProductId, dmsList.get(j).getProductId()); + obj.put(CommonString.KEY_INVOICE_ID, dmsList.get(j).getInvId()); + obj.put(CommonString.KEY_INVOICE_STATUS, dmsList.get(j).getInvoice_Status()); + obj.put(CommonString.KEY_INVOICE_NUMBER, dmsList.get(j).getInvoice_number()); + obj.put(CommonString.KEY_INVOICE_TYPE, dmsList.get(j).getInvoice_type()); + obj.put(CommonString.KEY_INVOICE_DATE, dmsList.get(j).getInvoice_date()); + obj.put(CommonString.KEY_INVOICE_QTY, dmsList.get(j).getConsumer_qty()); + obj.put(CommonString.KEY_ACTUAL_QTY, dmsList.get(j).getActualQty()); + obj.put(CommonString.KEY_COUNTER_ID, dmsList.get(j).getCounter_id()); + if (dmsList.get(j).isConfirmChecked()) { + obj.put(CommonString.KEY_COUNTER_CONFIRM, "1"); + } else { + obj.put(CommonString.KEY_COUNTER_CONFIRM, "0"); + } + obj.put(CommonString.KEY_REASON_ID, dmsList.get(j).getReasonId()); + obj.put(CommonString.KEY_SOURCE, dmsList.get(j).getSource()); + + topUpArray.put(obj); + } + + complete_json_str = topUpArray.toString(); + } + + } else if (objectcurrent.getStock_type().equalsIgnoreCase(CommonString.MANUALINWARD_DMS_NEWPRODUCT)) { + db.open(); + ArrayList manualIList = db.getManualInwardStock(objectcurrent.getTransaction_Id()); + if (manualIList.size() > 0) { + topUpArray = new JSONArray(); + complete_json_str = ""; + key = "Manual_Inward_NewProduct"; + db.open(); + jcp_Object = db.getBIDfromJCP(null, counter_id); + for (int j = 0; j < manualIList.size(); j++) { + JSONObject obj = new JSONObject(); + obj.put("MID", jcp_Object.getMID()); + obj.put("UserId", manualIList.get(j).getUser_id()); + obj.put(CommonString.KEY_VISIT_DATE, manualIList.get(j).getVisit_date()); + obj.put("TranId", manualIList.get(j).getTransaction_Id()); + obj.put(CommonString.KEY_ProductId, manualIList.get(j).getProductId()); + obj.put(CommonString.KEY_INVOICE_ID, manualIList.get(j).getInvId()); + obj.put(CommonString.KEY_INVOICE_STATUS, manualIList.get(j).getInvoice_Status()); + obj.put(CommonString.KEY_INVOICE_NUMBER, manualIList.get(j).getInvoice_number()); + obj.put(CommonString.KEY_INVOICE_TYPE, manualIList.get(j).getInvoice_type()); + obj.put(CommonString.KEY_INVOICE_DATE, manualIList.get(j).getInvoice_date()); + obj.put(CommonString.KEY_INVOICE_QTY, manualIList.get(j).getConsumer_qty()); + obj.put(CommonString.KEY_ACTUAL_QTY, manualIList.get(j).getActualQty()); + obj.put(CommonString.KEY_COUNTER_ID, manualIList.get(j).getCounter_id()); + obj.put(CommonString.KEY_INVOICE_IMG, manualIList.get(j).getInvoice_img()); + if (manualIList.get(j).isConfirmChecked()) { + obj.put(CommonString.KEY_COUNTER_CONFIRM, "1"); + } else { + obj.put(CommonString.KEY_COUNTER_CONFIRM, "0"); + } + + obj.put(CommonString.KEY_REASON_ID, manualIList.get(j).getReasonId()); + obj.put(CommonString.KEY_SOURCE, manualIList.get(j).getSource()); + topUpArray.put(obj); + } + + complete_json_str = topUpArray.toString(); + } + + } else if (objectcurrent.getStock_type().equalsIgnoreCase(CommonString.MANUALINWARD_DMS)) { + db.open(); + ArrayList manualIList = db.getManualInwardStock(objectcurrent.getTransaction_Id()); + if (manualIList.size() > 0) { + topUpArray = new JSONArray(); + complete_json_str = ""; + key = "Manual_Inward_ExistProduct"; + db.open(); + jcp_Object = db.getBIDfromJCP(null, counter_id); + for (int j = 0; j < manualIList.size(); j++) { + JSONObject obj = new JSONObject(); + obj.put("MID", jcp_Object.getMID()); + obj.put("UserId", manualIList.get(j).getUser_id()); + obj.put(CommonString.KEY_VISIT_DATE, manualIList.get(j).getVisit_date()); + obj.put("TranId", manualIList.get(j).getTransaction_Id()); + obj.put(CommonString.KEY_ProductId, manualIList.get(j).getProductId()); + obj.put(CommonString.KEY_INVOICE_ID, manualIList.get(j).getInvId()); + obj.put(CommonString.KEY_INVOICE_STATUS, manualIList.get(j).getInvoice_Status()); + obj.put(CommonString.KEY_INVOICE_NUMBER, manualIList.get(j).getInvoice_number()); + obj.put(CommonString.KEY_INVOICE_TYPE, manualIList.get(j).getInvoice_type()); + obj.put(CommonString.KEY_INVOICE_DATE, manualIList.get(j).getInvoice_date()); + obj.put(CommonString.KEY_INVOICE_QTY, manualIList.get(j).getConsumer_qty()); + obj.put(CommonString.KEY_ACTUAL_QTY, manualIList.get(j).getActualQty()); + obj.put(CommonString.KEY_COUNTER_ID, manualIList.get(j).getCounter_id()); + obj.put(CommonString.KEY_INVOICE_IMG, manualIList.get(j).getInvoice_img()); + + if (manualIList.get(j).isConfirmChecked()) { + obj.put(CommonString.KEY_COUNTER_CONFIRM, "1"); + } else { + obj.put(CommonString.KEY_COUNTER_CONFIRM, "0"); + } + + obj.put(CommonString.KEY_REASON_ID, manualIList.get(j).getReasonId()); + obj.put(CommonString.KEY_SOURCE, manualIList.get(j).getSource()); + topUpArray.put(obj); + } + + complete_json_str = topUpArray.toString(); + } + } else if (objectcurrent.getStock_type().equalsIgnoreCase(CommonString.CONSUMERSALE)) { + db.open(); + ArrayList consumerSalesList = db.getsaleTrackingHeaderData(visit_date, counter_id, null, false, true, objectcurrent.getTransaction_Id()); + if (!consumerSalesList.isEmpty()) { + complete_json_str = ""; + int consumerIndex = 0; + topUpArray = new JSONArray(); + if (consumerSalesList.get(consumerIndex).getUserType().equalsIgnoreCase(CommonString.TAG_FROM_ME)) { + key = "ConsumerSalesWithapplyiedProductFromME"; + } else { + key = "ConsumerSalesWithapplyiedProduct"; + } + db.open(); + jcp_Object = db.getBIDfromJCP(consumerSalesList.get(consumerIndex).getStrUserId(), counter_id); + JSONArray consumerUserInfoArray = new JSONArray(); + JSONArray consumerGivenProductArray = new JSONArray(); + JSONArray consumerpromotionArray = new JSONArray(); + JSONObject obj = new JSONObject(); + obj.put("MID", jcp_Object.getMID()); + obj.put("BID", jcp_Object.getBID()); + obj.put("UserId", consumerSalesList.get(consumerIndex).getStrUserId()); + obj.put("VisiteDate", visit_date); + obj.put("POS_Sale", "1"); + obj.put("TranId", consumerSalesList.get(consumerIndex).getUnique_code()); + obj.put("ConsumerName", consumerSalesList.get(consumerIndex).getCustomer_name()); + obj.put("MobileNumber", consumerSalesList.get(consumerIndex).getMobile_no()); + obj.put("EmailId", consumerSalesList.get(consumerIndex).getConsumer_email_Id()); + obj.put("Age", consumerSalesList.get(consumerIndex).getConsumer_age()); + obj.put("SkinType", consumerSalesList.get(consumerIndex).getConsumer_skinType()); + obj.put("Gender", consumerSalesList.get(consumerIndex).getCustomer_gender()); + obj.put("DemoGiven", consumerSalesList.get(consumerIndex).getDemo_given_str()); + obj.put("ProductSold", consumerSalesList.get(consumerIndex).getProduct_sold_str()); + obj.put("SkinGenius", consumerSalesList.get(consumerIndex).getSkin_genius_str()); + obj.put("MaybellineVTO", consumerSalesList.get(consumerIndex).getMaybelline_vto_str()); + obj.put("ReceiptNumber", consumerSalesList.get(consumerIndex).getReccept_count()); + obj.put("ConsumerTime", consumerSalesList.get(consumerIndex).getPercheasing_tym()); + obj.put("TermConditions", consumerSalesList.get(consumerIndex).getStr_termcondition()); + obj.put("ConsumerNoSaleImg", consumerSalesList.get(consumerIndex).getConsumer_no_saleImg()); + obj.put("SourceofSales", consumerSalesList.get(consumerIndex).getSourceofSales()); + consumerUserInfoArray.put(obj); + db.open(); + ArrayList childList = db.getsalesTrackingByUserMobile(consumerSalesList.get(consumerIndex).getReccept_count(), consumerSalesList.get(consumerIndex).getMobile_no(), consumerSalesList.get(consumerIndex).getVisit_date(), counter_id, consumerSalesList.get(consumerIndex).getStrUserId()); + if (!childList.isEmpty()) { + for (int k = 0; k < childList.size(); k++) { + if (!childList.get(k).getProduct_Id().equals("0") && !childList.get(k).isPromo_flag()) { + obj = new JSONObject(); + obj.put("MID", jcp_Object.getMID()); + obj.put("BID", jcp_Object.getBID()); + obj.put("UserId", consumerSalesList.get(consumerIndex).getStrUserId()); + obj.put("TranId", consumerSalesList.get(consumerIndex).getUnique_code()); + obj.put("ProductId", childList.get(k).getProduct_Id()); + obj.put("Quantity", childList.get(k).getQuantity()); + obj.put("ProductMRP", childList.get(k).getProduct_rate()); + obj.put("EANCode", childList.get(k).getScan_ean_code_or_enterd_ean_code()); + obj.put("Invoice_Type", childList.get(k).getStr_invoiceType()); + consumerGivenProductArray.put(obj); + + } else if (childList.get(k).isPromo_flag() && childList.get(k).getPromo_type().equalsIgnoreCase("OffProduct")) { + obj = new JSONObject(); + obj.put("MID", jcp_Object.getMID()); + obj.put("BID", jcp_Object.getBID()); + obj.put("UserId", consumerSalesList.get(consumerIndex).getStrUserId()); + obj.put("TranId", consumerSalesList.get(consumerIndex).getUnique_code()); + obj.put("ProductId", childList.get(k).getProduct_Id()); + obj.put("Quantity", childList.get(k).getQuantity()); + obj.put("ProductMRP", childList.get(k).getProduct_rate()); + obj.put("EANCode", childList.get(k).getScan_ean_code_or_enterd_ean_code()); + obj.put("Invoice_Type", "Saleable"); + consumerGivenProductArray.put(obj); + } + } + } + ///get promo product + db.open(); + ArrayList promotionList = db.getapplyeid_promotion(consumerSalesList.get(consumerIndex).getReccept_count(), consumerSalesList.get(consumerIndex).getMobile_no(), consumerSalesList.get(consumerIndex).getVisit_date(), counter_id, consumerSalesList.get(consumerIndex).getStrUserId()); + if (!promotionList.isEmpty()) { + for (int k = 0; k < promotionList.size(); k++) { + obj = new JSONObject(); + obj.put("MID", jcp_Object.getMID()); + obj.put("BID", jcp_Object.getBID()); + obj.put("UserId", consumerSalesList.get(consumerIndex).getStrUserId()); + obj.put("TranId", consumerSalesList.get(consumerIndex).getUnique_code()); + obj.put("PromoType", promotionList.get(k).getPromo_type()); + + ArrayList applyedProducts = new ArrayList<>(); + JSONArray jsonArrayPromoApplyiedOnProductId = new JSONArray(); + if (promotionList.get(k).getPromo_type().equalsIgnoreCase("OffSameProduct")) { + applyedProducts = promotionList.get(k).getApplyiedproductList(); + if (!applyedProducts.isEmpty()) { + jsonArrayPromoApplyiedOnProductId = new JSONArray(); + for (int h = 0; h < applyedProducts.size(); h++) { + JSONObject obj7 = new JSONObject(); + obj7.put("MID", jcp_Object.getMID()); + obj7.put("BID", jcp_Object.getBID()); + obj7.put("UserId", consumerSalesList.get(consumerIndex).getStrUserId()); + obj7.put("TranId", consumerSalesList.get(consumerIndex).getUnique_code()); + obj7.put("PromoType", promotionList.get(k).getPromo_type()); + obj7.put("PromoId", applyedProducts.get(h).getPromotion_Id()); + obj7.put("PromoApplyiedOnProductId", applyedProducts.get(h).getProduct_Id()); + obj7.put("Rate", applyedProducts.get(h).getProduct_rate()); + obj7.put("MRP", applyedProducts.get(h).getMrp()); + obj7.put("EanCode", applyedProducts.get(h).getScan_ean_code_or_enterd_ean_code()); + obj7.put("QTY", applyedProducts.get(h).getQuantity()); + obj7.put("DISCOUNT", applyedProducts.get(h).getDiscounted_value_productwise()); + jsonArrayPromoApplyiedOnProductId.put(obj7); + } + } + obj.put("PromoId", promotionList.get(k).getPromotion_Id()); + obj.put("Discounted_Rs", promotionList.get(k).getDiscounted_value()); + obj.put("Rate", "0"); + obj.put("ProductId", 0); + obj.put("Quantity", 0); + if (!applyedProducts.isEmpty()) { + obj.put("PromoApplyiedOnProducts", jsonArrayPromoApplyiedOnProductId); + } else { + obj.put("PromoApplyiedOnProducts", ""); + } + } else if (promotionList.get(k).getPromo_type().equalsIgnoreCase("OffAdditionalProduct")) { + applyedProducts = promotionList.get(k).getApplyiedproductList(); + if (!applyedProducts.isEmpty()) { + jsonArrayPromoApplyiedOnProductId = new JSONArray(); + for (int h = 0; h < applyedProducts.size(); h++) { + JSONObject obj7 = new JSONObject(); + obj7.put("MID", jcp_Object.getMID()); + obj7.put("BID", jcp_Object.getBID()); + obj7.put("UserId", consumerSalesList.get(consumerIndex).getStrUserId()); + obj7.put("TranId", consumerSalesList.get(consumerIndex).getUnique_code()); + obj7.put("PromoType", promotionList.get(k).getPromo_type()); + obj7.put("PromoId", applyedProducts.get(h).getPromotion_Id()); + obj7.put("PromoApplyiedOnProductId", applyedProducts.get(h).getProduct_Id()); + obj7.put("Rate", applyedProducts.get(h).getProduct_rate()); + obj7.put("MRP", applyedProducts.get(h).getMrp()); + obj7.put("EanCode", applyedProducts.get(h).getScan_ean_code_or_enterd_ean_code()); + obj7.put("QTY", applyedProducts.get(h).getQuantity()); + obj7.put("DISCOUNT", applyedProducts.get(h).getDiscounted_value_productwise()); + jsonArrayPromoApplyiedOnProductId.put(obj7); + } + } + obj.put("PromoId", promotionList.get(k).getPromotion_Id()); + obj.put("Discounted_Rs", promotionList.get(k).getDiscounted_value()); + obj.put("Rate", "0"); + obj.put("ProductId", 0); + obj.put("Quantity", 0); + if (!applyedProducts.isEmpty()) { + obj.put("PromoApplyiedOnProducts", jsonArrayPromoApplyiedOnProductId); + } else { + obj.put("PromoApplyiedOnProducts", ""); + } + } else if (promotionList.get(k).getPromo_type().equalsIgnoreCase("ValueOffAdditionalProduct")) { + applyedProducts = promotionList.get(k).getApplyiedproductList(); + if (!applyedProducts.isEmpty()) { + jsonArrayPromoApplyiedOnProductId = new JSONArray(); + for (int h = 0; h < applyedProducts.size(); h++) { + JSONObject obj7 = new JSONObject(); + obj7.put("MID", jcp_Object.getMID()); + obj7.put("BID", jcp_Object.getBID()); + obj7.put("UserId", consumerSalesList.get(consumerIndex).getStrUserId()); + obj7.put("TranId", consumerSalesList.get(consumerIndex).getUnique_code()); + obj7.put("PromoType", promotionList.get(k).getPromo_type()); + obj7.put("PromoId", applyedProducts.get(h).getPromotion_Id()); + obj7.put("PromoApplyiedOnProductId", applyedProducts.get(h).getProduct_Id()); + obj7.put("Rate", applyedProducts.get(h).getProduct_rate()); + obj7.put("MRP", applyedProducts.get(h).getMrp()); + obj7.put("EanCode", applyedProducts.get(h).getScan_ean_code_or_enterd_ean_code()); + obj7.put("QTY", applyedProducts.get(h).getQuantity()); + obj7.put("DISCOUNT", applyedProducts.get(h).getDiscounted_value_productwise()); + jsonArrayPromoApplyiedOnProductId.put(obj7); + } + } + obj.put("PromoId", promotionList.get(k).getPromotion_Id()); + obj.put("Discounted_Rs", promotionList.get(k).getDiscounted_value()); + obj.put("Rate", "0"); + obj.put("ProductId", 0); + obj.put("Quantity", 0); + if (!applyedProducts.isEmpty()) { + obj.put("PromoApplyiedOnProducts", jsonArrayPromoApplyiedOnProductId); + } else { + obj.put("PromoApplyiedOnProducts", ""); + } + } else if (promotionList.get(k).getPromo_type().equalsIgnoreCase("OffWorth")) { + applyedProducts = promotionList.get(k).getApplyiedproductList(); + if (!applyedProducts.isEmpty()) { + jsonArrayPromoApplyiedOnProductId = new JSONArray(); + for (int h = 0; h < applyedProducts.size(); h++) { + JSONObject obj7 = new JSONObject(); + obj7.put("MID", jcp_Object.getMID()); + obj7.put("BID", jcp_Object.getBID()); + obj7.put("UserId", consumerSalesList.get(consumerIndex).getStrUserId()); + obj7.put("TranId", consumerSalesList.get(consumerIndex).getUnique_code()); + obj7.put("PromoType", promotionList.get(k).getPromo_type()); + obj7.put("PromoId", applyedProducts.get(h).getPromotion_Id()); + obj7.put("PromoApplyiedOnProductId", applyedProducts.get(h).getProduct_Id()); + obj7.put("Rate", applyedProducts.get(h).getProduct_rate()); + obj7.put("MRP", applyedProducts.get(h).getMrp()); + obj7.put("EanCode", applyedProducts.get(h).getScan_ean_code_or_enterd_ean_code()); + obj7.put("QTY", applyedProducts.get(h).getQuantity()); + obj7.put("DISCOUNT", applyedProducts.get(h).getDiscounted_value_productwise()); + jsonArrayPromoApplyiedOnProductId.put(obj7); + } + } + obj.put("PromoId", promotionList.get(k).getPromotion_Id()); + obj.put("Discounted_Rs", promotionList.get(k).getDiscounted_value()); + obj.put("Rate", "0"); + obj.put("ProductId", 0); + obj.put("Quantity", 0); + if (!applyedProducts.isEmpty()) { + obj.put("PromoApplyiedOnProducts", jsonArrayPromoApplyiedOnProductId); + } else { + obj.put("PromoApplyiedOnProducts", ""); + } + + + } else if (promotionList.get(k).getPromo_type().equalsIgnoreCase("Worth")) { + obj.put("PromoId", promotionList.get(k).getPromotion_Id()); + obj.put("Discounted_Rs", promotionList.get(k).getDiscounted_value()); + obj.put("Rate", "0"); + obj.put("ProductId", 0); + obj.put("Quantity", 0); + obj.put("PromoApplyiedOnProducts", ""); + + } else if (promotionList.get(k).getPromo_type().equalsIgnoreCase("OffProduct")) { + obj.put("PromoId", promotionList.get(k).getPromotion_Id()); + obj.put("Discounted_Rs", promotionList.get(k).getDiscounted_value()); + obj.put("Rate", promotionList.get(k).getProduct_rate()); + obj.put("ProductId", promotionList.get(k).getProduct_Id()); + obj.put("Quantity", promotionList.get(k).getQuantity()); + obj.put("PromoApplyiedOnProducts", ""); + + } else if (promotionList.get(k).getPromo_type().equalsIgnoreCase("Gift")) { + obj.put("PromoId", promotionList.get(k).getPromotion_Id()); + obj.put("Discounted_Rs", 0); + obj.put("Rate", 0); + obj.put("ProductId", promotionList.get(k).getProduct_Id()); + obj.put("Quantity", promotionList.get(k).getQuantity()); + obj.put("PromoApplyiedOnProducts", ""); + + } else if (promotionList.get(k).getPromo_type().equalsIgnoreCase("Product")) { + obj.put("PromoId", promotionList.get(k).getPromotion_Id()); + obj.put("Discounted_Rs", 0); + obj.put("Rate", 0); + obj.put("ProductId", promotionList.get(k).getProduct_Id()); + obj.put("Quantity", promotionList.get(k).getQuantity()); + obj.put("PromoApplyiedOnProducts", ""); + } else if (promotionList.get(k).getPromo_type().equalsIgnoreCase("WorthWithProduct")) { + applyedProducts = promotionList.get(k).getApplyiedproductList(); + if (!applyedProducts.isEmpty()) { + jsonArrayPromoApplyiedOnProductId = new JSONArray(); + for (int h = 0; h < applyedProducts.size(); h++) { + JSONObject obj7 = new JSONObject(); + obj7.put("MID", jcp_Object.getMID()); + obj7.put("BID", jcp_Object.getBID()); + obj7.put("UserId", consumerSalesList.get(consumerIndex).getStrUserId()); + obj7.put("TranId", consumerSalesList.get(consumerIndex).getUnique_code()); + obj7.put("PromoType", promotionList.get(k).getPromo_type()); + obj7.put("PromoId", applyedProducts.get(h).getPromotion_Id()); + obj7.put("PromoApplyiedOnProductId", applyedProducts.get(h).getProduct_Id()); + obj7.put("Rate", applyedProducts.get(h).getProduct_rate()); + obj7.put("MRP", applyedProducts.get(h).getMrp()); + obj7.put("EanCode", applyedProducts.get(h).getScan_ean_code_or_enterd_ean_code()); + obj7.put("QTY", applyedProducts.get(h).getQuantity()); + obj7.put("DISCOUNT", 0); + jsonArrayPromoApplyiedOnProductId.put(obj7); + } + } + obj.put("PromoId", promotionList.get(k).getPromotion_Id()); + obj.put("Discounted_Rs", promotionList.get(k).getDiscounted_value()); + obj.put("Rate", "0"); + obj.put("ProductId", 0); + obj.put("Quantity", 0); + if (!applyedProducts.isEmpty()) { + obj.put("PromoApplyiedOnProducts", jsonArrayPromoApplyiedOnProductId); + } else { + obj.put("PromoApplyiedOnProducts", ""); + } + } + ///adding promotion Data-------------- + consumerpromotionArray.put(obj); + } + } + + JSONObject jsonObject4 = null; + if (!childList.isEmpty()) { + jsonObject4 = new JSONObject(); + jsonObject4.put("Consumer_User_Info", consumerUserInfoArray); + jsonObject4.put("Consumer_Product_Sold", consumerGivenProductArray); + jsonObject4.put("Consumer_Applied_Promo", consumerpromotionArray); + } else { + jsonObject4 = new JSONObject(); + jsonObject4.put("Consumer_User_Info", consumerUserInfoArray); + jsonObject4.put("Consumer_Product_Sold", ""); + jsonObject4.put("Consumer_Applied_Promo", ""); + } + //test("promojsondata", jsonObject4.toString()); + complete_json_str = jsonObject4.toString(); + } + } else if (objectcurrent.getStock_type().equalsIgnoreCase(CommonString.CONSUMERRETURN)) { + db.open(); + ArrayList consumerreturnList = db.getsaleReturnHeaderData(jcp_Object.getVisitDate(), counter_id, username, true, true, objectcurrent.getTransaction_Id()); + if (!consumerreturnList.isEmpty()) { + int consumerIndex = 0; + complete_json_str = ""; + topUpArray = new JSONArray(); + key = "Consumer_Return_Data"; + db.open(); + jcp_Object = db.getBIDfromJCP(consumerreturnList.get(consumerIndex).getStrUserId(), counter_id); + JSONArray consumerReturnUserInfoArray = new JSONArray(); + JSONArray consumerReturnProductArray = new JSONArray(); + JSONArray replaceProductArray = new JSONArray(); + JSONObject obj = new JSONObject(); + obj.put("MID", jcp_Object.getMID()); + obj.put("BID", jcp_Object.getBID()); + obj.put("UserId", consumerreturnList.get(consumerIndex).getStrUserId()); + obj.put("Counter_Id", counter_id); + obj.put("VisiteDate", jcp_Object.getVisitDate()); + obj.put("TranId", consumerreturnList.get(consumerIndex).getUnique_code()); + obj.put("ConsumerName", consumerreturnList.get(consumerIndex).getCustomer_name()); + obj.put("BillNo", consumerreturnList.get(consumerIndex).getConsumer_return_bill_no()); + obj.put("MobileNo", consumerreturnList.get(consumerIndex).getMobile_no()); + obj.put("Gender", consumerreturnList.get(consumerIndex).getCustomer_gender()); + obj.put("KeyId", consumerreturnList.get(consumerIndex).getReccept_count()).toString(); + consumerReturnUserInfoArray.put(obj); + + db.open(); + ArrayList childList = db.getsalesReturnChildData(consumerreturnList.get(consumerIndex).getReccept_count(), jcp_Object.getVisitDate(), counter_id, username, true); + for (int k = 0; k < childList.size(); k++) { + obj = new JSONObject(); + obj.put("MID", jcp_Object.getMID()); + obj.put("BID", jcp_Object.getBID()); + obj.put("UserId", childList.get(k).getUserName()); + obj.put("Counter_Id", counter_id); + obj.put("TranId", consumerreturnList.get(consumerIndex).getUnique_code()); + obj.put("ProductId", childList.get(k).getProduct_Id()); + obj.put("Quantity", childList.get(k).getQuantity()); + obj.put("ProductMRP", childList.get(k).getProduct_rate()); + obj.put("EANCode", childList.get(k).getScan_ean_code_or_enterd_ean_code()); + obj.put("Reason_Id", childList.get(k).getCon_return_reason_Id()); + consumerReturnProductArray.put(obj); + + } + + db.open(); + ArrayList replaceProductList = db.getsalesReturnReplaceProduct(consumerreturnList.get(consumerIndex).getReccept_count(), jcp_Object.getVisitDate(), counter_id, username, true); + for (int k = 0; k < replaceProductList.size(); k++) { + obj = new JSONObject(); + obj.put("MID", jcp_Object.getMID()); + obj.put("BID", jcp_Object.getBID()); + obj.put("UserId", consumerreturnList.get(consumerIndex).getStrUserId()); + obj.put("Counter_Id", counter_id); + obj.put("TranId", consumerreturnList.get(consumerIndex).getUnique_code()); + obj.put("ProductId", replaceProductList.get(k).getProduct_Id()); + obj.put("Quantity", replaceProductList.get(k).getQuantity()); + obj.put("ProductMRP", replaceProductList.get(k).getProduct_rate()); + obj.put("EANCode", replaceProductList.get(k).getScan_ean_code_or_enterd_ean_code()); + replaceProductArray.put(obj); + + } + + + JSONObject jsonObject4 = new JSONObject(); + jsonObject4.put("Consumer_Return_User_Info", consumerReturnUserInfoArray); + jsonObject4.put("Consumer_Return_Product", consumerReturnProductArray); + jsonObject4.put("Consumer_Return_Replace_Product", replaceProductArray); + + complete_json_str = jsonObject4.toString(); + } + } else if (objectcurrent.getStock_type().equalsIgnoreCase(CommonString.LEAVE_MANAGEMENT)) { + db.open(); + T_LeaveRequest leaveRequestObject = db.getinserted_leave_request_data(counter_id, username, jcp_Object.getVisitDate(), objectcurrent.getTransaction_Id(), true); + if (leaveRequestObject.getTransId() != null && !leaveRequestObject.getTransId().equals("")) { + key = "RequestFor_Leave_Approval"; + complete_json_str = ""; + topUpArray = new JSONArray(); + db.open(); + JourneyPlan jcpfor_bid = db.getBIDfromJCP(leaveRequestObject.getUserId(), counter_id); + JSONObject obj = getJsonObject(jcpfor_bid, leaveRequestObject); + topUpArray.put(obj); + + complete_json_str = topUpArray.toString(); + } + + } else if (objectcurrent.getStock_type().equalsIgnoreCase(CommonString.BREAK_MANAGEMENT)) { + db.open(); + MasterBreak breakManagementObject = db.getBreakManagementforuploadList(counter_id, jcp_Object.getVisitDate(), username, objectcurrent.getTransaction_Id(), true); + if (breakManagementObject.getBreakId() != null && !breakManagementObject.getEndTym().equals("")) { + key = "Break_Management_Data"; + complete_json_str = ""; + topUpArray = new JSONArray(); + db.open(); + JourneyPlan jcpfor_bid = db.getBIDfromJCP(breakManagementObject.getUserId(), counter_id); + JSONObject obj = new JSONObject(); + obj.put("MID", jcpfor_bid.getMID()); + obj.put("BID", jcpfor_bid.getBID()); + obj.put("UserId", breakManagementObject.getUserId()); + obj.put("VisitDate", jcpfor_bid.getVisitDate()); + obj.put("TranId", breakManagementObject.getTransId()); + obj.put("BreakId", breakManagementObject.getBreakId().toString()); + obj.put("StartTym", convertTym(breakManagementObject.getStartTym())); + obj.put("EndTym", convertTym(breakManagementObject.getEndTym())); + obj.put("TotalDuration", breakManagementObject.getTotalDuration().toString()); + topUpArray.put(obj); + + complete_json_str = topUpArray.toString(); + } + } else if (objectcurrent.getStock_type().equalsIgnoreCase(CommonString.VISIBILITY)) { + db.open(); + ArrayList visibilityList = db.getVisibility_inserted_data(counter_id, jcp_Object.getVisitDate(), objectcurrent.getTransaction_Id(), true); + if (!visibilityList.isEmpty()) { + key = "VisibiliElementData"; + complete_json_str = ""; + topUpArray = new JSONArray(); + db.open(); + jcp_Object = db.getBIDfromJCP(null, counter_id); + for (int j = 0; j < visibilityList.size(); j++) { + JSONObject obj = new JSONObject(); + obj.put("MID", jcp_Object.getMID()); + obj.put("UserId", visibilityList.get(j).getUserId()); + obj.put("PosmId", visibilityList.get(j).getPosmId()); + obj.put("PosmTypeId", visibilityList.get(j).getPosmTypeId()); + obj.put("Counter_id", counter_id); + if (visibilityList.get(j).getPromotion_exists_state().equalsIgnoreCase("Yes")) { + obj.put("Promotion_Exists", "1"); + obj.put("Promo_Img", visibilityList.get(j).getPromotion_img()); + obj.put("PReason_Id", "0"); + } else { + obj.put("Promotion_Exists", "0"); + obj.put("Promo_Img", ""); + obj.put("PReason_Id", visibilityList.get(j).getPromotion_currect_ans_Id()); + } + + topUpArray.put(obj); + } + + complete_json_str = topUpArray.toString(); + } + } else if (objectcurrent.getStock_type().equalsIgnoreCase(CommonString.MAKEOVER_CAPTURE)) { + db.open(); + ArrayList memakeoverList = db.getMakeover(jcp_Object.getVisitDate(), counter_id, username, objectcurrent.getTransaction_Id(), true); + if (!memakeoverList.isEmpty()) { + key = "ME_Makeover_Capture"; + complete_json_str = ""; + topUpArray = new JSONArray(); + int consumerIndex = 0; + db.open(); + JourneyPlan jcp = db.getBIDfromJCP(memakeoverList.get(consumerIndex).getStrUserId(), counter_id); + JSONObject obj = getJsonObject(jcp, memakeoverList, consumerIndex); + + topUpArray.put(obj); + + complete_json_str = topUpArray.toString(); + } + } else if (objectcurrent.getStock_type().equalsIgnoreCase(CommonString.SKINGENIUS)) { + db.open(); + ArrayList memakeoverList = db.getskinGeniusData(jcp_Object.getVisitDate(), counter_id, username, objectcurrent.getTransaction_Id(), true); + if (!memakeoverList.isEmpty()) { + key = "Skin_Genius"; + complete_json_str = ""; + topUpArray = new JSONArray(); + int consumerIndex = 0; + db.open(); + JourneyPlan jcp = db.getBIDfromJCP(memakeoverList.get(consumerIndex).getStrUserId(), counter_id); + JSONObject obj = new JSONObject(); + obj.put("MID", jcp.getMID()); + obj.put("BID", jcp.getBID()); + obj.put("VisiteDate", jcp.getVisitDate()); + obj.put("UserId", memakeoverList.get(consumerIndex).getStrUserId()); + obj.put("TranId", memakeoverList.get(consumerIndex).getUnique_code()); + obj.put("SkinGeniusImg", memakeoverList.get(consumerIndex).getInvoice_img()); + topUpArray.put(obj); + complete_json_str = topUpArray.toString(); + } + } else if (objectcurrent.getStock_type().equalsIgnoreCase(CommonString.OPEN_SKINGENIUS)) { + db.open(); + ArrayList memakeoverList = db.getOpenskinGeniusData(jcp_Object.getVisitDate(), counter_id, username, objectcurrent.getTransaction_Id(), true); + if (!memakeoverList.isEmpty()) { + key = "Open_Skin_Genius_Count"; + complete_json_str = ""; + topUpArray = new JSONArray(); + int consumerIndex = 0; + db.open(); + JourneyPlan jcp = db.getBIDfromJCP(memakeoverList.get(consumerIndex).getStrUserId(), counter_id); + JSONObject obj = new JSONObject(); + obj.put("MID", jcp.getMID()); + obj.put("BID", jcp.getBID()); + obj.put("VisiteDate", memakeoverList.get(consumerIndex).getVisit_date()); + obj.put("UserId", memakeoverList.get(consumerIndex).getStrUserId()); + obj.put("TranId", memakeoverList.get(consumerIndex).getUnique_code()); + obj.put("OpenSkinGeniusCount", memakeoverList.get(consumerIndex).getMaybellineorskingenius_count()); + topUpArray.put(obj); + complete_json_str = topUpArray.toString(); + } + } else if (objectcurrent.getStock_type().equalsIgnoreCase(CommonString.OPEN_MAYBELLINE)) { + db.open(); + ArrayList memakeoverList = db.getOpenMaybellineData(jcp_Object.getVisitDate(), counter_id, username, objectcurrent.getTransaction_Id(), true); + if (!memakeoverList.isEmpty()) { + key = "Open_Maybelline_Count"; + complete_json_str = ""; + topUpArray = new JSONArray(); + int consumerIndex = 0; + db.open(); + JourneyPlan jcp = db.getBIDfromJCP(memakeoverList.get(consumerIndex).getStrUserId(), counter_id); + JSONObject obj = new JSONObject(); + obj.put("MID", jcp.getMID()); + obj.put("BID", jcp.getBID()); + obj.put("VisiteDate", jcp.getVisitDate()); + obj.put("UserId", memakeoverList.get(consumerIndex).getStrUserId()); + obj.put("TranId", memakeoverList.get(consumerIndex).getUnique_code()); + obj.put("OpenMaybellineCount", memakeoverList.get(consumerIndex).getMaybellineorskingenius_count()); + topUpArray.put(obj); + complete_json_str = topUpArray.toString(); + } + } else if (objectcurrent.getStock_type().equalsIgnoreCase(CommonString.COMP_OFFERS)) { + db.open(); + ArrayList compOffers = db.getInsertedCompOffers(visit_date, counter_id, objectcurrent.getTransaction_Id(), true); + if (compOffers.size() > 0) { + key = "CompOffers_TVA_New"; + complete_json_str = ""; + topUpArray = new JSONArray(); + Gson gson = new Gson(); + db.open(); + jcp_Object = db.getBIDfromJCP(null, counter_id); + for (int j = 0; j < compOffers.size(); j++) { + JSONObject obj = new JSONObject(); + obj.put("MID", jcp_Object.getMID()); + obj.put("Counter_id", counter_id); + obj.put("UserId", compOffers.get(j).get_userId()); + obj.put("TransId", objectcurrent.getTransaction_Id()); + + if (compOffers.get(j).getPresent_str().equals("1")) { + String baInfoJson = gson.toJson(compOffers.get(j).getBaTenureDetailList()); + JSONArray baListJsonArray = new JSONArray(baInfoJson); + for (int i = 0; i < baListJsonArray.length(); i++) { + JSONObject baObj = baListJsonArray.getJSONObject(i); + baObj.put("KeyID", compOffers.get(j).getKeyId()); + } + obj.put("Present", 1); + if (compOffers.get(j).getGwpAvailable().equalsIgnoreCase("1")) { + obj.put("GWP_Available", 1); + } else { + obj.put("GWP_Available", 0); + } + obj.put("GWP_Image", compOffers.get(j).getGwpImage()); + obj.put("KeyID", compOffers.get(j).getKeyId()); + obj.put("DataForMonth", compOffers.get(j).getDateOfMonth()); + obj.put("CompBrandId", compOffers.get(j).getCompetitionBrandId()); + obj.put("NuanceId", compOffers.get(j).getCompetitionNuanceId()); + obj.put("CompOfferId", compOffers.get(j).getPromoTypeId()); + obj.put("FromDate", compOffers.get(j).getFromDate()); + obj.put("ToDate", compOffers.get(j).getToDate()); + obj.put("CompBuyTypeId", compOffers.get(j).getBuyTypeId()); + obj.put("CompSetId", compOffers.get(j).getBuyTypeInputId()); + obj.put("CompGetId", compOffers.get(j).getGetTypeInputId()); + obj.put("SaleRange", compOffers.get(j).getSaleRange()); + obj.put("NoOfBa", compOffers.get(j).getNoOfBa()); + obj.put("NumOfCounter", compOffers.get(j).getCounter()); + obj.put("NewLaunchMrp", compOffers.get(j).getNewLaunchMrp()); + obj.put("PromoDetails", compOffers.get(j).getCompPromDetail()); + obj.put("CompOfferImg", compOffers.get(j).getCompOfferImg()); + obj.put("AvgTarget", compOffers.get(j).getAvgtarget()); + obj.put("AvgOfftake", compOffers.get(j).getAvgOfftake()); + obj.put("TvaPercentage", compOffers.get(j).getTvapercent()); + obj.put("BAListData", baListJsonArray); + } else { + JSONArray balistdata = new JSONArray(); + obj.put("KeyID", 0); + obj.put("Present", 0); + obj.put("DataForMonth", ""); + obj.put("CompBrandId", 0); + obj.put("NuanceId", 0); + obj.put("CompOfferId", 0); + obj.put("FromDate", ""); + obj.put("ToDate", ""); + obj.put("PromoDetails", ""); + obj.put("CompOfferImg", ""); + obj.put("CompBuyTypeId", 0); + obj.put("CompSetId", 0); + obj.put("CompGetId", 0); + obj.put("SaleRange", ""); + obj.put("GWP_Available", 0); + obj.put("GWP_Image", ""); + obj.put("NoOfBa", 0); + obj.put("NumOfCounter", 0); + obj.put("NewLaunchMrp", 0); + obj.put("AvgTarget", 0); + obj.put("AvgOfftake", 0); + obj.put("TvaPercentage", 0); + obj.put("BAListData", balistdata); + } + topUpArray.put(obj); + } + complete_json_str = topUpArray.toString(); + } + } + + if (!complete_json_str.isEmpty()) { + db.open(); + jcp_Object = db.getBIDfromJCP(null, counter_id); + JSONObject jsonObject = new JSONObject(); + jsonObject.put("MID", jcp_Object.getMID()); + jsonObject.put("Keys", key); + jsonObject.put("JsonData", complete_json_str); + jsonObject.put("UserId", username); + saleablejson_str = jsonObject.toString(); + //test("compjsondata", saleablejson_str); + } + } catch (JSONException e) { + e.fillInStackTrace(); + pd.dismiss(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INVALID_JSON); + } + + return saleablejson_str; + } + + private static @NonNull JSONObject getJsonObject(JourneyPlan jcp, ArrayList memakeoverList, int consumerIndex) throws JSONException { + JSONObject obj = new JSONObject(); + obj.put("MID", jcp.getMID()); + obj.put("BID", jcp.getBID()); + obj.put("VisiteDate", jcp.getVisitDate()); + obj.put("UserId", memakeoverList.get(consumerIndex).getStrUserId()); + obj.put("TranId", memakeoverList.get(consumerIndex).getUnique_code()); + obj.put("ConsumerName", memakeoverList.get(consumerIndex).getCustomer_name()); + obj.put("MobileNumber", memakeoverList.get(consumerIndex).getMobile_no()); + obj.put("EmailId", memakeoverList.get(consumerIndex).getConsumer_email_Id()); + obj.put("Age", memakeoverList.get(consumerIndex).getConsumer_age()); + obj.put("SkinType", memakeoverList.get(consumerIndex).getConsumer_skinType()); + obj.put("Look", memakeoverList.get(consumerIndex).getLook_creater_str()); + obj.put("Gender", memakeoverList.get(consumerIndex).getCustomer_gender()); + obj.put("BeforeMakeoverImg", memakeoverList.get(consumerIndex).getBefore_makeover_img()); + obj.put("AfterMakeoverImg", memakeoverList.get(consumerIndex).getAfter_makeover_img()); + obj.put("Feedback", memakeoverList.get(consumerIndex).getCst_feed_back_value()); + obj.put("TermConditions", memakeoverList.get(consumerIndex).getStr_termcondition()); + return obj; + } + + private static @NonNull JSONObject getJsonObject(JourneyPlan jcpfor_bid, T_LeaveRequest leaveRequestObject) throws JSONException { + JSONObject obj = new JSONObject(); + obj.put("MID", jcpfor_bid.getMID()); + obj.put("BID", jcpfor_bid.getBID()); + obj.put("UserId", leaveRequestObject.getUserId()); + obj.put("TranId", leaveRequestObject.getTransId()); + obj.put("Applied_Date", leaveRequestObject.getUpload_request_date()); + obj.put("From_Date", leaveRequestObject.getUpload_start_date_str()); + obj.put("End_Date", leaveRequestObject.getUpload_end_date_str()); + obj.put("Leave_Type", leaveRequestObject.getOne_day_leave_str()); + obj.put("Leave_TypeId", leaveRequestObject.getStr_leaveTypeId()); + obj.put("Reason", leaveRequestObject.getLeave_reason()); + return obj; + } + + private void UploadStockRecursive(final String status, final int startIndex, final int endIndex, final ArrayList stockList, final ArrayList masterfinalList, final int masterfinal_index, final ProgressDialog pd) { + try { + db.open(); + JourneyPlan jcp_Object = db.getBIDfromJCP(null, counter_Id); + JSONArray topUpArray = new JSONArray(); + String key = ""; + if (!stockList.isEmpty()) { + if (stockList.get(0).getStock_type().equalsIgnoreCase(CommonString.SALEABLE)) { + key = "SaleableFData"; + for (int j = startIndex; j < endIndex; j++) { + JSONObject obj = new JSONObject(); + obj.put("ProductId", stockList.get(j).getProductId()); + obj.put("MID", jcp_Object.getMID()); + obj.put("REASON_ID", stockList.get(j).getReasonId()); + obj.put("TranId", stockList.get(j).getTransaction_Id()); + obj.put("UserId", username); + obj.put("CounterId", counter_Id); + //header image + String img = stockList.get(j).getImagePath(); + if (img == null) { + img = ""; + } + + obj.put("Image", img); + ////for uploaded first time data if status is not null + int stk = stockList.get(j).getStock(); + if (stk == -1) { + stk = 0; + } + obj.put("STOCK", stk); + obj.put("Status", status); + topUpArray.put(obj); + } + + + } else if (stockList.get(0).getStock_type().equalsIgnoreCase(CommonString.TESTER)) { + key = "TesterFData"; + db.open(); + jcp_Object = db.getBIDfromJCP(null, counter_Id); + for (int j = startIndex; j < endIndex; j++) { + JSONObject obj = new JSONObject(); + obj.put("ProductId", stockList.get(j).getProductId()); + obj.put("MID", jcp_Object.getMID()); + obj.put("TranId", stockList.get(j).getTransaction_Id()); + obj.put("UserId", username); + obj.put("CounterId", counter_Id); + ////for uploaded first time data if status is not null + int stk = stockList.get(j).getStock(); + if (stk == -1) { + stk = 0; + } + + obj.put("STOCK", stk); + obj.put("Status", status); + topUpArray.put(obj); + } + + } else if (stockList.get(0).getStock_type().equalsIgnoreCase(CommonString.SAMPLE)) { + key = "SampleFData"; + db.open(); + jcp_Object = db.getBIDfromJCP(null, counter_Id); + for (int j = startIndex; j < endIndex; j++) { + JSONObject obj = new JSONObject(); + obj.put("ProductId", stockList.get(j).getProductId()); + obj.put("MID", jcp_Object.getMID()); + obj.put("TranId", stockList.get(j).getTransaction_Id()); + obj.put("UserId", username); + obj.put("CounterId", counter_Id); + ////for uploaded first time data if status is not null + int stk = stockList.get(j).getStock(); + if (stk == -1) { + stk = 0; + } + + obj.put("STOCK", stk); + obj.put("Status", status); + topUpArray.put(obj); + } + + } else if (stockList.get(0).getStock_type().equalsIgnoreCase(CommonString.GWP)) { + key = "GWPFData"; + db.open(); + jcp_Object = db.getBIDfromJCP(null, counter_Id); + for (int j = startIndex; j < endIndex; j++) { + JSONObject obj = new JSONObject(); + obj.put("ProductId", stockList.get(j).getProductId()); + obj.put("MID", jcp_Object.getMID()); + obj.put("TranId", stockList.get(j).getTransaction_Id()); + obj.put("UserId", username); + obj.put("CounterId", counter_Id); + ////for uploaded first time data if status is not null + int stk = stockList.get(j).getStock(); + if (stk == -1) { + stk = 0; + } + + obj.put("STOCK", stk); + obj.put("Status", status); + topUpArray.put(obj); + } + } + } + + db.open(); + jcp_Object = db.getBIDfromJCP(null, counter_Id); + JSONObject jsonObject = new JSONObject(); + jsonObject.put("MID", jcp_Object.getMID()); + jsonObject.put("Keys", key); + jsonObject.put("JsonData", topUpArray.toString()); + jsonObject.put("UserId", username); + + String jsonString = jsonObject.toString(); + OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build(); + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsonString); + Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build(); + PostApi api = adapter.create(PostApi.class); + Call call = api.getGeotag(jsonData); + call.enqueue(new Callback() { + @Override + public void onResponse(@NonNull Call call, @NonNull Response response) { + String data = null; + if (response.isSuccessful()) { + try { + assert response.body() != null; + data = response.body().get("UploadJsonResult").toString(); + if (data.isEmpty()) { + } else { + data = data.substring(1, data.length() - 1).replace("\\", ""); + if (data.equalsIgnoreCase(CommonString.KEY_SUCCESS)) { + if (endIndex < stockList.size()) { + int startIndex1 = endIndex; + int endIndex1 = 0; + if (startIndex1 + 200 < stockList.size()) { + endIndex1 = startIndex1 + 200; + } else { + endIndex1 = stockList.size(); + } + UploadStockRecursive(status, startIndex1, endIndex1, stockList, masterfinalList, masterfinal_index, pd); + } else { + ///-------------update status..........////---------- + db.open(); + update_upload_status(counter_Id, masterfinalList.get(masterfinal_index)); + //-------------------//upload recursive.........method.............. + final int[] finalJsonIndex = {masterfinal_index}; + finalJsonIndex[0]++; + if (finalJsonIndex[0] != masterfinalList.size()) { + handleuploaddata_withcase(masterfinalList, finalJsonIndex[0], pd); + } else { + //////show masage......data upload .... success...... + pd.dismiss(); + if (!CommonFunctions.checkincomplete_upload_data(visit_date, counter_Id, db, true)) { + ProgressDialog pd = new ProgressDialog(context); + pd.setCancelable(false); + pd.setMessage("Uploading Data" + "(" + "0/" + ")"); + pd.show(); + CommonUploadwithrecursive(db, true, pd); + } else { + ///finish activity........ + pd.dismiss(); + calling_method(); + } + } + } + } else { + pd.dismiss(); + AlertandMessages.showAlert((Activity) context, "Server Not Responding. Please upload again", false); + } + } + } catch (Exception e) { + db.open(); + pd.dismiss(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE + " - " + e.toString() + " - Please Try Again"); + } + } else { + pd.dismiss(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_NO_RESPONSE_SERVER + " - Please Try Again"); + } + } + + @Override + public void onFailure(@NonNull Call call, @NonNull Throwable t) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE + " - Please Try Again"); + } + }); + } catch (JSONException e) { + e.fillInStackTrace(); + pd.dismiss(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INVALID_JSON + " - Please Try Again"); + } + } + + + public void upload_recursive_Data(String jsondata, final int index, final ArrayList final_list, final ProgressDialog pd) { + try { + final int[] finalJsonIndex = {index}; + final OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build(); + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsondata); + Retrofit adapter; + adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build(); + PostApi api = adapter.create(PostApi.class); + Call call = api.getGeotag(jsonData); + call.enqueue(new Callback() { + @Override + public void onResponse(@NonNull Call call, @NonNull Response response) { + String data = null; + if (response.isSuccessful()) { + try { + assert response.body() != null; + data = response.body().get("UploadJsonResult").toString(); + if (data.equals("")) { + } else { + data = data.substring(1, data.length() - 1).replace("\\", ""); + if (data.equalsIgnoreCase(CommonString.KEY_SUCCESS)) { + db.open(); + update_upload_status(counter_Id, final_list.get(index)); + finalJsonIndex[0]++; + if (finalJsonIndex[0] != final_list.size()) { + handleuploaddata_withcase(final_list, finalJsonIndex[0], pd); + } else { + //////show masage......data upload .... success...... + pd.dismiss(); + if (!CommonFunctions.checkincomplete_upload_data(visit_date, counter_Id, db, true)) { + ProgressDialog pd = new ProgressDialog(context); + pd.setCancelable(false); + pd.setMessage("Uploading Data" + "(" + "0/" + ")"); + pd.show(); + CommonUploadwithrecursive(db, true, pd); + } else { + ////////////finish activty............ + pd.dismiss(); + calling_method(); + } + } + } else { + pd.dismiss(); + AlertandMessages.showAlert((Activity) context, "Server Not Responding. Please upload again", false); + } + } + } catch (Exception e) { + e.fillInStackTrace(); + pd.dismiss(); + } + } else { + pd.dismiss(); + AlertandMessages.showAlert((Activity) context, "Server Not Responding. Please upload again", false); + } + } + + @Override + public void onFailure(@NonNull Call call, @NonNull Throwable t) { + pd.dismiss(); + AlertandMessages.showAlert((Activity) context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE + " Please upload again", false); + } + }); + + } catch (Exception e) { + pd.dismiss(); + e.fillInStackTrace(); + } + } + + + private void update_upload_status(String counter_Id, ProductMaster currentobj) { + if (currentobj != null) { + /////............update status..................................... + db.open(); + db.updateMasterTransactionDataStatus(currentobj.getTransaction_Id()); + if (currentobj.getStock_type().equalsIgnoreCase(CommonString.RETURNTO_DB)) { + db.open(); + db.updatereturntodistributor(counter_Id, currentobj.getTransaction_Id()); + } else if (currentobj.getStock_type().equalsIgnoreCase(CommonString.INWARD_DMS) || currentobj.getStock_type().equalsIgnoreCase(CommonString.INWARD_DMS_NEW_SKU)) { + db.open(); + db.updateinwarddms(counter_Id, currentobj.getTransaction_Id()); + } else if (currentobj.getStock_type().equalsIgnoreCase(CommonString.MANUALINWARD_DMS) || currentobj.getStock_type().equalsIgnoreCase(CommonString.MANUALINWARD_DMS_NEWPRODUCT)) { + db.open(); + db.updatemanualinward(counter_Id, currentobj.getTransaction_Id()); + } else if (currentobj.getStock_type().equalsIgnoreCase(CommonString.CONSUMERSALE)) { + db.open(); + db.update_SalesTRacking(counter_Id, currentobj.getTransaction_Id()); + } else if (currentobj.getStock_type().equalsIgnoreCase(CommonString.CONSUMERRETURN)) { + db.open(); + db.update_ConsumersReturn(counter_Id, currentobj.getTransaction_Id()); + } else if (currentobj.getStock_type().equalsIgnoreCase(CommonString.LEAVE_MANAGEMENT)) { + db.open(); + db.update_leave_management_status(counter_Id, visit_date, username, currentobj.getTransaction_Id(), true); + } else if (currentobj.getStock_type().equalsIgnoreCase(CommonString.BREAK_MANAGEMENT)) { + db.open(); + db.update_break_management_status(counter_Id, visit_date, username, currentobj.getTransaction_Id(), true); + } else if (currentobj.getStock_type().equalsIgnoreCase(CommonString.VISIBILITY)) { + db.open(); + db.update_visibility(counter_Id, username, currentobj.getTransaction_Id(), CommonString.Table_visibilisty); + db.updateStockTransactionDataStatus(currentobj.getTransaction_Id()); + } else if (currentobj.getStock_type().equalsIgnoreCase(CommonString.MAKEOVER_CAPTURE)) { + db.open(); + db.update_makeover(counter_Id, username, currentobj.getTransaction_Id(), true); + } else if (currentobj.getStock_type().equalsIgnoreCase(CommonString.SKINGENIUS)) { + db.open(); + db.update_skinGenius_Category(counter_Id, username, currentobj.getTransaction_Id(), CommonString.Table_Skin_Genius_Table); + } else if (currentobj.getStock_type().equalsIgnoreCase(CommonString.OPEN_SKINGENIUS)) { + db.open(); + db.update_skinGenius_Category(counter_Id, username, currentobj.getTransaction_Id(), CommonString.Table_Open_Skin_Genius_Table); + } else if (currentobj.getStock_type().equalsIgnoreCase(CommonString.OPEN_MAYBELLINE)) { + db.open(); + db.update_skinGenius_Category(counter_Id, username, currentobj.getTransaction_Id(), CommonString.Table_Open_Maybelline_Table); + } else if (currentobj.getStock_type().equalsIgnoreCase(CommonString.COMP_OFFERS)) { + db.open(); + db.update_visibility(counter_Id, username, currentobj.getTransaction_Id(), CommonString.COMP_OFFERS); + db.updateStockTransactionDataStatus(currentobj.getTransaction_Id()); + } else { + db.open(); + db.updateStockTransactionDataStatus(currentobj.getTransaction_Id()); + } + } + } + + @SuppressLint("NonConstantResourceId") + @Override + public void onClick(View view) { + + if (view.getId() == R.id.img_manual_dataupload) { + if (CommonFunctions.checkNetIsAvailable(context)) { + masterList = db.getmasterTransaction(visit_date, counter_Id, true); + if (masterList.size() > 0) { + clicked_flag = true; + pd = new ProgressDialog(context); + pd.setCancelable(false); + pd.setMessage("Uploading Data" + "(" + "0/" + ")"); + pd.show(); + handleuploaddata_withcase(masterList, 0, pd); + } else if (!CommonFunctions.checkincomplete_upload_data(visit_date, counter_Id, db, true)) { + pd = new ProgressDialog(context); + pd.setCancelable(false); + pd.setMessage("Uploading Data" + "(" + "0/" + ")"); + pd.show(); + CommonUploadwithrecursive(db, true, pd); + } else { + AlertandMessages.showToastMsg(context, "No data for upload"); + } + } else { + AlertandMessages.showToastMsg(context, getString(R.string.nonetwork)); + } + + + } else if (view.getId() == R.id.img_manual_imageupload) { + if (CommonFunctions.checkNetIsAvailable(context)) { + upload_imagewithfolder(); + } else { + AlertandMessages.showToastMsg(context, getString(R.string.nonetwork)); + } + + } + } + + + private void upload_imagewithfolder() { + try { + File f = new File(CommonString.getImagesFolder(context)); + ArrayList finalList = new ArrayList<>(); + if (!getFileNames(f.listFiles()).isEmpty()) { + for (int k = 0; k < getFileNames(f.listFiles()).size(); k++) { + if (!db.ischeck_uploaded_image(visit_date, getFileNames(f.listFiles()).get(k))) { + finalList.add(getFileNames(f.listFiles()).get(k)); + } + } + } + if (!finalList.isEmpty()) { + clicked_flag = true; + pd = new ProgressDialog(context); + pd.setCancelable(false); + pd.setMessage("Uploading Images"); + pd.show(); + totalFiles = finalList.size(); + uploadedFiles = 0; + UploadImageRecursive(pd); + } else { + AlertandMessages.showToastMsg(context, "No images for upload"); + } + } catch (Exception e) { + e.fillInStackTrace(); + } + } + + + public void UploadImageRecursive(final ProgressDialog pd) { + try { + final int[] uploadedFiles = {0}; + final int[] statusforimage = {0}; + statusforimage[0] = 0; + String filename = null, foldername = null; + File f = new File(CommonString.getImagesFolder(context)); + ArrayList finalList = new ArrayList<>(); + if (!getFileNames(f.listFiles()).isEmpty()) { + for (int k = 0; k < getFileNames(f.listFiles()).size(); k++) { + if (!db.ischeck_uploaded_image(visit_date, getFileNames(f.listFiles()).get(k))) { + finalList.add(getFileNames(f.listFiles()).get(k)); + } + } + } + + if (!finalList.isEmpty()) { + filename = ""; + for (int i = 0; i < finalList.size(); i++) { + pd.setMessage("Uploading images" + "(" + uploadedFiles[0] + "/" + totalFiles + ")"); + if (new File(CommonString.getImagesFolder(context) + finalList.get(i)).exists()) { + if (finalList.get(i).contains("_Counter_Selfie_img_")) { + foldername = "BACoverageImages"; + } else if (finalList.get(i).contains("_cp_img_one_") || finalList.get(i).contains("_cp_img_two_")) { + foldername = "CounterProfileImages"; + } else if (finalList.get(i).contains("_counter_img_one_") || finalList.get(i).contains("_counter_img_two_")) { + foldername = "CounterImages"; + } else if (finalList.get(i).contains("_ba_AuditPic_") || finalList.get(i).contains("_ba_profile_img_")) { + foldername = "BAProfileImages"; + } else if (finalList.get(i).contains("_Damaged_stock_img_") || finalList.get(i).contains("_Damage_header_img_")) { + foldername = "DamageStockImages"; + } else if (finalList.get(i).contains("_groomed_img_mrng_") || finalList.get(i).contains("_groomed_img_noon_") || finalList.get(i).contains("_groomed_img_evning_")) { + foldername = "GroomingImages"; + } else if (finalList.get(i).contains("_stock_check_img_") || finalList.get(i).contains("_tester_stock_img_") || finalList.get(i).contains("_suggested_stk_img") || finalList.get(i).contains("_Sample_stock_img")) { + foldername = "SaleableStockImages"; + } else if (finalList.get(i).contains("_visibility_img_")) { + foldername = "VisibilityImages"; + } else if (finalList.get(i).contains("_ConsumerSimg_")) { + foldername = "ConsumerInteractionImages"; + } else if (finalList.get(i).contains("_QuizPic-")) { + foldername = "MEAuditImages"; + } else if (finalList.get(i).contains("_before_makeo_img_") || finalList.get(i).contains("_after_makeo_img_")) { + foldername = "MeMakeoverImages"; + } else if (finalList.get(i).contains("SurveyPic-")) { + foldername = "SurveyImages"; + } else if (finalList.get(i).contains("_invoiceimg_")) { + foldername = "ConsumerReturnImages"; + } else if (finalList.get(i).contains("_minwordsimg_")) { + foldername = "InwardImages"; + } else if (finalList.get(i).contains("-SkinGenius-")) { + foldername = "SkinGeniusImages"; + } else if (finalList.get(i).contains("-CompOfferImg-") || finalList.get(i).contains("-Gwp_CompOfferImg-")) { + foldername = "CompetitionOffersImages"; + } else if (finalList.get(i).contains("_GeoTag-")) { + foldername = "GeoTagImages"; + } else { + foldername = "BulkUpload"; + } + + filename = finalList.get(i); + } + break; + } + + File originalFile = new File(CommonString.getImagesFolder(context) + filename); + File finalFile = saveBitmapToFile(originalFile); + if (finalFile == null) { + finalFile = originalFile; + } + + String date = visit_date.replace("/", ""); + + com.squareup.okhttp.OkHttpClient okHttpClient = new com.squareup.okhttp.OkHttpClient(); + okHttpClient.setConnectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS); + okHttpClient.setWriteTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS); + okHttpClient.setReadTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS); + com.squareup.okhttp.RequestBody photo = com.squareup.okhttp.RequestBody.create(com.squareup + .okhttp.MediaType.parse("application/octet-stream"), finalFile); + com.squareup.okhttp.RequestBody body1 = new MultipartBuilder().type(MultipartBuilder.FORM).addFormDataPart("file", + finalFile.getName(), photo).addFormDataPart("FolderName", foldername).addFormDataPart("Path", date).build(); + + retrofit.Retrofit adapter = new retrofit.Retrofit.Builder().baseUrl(CommonString.URLGORIMAG).client(okHttpClient) + .addConverterFactory(new StringConverterFactory()).build(); + PostApiForUpload api = adapter.create(PostApiForUpload.class); + retrofit.Call call = api.getUploadImageRetrofitOne(body1); + final File finalFile1 = finalFile; + final String finalFilename = filename; + call.enqueue(new retrofit.Callback() { + @Override + public void onResponse(retrofit.Response response) { + try { + if (response.code() == 200 && response.message().equalsIgnoreCase("OK") && response.isSuccess() && response.body().contains("Success")) { + if (finalFilename.contains("_counter_img_two_") || finalFilename.contains("_counter_img_one_") || finalFilename.contains("_cp_img_one_") || finalFilename.contains("_cp_img_two_") || finalFilename.contains("_groomed_img_mrng_") || finalFilename.contains("_groomed_img_noon_") || finalFilename.contains("_groomed_img_evning_")) { + db.open(); + db.insert_temp_image(finalFilename, visit_date); + } else { + finalFile1.delete(); + } + + statusforimage[0] = 1; + uploadedFiles[0]++; + } else { + statusforimage[0] = 0; + } + if (statusforimage[0] == 0) { + pd.dismiss(); + AlertandMessages.showAlertlogin((Activity) context, "Image not uploaded.Please try again." + "\n" + uploadedFiles + " images uploaded out of " + totalFiles); + + } else { + if (totalFiles == uploadedFiles[0]) { + pd.dismiss(); + AlertandMessages.showAlertlogin((Activity) context, "All images upload successfully"); + + } else { + UploadImageRecursive(pd); + } + } + } catch (Exception e) { + e.fillInStackTrace(); + statusforimage[0] = -1; + pd.dismiss(); + AlertandMessages.showAlertlogin((Activity) context, "Image not uploaded.Please try again." + "\n" + uploadedFiles + " images uploaded out of " + totalFiles); + + } catch (OutOfMemoryError error) { + statusforimage[0] = -1; + error.fillInStackTrace(); + pd.dismiss(); + AlertandMessages.showAlertlogin((Activity) context, "Image not uploaded.Please try again." + "\n" + uploadedFiles + " images uploaded out of " + totalFiles); + } + } + + @Override + public void onFailure(Throwable t) { + if (t instanceof IOException || t instanceof SocketTimeoutException || t instanceof SocketException) { + statusforimage[0] = -1; + pd.dismiss(); + AlertandMessages.showAlertlogin((Activity) context, "Image not uploaded.Please try again." + "\n" + uploadedFiles + " images uploaded out of " + totalFiles); + + } + } + }); + } + } catch (JsonSyntaxException e) { + pd.dismiss(); + e.fillInStackTrace(); + AlertandMessages.showAlertlogin((Activity) context, "Image not uploaded.Please try again." + "\n" + uploadedFiles + " images uploaded out of " + totalFiles); + } catch (Exception e) { + pd.dismiss(); + e.fillInStackTrace(); + AlertandMessages.showAlertlogin((Activity) context, "Image not uploaded.Please try again." + "\n" + uploadedFiles + " images uploaded out of " + totalFiles); + + } + } + + public void CommonUploadwithrecursive(Lorealba_Database db, boolean previous_date, ProgressDialog pd) { + pd.setMessage("Uploading Data"); + db.open(); + baProfile_ImageList = db.getBaProfileListData(visit_date, counter_Id, previous_date); + counterprofile_imgList = db.getCounterProfileListData(visit_date, counter_Id, previous_date); + meQuizList = db.getme_quiz_from(visit_date, counter_Id, previous_date); + masterRetailExcellenceArrayList = db.getRetailExcellence_from(visit_date, counter_Id, previous_date); + productMasterArrayList = db.getProductMasterMeSale_from(visit_date, counter_Id, previous_date); + groomingList = db.getgroomingdata(counter_Id, visit_date, previous_date); + db.open(); + counterList = db.getba_counterimgList(counter_Id, visit_date, previous_date); + if (baProfile_ImageList.size() > 0) { + UploadBaProfile(pd, db, baProfile_ImageList, 0); + } else if (counterprofile_imgList.size() > 0) { + UploadCounterProfile(pd, db, counterprofile_imgList, 0); + } else if (meQuizList.size() > 0) { + UploadMeQuiz(pd, db, meQuizList, 0); + } else if (groomingList.size() > 0) { + UploadGrooming(pd, db, groomingList, 0); + } else if (counterList.size() > 0) { + UploadCounter(pd, db, counterList, 0); + } else if (masterRetailExcellenceArrayList.size() > 0) { + UploadRetailExcellence(pd, db, masterRetailExcellenceArrayList, 0); + } else if (productMasterArrayList.size() > 0) { + UploadMeSaleData(pd, db, productMasterArrayList, 0); + } + } + + + private void UploadBaProfile(ProgressDialog loading, Lorealba_Database db, ArrayList baProfile_ImageList, int consumerIndex) { + try { + JSONArray topUpArray = new JSONArray(); + JSONArray storeDetail = new JSONArray(); + db.open(); + ArrayList ba_profile_auditList = db.getAfterSaveAuditQuestionAnswerData(baProfile_ImageList.get(consumerIndex).getUserId(), null); + if (ba_profile_auditList.size() > 0) { + for (int j = 0; j < ba_profile_auditList.size(); j++) { + JSONObject obj = new JSONObject(); + obj.put("Category_Id", ba_profile_auditList.get(j).getCATEGORY_ID()); + obj.put("Question_Id", ba_profile_auditList.get(j).getQUESTION_ID()); + obj.put("Question", ba_profile_auditList.get(j).getQUESTION()); + obj.put("Answer_type", ba_profile_auditList.get(j).getANSWER_TYPE()); + obj.put("Answer_Id", ba_profile_auditList.get(j).getANSWER_ID()); + obj.put("Answer", ba_profile_auditList.get(j).getANSWER()); + obj.put("Visit_Date", baProfile_ImageList.get(consumerIndex).getViisitDate()); + db.open(); + obj.put("MID", db.getBIDfromJCP(baProfile_ImageList.get(consumerIndex).getUserId(), counter_Id).getMID()); + obj.put("UserId", baProfile_ImageList.get(consumerIndex).getUserId()); + obj.put("Counter_id", counter_Id); + topUpArray.put(obj); + } + } + + JSONObject jsonObject = new JSONObject(); + jsonObject.put("Address", baProfile_ImageList.get(consumerIndex).getAddress()); + jsonObject.put("Dob", baProfile_ImageList.get(consumerIndex).getDob()); + jsonObject.put("Mobile_no", baProfile_ImageList.get(consumerIndex).getMobile()); + jsonObject.put("Email_Address", baProfile_ImageList.get(consumerIndex).getEmail()); + jsonObject.put("Instagram_Address", baProfile_ImageList.get(consumerIndex).getInstragramAddress()); + jsonObject.put("Profile_pic", baProfile_ImageList.get(consumerIndex).getProfilePic()); + jsonObject.put("Location", baProfile_ImageList.get(consumerIndex).getLocation()); + jsonObject.put("Landmark", baProfile_ImageList.get(consumerIndex).getLandmark()); + db.open(); + jsonObject.put("MID", db.getBIDfromJCP(baProfile_ImageList.get(consumerIndex).getUserId(), counter_Id).getMID()); + jsonObject.put("UserId", baProfile_ImageList.get(consumerIndex).getUserId()); + jsonObject.put("Counter_id", counter_Id); + if (ba_profile_auditList.size() > 0) { + jsonObject.put("BA_PROFILE_DATA", topUpArray); + } else { + jsonObject.put("BA_PROFILE_DATA", ""); + } + storeDetail.put(jsonObject); + + JSONObject jsonFinalObject = new JSONObject(); + db.open(); + jsonFinalObject.put("MID", db.getBIDfromJCP(baProfile_ImageList.get(consumerIndex).getUserId(), counter_Id).getMID()); + jsonFinalObject.put("Keys", "BaProfileData"); + jsonFinalObject.put("JsonData", storeDetail.toString()); + jsonFinalObject.put("UserId", baProfile_ImageList.get(consumerIndex).getUserId()); + upload_BaProfilewithaudit(jsonFinalObject.toString(), loading, baProfile_ImageList.get(consumerIndex), consumerIndex); + } catch (JSONException e) { + e.fillInStackTrace(); + } + } + + public void upload_BaProfilewithaudit(String jsondata, final ProgressDialog loading, final MasterProfile object, final int index) { + try { + final int[] finalJsonIndex = {index}; + final OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build(); + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsondata); + Retrofit adapter; + adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build(); + PostApi api = adapter.create(PostApi.class); + Call call = api.getGeotag(jsonData); + call.enqueue(new Callback() { + @Override + public void onResponse(@NonNull Call call, @NonNull Response response) { + assert response.body() != null; + String responseBody = response.body().get("UploadJsonResult").toString(); + String data = null; + if (response.isSuccessful()) { + try { + data = response.body().get("UploadJsonResult").toString(); + if (data.equals("")) { + } else { + data = data.substring(1, data.length() - 1).replace("\\", ""); + if (data.equalsIgnoreCase(CommonString.KEY_SUCCESS)) { + db.open(); + db.updateBaProfileStatus(object.getUserId(), object.getViisitDate(), CommonString.KEY_Y); + finalJsonIndex[0]++; + if (finalJsonIndex[0] != baProfile_ImageList.size()) { + UploadBaProfile(loading, db, baProfile_ImageList, finalJsonIndex[0]); + } else if (counterprofile_imgList.size() > 0) { + UploadCounterProfile(loading, db, counterprofile_imgList, 0); + } else if (meQuizList.size() > 0) { + UploadMeQuiz(loading, db, meQuizList, 0); + } else if (groomingList.size() > 0) { + UploadGrooming(loading, db, groomingList, 0); + } else if (counterList.size() > 0) { + UploadCounter(loading, db, counterList, 0); + } else { + ///finish activity + loading.dismiss(); + calling_method(); + + } + } else { + AlertandMessages.showAlert((Activity) context, "Server Not Responding,(Ba Profile). Please LogOut Again", false); + } + } + } catch (Exception e) { + e.fillInStackTrace(); + loading.dismiss(); + } + } + } + + @Override + public void onFailure(@NonNull Call call, @NonNull Throwable t) { + loading.dismiss(); + AlertandMessages.showAlert((Activity) context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE + " Please LogOut Again", false); + } + }); + } catch (Exception e) { + loading.dismiss(); + e.fillInStackTrace(); + } + } + + private void UploadCounterProfile(ProgressDialog loading, Lorealba_Database db, ArrayList counterimgList, int consumerIndex) { + try { + JSONArray storeDetail = new JSONArray(); + JSONObject jsonObject; + if (counterimgList.size() > 0) { + jsonObject = new JSONObject(); + db.open(); + jsonObject.put("MID", db.getBIDfromJCP(counterimgList.get(consumerIndex).getUserId(), counter_Id).getMID()); + jsonObject.put("UserId", counterimgList.get(consumerIndex).getUserId()); + jsonObject.put("ProfileImage1", counterimgList.get(consumerIndex).getProfileImage1()); + jsonObject.put("ProfileImage2", counterimgList.get(consumerIndex).getProfileImage2()); + jsonObject.put("Counterlength", counterimgList.get(consumerIndex).getCounterlength()); + jsonObject.put("Counterwidth", counterimgList.get(consumerIndex).getCounterwidth()); + jsonObject.put("SetupDate", counterimgList.get(consumerIndex).getSetupDate()); + jsonObject.put("Visit_Date", counterimgList.get(consumerIndex).getVisitDate()); + jsonObject.put("Counter_id", counter_Id); + storeDetail.put(jsonObject); + } + + jsonObject = new JSONObject(); + db.open(); + jsonObject.put("MID", db.getBIDfromJCP(counterimgList.get(consumerIndex).getUserId(), counter_Id).getMID()); + jsonObject.put("Keys", "ConterProfileData"); + jsonObject.put("JsonData", storeDetail.toString()); + jsonObject.put("UserId", counterimgList.get(consumerIndex).getUserId()); + upload_CounterProfile(jsonObject.toString(), loading, db, counterimgList.get(consumerIndex), consumerIndex); + + } catch (JSONException e) { + e.fillInStackTrace(); + } + } + + public void upload_CounterProfile(String jsondata, final ProgressDialog loading, final Lorealba_Database db, final JourneyPlan object, final int index) { + try { + final int[] finalJsonIndex = {index}; + final OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build(); + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsondata); + Retrofit adapter; + adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build(); + PostApi api = adapter.create(PostApi.class); + Call call = api.getGeotag(jsonData); + call.enqueue(new Callback() { + @Override + public void onResponse(@NonNull Call call, @NonNull Response response) { + String data = null; + if (response.isSuccessful()) { + try { + assert response.body() != null; + data = response.body().get("UploadJsonResult").toString(); + if (data.equals("")) { + } else { + data = data.substring(1, data.length() - 1).replace("\\", ""); + if (data.equalsIgnoreCase(CommonString.KEY_SUCCESS)) { + db.open(); + db.updateCounterProfileStatus(object.getUserId(), object.getVisitDate(), CommonString.KEY_Y); + finalJsonIndex[0]++; + if (finalJsonIndex[0] != counterprofile_imgList.size()) { + UploadCounterProfile(loading, db, counterprofile_imgList, finalJsonIndex[0]); + } else if (meQuizList.size() > 0) { + UploadMeQuiz(loading, db, meQuizList, 0); + } else if (groomingList.size() > 0) { + UploadGrooming(loading, db, groomingList, 0); + } else if (counterList.size() > 0) { + UploadCounter(loading, db, counterList, 0); + } else { + ///finish activity.... + loading.dismiss(); + calling_method(); + } + } else { + loading.dismiss(); + AlertandMessages.showAlert((Activity) context, "Server Not Responding,(Counter Profile). Please LogOut Again", false); + } + } + } catch (Exception e) { + e.fillInStackTrace(); + loading.dismiss(); + } + } + } + + @Override + public void onFailure(@NonNull Call call, @NonNull Throwable t) { + AlertandMessages.showAlert((Activity) context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE + " Please LogOut Again", false); + loading.dismiss(); + } + }); + + } catch (Exception e) { + e.fillInStackTrace(); + loading.dismiss(); + } + } + + private void UploadMeQuiz(ProgressDialog loading, Lorealba_Database db, ArrayList me_quizList, int consumerIndex) { + try { + if (me_quizList.size() > 0) { + ArrayList specific_meQuizList = db.getme_quiz_from_database(null, me_quizList.get(consumerIndex).getUser_Id(), visit_date, counter_Id, null); + if (specific_meQuizList.size() > 0) { + db.open(); + JourneyPlan jcp_Object = db.getBIDfromJCP(me_quizList.get(consumerIndex).getUser_Id(), counter_Id); + JSONArray consumerUserInfoArray = new JSONArray(); + for (int k = 0; k < me_quizList.size(); k++) { + JSONObject obj = new JSONObject(); + obj.put("MID", jcp_Object.getMID()); + obj.put("BID", jcp_Object.getBID()); + obj.put("VisiteDate", me_quizList.get(consumerIndex).getVisit_date()); + obj.put("UserId", specific_meQuizList.get(k).getUser_Id()); + obj.put("QuizId", specific_meQuizList.get(k).getQuizId()); + obj.put("Question_Id", specific_meQuizList.get(k).getQuestionId()); + obj.put("Question_Type", specific_meQuizList.get(k).getQuestionType()); + JSONArray compArraymult = new JSONArray(); + JSONObject objmultians = new JSONObject(); + if (specific_meQuizList.get(k).getQuestionType().equalsIgnoreCase("List Single Choice")) { + objmultians.put("Answer", specific_meQuizList.get(k).getAnswer()); + objmultians.put("Answer_Id", specific_meQuizList.get(k).getAnswerId()); + objmultians.put("Answer_Image", specific_meQuizList.get(k).getStr_audit_img()); + compArraymult.put(objmultians); + } else if (!specific_meQuizList.get(k).getQuestionType().equalsIgnoreCase("List Multiple Choice")) { + objmultians.put("Answer", specific_meQuizList.get(k).getAnswer()); + objmultians.put("Answer_Id", 0); + objmultians.put("Answer_Image", ""); + compArraymult.put(objmultians); + } else { + db.open(); + ArrayList multiansList = db.getquiz_answer(specific_meQuizList.get(k).getKeyId()); + if (multiansList.size() > 0) { + for (int j2 = 0; j2 < multiansList.size(); j2++) { + objmultians = new JSONObject(); + objmultians.put("Answer", multiansList.get(j2).getAnswer()); + objmultians.put("Answer_Id", multiansList.get(j2).getAnswerId()); + objmultians.put("Answer_Image", ""); + compArraymult.put(objmultians); + } + } + } + obj.put("AnsList", compArraymult); + consumerUserInfoArray.put(obj); + } + + JSONObject jsonObject = new JSONObject(); + jsonObject.put("MID", jcp_Object.getMID()); + jsonObject.put("Keys", "ME_Quiz_Data"); + jsonObject.put("JsonData", consumerUserInfoArray.toString()); + jsonObject.put("UserId", me_quizList.get(consumerIndex).getUser_Id().toLowerCase()); + upload_me_Quiz(jsonObject.toString(), loading, db, me_quizList.get(consumerIndex), consumerIndex); + } + + } + + } catch (JSONException e) { + e.fillInStackTrace(); + } + } + + private void UploadRetailExcellence(ProgressDialog loading, Lorealba_Database db, ArrayList masterRetailExcellenceArrayList, int consumerIndex) { + try { + if (masterRetailExcellenceArrayList.size() > 0) { + ArrayList masterRetailExcellence = db.getRetailExcellencedata(null, masterRetailExcellenceArrayList.get(consumerIndex).getUser_Id(), visit_date, counter_Id); + if (masterRetailExcellence.size() > 0) { + db.open(); + JourneyPlan jcp_Object = db.getBIDfromJCP(masterRetailExcellence.get(consumerIndex).getUser_Id(), counter_Id); + JSONArray consumerUserInfoArray = new JSONArray(); + for (int k = 0; k < masterRetailExcellence.size(); k++) { + JSONObject obj = new JSONObject(); + obj.put("MID", jcp_Object.getMID()); + obj.put("BID", jcp_Object.getBID()); + obj.put("UserId", username.toLowerCase()); + obj.put("VisiteDate", visit_date); + obj.put("ItemCategoryId", masterRetailExcellence.get(k).getItemCatId()); + obj.put("ItemId", masterRetailExcellence.get(k).getItemId()); + if (masterRetailExcellence.get(k).getAnswer().equalsIgnoreCase("Yes")) { + obj.put("Available", 1); + } else { + obj.put("Available", 0); + } + consumerUserInfoArray.put(obj); + } + JSONObject jsonObject = new JSONObject(); + jsonObject.put("MID", jcp_Object.getMID()); + jsonObject.put("Keys", "Retail_Excellence_Data"); + jsonObject.put("JsonData", consumerUserInfoArray.toString()); + jsonObject.put("UserId", username.toLowerCase()); + // upload_Retail_Excellence_Data(jsonObject.toString(), loading, db, masterRetailExcellence.get(consumerIndex), consumerIndex); + upload_retail_excellence(jsonObject.toString(), loading, db, masterRetailExcellence.get(consumerIndex), consumerIndex); + } + } + } catch (JSONException e) { + e.fillInStackTrace(); + } + } + + private void UploadMeSaleData(ProgressDialog loading, Lorealba_Database db, ArrayList productMasterArrayListData, int consumerIndex) { + try { + if (productMasterArrayList.size() > 0) { + ArrayList productMasterArrayList = db.getMeSaledata(null, productMasterArrayListData.get(consumerIndex).getUser_id(), visit_date, counter_Id); + if (productMasterArrayList.size() > 0) { + db.open(); + JourneyPlan jcp_Object = db.getBIDfromJCP(productMasterArrayList.get(consumerIndex).getUser_id(), counter_Id); + JSONArray consumerUserInfoArray = new JSONArray(); + for (int k = 0; k < productMasterArrayList.size(); k++) { + if (productMasterArrayList.get(k).getStock() > 0) { + JSONObject obj = new JSONObject(); + obj.put("MID", jcp_Object.getMID()); + obj.put("BID", jcp_Object.getBID()); + obj.put("UserId", username.toLowerCase()); + obj.put("VisiteDate", visit_date); + obj.put("ProductId", productMasterArrayList.get(k).getProductId()); + obj.put("Sale", productMasterArrayList.get(k).getStock()); + consumerUserInfoArray.put(obj); + } + } + JSONObject jsonObject = new JSONObject(); + jsonObject.put("MID", jcp_Object.getMID()); + jsonObject.put("Keys", "ME_Sale_Data"); + jsonObject.put("JsonData", consumerUserInfoArray.toString()); + jsonObject.put("UserId", username.toLowerCase()); + upload_ME_Sale_Data(jsonObject.toString(), loading, db, productMasterArrayList.get(consumerIndex), consumerIndex); + } + + } + + } catch (JSONException e) { + e.fillInStackTrace(); + } + } + + + public void upload_me_Quiz(String jsondata, final ProgressDialog loading, final Lorealba_Database db, final MEMEAuditQuestion object, final int index) { + try { + final int[] finalJsonIndex = {index}; + final OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build(); + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsondata); + Retrofit adapter; + adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build(); + PostApi api = adapter.create(PostApi.class); + Call call = api.getGeotag(jsonData); + call.enqueue(new Callback() { + @Override + public void onResponse(@NonNull Call call, @NonNull Response response) { + String responseBody = response.body().get("UploadJsonResult").toString(); + String data = null; + if (responseBody != null && response.isSuccessful()) { + try { + data = response.body().get("UploadJsonResult").toString(); + if (data.equals("")) { + } else { + data = data.substring(1, data.length() - 1).replace("\\", ""); + if (data.equalsIgnoreCase(CommonString.KEY_SUCCESS)) { + db.open(); + db.update_Me_Quiz(counter_Id, object.getUser_Id()); + finalJsonIndex[0]++; + if (finalJsonIndex[0] != meQuizList.size()) { + UploadMeQuiz(loading, db, meQuizList, finalJsonIndex[0]); + } else if (groomingList.size() > 0) { + UploadGrooming(loading, db, groomingList, 0); + } else if (counterList.size() > 0) { + UploadCounter(loading, db, counterList, 0); + } else { + ////finish activity........... + loading.dismiss(); + calling_method(); + } + } else { + loading.dismiss(); + AlertandMessages.showAlert((Activity) context, "Server Not Responding,(Me Quiz). Please LogOut Again", false); + } + } + } catch (Exception e) { + e.fillInStackTrace(); + loading.dismiss(); + } + } + } + + @Override + public void onFailure(@NonNull Call call, @NonNull Throwable t) { + AlertandMessages.showAlert((Activity) context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE + " Please LogOut Again", false); + loading.dismiss(); + } + }); + + } catch (Exception e) { + loading.dismiss(); + e.fillInStackTrace(); + } + } + + public void upload_retail_excellence(String jsondata, final ProgressDialog loading, final Lorealba_Database db, final MasterRetailExcellence object, final int index) { + try { + final int[] finalJsonIndex = {index}; + final OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build(); + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsondata); + Retrofit adapter; + adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build(); + PostApi api = adapter.create(PostApi.class); + Call call = api.getGeotag(jsonData); + call.enqueue(new Callback() { + @Override + public void onResponse(@NonNull Call call, @NonNull Response response) { + String responseBody = response.body().get("UploadJsonResult").toString(); + String data = null; + if (responseBody != null && response.isSuccessful()) { + try { + data = response.body().get("UploadJsonResult").toString(); + if (data.equals("")) { + } else { + data = data.substring(1, data.length() - 1).replace("\\", ""); + if (data.equalsIgnoreCase(CommonString.KEY_SUCCESS)) { + db.open(); + db.update_retail_excellence(counter_Id, object.getUser_Id()); + finalJsonIndex[0]++; + if (finalJsonIndex[0] != masterRetailExcellenceArrayList.size()) { + UploadRetailExcellence(loading, db, masterRetailExcellenceArrayList, finalJsonIndex[0]); + } else if (groomingList.size() > 0) { + UploadGrooming(loading, db, groomingList, 0); + } else if (counterList.size() > 0) { + UploadCounter(loading, db, counterList, 0); + } else { + ////finish activity........... + loading.dismiss(); + calling_method(); + } + } else { + loading.dismiss(); + AlertandMessages.showAlert((Activity) context, "Server Not Responding,(Me Quiz). Please LogOut Again", false); + } + } + } catch (Exception e) { + e.fillInStackTrace(); + loading.dismiss(); + } + } + } + + @Override + public void onFailure(@NonNull Call call, @NonNull Throwable t) { + AlertandMessages.showAlert((Activity) context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE + " Please LogOut Again", false); + loading.dismiss(); + } + }); + + } catch (Exception e) { + loading.dismiss(); + e.fillInStackTrace(); + } + } + + + public void upload_ME_Sale_Data(String jsondata, final ProgressDialog loading, final Lorealba_Database db, final ProductMaster object, final int index) { + try { + final int[] finalJsonIndex = {index}; + final OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build(); + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsondata); + Retrofit adapter; + adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build(); + PostApi api = adapter.create(PostApi.class); + Call call = api.getGeotag(jsonData); + call.enqueue(new Callback() { + @Override + public void onResponse(@NonNull Call call, @NonNull Response response) { + String responseBody = response.body().get("UploadJsonResult").toString(); + String data = null; + if (responseBody != null && response.isSuccessful()) { + try { + data = response.body().get("UploadJsonResult").toString(); + if (data.equals("")) { + } else { + data = data.substring(1, data.length() - 1).replace("\\", ""); + if (data.equalsIgnoreCase(CommonString.KEY_SUCCESS)) { + db.open(); + db.update_me_sale(counter_Id, object.getUser_id()); + finalJsonIndex[0]++; + if (finalJsonIndex[0] != productMasterArrayList.size()) { + UploadMeSaleData(loading, db, productMasterArrayList, finalJsonIndex[0]); + } else if (groomingList.size() > 0) { + UploadGrooming(loading, db, groomingList, 0); + } else if (counterList.size() > 0) { + UploadCounter(loading, db, counterList, 0); + } else { + ////finish activity........... + loading.dismiss(); + calling_method(); + } + } else { + loading.dismiss(); + AlertandMessages.showAlert((Activity) context, "Server Not Responding,(Me Quiz). Please LogOut Again", false); + } + } + } catch (Exception e) { + e.fillInStackTrace(); + loading.dismiss(); + } + } + } + + @Override + public void onFailure(@NonNull Call call, @NonNull Throwable t) { + AlertandMessages.showAlert((Activity) context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE + " Please LogOut Again", false); + loading.dismiss(); + } + }); + + } catch (Exception e) { + loading.dismiss(); + e.fillInStackTrace(); + } + } + + private void UploadGrooming(ProgressDialog loading, Lorealba_Database db, ArrayList groomingList, int grooming_index) { + try { + if (groomingList.size() > 0) { + db.open(); + JourneyPlan jcp_Object = db.getBIDfromJCP(groomingList.get(grooming_index).getUser_Id(), counter_Id); + JSONArray consumerUserInfoArray = new JSONArray(); + JSONObject obj = new JSONObject(); + obj.put("MID", jcp_Object.getMID()); + obj.put("BID", jcp_Object.getBID()); + obj.put("VisiteDate", groomingList.get(grooming_index).getVisit_date()); + obj.put("UserId", groomingList.get(grooming_index).getUser_Id()); + obj.put("Groomed_Morng_Img", groomingList.get(grooming_index).getMorning_groom_img_str()); + obj.put("Groomed_Morng_Time_Str", groomingList.get(grooming_index).getMorning_groom_time_str()); + obj.put("Groomed_Noon_Img", groomingList.get(grooming_index).getNoon_groom_img_str()); + obj.put("Groomed_Noon_Time_Str", groomingList.get(grooming_index).getNoon_groom_time_str()); + obj.put("Groomed_Eveng_Img", groomingList.get(grooming_index).getEvenning_groom_img_str()); + obj.put("Groomed_Eveng_Time_Str", groomingList.get(grooming_index).getEvenning_groom_time_str()); + + consumerUserInfoArray.put(obj); + + JSONObject jsonObject = new JSONObject(); + jsonObject.put("MID", jcp_Object.getMID()); + jsonObject.put("Keys", "Groomed_Data"); + jsonObject.put("JsonData", consumerUserInfoArray.toString()); + jsonObject.put("UserId", groomingList.get(grooming_index).getUser_Id()); + upload_grooming(jsonObject.toString(), loading, db, groomingList.get(grooming_index), grooming_index); + } + + + } catch (JSONException e) { + e.fillInStackTrace(); + } + } + + public void upload_grooming(String jsondata, final ProgressDialog loading, final Lorealba_Database db, final GroomingGetterSetter object, final int index) { + try { + + final int[] finalJsonIndex = {index}; + final OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build(); + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsondata); + Retrofit adapter; + adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build(); + PostApi api = adapter.create(PostApi.class); + Call call = api.getGeotag(jsonData); + call.enqueue(new Callback() { + @Override + public void onResponse(@NonNull Call call, @NonNull Response response) { + String responseBody = response.body().get("UploadJsonResult").toString(); + String data = null; + if (responseBody != null && response.isSuccessful()) { + try { + data = response.body().get("UploadJsonResult").toString(); + if (data.equals("")) { + } else { + data = data.substring(1, data.length() - 1).replace("\\", ""); + if (data.equalsIgnoreCase(CommonString.KEY_SUCCESS)) { + db.open(); + db.update_groomed_img(counter_Id, object.getVisit_date(), object.getUser_Id()); + finalJsonIndex[0]++; + if (finalJsonIndex[0] != groomingList.size()) { + UploadGrooming(loading, db, groomingList, finalJsonIndex[0]); + } else if (counterList.size() > 0) { + UploadCounter(loading, db, counterList, 0); + } else { + ////finish + loading.dismiss(); + calling_method(); + } + + } else { + loading.dismiss(); + AlertandMessages.showAlert((Activity) context, "Server Not Responding,(Grooming). Please LogOut Again", false); + } + } + } catch (Exception e) { + e.fillInStackTrace(); + loading.dismiss(); + } + } + } + + @Override + public void onFailure(@NonNull Call call, @NonNull Throwable t) { + AlertandMessages.showAlert((Activity) context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE + " Please LogOut Again", false); + loading.dismiss(); + } + }); + + } catch (Exception e) { + e.fillInStackTrace(); + loading.dismiss(); + } + } + + private void UploadCounter(ProgressDialog loading, Lorealba_Database db, ArrayList counterList, int counter_index) { + try { + if (counterList.size() > 0) { + db.open(); + JourneyPlan jcp_Object = db.getBIDfromJCP(null, counter_Id); + JSONArray consumerUserInfoArray = new JSONArray(); + JSONObject obj = new JSONObject(); + String key = ""; + if (counterList.get(counter_index).getUser_type().equalsIgnoreCase(CommonString.TAG_FROM_BA) || counterList.get(counter_index).getUser_type().equalsIgnoreCase(CommonString.TAG_FROM_TBA)) { + key = "Counter_Image_Data"; + obj = new JSONObject(); + consumerUserInfoArray = new JSONArray(); + obj.put("MID", jcp_Object.getMID()); + obj.put("VisitDate", counterList.get(counter_index).getVisitDate()); + obj.put("UserId", counterList.get(counter_index).getUserId()); + obj.put("Counter_Img_One", counterList.get(counter_index).getCounter_img_onefor_ba()); + obj.put("Counter_Img_Two", counterList.get(counter_index).getCounter_img_two_for_ba()); + consumerUserInfoArray.put(obj); + } else { + key = "ME_Counter_Image_Data"; + obj = new JSONObject(); + consumerUserInfoArray = new JSONArray(); + + obj.put("MID", jcp_Object.getMID()); + obj.put("VisitDate", counterList.get(counter_index).getVisitDate()); + obj.put("UserId", counterList.get(counter_index).getUserId()); + obj.put("PreSetUpImgOne", counterList.get(counter_index).getPresetup_img_one_str()); + obj.put("PreSetUpImgTwo", counterList.get(counter_index).getPresetup_img_two_str()); + obj.put("PostSetUpImgOne", counterList.get(counter_index).getPostsetup_img_one_str()); + obj.put("PostSetUpImgTwo", counterList.get(counter_index).getPostsetup_img_two_str()); + consumerUserInfoArray.put(obj); + } + + + JSONObject jsonObject = new JSONObject(); + jsonObject.put("MID", jcp_Object.getMID()); + jsonObject.put("Keys", key); + jsonObject.put("JsonData", consumerUserInfoArray.toString()); + jsonObject.put("UserId", counterList.get(counter_index).getUserId()); + upload_counter(jsonObject.toString(), loading, db, counterList.get(counter_index), counter_index); + } + + + } catch (JSONException e) { + e.fillInStackTrace(); + } + } + + public void upload_counter(String jsondata, final ProgressDialog loading, final Lorealba_Database db, final JourneyPlan object, final int index) { + try { + final int[] finalJsonIndex = {index}; + final OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build(); + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsondata); + Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build(); + PostApi api = adapter.create(PostApi.class); + Call call = api.getGeotag(jsonData); + call.enqueue(new Callback() { + @Override + public void onResponse(@NonNull Call call, @NonNull Response response) { + String responseBody = response.body().get("UploadJsonResult").toString(); + String data = null; + if (responseBody != null && response.isSuccessful()) { + try { + data = response.body().get("UploadJsonResult").toString(); + if (data.equals("")) { + } else { + data = data.substring(1, data.length() - 1).replace("\\", ""); + if (data.equalsIgnoreCase(CommonString.KEY_SUCCESS)) { + db.open(); + db.update_ba_counter_img(counter_Id, object.getVisitDate(), object.getUserId(), object.getTransId()); + finalJsonIndex[0]++; + if (finalJsonIndex[0] != groomingList.size()) { + UploadCounter(loading, db, counterList, finalJsonIndex[0]); + } else { + ///finish.. + loading.dismiss(); + calling_method(); + } + + } else { + loading.dismiss(); + AlertandMessages.showAlert((Activity) context, "Server Not Responding,(Counter). Please LogOut Again", false); + } + } + } catch (Exception e) { + e.fillInStackTrace(); + loading.dismiss(); + } + } + } + + @Override + public void onFailure(@NonNull Call call, @NonNull Throwable t) { + AlertandMessages.showAlert((Activity) context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE + " Please LogOut Again", false); + loading.dismiss(); + } + }); + + } catch (Exception e) { + e.fillInStackTrace(); + loading.dismiss(); + } + } + + private void calling_method() { + try { + db.open(); + db.deleteSpecificStoreData(); + editor.putString("Previous_Login", "Previous_Login"); + editor.commit(); + startActivity(new Intent(getBaseContext(), UserLoginActivity.class)); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + AlertandMessages.showToastMsg(context, "Data Upload Successfully"); + ManualUploadActivity.this.finish(); + } catch (Exception e) { + e.fillInStackTrace(); + editor.putString("Previous_Login", "Previous_Login"); + editor.commit(); + startActivity(new Intent(getBaseContext(), UserLoginActivity.class)); + overridePendingTransition(R.anim.activity_in, R.anim.activity_out); + AlertandMessages.showToastMsg(context, "Data Upload Successfully"); + ManualUploadActivity.this.finish(); + } + } + + @Override + protected void onResume() { + super.onResume(); + db.open(); + + } + + @Override + public void onBackPressed() { + if (clicked_flag) { + AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle(R.string.parinaam).setMessage(CommonString.UPLOAD_PONBACK_ALERT_MESSAGE).setCancelable(false).setPositiveButton("Ok", (dialog, id) -> { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + ManualUploadActivity.this.finish(); + }).setNegativeButton("Cancel", (dialog, id) -> dialog.cancel()); + + AlertDialog alert = builder.create(); + alert.show(); + } else { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + ManualUploadActivity.this.finish(); + } + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + getMenuInflater().inflate(R.menu.menu_takebackup, menu); + return super.onCreateOptionsMenu(menu); + } + + @Override + public boolean onKeyLongPress(int keyCode, KeyEvent event) { + if (keyCode == KeyEvent.KEYCODE_BACK) { + showExportDialog(); + return true; + } + return super.onKeyLongPress(keyCode, event); + } + + @SuppressLint("NonConstantResourceId") + @Override + public boolean onOptionsItemSelected(MenuItem item) { + int id = item.getItemId(); + + + if (id == R.id.nav_takebackup) { + showExportDialog(); + } else if (id == android.R.id.home) { + if (clicked_flag) { + AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle(R.string.parinaam).setMessage(CommonString.UPLOAD_PONBACK_ALERT_MESSAGE).setCancelable(false).setPositiveButton("Ok", (dialog, id12) -> { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + ManualUploadActivity.this.finish(); + }).setNegativeButton("Cancel", (dialog, id1) -> dialog.cancel()); + + AlertDialog alert = builder.create(); + alert.show(); + } else { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + ManualUploadActivity.this.finish(); + } + } + + return super.onOptionsItemSelected(item); + } + + @Override + protected void onDestroy() { + super.onDestroy(); + if (pd != null && pd.isShowing()) { + pd.dismiss(); + } + } + + + public void showExportDialog() { + android.app.AlertDialog.Builder builder1 = new android.app.AlertDialog.Builder(context).setTitle(R.string.dialog_title); + builder1.setMessage(R.string.Areyou_sure_take_backup).setCancelable(false).setPositiveButton(R.string.ok, (dialog, id) -> { + try { + File sd = context.getExternalFilesDir(""); + File data = Environment.getDataDirectory(); + assert sd != null; + if (sd.canWrite()) { + long date = System.currentTimeMillis(); + @SuppressLint("SimpleDateFormat") SimpleDateFormat sdf = new SimpleDateFormat("MMM/dd/yy"); + String dateString = sdf.format(date); + String currentDBPath = "//data//" + BuildConfig.APPLICATION_ID + "//databases//" + Lorealba_Database.DATABASE_NAME; + String backupDBPath = username + CommonString.BACKUP_FOLDER_NAME + dateString.replace('/', '_') + CommonFunctions.getCurrentTime_only().replace(":", "") + ".db"; + String path = CommonString.getBackupFolder(context); + File currentDB = new File(data, currentDBPath); + File backupDB = new File(path, backupDBPath); + if (currentDB.exists()) { + @SuppressWarnings("resource") + FileChannel src = new FileInputStream(currentDB).getChannel(); + FileChannel dst = new FileOutputStream(backupDB).getChannel(); + dst.transferFrom(src, 0, src.size()); + src.close(); + dst.close(); + } + File dir = new File(CommonString.getBackupFolder(context)); + ArrayList list = new ArrayList<>(); + list = getFileNames(dir.listFiles()); + if (!list.isEmpty()) { + for (int i1 = 0; i1 < list.size(); i1++) { + if (list.get(i1).contains(CommonString.BACKUP_FOLDER_NAME)) { + File originalFile = new File(CommonString.getBackupFolder(context) + list.get(i1)); + uploadBackup(context, originalFile.getName(), "DBBackup"); + } + } + } + } + } catch (Exception e) { + e.fillInStackTrace(); + AlertandMessages.showAlert((Activity) context, context.getString(R.string.errordatabase_not_exporting), true); + } + }).setNegativeButton(android.R.string.cancel, (dialog, id) -> dialog.cancel()); + AlertDialog alert1 = builder1.create(); + alert1.show(); + } + +} + diff --git a/app/src/main/java/com/cpm/lorealbaautomation/upload/UploadKeyData.java b/app/src/main/java/com/cpm/lorealbaautomation/upload/UploadKeyData.java new file mode 100644 index 0000000..69a2929 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/upload/UploadKeyData.java @@ -0,0 +1,2040 @@ +package com.cpm.lorealbaautomation.upload; + +import static com.cpm.lorealbaautomation.constant.CommonFunctions.saveBitmapToFile; +import static com.cpm.lorealbaautomation.download.Downloader.convertTym; +import static com.cpm.lorealbaautomation.download.Downloader.getFileNames; + +import android.annotation.SuppressLint; +import android.app.Activity; +import android.app.AlertDialog; +import android.app.ProgressDialog; +import android.content.Context; +import android.content.SharedPreferences; +import android.os.Bundle; +import android.view.MenuItem; +import android.view.View; +import android.widget.ImageView; +import android.widget.TextView; + +import androidx.annotation.NonNull; +import androidx.appcompat.app.AppCompatActivity; +import androidx.appcompat.widget.Toolbar; + +import com.google.gson.Gson; +import com.google.gson.JsonObject; +import com.cpm.lorealbaautomation.Database.Lorealba_Database; +import com.cpm.lorealbaautomation.R; +import com.cpm.lorealbaautomation.constant.AlertandMessages; +import com.cpm.lorealbaautomation.constant.CommonFunctions; +import com.cpm.lorealbaautomation.constant.CommonString; +import com.cpm.lorealbaautomation.delegates.PrefHelper; +import com.cpm.lorealbaautomation.gsonGetterSetter.InvoiceGetterSetter; +import com.cpm.lorealbaautomation.gsonGetterSetter.JourneyPlan; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterBreak; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterCompetitonBrandWiseNuance; +import com.cpm.lorealbaautomation.gsonGetterSetter.MasterPosm; +import com.cpm.lorealbaautomation.gsonGetterSetter.ProductMaster; +import com.cpm.lorealbaautomation.gsonGetterSetter.T_LeaveRequest; +import com.cpm.lorealbaautomation.retrofit.PostApi; +import com.cpm.lorealbaautomation.retrofit.PostApiForUpload; +import com.cpm.lorealbaautomation.retrofit.StringConverterFactory; +import com.squareup.okhttp.MultipartBuilder; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Objects; +import java.util.concurrent.TimeUnit; + +import okhttp3.MediaType; +import okhttp3.OkHttpClient; +import okhttp3.RequestBody; +import retrofit2.Call; +import retrofit2.Callback; +import retrofit2.Response; +import retrofit2.Retrofit; +import retrofit2.converter.gson.GsonConverterFactory; + +public class UploadKeyData extends AppCompatActivity implements View.OnClickListener { + ImageView img_manual_dataupload, img_manual_imageupload; + ArrayList masterList = new ArrayList<>(); + public static int uploadedFiles = 0; + public static int totalFiles = 0; + ProductMaster obj = new ProductMaster(); + String counter_Id, visit_date, username, upload_key = ""; + boolean clicked_flag = false; + Lorealba_Database db; + ProgressDialog pd; + Context context; + + @SuppressLint("SetTextI18n") + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_manual_upload); + context = this; + db = new Lorealba_Database(context); + db.open(); + Toolbar toolbar = findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + Objects.requireNonNull(getSupportActionBar()).setHomeButtonEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + SharedPreferences preferences = PrefHelper.getPrefs(context); + counter_Id = preferences.getString(CommonString.KEY_COUNTER_ID, ""); + username = preferences.getString(CommonString.KEY_USERNAME, ""); + visit_date = preferences.getString(CommonString.KEY_DATE, ""); + img_manual_dataupload = (ImageView) findViewById(R.id.img_manual_dataupload); + img_manual_imageupload = (ImageView) findViewById(R.id.img_manual_imageupload); + setTitle("Manual Upload - " + username); + db.open(); + + if (getIntent().getStringExtra(CommonString.TAG_OBJECT) != null) { + upload_key = getIntent().getStringExtra(CommonString.TAG_OBJECT); + } + + if (upload_key != null && !upload_key.isEmpty() && upload_key.equals("1")) { + masterList = db.getmasterTransaction(visit_date, counter_Id, false); + if (!masterList.isEmpty()) { + clicked_flag = true; + pd = new ProgressDialog(context); + pd.setCancelable(false); + pd.setMessage("Uploading Data" + "(" + "0/" + ")"); + pd.show(); + handleuploaddata_withcase(masterList, 0, pd); + } else { + AlertandMessages.showToastMsg(context, "No data for upload"); + } + } + + ////...............call interface.................. + img_manual_dataupload.setOnClickListener(this); + img_manual_imageupload.setOnClickListener(this); + + String couter_code = preferences.getString(CommonString.KEY_COUNTER_CODE, ""); + TextView txt_counter_code = (TextView) findViewById(R.id.txt_counter_code); + txt_counter_code.setText("Counter Code - " + couter_code + " / Id - " + counter_Id); + } + + @SuppressLint("LongLogTag") + private void handleuploaddata_withcase(ArrayList masterList, int masterfinalindex, ProgressDialog pd) { + if (!masterList.isEmpty()) { + obj = new ProductMaster(); + obj = masterList.get(masterfinalindex); + pd.setMessage("Uploading (" + masterfinalindex + "/" + masterList.size() + ") \n" + obj.getStock_type() + ""); + switch (obj.getStock_type()) { + case CommonString.SALEABLE: + if (obj.getEntry_type().equalsIgnoreCase(CommonString.KEY_DRAFT) || obj.getEntry_type().equalsIgnoreCase(CommonString.KEY_REGULAR)) { + String final_saleable_str = saleablejsonstr(counter_Id, obj); + if (final_saleable_str != null && !final_saleable_str.equals("")) { + upload_recursive_Data(final_saleable_str, masterfinalindex, masterList, pd); + //test(CommonString.KEY_JSON + "," + CommonString.SALEABLE, final_saleable_str); + } else { + pd.dismiss(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INVALID_JSON); + } + } else { + db.open(); + ArrayList saleableCompstockList = db.gettransaction_date(obj.getMaster_transaction_id()); + int endIndex = 0; + int startIndex = endIndex; + if (startIndex + 200 < saleableCompstockList.size()) { + endIndex = startIndex + 200; + } else { + endIndex = saleableCompstockList.size(); + } + + UploadStockRecursive(CommonString.KEY_COMPLETE, 0, endIndex, saleableCompstockList, masterList, masterfinalindex, pd); + } + + break; + + case CommonString.TESTER: + if (obj.getEntry_type().equalsIgnoreCase(CommonString.KEY_DRAFT) || obj.getEntry_type().equalsIgnoreCase(CommonString.KEY_REGULAR)) { + String final_saleable_str = saleablejsonstr(counter_Id, obj); + if (final_saleable_str != null && !final_saleable_str.equals("")) { + upload_recursive_Data(final_saleable_str, masterfinalindex, masterList, pd); + //test(CommonString.KEY_JSON + "," + CommonString.TESTER, final_saleable_str); + } else { + pd.dismiss(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INVALID_JSON); + } + } else { + db.open(); + ArrayList saleableCompstockList = db.gettransaction_date(obj.getMaster_transaction_id()); + int endIndex = 0; + int startIndex = endIndex; + if (startIndex + 200 < saleableCompstockList.size()) { + endIndex = startIndex + 200; + } else { + endIndex = saleableCompstockList.size(); + } + UploadStockRecursive(CommonString.KEY_COMPLETE, 0, endIndex, saleableCompstockList, masterList, masterfinalindex, pd); + } + + break; + + case CommonString.SAMPLE: + if (obj.getEntry_type().equalsIgnoreCase(CommonString.KEY_DRAFT) || obj.getEntry_type().equalsIgnoreCase(CommonString.KEY_REGULAR)) { + String final_saleable_str = saleablejsonstr(counter_Id, obj); + if (final_saleable_str != null && !final_saleable_str.equals("")) { + upload_recursive_Data(final_saleable_str, masterfinalindex, masterList, pd); + //test(CommonString.KEY_JSON + "," + CommonString.SAMPLE, final_saleable_str); + } else { + pd.dismiss(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INVALID_JSON); + } + } else { + db.open(); + ArrayList saleableCompstockList = db.gettransaction_date(obj.getMaster_transaction_id()); + int endIndex = 0; + int startIndex = endIndex; + if (startIndex + 200 < saleableCompstockList.size()) { + endIndex = startIndex + 200; + } else { + endIndex = saleableCompstockList.size(); + } + + UploadStockRecursive(CommonString.KEY_COMPLETE, 0, endIndex, saleableCompstockList, masterList, masterfinalindex, pd); + } + + break; + + case CommonString.GWP: + if (obj.getEntry_type().equalsIgnoreCase(CommonString.KEY_DRAFT) || obj.getEntry_type().equalsIgnoreCase(CommonString.KEY_REGULAR)) { + String final_saleable_str = saleablejsonstr(counter_Id, obj); + if (final_saleable_str != null && !final_saleable_str.equals("")) { + upload_recursive_Data(final_saleable_str, masterfinalindex, masterList, pd); + //test(CommonString.KEY_JSON + "," + CommonString.GWP, final_saleable_str); + } + } else { + db.open(); + ArrayList saleableCompstockList = db.gettransaction_date(obj.getMaster_transaction_id()); + int endIndex = 0; + int startIndex = endIndex; + if (startIndex + 200 < saleableCompstockList.size()) { + endIndex = startIndex + 200; + } else { + endIndex = saleableCompstockList.size(); + } + UploadStockRecursive(CommonString.KEY_COMPLETE, 0, endIndex, saleableCompstockList, masterList, masterfinalindex, pd); + } + + break; + + case CommonString.DAMAGE: + if (obj.getEntry_type().equalsIgnoreCase(CommonString.KEY_REGULAR)) { + String final_saleable_str = saleablejsonstr(counter_Id, obj); + if (final_saleable_str != null && !final_saleable_str.equals("")) { + upload_recursive_Data(final_saleable_str, masterfinalindex, masterList, pd); + //test(CommonString.KEY_JSON + "," + CommonString.DAMAGE, final_saleable_str); + } else { + pd.dismiss(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INVALID_JSON); + } + } + + break; + + case CommonString.RETURNTO_DB: + if (obj.getEntry_type().equalsIgnoreCase(CommonString.KEY_REGULAR)) { + String final_saleable_str = saleablejsonstr(counter_Id, obj); + if (final_saleable_str != null && !final_saleable_str.equals("")) { + upload_recursive_Data(final_saleable_str, masterfinalindex, masterList, pd); + //test(CommonString.KEY_JSON + "," + CommonString.RETURNTO_DB, final_saleable_str); + } else { + pd.dismiss(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INVALID_JSON); + } + } + + break; + + case CommonString.INWARD_DMS_NEW_SKU: + if (obj.getEntry_type().equalsIgnoreCase(CommonString.KEY_REGULAR)) { + String final_saleable_str = saleablejsonstr(counter_Id, obj); + if (final_saleable_str != null && !final_saleable_str.equals("")) { + upload_recursive_Data(final_saleable_str, masterfinalindex, masterList, pd); + //test(CommonString.KEY_JSON + "," + CommonString.INWARD_DMS_NEW_SKU, final_saleable_str); + } else { + pd.dismiss(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INVALID_JSON); + } + } + + break; + + case CommonString.INWARD_DMS: + if (obj.getEntry_type().equalsIgnoreCase(CommonString.KEY_REGULAR)) { + String final_saleable_str = saleablejsonstr(counter_Id, obj); + if (final_saleable_str != null && !final_saleable_str.equals("")) { + upload_recursive_Data(final_saleable_str, masterfinalindex, masterList, pd); + //test(CommonString.KEY_JSON + "," + CommonString.INWARD_DMS, final_saleable_str); + } else { + pd.dismiss(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INVALID_JSON); + } + } + + break; + + case CommonString.MANUALINWARD_DMS_NEWPRODUCT: + if (obj.getEntry_type().equalsIgnoreCase(CommonString.KEY_REGULAR)) { + String final_saleable_str = saleablejsonstr(counter_Id, obj); + if (final_saleable_str != null && !final_saleable_str.equals("")) { + upload_recursive_Data(final_saleable_str, masterfinalindex, masterList, pd); + //test(CommonString.KEY_JSON + "," + CommonString.MANUALINWARD_DMS_NEWPRODUCT, final_saleable_str); + } else { + pd.dismiss(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INVALID_JSON); + } + } + + break; + + case CommonString.MANUALINWARD_DMS: + if (obj.getEntry_type().equalsIgnoreCase(CommonString.KEY_REGULAR)) { + String final_saleable_str = saleablejsonstr(counter_Id, obj); + if (final_saleable_str != null && !final_saleable_str.equals("")) { + upload_recursive_Data(final_saleable_str, masterfinalindex, masterList, pd); + //test(CommonString.KEY_JSON + "," + CommonString.MANUALINWARD_DMS, final_saleable_str); + } else { + pd.dismiss(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INVALID_JSON); + } + } + + break; + + case CommonString.CONSUMERSALE: + if (obj.getEntry_type().equalsIgnoreCase(CommonString.KEY_REGULAR)) { + String final_saleable_str = saleablejsonstr(counter_Id, obj); + if (final_saleable_str != null && !final_saleable_str.isEmpty()) { + upload_recursive_Data(final_saleable_str, masterfinalindex, masterList, pd); + //test(CommonString.KEY_JSON + "," + CommonString.CONSUMERSALE, final_saleable_str); + } else { + pd.dismiss(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INVALID_JSON); + } + } + break; + + case CommonString.CONSUMERRETURN: + if (obj.getEntry_type().equalsIgnoreCase(CommonString.KEY_REGULAR)) { + String final_saleable_str = saleablejsonstr(counter_Id, obj); + if (final_saleable_str != null && !final_saleable_str.equals("")) { + upload_recursive_Data(final_saleable_str, masterfinalindex, masterList, pd); + //test(CommonString.KEY_JSON + "," + CommonString.CONSUMERRETURN, final_saleable_str); + } else { + pd.dismiss(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INVALID_JSON); + } + } + break; + + case CommonString.LEAVE_MANAGEMENT: + if (obj.getEntry_type().equalsIgnoreCase(CommonString.KEY_REGULAR)) { + String final_saleable_str = saleablejsonstr(counter_Id, obj); + if (final_saleable_str != null && !final_saleable_str.equals("")) { + upload_recursive_Data(final_saleable_str, masterfinalindex, masterList, pd); + //test(CommonString.KEY_JSON + "," + CommonString.LEAVE_MANAGEMENT, final_saleable_str); + } else { + pd.dismiss(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INVALID_JSON); + } + } + break; + + case CommonString.BREAK_MANAGEMENT: + if (obj.getEntry_type().equalsIgnoreCase(CommonString.KEY_REGULAR)) { + String final_saleable_str = saleablejsonstr(counter_Id, obj); + if (final_saleable_str != null && !final_saleable_str.equals("")) { + upload_recursive_Data(final_saleable_str, masterfinalindex, masterList, pd); + //test(CommonString.KEY_JSON + "," + CommonString.BREAK_MANAGEMENT, final_saleable_str); + } else { + pd.dismiss(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INVALID_JSON); + } + } + + break; + + case CommonString.VISIBILITY: + if (obj.getEntry_type().equalsIgnoreCase(CommonString.KEY_REGULAR)) { + String final_saleable_str = saleablejsonstr(counter_Id, obj); + if (final_saleable_str != null && !final_saleable_str.equals("")) { + upload_recursive_Data(final_saleable_str, masterfinalindex, masterList, pd); + //test(CommonString.KEY_JSON + "," + CommonString.VISIBILITY, final_saleable_str); + } else { + pd.dismiss(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INVALID_JSON); + } + } + + break; + + case CommonString.MAKEOVER_CAPTURE: + if (obj.getEntry_type().equalsIgnoreCase(CommonString.KEY_REGULAR)) { + String final_saleable_str = saleablejsonstr(counter_Id, obj); + if (final_saleable_str != null && !final_saleable_str.equals("")) { + upload_recursive_Data(final_saleable_str, masterfinalindex, masterList, pd); + //test(CommonString.KEY_JSON + "," + CommonString.MAKEOVER_CAPTURE, final_saleable_str); + } else { + pd.dismiss(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INVALID_JSON); + } + } + + break; + + case CommonString.SKINGENIUS: + if (obj.getEntry_type().equalsIgnoreCase(CommonString.KEY_REGULAR)) { + String final_saleable_str = saleablejsonstr(counter_Id, obj); + if (final_saleable_str != null && !final_saleable_str.equals("")) { + upload_recursive_Data(final_saleable_str, masterfinalindex, masterList, pd); + //test(CommonString.KEY_JSON + "," + CommonString.SKINGENIUS, final_saleable_str); + } else { + pd.dismiss(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INVALID_JSON); + } + } + + break; + + case CommonString.OPEN_SKINGENIUS: + if (obj.getEntry_type().equalsIgnoreCase(CommonString.KEY_REGULAR)) { + String final_saleable_str = saleablejsonstr(counter_Id, obj); + if (final_saleable_str != null && !final_saleable_str.equals("")) { + upload_recursive_Data(final_saleable_str, masterfinalindex, masterList, pd); + //test(CommonString.KEY_JSON + "," + CommonString.OPEN_SKINGENIUS, final_saleable_str); + } else { + pd.dismiss(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INVALID_JSON); + } + } + + break; + + case CommonString.OPEN_MAYBELLINE: + if (obj.getEntry_type().equalsIgnoreCase(CommonString.KEY_REGULAR)) { + String final_saleable_str = saleablejsonstr(counter_Id, obj); + if (final_saleable_str != null && !final_saleable_str.equals("")) { + upload_recursive_Data(final_saleable_str, masterfinalindex, masterList, pd); + //test(CommonString.KEY_JSON + "," + CommonString.OPEN_MAYBELLINE, final_saleable_str); + } else { + pd.dismiss(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INVALID_JSON); + } + } + + break; + + case CommonString.COMP_OFFERS: + if (obj.getEntry_type().equalsIgnoreCase(CommonString.KEY_REGULAR)) { + String final_saleable_str = saleablejsonstr(counter_Id, obj); + if (final_saleable_str != null && !final_saleable_str.equals("")) { + upload_recursive_Data(final_saleable_str, masterfinalindex, masterList, pd); + //test(CommonString.KEY_JSON + "," + CommonString.COMP_OFFERS, final_saleable_str); + } else { + pd.dismiss(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INVALID_JSON); + } + } + + break; + + default: + pd.dismiss(); + AlertandMessages.showToastMsg(context, "Error in uploading"); + break; + } + } + } + + private String saleablejsonstr(String counter_id, ProductMaster objectcurrent) { + String saleablejson_str = ""; + db.open(); + JourneyPlan jcp_Object = db.getBIDfromJCP(null, counter_id); + db.open(); + ArrayList saleablestockList = db.gettransaction_date(objectcurrent.getMaster_transaction_id()); + try { + String key = "", complete_json_str = ""; + JSONArray topUpArray = null; + if (objectcurrent.getStock_type().equalsIgnoreCase(CommonString.SALEABLE)) { + if (saleablestockList.size() > 0) { + key = "SaleableFData"; + complete_json_str = ""; + topUpArray = new JSONArray(); + for (int j = 0; j < saleablestockList.size(); j++) { + JSONObject obj = new JSONObject(); + obj.put("ProductId", saleablestockList.get(j).getProductId()); + obj.put("MID", jcp_Object.getMID()); + obj.put("REASON_ID", saleablestockList.get(j).getReasonId()); + obj.put("TranId", saleablestockList.get(j).getTransaction_Id()); + obj.put("UserId", saleablestockList.get(j).getUser_id()); + obj.put("CounterId", counter_id); + //header image + String img = saleablestockList.get(j).getImagePath(); + if (img == null) { + img = ""; + } + obj.put("Image", img); + int stk = saleablestockList.get(j).getStock(); + if (stk == -1) { + stk = 0; + } + + obj.put("STOCK", stk); + if (objectcurrent.getEntry_type().equalsIgnoreCase(CommonString.KEY_DRAFT)) { + obj.put("Status", saleablestockList.get(j).getEntry_type()); + } else { + key = "SaleableData"; + } + + topUpArray.put(obj); + } + complete_json_str = topUpArray.toString(); + } + } else if (objectcurrent.getStock_type().equalsIgnoreCase(CommonString.TESTER)) { + if (saleablestockList.size() > 0) { + key = "TesterFData"; + complete_json_str = ""; + topUpArray = new JSONArray(); + db.open(); + jcp_Object = db.getBIDfromJCP(null, counter_id); + for (int j = 0; j < saleablestockList.size(); j++) { + JSONObject obj = new JSONObject(); + obj.put("ProductId", saleablestockList.get(j).getProductId()); + obj.put("MID", jcp_Object.getMID()); + obj.put("TranId", saleablestockList.get(j).getTransaction_Id()); + obj.put("UserId", saleablestockList.get(j).getUser_id()); + obj.put("CounterId", counter_id); + int stk = saleablestockList.get(j).getStock(); + if (stk == -1) { + stk = 0; + } + + obj.put("STOCK", stk); + + if (objectcurrent.getEntry_type().equalsIgnoreCase(CommonString.KEY_DRAFT)) { + obj.put("Status", saleablestockList.get(j).getEntry_type()); + } else { + key = "TesterData"; + } + + topUpArray.put(obj); + } + + complete_json_str = topUpArray.toString(); + } + } else if (objectcurrent.getStock_type().equalsIgnoreCase(CommonString.SAMPLE)) { + if (saleablestockList.size() > 0) { + key = "SampleFData"; + complete_json_str = ""; + topUpArray = new JSONArray(); + db.open(); + jcp_Object = db.getBIDfromJCP(null, counter_id); + for (int j = 0; j < saleablestockList.size(); j++) { + JSONObject obj = new JSONObject(); + obj.put("ProductId", saleablestockList.get(j).getProductId()); + obj.put("MID", jcp_Object.getMID()); + obj.put("TranId", saleablestockList.get(j).getTransaction_Id()); + obj.put("UserId", saleablestockList.get(j).getUser_id()); + obj.put("CounterId", counter_id); + int stk = saleablestockList.get(j).getStock(); + if (stk == -1) { + stk = 0; + } + obj.put("STOCK", stk); + + if (objectcurrent.getEntry_type().equalsIgnoreCase(CommonString.KEY_DRAFT)) { + obj.put("Status", saleablestockList.get(j).getEntry_type()); + } else { + key = "SampleData"; + } + topUpArray.put(obj); + } + + complete_json_str = topUpArray.toString(); + } + + } else if (objectcurrent.getStock_type().equalsIgnoreCase(CommonString.GWP)) { + if (saleablestockList.size() > 0) { + key = "GWPFData"; + complete_json_str = ""; + topUpArray = new JSONArray(); + db.open(); + jcp_Object = db.getBIDfromJCP(null, counter_id); + for (int j = 0; j < saleablestockList.size(); j++) { + JSONObject obj = new JSONObject(); + obj.put("ProductId", saleablestockList.get(j).getProductId()); + obj.put("MID", jcp_Object.getMID()); + obj.put("TranId", saleablestockList.get(j).getTransaction_Id()); + obj.put("UserId", saleablestockList.get(j).getUser_id()); + obj.put("CounterId", counter_id); + int stk = saleablestockList.get(j).getStock(); + if (stk == -1) { + stk = 0; + } + + obj.put("STOCK", stk); + + if (objectcurrent.getEntry_type().equalsIgnoreCase(CommonString.KEY_DRAFT)) { + obj.put("Status", saleablestockList.get(j).getEntry_type()); + } else { + key = "GWPData"; + } + + topUpArray.put(obj); + } + + complete_json_str = topUpArray.toString(); + } + } else if (objectcurrent.getStock_type().equalsIgnoreCase(CommonString.ME_SALE)) { + if (saleablestockList.size() > 0) { + key = "ME_SaleFData"; + complete_json_str = ""; + topUpArray = new JSONArray(); + db.open(); + jcp_Object = db.getBIDfromJCP(null, counter_id); + for (int j = 0; j < saleablestockList.size(); j++) { + JSONObject obj = new JSONObject(); + obj.put("ProductId", saleablestockList.get(j).getProductId()); + obj.put("MID", jcp_Object.getMID()); + obj.put("TranId", saleablestockList.get(j).getTransaction_Id()); + obj.put("UserId", saleablestockList.get(j).getUser_id()); + obj.put("CounterId", counter_id); + int stk = saleablestockList.get(j).getStock(); + if (stk == -1) { + stk = 0; + } + obj.put("STOCK", stk); + if (objectcurrent.getEntry_type().equalsIgnoreCase(CommonString.KEY_DRAFT)) { + obj.put("Status", saleablestockList.get(j).getEntry_type()); + } else { + key = "ME_SaleData"; + } + topUpArray.put(obj); + } + complete_json_str = topUpArray.toString(); + } + + } else if (objectcurrent.getStock_type().equalsIgnoreCase(CommonString.DAMAGE)) { + if (saleablestockList.size() > 0) { + key = "DamageData"; + complete_json_str = ""; + topUpArray = new JSONArray(); + db.open(); + jcp_Object = db.getBIDfromJCP(null, counter_id); + for (int j = 0; j < saleablestockList.size(); j++) { + JSONObject obj = new JSONObject(); + obj.put("ProductId", saleablestockList.get(j).getProductId()); + obj.put("MID", jcp_Object.getMID()); + obj.put("TranId", saleablestockList.get(j).getTransaction_Id()); + obj.put("UserId", saleablestockList.get(j).getUser_id()); + obj.put("CounterId", counter_id); + //header image + String img = saleablestockList.get(j).getImagePath(); + if (img == null) { + img = ""; + } + + obj.put("Image", img); + int stk = saleablestockList.get(j).getStock(); + if (stk == -1) { + stk = 0; + } + obj.put("STOCK", stk); + topUpArray.put(obj); + } + + complete_json_str = topUpArray.toString(); + } + } else if (objectcurrent.getStock_type().equalsIgnoreCase(CommonString.RETURNTO_DB)) { + db.open(); + ArrayList damagestockList = db.getreturntodistributor_byUUID(objectcurrent.getTransaction_Id()); + if (damagestockList.size() > 0) { + complete_json_str = ""; + key = "DamageReturnToDistributor"; + topUpArray = new JSONArray(); + db.open(); + jcp_Object = db.getBIDfromJCP(null, counter_id); + for (int j = 0; j < damagestockList.size(); j++) { + JSONObject obj = new JSONObject(); + obj.put("ProductId", damagestockList.get(j).getProductId()); + obj.put("MID", jcp_Object.getMID()); + obj.put("TranId", damagestockList.get(j).getTransaction_Id()); + obj.put("UserId", damagestockList.get(j).getUser_id()); + obj.put("CounterId", counter_id); + int stk = damagestockList.get(j).getStock(); + if (stk == -1) { + stk = 0; + } + obj.put("STOCK", stk); + + topUpArray.put(obj); + } + + complete_json_str = topUpArray.toString(); + } + } else if (objectcurrent.getStock_type().equalsIgnoreCase(CommonString.INWARD_DMS_NEW_SKU)) { + db.open(); + ArrayList dmsList = db.getInwardStockTransactionData(objectcurrent.getTransaction_Id()); + if (dmsList.size() > 0) { + key = "Inward_NewProduct_Stock"; + complete_json_str = ""; + topUpArray = new JSONArray(); + db.open(); + jcp_Object = db.getBIDfromJCP(null, counter_id); + for (int j = 0; j < dmsList.size(); j++) { + JSONObject obj = new JSONObject(); + obj.put("MID", jcp_Object.getMID()); + obj.put("UserId", dmsList.get(j).getUser_id()); + obj.put(CommonString.KEY_VISIT_DATE, dmsList.get(j).getVisit_date()); + obj.put("TranId", dmsList.get(j).getTransaction_Id()); + obj.put(CommonString.KEY_ProductId, dmsList.get(j).getProductId()); + obj.put(CommonString.KEY_INVOICE_ID, dmsList.get(j).getInvId()); + obj.put(CommonString.KEY_INVOICE_STATUS, dmsList.get(j).getInvoice_Status()); + obj.put(CommonString.KEY_INVOICE_NUMBER, dmsList.get(j).getInvoice_number()); + obj.put(CommonString.KEY_INVOICE_TYPE, dmsList.get(j).getInvoice_type()); + obj.put(CommonString.KEY_INVOICE_DATE, dmsList.get(j).getInvoice_date()); + obj.put(CommonString.KEY_INVOICE_QTY, dmsList.get(j).getConsumer_qty()); + obj.put(CommonString.KEY_ACTUAL_QTY, dmsList.get(j).getActualQty()); + obj.put(CommonString.KEY_COUNTER_ID, dmsList.get(j).getCounter_id()); + if (dmsList.get(j).isConfirmChecked()) { + obj.put(CommonString.KEY_COUNTER_CONFIRM, "1"); + } else { + obj.put(CommonString.KEY_COUNTER_CONFIRM, "0"); + } + obj.put(CommonString.KEY_REASON_ID, dmsList.get(j).getReasonId()); + obj.put(CommonString.KEY_SOURCE, dmsList.get(j).getSource()); + + topUpArray.put(obj); + } + + complete_json_str = topUpArray.toString(); + } + } else if (objectcurrent.getStock_type().equalsIgnoreCase(CommonString.INWARD_DMS)) { + db.open(); + ArrayList dmsList = db.getInwardStockTransactionData(objectcurrent.getTransaction_Id()); + if (dmsList.size() > 0) { + key = "Inward_ExistingProduct_Stock"; + complete_json_str = ""; + topUpArray = new JSONArray(); + db.open(); + jcp_Object = db.getBIDfromJCP(null, counter_id); + for (int j = 0; j < dmsList.size(); j++) { + JSONObject obj = new JSONObject(); + obj.put("MID", jcp_Object.getMID()); + obj.put("UserId", dmsList.get(j).getUser_id()); + obj.put(CommonString.KEY_VISIT_DATE, dmsList.get(j).getVisit_date()); + obj.put("TranId", dmsList.get(j).getTransaction_Id()); + obj.put(CommonString.KEY_ProductId, dmsList.get(j).getProductId()); + obj.put(CommonString.KEY_INVOICE_ID, dmsList.get(j).getInvId()); + obj.put(CommonString.KEY_INVOICE_STATUS, dmsList.get(j).getInvoice_Status()); + obj.put(CommonString.KEY_INVOICE_NUMBER, dmsList.get(j).getInvoice_number()); + obj.put(CommonString.KEY_INVOICE_TYPE, dmsList.get(j).getInvoice_type()); + obj.put(CommonString.KEY_INVOICE_DATE, dmsList.get(j).getInvoice_date()); + obj.put(CommonString.KEY_INVOICE_QTY, dmsList.get(j).getConsumer_qty()); + obj.put(CommonString.KEY_ACTUAL_QTY, dmsList.get(j).getActualQty()); + obj.put(CommonString.KEY_COUNTER_ID, dmsList.get(j).getCounter_id()); + if (dmsList.get(j).isConfirmChecked()) { + obj.put(CommonString.KEY_COUNTER_CONFIRM, "1"); + } else { + obj.put(CommonString.KEY_COUNTER_CONFIRM, "0"); + } + obj.put(CommonString.KEY_REASON_ID, dmsList.get(j).getReasonId()); + obj.put(CommonString.KEY_SOURCE, dmsList.get(j).getSource()); + + topUpArray.put(obj); + } + + complete_json_str = topUpArray.toString(); + } + + } else if (objectcurrent.getStock_type().equalsIgnoreCase(CommonString.MANUALINWARD_DMS_NEWPRODUCT)) { + db.open(); + ArrayList manualIList = db.getManualInwardStock(objectcurrent.getTransaction_Id()); + if (manualIList.size() > 0) { + topUpArray = new JSONArray(); + complete_json_str = ""; + key = "Manual_Inward_NewProduct"; + db.open(); + jcp_Object = db.getBIDfromJCP(null, counter_id); + for (int j = 0; j < manualIList.size(); j++) { + JSONObject obj = new JSONObject(); + obj.put("MID", jcp_Object.getMID()); + obj.put("UserId", manualIList.get(j).getUser_id()); + obj.put(CommonString.KEY_VISIT_DATE, manualIList.get(j).getVisit_date()); + obj.put("TranId", manualIList.get(j).getTransaction_Id()); + obj.put(CommonString.KEY_ProductId, manualIList.get(j).getProductId()); + obj.put(CommonString.KEY_INVOICE_ID, manualIList.get(j).getInvId()); + obj.put(CommonString.KEY_INVOICE_STATUS, manualIList.get(j).getInvoice_Status()); + obj.put(CommonString.KEY_INVOICE_NUMBER, manualIList.get(j).getInvoice_number()); + obj.put(CommonString.KEY_INVOICE_TYPE, manualIList.get(j).getInvoice_type()); + obj.put(CommonString.KEY_INVOICE_DATE, manualIList.get(j).getInvoice_date()); + obj.put(CommonString.KEY_INVOICE_QTY, manualIList.get(j).getConsumer_qty()); + obj.put(CommonString.KEY_ACTUAL_QTY, manualIList.get(j).getActualQty()); + obj.put(CommonString.KEY_COUNTER_ID, manualIList.get(j).getCounter_id()); + obj.put(CommonString.KEY_INVOICE_IMG, manualIList.get(j).getInvoice_img()); + if (manualIList.get(j).isConfirmChecked()) { + obj.put(CommonString.KEY_COUNTER_CONFIRM, "1"); + } else { + obj.put(CommonString.KEY_COUNTER_CONFIRM, "0"); + } + + obj.put(CommonString.KEY_REASON_ID, manualIList.get(j).getReasonId()); + obj.put(CommonString.KEY_SOURCE, manualIList.get(j).getSource()); + topUpArray.put(obj); + } + + complete_json_str = topUpArray.toString(); + } + + } else if (objectcurrent.getStock_type().equalsIgnoreCase(CommonString.MANUALINWARD_DMS)) { + db.open(); + ArrayList manualIList = db.getManualInwardStock(objectcurrent.getTransaction_Id()); + if (manualIList.size() > 0) { + topUpArray = new JSONArray(); + complete_json_str = ""; + key = "Manual_Inward_ExistProduct"; + db.open(); + jcp_Object = db.getBIDfromJCP(null, counter_id); + for (int j = 0; j < manualIList.size(); j++) { + JSONObject obj = new JSONObject(); + obj.put("MID", jcp_Object.getMID()); + obj.put("UserId", manualIList.get(j).getUser_id()); + obj.put(CommonString.KEY_VISIT_DATE, manualIList.get(j).getVisit_date()); + obj.put("TranId", manualIList.get(j).getTransaction_Id()); + obj.put(CommonString.KEY_ProductId, manualIList.get(j).getProductId()); + obj.put(CommonString.KEY_INVOICE_ID, manualIList.get(j).getInvId()); + obj.put(CommonString.KEY_INVOICE_STATUS, manualIList.get(j).getInvoice_Status()); + obj.put(CommonString.KEY_INVOICE_NUMBER, manualIList.get(j).getInvoice_number()); + obj.put(CommonString.KEY_INVOICE_TYPE, manualIList.get(j).getInvoice_type()); + obj.put(CommonString.KEY_INVOICE_DATE, manualIList.get(j).getInvoice_date()); + obj.put(CommonString.KEY_INVOICE_QTY, manualIList.get(j).getConsumer_qty()); + obj.put(CommonString.KEY_ACTUAL_QTY, manualIList.get(j).getActualQty()); + obj.put(CommonString.KEY_COUNTER_ID, manualIList.get(j).getCounter_id()); + obj.put(CommonString.KEY_INVOICE_IMG, manualIList.get(j).getInvoice_img()); + + if (manualIList.get(j).isConfirmChecked()) { + obj.put(CommonString.KEY_COUNTER_CONFIRM, "1"); + } else { + obj.put(CommonString.KEY_COUNTER_CONFIRM, "0"); + } + + obj.put(CommonString.KEY_REASON_ID, manualIList.get(j).getReasonId()); + obj.put(CommonString.KEY_SOURCE, manualIList.get(j).getSource()); + topUpArray.put(obj); + } + + complete_json_str = topUpArray.toString(); + } + + } else if (objectcurrent.getStock_type().equalsIgnoreCase(CommonString.CONSUMERSALE)) { + db.open(); + ArrayList consumerSalesList = db.getsaleTrackingHeaderData(visit_date, counter_id, null, false, true, objectcurrent.getTransaction_Id()); + if (!consumerSalesList.isEmpty()) { + complete_json_str = ""; + int consumerIndex = 0; + topUpArray = new JSONArray(); + if (consumerSalesList.get(consumerIndex).getUserType().equalsIgnoreCase(CommonString.TAG_FROM_ME)) { + key = "ConsumerSalesWithapplyiedProductFromME"; + } else { + key = "ConsumerSalesWithapplyiedProduct"; + } + db.open(); + jcp_Object = db.getBIDfromJCP(consumerSalesList.get(consumerIndex).getStrUserId(), counter_id); + JSONArray consumerUserInfoArray = new JSONArray(); + JSONArray consumerGivenProductArray = new JSONArray(); + JSONArray consumerpromotionArray = new JSONArray(); + JSONObject obj = new JSONObject(); + obj.put("MID", jcp_Object.getMID()); + obj.put("BID", jcp_Object.getBID()); + obj.put("UserId", consumerSalesList.get(consumerIndex).getStrUserId()); + obj.put("VisiteDate", visit_date); + obj.put("POS_Sale", "1"); + obj.put("TranId", consumerSalesList.get(consumerIndex).getUnique_code()); + obj.put("ConsumerName", consumerSalesList.get(consumerIndex).getCustomer_name()); + obj.put("MobileNumber", consumerSalesList.get(consumerIndex).getMobile_no()); + obj.put("EmailId", consumerSalesList.get(consumerIndex).getConsumer_email_Id()); + obj.put("Age", consumerSalesList.get(consumerIndex).getConsumer_age()); + obj.put("SkinType", consumerSalesList.get(consumerIndex).getConsumer_skinType()); + obj.put("Gender", consumerSalesList.get(consumerIndex).getCustomer_gender()); + obj.put("DemoGiven", consumerSalesList.get(consumerIndex).getDemo_given_str()); + obj.put("ProductSold", consumerSalesList.get(consumerIndex).getProduct_sold_str()); + obj.put("SkinGenius", consumerSalesList.get(consumerIndex).getSkin_genius_str()); + obj.put("MaybellineVTO", consumerSalesList.get(consumerIndex).getMaybelline_vto_str()); + obj.put("ReceiptNumber", consumerSalesList.get(consumerIndex).getReccept_count()); + obj.put("ConsumerTime", consumerSalesList.get(consumerIndex).getPercheasing_tym()); + obj.put("TermConditions", consumerSalesList.get(consumerIndex).getStr_termcondition()); + obj.put("ConsumerNoSaleImg", consumerSalesList.get(consumerIndex).getConsumer_no_saleImg()); + obj.put("SourceofSales", consumerSalesList.get(consumerIndex).getSourceofSales()); + consumerUserInfoArray.put(obj); + db.open(); + ArrayList childList = db.getsalesTrackingByUserMobile(consumerSalesList.get(consumerIndex).getReccept_count(), consumerSalesList.get(consumerIndex).getMobile_no(), consumerSalesList.get(consumerIndex).getVisit_date(), counter_id, consumerSalesList.get(consumerIndex).getStrUserId()); + if (!childList.isEmpty()) { + for (int k = 0; k < childList.size(); k++) { + if (!childList.get(k).getProduct_Id().equals("0") && !childList.get(k).isPromo_flag()) { + obj = new JSONObject(); + obj.put("MID", jcp_Object.getMID()); + obj.put("BID", jcp_Object.getBID()); + obj.put("UserId", consumerSalesList.get(consumerIndex).getStrUserId()); + obj.put("TranId", consumerSalesList.get(consumerIndex).getUnique_code()); + obj.put("ProductId", childList.get(k).getProduct_Id()); + obj.put("Quantity", childList.get(k).getQuantity()); + obj.put("ProductMRP", childList.get(k).getProduct_rate()); + obj.put("EANCode", childList.get(k).getScan_ean_code_or_enterd_ean_code()); + obj.put("Invoice_Type", childList.get(k).getStr_invoiceType()); + consumerGivenProductArray.put(obj); + + } else if (childList.get(k).isPromo_flag() && childList.get(k).getPromo_type().equalsIgnoreCase("OffProduct")) { + obj = new JSONObject(); + obj.put("MID", jcp_Object.getMID()); + obj.put("BID", jcp_Object.getBID()); + obj.put("UserId", consumerSalesList.get(consumerIndex).getStrUserId()); + obj.put("TranId", consumerSalesList.get(consumerIndex).getUnique_code()); + obj.put("ProductId", childList.get(k).getProduct_Id()); + obj.put("Quantity", childList.get(k).getQuantity()); + obj.put("ProductMRP", childList.get(k).getProduct_rate()); + obj.put("EANCode", childList.get(k).getScan_ean_code_or_enterd_ean_code()); + obj.put("Invoice_Type", "Saleable"); + consumerGivenProductArray.put(obj); + } + } + } + ///get promo product + db.open(); + ArrayList promotionList = db.getapplyeid_promotion(consumerSalesList.get(consumerIndex).getReccept_count(), consumerSalesList.get(consumerIndex).getMobile_no(), consumerSalesList.get(consumerIndex).getVisit_date(), counter_id, consumerSalesList.get(consumerIndex).getStrUserId()); + if (!promotionList.isEmpty()) { + for (int k = 0; k < promotionList.size(); k++) { + obj = new JSONObject(); + obj.put("MID", jcp_Object.getMID()); + obj.put("BID", jcp_Object.getBID()); + obj.put("UserId", consumerSalesList.get(consumerIndex).getStrUserId()); + obj.put("TranId", consumerSalesList.get(consumerIndex).getUnique_code()); + obj.put("PromoType", promotionList.get(k).getPromo_type()); + + ArrayList applyedProducts = new ArrayList<>(); + JSONArray jsonArrayPromoApplyiedOnProductId = new JSONArray(); + if (promotionList.get(k).getPromo_type().equalsIgnoreCase("OffSameProduct")) { + applyedProducts = promotionList.get(k).getApplyiedproductList(); + if (!applyedProducts.isEmpty()) { + jsonArrayPromoApplyiedOnProductId = new JSONArray(); + for (int h = 0; h < applyedProducts.size(); h++) { + JSONObject obj7 = new JSONObject(); + obj7.put("MID", jcp_Object.getMID()); + obj7.put("BID", jcp_Object.getBID()); + obj7.put("UserId", consumerSalesList.get(consumerIndex).getStrUserId()); + obj7.put("TranId", consumerSalesList.get(consumerIndex).getUnique_code()); + obj7.put("PromoType", promotionList.get(k).getPromo_type()); + obj7.put("PromoId", applyedProducts.get(h).getPromotion_Id()); + obj7.put("PromoApplyiedOnProductId", applyedProducts.get(h).getProduct_Id()); + obj7.put("Rate", applyedProducts.get(h).getProduct_rate()); + obj7.put("MRP", applyedProducts.get(h).getMrp()); + obj7.put("EanCode", applyedProducts.get(h).getScan_ean_code_or_enterd_ean_code()); + obj7.put("QTY", applyedProducts.get(h).getQuantity()); + obj7.put("DISCOUNT", applyedProducts.get(h).getDiscounted_value_productwise()); + jsonArrayPromoApplyiedOnProductId.put(obj7); + } + } + obj.put("PromoId", promotionList.get(k).getPromotion_Id()); + obj.put("Discounted_Rs", promotionList.get(k).getDiscounted_value()); + obj.put("Rate", "0"); + obj.put("ProductId", 0); + obj.put("Quantity", 0); + if (!applyedProducts.isEmpty()) { + obj.put("PromoApplyiedOnProducts", jsonArrayPromoApplyiedOnProductId); + } else { + obj.put("PromoApplyiedOnProducts", ""); + } + } else if (promotionList.get(k).getPromo_type().equalsIgnoreCase("OffAdditionalProduct")) { + applyedProducts = promotionList.get(k).getApplyiedproductList(); + if (!applyedProducts.isEmpty()) { + jsonArrayPromoApplyiedOnProductId = new JSONArray(); + for (int h = 0; h < applyedProducts.size(); h++) { + JSONObject obj7 = new JSONObject(); + obj7.put("MID", jcp_Object.getMID()); + obj7.put("BID", jcp_Object.getBID()); + obj7.put("UserId", consumerSalesList.get(consumerIndex).getStrUserId()); + obj7.put("TranId", consumerSalesList.get(consumerIndex).getUnique_code()); + obj7.put("PromoType", promotionList.get(k).getPromo_type()); + obj7.put("PromoId", applyedProducts.get(h).getPromotion_Id()); + obj7.put("PromoApplyiedOnProductId", applyedProducts.get(h).getProduct_Id()); + obj7.put("Rate", applyedProducts.get(h).getProduct_rate()); + obj7.put("MRP", applyedProducts.get(h).getMrp()); + obj7.put("EanCode", applyedProducts.get(h).getScan_ean_code_or_enterd_ean_code()); + obj7.put("QTY", applyedProducts.get(h).getQuantity()); + obj7.put("DISCOUNT", applyedProducts.get(h).getDiscounted_value_productwise()); + jsonArrayPromoApplyiedOnProductId.put(obj7); + } + } + obj.put("PromoId", promotionList.get(k).getPromotion_Id()); + obj.put("Discounted_Rs", promotionList.get(k).getDiscounted_value()); + obj.put("Rate", "0"); + obj.put("ProductId", 0); + obj.put("Quantity", 0); + if (!applyedProducts.isEmpty()) { + obj.put("PromoApplyiedOnProducts", jsonArrayPromoApplyiedOnProductId); + } else { + obj.put("PromoApplyiedOnProducts", ""); + } + } else if (promotionList.get(k).getPromo_type().equalsIgnoreCase("ValueOffAdditionalProduct")) { + applyedProducts = promotionList.get(k).getApplyiedproductList(); + if (!applyedProducts.isEmpty()) { + jsonArrayPromoApplyiedOnProductId = new JSONArray(); + for (int h = 0; h < applyedProducts.size(); h++) { + JSONObject obj7 = new JSONObject(); + obj7.put("MID", jcp_Object.getMID()); + obj7.put("BID", jcp_Object.getBID()); + obj7.put("UserId", consumerSalesList.get(consumerIndex).getStrUserId()); + obj7.put("TranId", consumerSalesList.get(consumerIndex).getUnique_code()); + obj7.put("PromoType", promotionList.get(k).getPromo_type()); + obj7.put("PromoId", applyedProducts.get(h).getPromotion_Id()); + obj7.put("PromoApplyiedOnProductId", applyedProducts.get(h).getProduct_Id()); + obj7.put("Rate", applyedProducts.get(h).getProduct_rate()); + obj7.put("MRP", applyedProducts.get(h).getMrp()); + obj7.put("EanCode", applyedProducts.get(h).getScan_ean_code_or_enterd_ean_code()); + obj7.put("QTY", applyedProducts.get(h).getQuantity()); + obj7.put("DISCOUNT", applyedProducts.get(h).getDiscounted_value_productwise()); + jsonArrayPromoApplyiedOnProductId.put(obj7); + } + } + obj.put("PromoId", promotionList.get(k).getPromotion_Id()); + obj.put("Discounted_Rs", promotionList.get(k).getDiscounted_value()); + obj.put("Rate", "0"); + obj.put("ProductId", 0); + obj.put("Quantity", 0); + if (!applyedProducts.isEmpty()) { + obj.put("PromoApplyiedOnProducts", jsonArrayPromoApplyiedOnProductId); + } else { + obj.put("PromoApplyiedOnProducts", ""); + } + } else if (promotionList.get(k).getPromo_type().equalsIgnoreCase("OffWorth")) { + applyedProducts = promotionList.get(k).getApplyiedproductList(); + if (!applyedProducts.isEmpty()) { + jsonArrayPromoApplyiedOnProductId = new JSONArray(); + for (int h = 0; h < applyedProducts.size(); h++) { + JSONObject obj7 = new JSONObject(); + obj7.put("MID", jcp_Object.getMID()); + obj7.put("BID", jcp_Object.getBID()); + obj7.put("UserId", consumerSalesList.get(consumerIndex).getStrUserId()); + obj7.put("TranId", consumerSalesList.get(consumerIndex).getUnique_code()); + obj7.put("PromoType", promotionList.get(k).getPromo_type()); + obj7.put("PromoId", applyedProducts.get(h).getPromotion_Id()); + obj7.put("PromoApplyiedOnProductId", applyedProducts.get(h).getProduct_Id()); + obj7.put("Rate", applyedProducts.get(h).getProduct_rate()); + obj7.put("MRP", applyedProducts.get(h).getMrp()); + obj7.put("EanCode", applyedProducts.get(h).getScan_ean_code_or_enterd_ean_code()); + obj7.put("QTY", applyedProducts.get(h).getQuantity()); + obj7.put("DISCOUNT", applyedProducts.get(h).getDiscounted_value_productwise()); + jsonArrayPromoApplyiedOnProductId.put(obj7); + } + } + obj.put("PromoId", promotionList.get(k).getPromotion_Id()); + obj.put("Discounted_Rs", promotionList.get(k).getDiscounted_value()); + obj.put("Rate", "0"); + obj.put("ProductId", 0); + obj.put("Quantity", 0); + if (!applyedProducts.isEmpty()) { + obj.put("PromoApplyiedOnProducts", jsonArrayPromoApplyiedOnProductId); + } else { + obj.put("PromoApplyiedOnProducts", ""); + } + + + } else if (promotionList.get(k).getPromo_type().equalsIgnoreCase("Worth")) { + obj.put("PromoId", promotionList.get(k).getPromotion_Id()); + obj.put("Discounted_Rs", promotionList.get(k).getDiscounted_value()); + obj.put("Rate", "0"); + obj.put("ProductId", 0); + obj.put("Quantity", 0); + obj.put("PromoApplyiedOnProducts", ""); + + } else if (promotionList.get(k).getPromo_type().equalsIgnoreCase("OffProduct")) { + obj.put("PromoId", promotionList.get(k).getPromotion_Id()); + obj.put("Discounted_Rs", promotionList.get(k).getDiscounted_value()); + obj.put("Rate", promotionList.get(k).getProduct_rate()); + obj.put("ProductId", promotionList.get(k).getProduct_Id()); + obj.put("Quantity", promotionList.get(k).getQuantity()); + obj.put("PromoApplyiedOnProducts", ""); + + } else if (promotionList.get(k).getPromo_type().equalsIgnoreCase("Gift")) { + obj.put("PromoId", promotionList.get(k).getPromotion_Id()); + obj.put("Discounted_Rs", 0); + obj.put("Rate", 0); + obj.put("ProductId", promotionList.get(k).getProduct_Id()); + obj.put("Quantity", promotionList.get(k).getQuantity()); + obj.put("PromoApplyiedOnProducts", ""); + + } else if (promotionList.get(k).getPromo_type().equalsIgnoreCase("Product")) { + obj.put("PromoId", promotionList.get(k).getPromotion_Id()); + obj.put("Discounted_Rs", 0); + obj.put("Rate", 0); + obj.put("ProductId", promotionList.get(k).getProduct_Id()); + obj.put("Quantity", promotionList.get(k).getQuantity()); + obj.put("PromoApplyiedOnProducts", ""); + } else if (promotionList.get(k).getPromo_type().equalsIgnoreCase("WorthWithProduct")) { + applyedProducts = promotionList.get(k).getApplyiedproductList(); + if (!applyedProducts.isEmpty()) { + jsonArrayPromoApplyiedOnProductId = new JSONArray(); + for (int h = 0; h < applyedProducts.size(); h++) { + JSONObject obj7 = new JSONObject(); + obj7.put("MID", jcp_Object.getMID()); + obj7.put("BID", jcp_Object.getBID()); + obj7.put("UserId", consumerSalesList.get(consumerIndex).getStrUserId()); + obj7.put("TranId", consumerSalesList.get(consumerIndex).getUnique_code()); + obj7.put("PromoType", promotionList.get(k).getPromo_type()); + obj7.put("PromoId", applyedProducts.get(h).getPromotion_Id()); + obj7.put("PromoApplyiedOnProductId", applyedProducts.get(h).getProduct_Id()); + obj7.put("Rate", applyedProducts.get(h).getProduct_rate()); + obj7.put("MRP", applyedProducts.get(h).getMrp()); + obj7.put("EanCode", applyedProducts.get(h).getScan_ean_code_or_enterd_ean_code()); + obj7.put("QTY", applyedProducts.get(h).getQuantity()); + obj7.put("DISCOUNT", 0); + jsonArrayPromoApplyiedOnProductId.put(obj7); + } + } + obj.put("PromoId", promotionList.get(k).getPromotion_Id()); + obj.put("Discounted_Rs", promotionList.get(k).getDiscounted_value()); + obj.put("Rate", "0"); + obj.put("ProductId", 0); + obj.put("Quantity", 0); + if (!applyedProducts.isEmpty()) { + obj.put("PromoApplyiedOnProducts", jsonArrayPromoApplyiedOnProductId); + } else { + obj.put("PromoApplyiedOnProducts", ""); + } + } + ///adding promotion Data-------------- + consumerpromotionArray.put(obj); + } + } + + JSONObject jsonObject4 = null; + if (!childList.isEmpty()) { + jsonObject4 = new JSONObject(); + jsonObject4.put("Consumer_User_Info", consumerUserInfoArray); + jsonObject4.put("Consumer_Product_Sold", consumerGivenProductArray); + jsonObject4.put("Consumer_Applied_Promo", consumerpromotionArray); + } else { + jsonObject4 = new JSONObject(); + jsonObject4.put("Consumer_User_Info", consumerUserInfoArray); + jsonObject4.put("Consumer_Product_Sold", ""); + jsonObject4.put("Consumer_Applied_Promo", ""); + } + //test("promojsondata", jsonObject4.toString()); + complete_json_str = jsonObject4.toString(); + } + } else if (objectcurrent.getStock_type().equalsIgnoreCase(CommonString.CONSUMERRETURN)) { + db.open(); + ArrayList consumerreturnList = db.getsaleReturnHeaderData(visit_date, counter_id, username, true, true, objectcurrent.getTransaction_Id()); + if (!consumerreturnList.isEmpty()) { + int consumerIndex = 0; + complete_json_str = ""; + topUpArray = new JSONArray(); + key = "Consumer_Return_Data"; + db.open(); + jcp_Object = db.getBIDfromJCP(consumerreturnList.get(consumerIndex).getStrUserId(), counter_id); + JSONArray consumerReturnUserInfoArray = new JSONArray(); + JSONArray consumerReturnProductArray = new JSONArray(); + JSONArray replaceProductArray = new JSONArray(); + JSONObject obj = new JSONObject(); + obj.put("MID", jcp_Object.getMID()); + obj.put("BID", jcp_Object.getBID()); + obj.put("UserId", consumerreturnList.get(consumerIndex).getStrUserId()); + obj.put("Counter_Id", counter_id); + obj.put("VisiteDate", visit_date); + obj.put("TranId", consumerreturnList.get(consumerIndex).getUnique_code()); + obj.put("ConsumerName", consumerreturnList.get(consumerIndex).getCustomer_name()); + obj.put("BillNo", consumerreturnList.get(consumerIndex).getConsumer_return_bill_no()); + obj.put("MobileNo", consumerreturnList.get(consumerIndex).getMobile_no()); + obj.put("Gender", consumerreturnList.get(consumerIndex).getCustomer_gender()); + obj.put("KeyId", consumerreturnList.get(consumerIndex).getReccept_count()).toString(); + consumerReturnUserInfoArray.put(obj); + db.open(); + ArrayList childList = db.getsalesReturnChildData(consumerreturnList.get(consumerIndex).getReccept_count(), visit_date, counter_id, username, true); + for (int k = 0; k < childList.size(); k++) { + obj = new JSONObject(); + obj.put("MID", jcp_Object.getMID()); + obj.put("BID", jcp_Object.getBID()); + obj.put("UserId", childList.get(k).getUserName()); + obj.put("Counter_Id", counter_id); + obj.put("TranId", consumerreturnList.get(consumerIndex).getUnique_code()); + obj.put("ProductId", childList.get(k).getProduct_Id()); + obj.put("Quantity", childList.get(k).getQuantity()); + obj.put("ProductMRP", childList.get(k).getProduct_rate()); + obj.put("EANCode", childList.get(k).getScan_ean_code_or_enterd_ean_code()); + obj.put("Reason_Id", childList.get(k).getCon_return_reason_Id()); + consumerReturnProductArray.put(obj); + + } + db.open(); + ArrayList replaceProductList = db.getsalesReturnReplaceProduct(consumerreturnList.get(consumerIndex).getReccept_count(), visit_date, counter_id, username, true); + for (int k = 0; k < replaceProductList.size(); k++) { + obj = new JSONObject(); + obj.put("MID", jcp_Object.getMID()); + obj.put("BID", jcp_Object.getBID()); + obj.put("UserId", consumerreturnList.get(consumerIndex).getStrUserId()); + obj.put("Counter_Id", counter_id); + obj.put("TranId", consumerreturnList.get(consumerIndex).getUnique_code()); + obj.put("ProductId", replaceProductList.get(k).getProduct_Id()); + obj.put("Quantity", replaceProductList.get(k).getQuantity()); + obj.put("ProductMRP", replaceProductList.get(k).getProduct_rate()); + obj.put("EANCode", replaceProductList.get(k).getScan_ean_code_or_enterd_ean_code()); + replaceProductArray.put(obj); + + } + + + JSONObject jsonObject4 = new JSONObject(); + jsonObject4.put("Consumer_Return_User_Info", consumerReturnUserInfoArray); + jsonObject4.put("Consumer_Return_Product", consumerReturnProductArray); + jsonObject4.put("Consumer_Return_Replace_Product", replaceProductArray); + + complete_json_str = jsonObject4.toString(); + } + } else if (objectcurrent.getStock_type().equalsIgnoreCase(CommonString.LEAVE_MANAGEMENT)) { + db.open(); + T_LeaveRequest leaveRequestObject = db.getinserted_leave_request_data(counter_id, username, visit_date, objectcurrent.getTransaction_Id(), true); + if (leaveRequestObject.getTransId() != null && !leaveRequestObject.getTransId().equals("")) { + key = "RequestFor_Leave_Approval"; + complete_json_str = ""; + topUpArray = new JSONArray(); + db.open(); + JourneyPlan jcpfor_bid = db.getBIDfromJCP(leaveRequestObject.getUserId(), counter_id); + JSONObject obj = new JSONObject(); + obj.put("MID", jcpfor_bid.getMID()); + obj.put("BID", jcpfor_bid.getBID()); + obj.put("UserId", leaveRequestObject.getUserId()); + + obj.put("TranId", leaveRequestObject.getTransId()); + obj.put("Applied_Date", leaveRequestObject.getUpload_request_date()); + obj.put("From_Date", leaveRequestObject.getUpload_start_date_str()); + obj.put("End_Date", leaveRequestObject.getUpload_end_date_str()); + obj.put("Leave_Type", leaveRequestObject.getOne_day_leave_str()); + obj.put("Leave_TypeId", leaveRequestObject.getStr_leaveTypeId()); + obj.put("Reason", leaveRequestObject.getLeave_reason()); + topUpArray.put(obj); + complete_json_str = topUpArray.toString(); + } + + } else if (objectcurrent.getStock_type().equalsIgnoreCase(CommonString.BREAK_MANAGEMENT)) { + db.open(); + MasterBreak breakManagementObject = db.getBreakManagementforuploadList(counter_id, visit_date, username, objectcurrent.getTransaction_Id(), true); + if (breakManagementObject.getBreakId() != null && !breakManagementObject.getEndTym().equals("")) { + key = "Break_Management_Data"; + complete_json_str = ""; + topUpArray = new JSONArray(); + db.open(); + JourneyPlan jcpfor_bid = db.getBIDfromJCP(breakManagementObject.getUserId(), counter_id); + JSONObject obj = new JSONObject(); + obj.put("MID", jcpfor_bid.getMID()); + obj.put("BID", jcpfor_bid.getBID()); + obj.put("UserId", breakManagementObject.getUserId()); + obj.put("VisitDate", visit_date); + obj.put("TranId", breakManagementObject.getTransId()); + obj.put("BreakId", breakManagementObject.getBreakId().toString()); + obj.put("StartTym", convertTym(breakManagementObject.getStartTym())); + obj.put("EndTym", convertTym(breakManagementObject.getEndTym())); + obj.put("TotalDuration", breakManagementObject.getTotalDuration().toString()); + topUpArray.put(obj); + + complete_json_str = topUpArray.toString(); + } + } else if (objectcurrent.getStock_type().equalsIgnoreCase(CommonString.VISIBILITY)) { + db.open(); + ArrayList visibilityList = db.getVisibility_inserted_data(counter_id, visit_date, objectcurrent.getTransaction_Id(), true); + if (visibilityList.size() > 0) { + key = "VisibiliElementData"; + complete_json_str = ""; + topUpArray = new JSONArray(); + db.open(); + jcp_Object = db.getBIDfromJCP(null, counter_id); + for (int j = 0; j < visibilityList.size(); j++) { + JSONObject obj = new JSONObject(); + obj.put("MID", jcp_Object.getMID()); + obj.put("UserId", visibilityList.get(j).getUserId()); + obj.put("PosmId", visibilityList.get(j).getPosmId()); + obj.put("PosmTypeId", visibilityList.get(j).getPosmTypeId()); + obj.put("Counter_id", counter_id); + if (visibilityList.get(j).getPromotion_exists_state().equalsIgnoreCase("Yes")) { + obj.put("Promotion_Exists", "1"); + obj.put("Promo_Img", visibilityList.get(j).getPromotion_img()); + obj.put("PReason_Id", "0"); + } else { + obj.put("Promotion_Exists", "0"); + obj.put("Promo_Img", ""); + obj.put("PReason_Id", visibilityList.get(j).getPromotion_currect_ans_Id()); + } + + topUpArray.put(obj); + } + + complete_json_str = topUpArray.toString(); + } + } else if (objectcurrent.getStock_type().equalsIgnoreCase(CommonString.MAKEOVER_CAPTURE)) { + db.open(); + ArrayList memakeoverList = db.getMakeover(visit_date, counter_id, username, objectcurrent.getTransaction_Id(), true); + if (memakeoverList.size() > 0) { + key = "ME_Makeover_Capture"; + complete_json_str = ""; + topUpArray = new JSONArray(); + int consumerIndex = 0; + db.open(); + JourneyPlan jcp = db.getBIDfromJCP(memakeoverList.get(consumerIndex).getStrUserId(), counter_id); + JSONObject obj = new JSONObject(); + obj.put("MID", jcp.getMID()); + obj.put("BID", jcp.getBID()); + obj.put("VisiteDate", visit_date); + obj.put("UserId", memakeoverList.get(consumerIndex).getStrUserId()); + obj.put("TranId", memakeoverList.get(consumerIndex).getUnique_code()); + obj.put("ConsumerName", memakeoverList.get(consumerIndex).getCustomer_name()); + obj.put("MobileNumber", memakeoverList.get(consumerIndex).getMobile_no()); + obj.put("EmailId", memakeoverList.get(consumerIndex).getConsumer_email_Id()); + obj.put("Age", memakeoverList.get(consumerIndex).getConsumer_age()); + obj.put("SkinType", memakeoverList.get(consumerIndex).getConsumer_skinType()); + obj.put("Look", memakeoverList.get(consumerIndex).getLook_creater_str()); + obj.put("Gender", memakeoverList.get(consumerIndex).getCustomer_gender()); + obj.put("BeforeMakeoverImg", memakeoverList.get(consumerIndex).getBefore_makeover_img()); + obj.put("AfterMakeoverImg", memakeoverList.get(consumerIndex).getAfter_makeover_img()); + obj.put("Feedback", memakeoverList.get(consumerIndex).getCst_feed_back_value()); + obj.put("TermConditions", memakeoverList.get(consumerIndex).getStr_termcondition()); + + topUpArray.put(obj); + + complete_json_str = topUpArray.toString(); + } + } else if (objectcurrent.getStock_type().equalsIgnoreCase(CommonString.SKINGENIUS)) { + db.open(); + ArrayList memakeoverList = db.getskinGeniusData(visit_date, counter_id, username, objectcurrent.getTransaction_Id(), true); + if (memakeoverList.size() > 0) { + key = "Skin_Genius"; + complete_json_str = ""; + topUpArray = new JSONArray(); + int consumerIndex = 0; + db.open(); + JourneyPlan jcp = db.getBIDfromJCP(memakeoverList.get(consumerIndex).getStrUserId(), counter_id); + JSONObject obj = new JSONObject(); + obj.put("MID", jcp.getMID()); + obj.put("BID", jcp.getBID()); + obj.put("VisiteDate", visit_date); + obj.put("UserId", memakeoverList.get(consumerIndex).getStrUserId()); + obj.put("TranId", memakeoverList.get(consumerIndex).getUnique_code()); + obj.put("SkinGeniusImg", memakeoverList.get(consumerIndex).getInvoice_img()); + topUpArray.put(obj); + complete_json_str = topUpArray.toString(); + } + } else if (objectcurrent.getStock_type().equalsIgnoreCase(CommonString.OPEN_SKINGENIUS)) { + db.open(); + ArrayList memakeoverList = db.getOpenskinGeniusData(visit_date, counter_id, username, objectcurrent.getTransaction_Id(), true); + if (memakeoverList.size() > 0) { + key = "Open_Skin_Genius_Count"; + complete_json_str = ""; + topUpArray = new JSONArray(); + int consumerIndex = 0; + db.open(); + JourneyPlan jcp = db.getBIDfromJCP(memakeoverList.get(consumerIndex).getStrUserId(), counter_id); + JSONObject obj = new JSONObject(); + obj.put("MID", jcp.getMID()); + obj.put("BID", jcp.getBID()); + obj.put("VisiteDate", visit_date); + obj.put("UserId", memakeoverList.get(consumerIndex).getStrUserId()); + obj.put("TranId", memakeoverList.get(consumerIndex).getUnique_code()); + obj.put("OpenSkinGeniusCount", memakeoverList.get(consumerIndex).getMaybellineorskingenius_count()); + topUpArray.put(obj); + complete_json_str = topUpArray.toString(); + } + } else if (objectcurrent.getStock_type().equalsIgnoreCase(CommonString.OPEN_MAYBELLINE)) { + db.open(); + ArrayList memakeoverList = db.getOpenMaybellineData(visit_date, counter_id, username, objectcurrent.getTransaction_Id(), true); + if (memakeoverList.size() > 0) { + key = "Open_Maybelline_Count"; + complete_json_str = ""; + topUpArray = new JSONArray(); + int consumerIndex = 0; + db.open(); + JourneyPlan jcp = db.getBIDfromJCP(memakeoverList.get(consumerIndex).getStrUserId(), counter_id); + JSONObject obj = new JSONObject(); + obj.put("MID", jcp.getMID()); + obj.put("BID", jcp.getBID()); + obj.put("VisiteDate", visit_date); + obj.put("UserId", memakeoverList.get(consumerIndex).getStrUserId()); + obj.put("TranId", memakeoverList.get(consumerIndex).getUnique_code()); + obj.put("OpenMaybellineCount", memakeoverList.get(consumerIndex).getMaybellineorskingenius_count()); + topUpArray.put(obj); + complete_json_str = topUpArray.toString(); + } + } else if (objectcurrent.getStock_type().equalsIgnoreCase(CommonString.COMP_OFFERS)) { + db.open(); + ArrayList compOffers = db.getInsertedCompOffers(visit_date, counter_id, objectcurrent.getTransaction_Id(), true); + if (compOffers.size() > 0) { + key = "CompOffers_TVA_New"; + complete_json_str = ""; + topUpArray = new JSONArray(); + Gson gson = new Gson(); + db.open(); + jcp_Object = db.getBIDfromJCP(null, counter_id); + for (int j = 0; j < compOffers.size(); j++) { + JSONObject obj = new JSONObject(); + obj.put("MID", jcp_Object.getMID()); + obj.put("Counter_id", counter_id); + obj.put("UserId", compOffers.get(j).get_userId()); + obj.put("TransId", objectcurrent.getTransaction_Id()); + + if (compOffers.get(j).getPresent_str().equals("1")) { + String baInfoJson = gson.toJson(compOffers.get(j).getBaTenureDetailList()); + JSONArray baListJsonArray = new JSONArray(baInfoJson); + for (int i = 0; i < baListJsonArray.length(); i++) { + JSONObject baObj = baListJsonArray.getJSONObject(i); + baObj.put("KeyID", compOffers.get(j).getKeyId()); + } + obj.put("Present", 1); + if (compOffers.get(j).getGwpAvailable().equalsIgnoreCase("1")) { + obj.put("GWP_Available", 1); + } else { + obj.put("GWP_Available", 0); + } + obj.put("GWP_Image", compOffers.get(j).getGwpImage()); + obj.put("KeyID", compOffers.get(j).getKeyId()); + obj.put("DataForMonth", compOffers.get(j).getDateOfMonth()); + obj.put("CompBrandId", compOffers.get(j).getCompetitionBrandId()); + obj.put("NuanceId", compOffers.get(j).getCompetitionNuanceId()); + obj.put("CompOfferId", compOffers.get(j).getPromoTypeId()); + obj.put("FromDate", compOffers.get(j).getFromDate()); + obj.put("ToDate", compOffers.get(j).getToDate()); + obj.put("CompBuyTypeId", compOffers.get(j).getBuyTypeId()); + obj.put("CompSetId", compOffers.get(j).getBuyTypeInputId()); + obj.put("CompGetId", compOffers.get(j).getGetTypeInputId()); + obj.put("SaleRange", compOffers.get(j).getSaleRange()); + obj.put("NoOfBa", compOffers.get(j).getNoOfBa()); + obj.put("NumOfCounter", compOffers.get(j).getCounter()); + obj.put("NewLaunchMrp", compOffers.get(j).getNewLaunchMrp()); + obj.put("PromoDetails", compOffers.get(j).getCompPromDetail()); + obj.put("CompOfferImg", compOffers.get(j).getCompOfferImg()); + obj.put("AvgTarget", compOffers.get(j).getAvgtarget()); + obj.put("AvgOfftake", compOffers.get(j).getAvgOfftake()); + obj.put("TvaPercentage", compOffers.get(j).getTvapercent()); + obj.put("BAListData", baListJsonArray); + } else { + JSONArray balistdata = new JSONArray(); + obj.put("KeyID", 0); + obj.put("Present", 0); + obj.put("DataForMonth", ""); + obj.put("CompBrandId", 0); + obj.put("NuanceId", 0); + obj.put("CompOfferId", 0); + obj.put("FromDate", ""); + obj.put("ToDate", ""); + obj.put("PromoDetails", ""); + obj.put("CompOfferImg", ""); + obj.put("CompBuyTypeId", 0); + obj.put("CompSetId", 0); + obj.put("CompGetId", 0); + obj.put("SaleRange", ""); + obj.put("GWP_Available", 0); + obj.put("GWP_Image", ""); + obj.put("NoOfBa", 0); + obj.put("NumOfCounter", 0); + obj.put("NewLaunchMrp", 0); + obj.put("AvgTarget", 0); + obj.put("AvgOfftake", 0); + obj.put("TvaPercentage", 0); + obj.put("BAListData", balistdata); + } + topUpArray.put(obj); + } + complete_json_str = topUpArray.toString(); + } + } + + if (!complete_json_str.equals("")) { + db.open(); + jcp_Object = db.getBIDfromJCP(null, counter_id); + JSONObject jsonObject = new JSONObject(); + jsonObject.put("MID", jcp_Object.getMID()); + jsonObject.put("Keys", key); + jsonObject.put("JsonData", complete_json_str); + jsonObject.put("UserId", username); + saleablejson_str = jsonObject.toString(); + //test("compjsondata", saleablejson_str); + } + } catch (JSONException e) { + e.fillInStackTrace(); + pd.dismiss(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INVALID_JSON); + } + + return saleablejson_str; + + } + + private void UploadStockRecursive(final String status, final int startIndex, final int endIndex, + final ArrayList stockList, + final ArrayList masterfinalList, + final int masterfinal_index, final ProgressDialog pd) { + try { + + db.open(); + JourneyPlan jcp_Object = db.getBIDfromJCP(null, counter_Id); + JSONArray topUpArray = new JSONArray(); + String key = ""; + if (stockList.size() > 0) { + if (stockList.get(0).getStock_type().equalsIgnoreCase(CommonString.SALEABLE)) { + key = "SaleableFData"; + for (int j = startIndex; j < endIndex; j++) { + JSONObject obj = new JSONObject(); + obj.put("ProductId", stockList.get(j).getProductId()); + obj.put("MID", jcp_Object.getMID()); + obj.put("REASON_ID", stockList.get(j).getReasonId()); + obj.put("TranId", stockList.get(j).getTransaction_Id()); + obj.put("UserId", username); + obj.put("CounterId", counter_Id); + //header image + String img = stockList.get(j).getImagePath(); + if (img == null) { + img = ""; + } + + obj.put("Image", img); + ////for uploaded first time data if status is not null + int stk = stockList.get(j).getStock(); + if (stk == -1) { + stk = 0; + } + obj.put("STOCK", stk); + obj.put("Status", status); + topUpArray.put(obj); + } + + + } else if (stockList.get(0).getStock_type().equalsIgnoreCase(CommonString.TESTER)) { + key = "TesterFData"; + for (int j = startIndex; j < endIndex; j++) { + JSONObject obj = new JSONObject(); + obj.put("ProductId", stockList.get(j).getProductId()); + obj.put("MID", jcp_Object.getMID()); + obj.put("TranId", stockList.get(j).getTransaction_Id()); + obj.put("UserId", username); + obj.put("CounterId", counter_Id); + ////for uploaded first time data if status is not null + int stk = stockList.get(j).getStock(); + if (stk == -1) { + stk = 0; + } + + obj.put("STOCK", stk); + obj.put("Status", status); + topUpArray.put(obj); + } + + } else if (stockList.get(0).getStock_type().equalsIgnoreCase(CommonString.SAMPLE)) { + key = "SampleFData"; + for (int j = startIndex; j < endIndex; j++) { + JSONObject obj = new JSONObject(); + obj.put("ProductId", stockList.get(j).getProductId()); + obj.put("MID", jcp_Object.getMID()); + obj.put("TranId", stockList.get(j).getTransaction_Id()); + obj.put("UserId", username); + obj.put("CounterId", counter_Id); + ////for uploaded first time data if status is not null + int stk = stockList.get(j).getStock(); + if (stk == -1) { + stk = 0; + } + + obj.put("STOCK", stk); + obj.put("Status", status); + topUpArray.put(obj); + } + + } else if (stockList.get(0).getStock_type().equalsIgnoreCase(CommonString.GWP)) { + key = "GWPFData"; + for (int j = startIndex; j < endIndex; j++) { + JSONObject obj = new JSONObject(); + obj.put("ProductId", stockList.get(j).getProductId()); + obj.put("MID", jcp_Object.getMID()); + obj.put("TranId", stockList.get(j).getTransaction_Id()); + obj.put("UserId", username); + obj.put("CounterId", counter_Id); + ////for uploaded first time data if status is not null + int stk = stockList.get(j).getStock(); + if (stk == -1) { + stk = 0; + } + + obj.put("STOCK", stk); + obj.put("Status", status); + topUpArray.put(obj); + } + } + } + + JSONObject jsonObject = new JSONObject(); + jsonObject.put("MID", jcp_Object.getMID()); + jsonObject.put("Keys", key); + jsonObject.put("JsonData", topUpArray.toString()); + jsonObject.put("UserId", username); + + String jsonString = jsonObject.toString(); + OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout + (CommonString.TIMEOUT, TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build(); + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsonString); + Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build(); + PostApi api = adapter.create(PostApi.class); + Call call = api.getGeotag(jsonData); + call.enqueue(new Callback() { + @Override + public void onResponse(@NonNull Call call, @NonNull Response response) { + String data = null; + if (response.isSuccessful()) { + try { + assert response.body() != null; + data = response.body().get("UploadJsonResult").toString(); + if (data.equals("")) { + } else { + data = data.substring(1, data.length() - 1).replace("\\", ""); + if (data.equalsIgnoreCase(CommonString.KEY_SUCCESS)) { + if (endIndex < stockList.size()) { + int startIndex1 = endIndex; + int endIndex1 = 0; + if (startIndex1 + 200 < stockList.size()) { + endIndex1 = startIndex1 + 200; + } else { + endIndex1 = stockList.size(); + } + UploadStockRecursive(status, startIndex1, endIndex1, stockList, masterfinalList, masterfinal_index, pd); + } else { + ///-------------update status..........////---------- + db.open(); + update_upload_status(counter_Id, masterfinalList.get(masterfinal_index)); + //-------------------//upload recursive.........method.............. + final int[] finalJsonIndex = {masterfinal_index}; + finalJsonIndex[0]++; + if (finalJsonIndex[0] != masterfinalList.size()) { + handleuploaddata_withcase(masterfinalList, finalJsonIndex[0], pd); + } else { + //////show masage......data upload .... success...... + pd.dismiss(); + clicked_flag = false; + AlertandMessages.showToastMsg(context, "Data Upload Successfully"); + if (upload_key != null && !upload_key.equals("") && upload_key.equals("1")) { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + UploadKeyData.this.finish(); + } + } + } + } else { + pd.dismiss(); + AlertandMessages.showAlert((Activity) context, "Server Not Responding. Please upload again", false); + } + } + } catch (Exception e) { + db.open(); + pd.dismiss(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE + " - " + e.toString() + " - Please Try Again"); + } + } else { + pd.dismiss(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_NO_RESPONSE_SERVER + " - Please Try Again"); + } + } + + @Override + public void onFailure(@NonNull Call call, @NonNull Throwable t) { + pd.dismiss(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE + " - Please Try Again"); + } + }); + } catch (JSONException e) { + e.fillInStackTrace(); + pd.dismiss(); + AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INVALID_JSON + " - Please Try Again"); + } + } + + + public void upload_recursive_Data(String jsondata, final int index, final ArrayList final_list, final ProgressDialog pd) { + try { + final int[] finalJsonIndex = {index}; + final OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS) + .writeTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build(); + RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsondata); + Retrofit adapter; + adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build(); + PostApi api = adapter.create(PostApi.class); + Call call = api.getGeotag(jsonData); + call.enqueue(new Callback() { + @Override + public void onResponse(@NonNull Call call, @NonNull Response response) { + String data = null; + if (response.isSuccessful()) { + try { + assert response.body() != null; + data = response.body().get("UploadJsonResult").toString(); + if (data.equals("")) { + } else { + data = data.substring(1, data.length() - 1).replace("\\", ""); + if (data.equalsIgnoreCase(CommonString.KEY_SUCCESS)) { + db.open(); + update_upload_status(counter_Id, final_list.get(index)); + finalJsonIndex[0]++; + if (finalJsonIndex[0] != final_list.size()) { + handleuploaddata_withcase(final_list, finalJsonIndex[0], pd); + } else { + //////show masage......data upload .... success...... + pd.dismiss(); + clicked_flag = false; + AlertandMessages.showToastMsg(context, "Data Upload Successfully"); + if (upload_key != null && !upload_key.equals("") && upload_key.equals("1")) { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + UploadKeyData.this.finish(); + } + } + } else { + pd.dismiss(); + AlertandMessages.showAlert((Activity) context, "Server Not Responding. Please upload again", false); + } + } + } catch (Exception e) { + e.fillInStackTrace(); + pd.dismiss(); + } + } else { + pd.dismiss(); + AlertandMessages.showAlert((Activity) context, "Server Not Responding. Please upload again", false); + } + } + + @Override + public void onFailure(@NonNull Call call, @NonNull Throwable t) { + pd.dismiss(); + AlertandMessages.showAlert((Activity) context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE + " Please upload again", false); + } + }); + + } catch (Exception e) { + pd.dismiss(); + e.fillInStackTrace(); + } + } + + + private void update_upload_status(String counter_Id, ProductMaster currentobj) { + if (currentobj != null) { + /////............update status..................................... + db.open(); + db.updateMasterTransactionDataStatus(currentobj.getTransaction_Id()); + if (currentobj.getStock_type().equalsIgnoreCase(CommonString.RETURNTO_DB)) { + db.open(); + db.updatereturntodistributor(counter_Id, currentobj.getTransaction_Id()); + } else if (currentobj.getStock_type().equalsIgnoreCase(CommonString.INWARD_DMS) || currentobj.getStock_type().equalsIgnoreCase(CommonString.INWARD_DMS_NEW_SKU)) { + db.open(); + db.updateinwarddms(counter_Id, currentobj.getTransaction_Id()); + } else if (currentobj.getStock_type().equalsIgnoreCase(CommonString.MANUALINWARD_DMS) || currentobj.getStock_type().equalsIgnoreCase(CommonString.MANUALINWARD_DMS_NEWPRODUCT)) { + db.open(); + db.updatemanualinward(counter_Id, currentobj.getTransaction_Id()); + } else if (currentobj.getStock_type().equalsIgnoreCase(CommonString.CONSUMERSALE)) { + db.open(); + db.update_SalesTRacking(counter_Id, currentobj.getTransaction_Id()); + } else if (currentobj.getStock_type().equalsIgnoreCase(CommonString.CONSUMERRETURN)) { + db.open(); + db.update_ConsumersReturn(counter_Id, currentobj.getTransaction_Id()); + } else if (currentobj.getStock_type().equalsIgnoreCase(CommonString.LEAVE_MANAGEMENT)) { + db.open(); + db.update_leave_management_status(counter_Id, visit_date, username, currentobj.getTransaction_Id(), true); + } else if (currentobj.getStock_type().equalsIgnoreCase(CommonString.BREAK_MANAGEMENT)) { + db.open(); + db.update_break_management_status(counter_Id, visit_date, username, currentobj.getTransaction_Id(), true); + } else if (currentobj.getStock_type().equalsIgnoreCase(CommonString.VISIBILITY)) { + db.open(); + db.update_visibility(counter_Id, username, currentobj.getTransaction_Id(), CommonString.Table_visibilisty); + db.updateStockTransactionDataStatus(currentobj.getTransaction_Id()); + } else if (currentobj.getStock_type().equalsIgnoreCase(CommonString.MAKEOVER_CAPTURE)) { + db.open(); + db.update_makeover(counter_Id, username, currentobj.getTransaction_Id(), true); + } else if (currentobj.getStock_type().equalsIgnoreCase(CommonString.SKINGENIUS)) { + db.open(); + db.update_skinGenius_Category(counter_Id, username, currentobj.getTransaction_Id(), CommonString.Table_Skin_Genius_Table); + } else if (currentobj.getStock_type().equalsIgnoreCase(CommonString.OPEN_SKINGENIUS)) { + db.open(); + db.update_skinGenius_Category(counter_Id, username, currentobj.getTransaction_Id(), CommonString.Table_Open_Skin_Genius_Table); + } else if (currentobj.getStock_type().equalsIgnoreCase(CommonString.OPEN_MAYBELLINE)) { + db.open(); + db.update_skinGenius_Category(counter_Id, username, currentobj.getTransaction_Id(), CommonString.Table_Open_Maybelline_Table); + } else if (currentobj.getStock_type().equalsIgnoreCase(CommonString.COMP_OFFERS)) { + db.open(); + db.update_visibility(counter_Id, username, currentobj.getTransaction_Id(), CommonString.TABLE_COMP_OFFERS); + db.updateStockTransactionDataStatus(currentobj.getTransaction_Id()); + } else { + db.open(); + db.updateStockTransactionDataStatus(currentobj.getTransaction_Id()); + } + } + } + + @SuppressLint("NonConstantResourceId") + @Override + public void onClick(View view) { + if (view.getId() == R.id.img_manual_dataupload) { + if (CommonFunctions.checkNetIsAvailable(context)) { + masterList = db.getmasterTransaction(visit_date, counter_Id, false); + if (masterList.size() > 0) { + clicked_flag = true; + pd = new ProgressDialog(context); + pd.setCancelable(false); + pd.setMessage("Uploading Data" + "(" + "0/" + ")"); + pd.show(); + handleuploaddata_withcase(masterList, 0, pd); + } else { + AlertandMessages.showToastMsg(context, "No data for upload"); + } + } else { + AlertandMessages.showToastMsg(context, getString(R.string.nonetwork)); + } + + + } else if (view.getId() == R.id.img_manual_imageupload) { + if (CommonFunctions.checkNetIsAvailable(context)) { + upload_imagewithfolder(); + } else { + AlertandMessages.showToastMsg(context, getString(R.string.nonetwork)); + } + } + } + + + private void upload_imagewithfolder() { + try { + + File f = new File(CommonString.getImagesFolder(context)); + ArrayList finalList = new ArrayList<>(); + if (!getFileNames(f.listFiles()).isEmpty()) { + for (int k = 0; k < getFileNames(f.listFiles()).size(); k++) { + if (!db.ischeck_uploaded_image(visit_date, getFileNames(f.listFiles()).get(k))) { + finalList.add(getFileNames(f.listFiles()).get(k)); + } + } + } + + if (!finalList.isEmpty()) { + clicked_flag = true; + pd = new ProgressDialog(context); + pd.setCancelable(false); + pd.setMessage("Uploading Images"); + pd.show(); + totalFiles = finalList.size(); + uploadedFiles = 0; + UploadImageRecursive(pd); + } else { + AlertandMessages.showToastMsg(context, "No images for upload"); + } + } catch (Exception e) { + e.fillInStackTrace(); + } + } + + + public void UploadImageRecursive(final ProgressDialog pd) { + try { + final int[] uploadedFiles = {0}; + final int[] statusforimage = {0}; + statusforimage[0] = 0; + String filename = null, foldername = null; + File f = new File(CommonString.getImagesFolder(context)); + ArrayList finalList = new ArrayList<>(); + if (!getFileNames(f.listFiles()).isEmpty()) { + for (int k = 0; k < getFileNames(f.listFiles()).size(); k++) { + if (!db.ischeck_uploaded_image(visit_date, getFileNames(f.listFiles()).get(k))) { + finalList.add(getFileNames(f.listFiles()).get(k)); + } + } + } + + if (!finalList.isEmpty()) { + filename = ""; + for (int i = 0; i < finalList.size(); i++) { + pd.setMessage("Uploading images" + "(" + uploadedFiles[0] + "/" + totalFiles + ")"); + if (new File(CommonString.getImagesFolder(context) + finalList.get(i)).exists()) { + if (finalList.get(i).contains("_Counter_Selfie_img_")) { + foldername = "BACoverageImages"; + } else if (finalList.get(i).contains("_cp_img_one_") || finalList.get(i).contains("_cp_img_two_")) { + foldername = "CounterProfileImages"; + } else if (finalList.get(i).contains("_counter_img_one_") || finalList.get(i).contains("_counter_img_two_")) { + foldername = "CounterImages"; + } else if (finalList.get(i).contains("_ba_AuditPic_") || finalList.get(i).contains("_ba_profile_img_")) { + foldername = "BAProfileImages"; + } else if (finalList.get(i).contains("_Damaged_stock_img_") || finalList.get(i).contains("_Damage_header_img_")) { + foldername = "DamageStockImages"; + } else if (finalList.get(i).contains("_groomed_img_mrng_") || finalList.get(i).contains("_groomed_img_noon_") || finalList.get(i).contains("_groomed_img_evning_")) { + foldername = "GroomingImages"; + } else if (finalList.get(i).contains("_stock_check_img_") || finalList.get(i).contains("_tester_stock_img_") || finalList.get(i).contains("_suggested_stk_img") || finalList.get(i).contains("_Sample_stock_img")) { + foldername = "SaleableStockImages"; + } else if (finalList.get(i).contains("_visibility_img_")) { + foldername = "VisibilityImages"; + } else if (finalList.get(i).contains("_ConsumerSimg_")) { + foldername = "ConsumerInteractionImages"; + } else if (finalList.get(i).contains("_QuizPic-")) { + foldername = "MEAuditImages"; + } else if (finalList.get(i).contains("_before_makeo_img_") || finalList.get(i).contains("_after_makeo_img_")) { + foldername = "MeMakeoverImages"; + } else if (finalList.get(i).contains("SurveyPic-")) { + foldername = "SurveyImages"; + } else if (finalList.get(i).contains("_invoiceimg_")) { + foldername = "ConsumerReturnImages"; + } else if (finalList.get(i).contains("_minwordsimg_")) { + foldername = "InwardImages"; + } else if (finalList.get(i).contains("-SkinGenius-")) { + foldername = "SkinGeniusImages"; + } else if (finalList.get(i).contains("-CompOfferImg-") || finalList.get(i).contains("-Gwp_CompOfferImg-")) { + foldername = "CompetitionOffersImages"; + } else if (finalList.get(i).contains("_GeoTag-")) { + foldername = "GeoTagImages"; + } else { + foldername = "BulkUpload"; + } + + filename = finalList.get(i); + } + + break; + } + + File originalFile = new File(CommonString.getImagesFolder(context) + filename); + File finalFile = saveBitmapToFile(originalFile); + if (finalFile == null) { + finalFile = originalFile; + } + + String date = visit_date.replace("/", ""); + com.squareup.okhttp.OkHttpClient okHttpClient = new com.squareup.okhttp.OkHttpClient(); + okHttpClient.setConnectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS); + okHttpClient.setWriteTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS); + okHttpClient.setReadTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS); + com.squareup.okhttp.RequestBody photo = com.squareup.okhttp.RequestBody.create(com.squareup.okhttp.MediaType.parse("application/octet-stream"), finalFile); + com.squareup.okhttp.RequestBody body1 = new MultipartBuilder().type(MultipartBuilder.FORM).addFormDataPart("file", finalFile.getName(), photo).addFormDataPart("FolderName", foldername).addFormDataPart("Path", date).build(); + retrofit.Retrofit adapter = new retrofit.Retrofit.Builder().baseUrl(CommonString.URLGORIMAG).client(okHttpClient).addConverterFactory(new StringConverterFactory()).build(); + PostApiForUpload api = adapter.create(PostApiForUpload.class); + retrofit.Call call = api.getUploadImageRetrofitOne(body1); + final File finalFile1 = finalFile; + final String finalFilename = filename; + call.enqueue(new retrofit.Callback() { + @Override + public void onResponse(retrofit.Response response) { + try { + if (response.code() == 200 && response.message().equalsIgnoreCase("OK") && response.isSuccess() && response.body().contains("Success")) { + if (finalFilename.contains("_counter_img_two_") || finalFilename.contains("_counter_img_one_") || finalFilename.contains("_cp_img_one_") || finalFilename.contains("_cp_img_two_") || finalFilename.contains("_groomed_img_mrng_") || finalFilename.contains("_groomed_img_noon_") || finalFilename.contains("_groomed_img_evning_")) { + db.open(); + db.insert_temp_image(finalFilename, visit_date); + } else { + finalFile1.delete(); + } + statusforimage[0] = 1; + uploadedFiles[0]++; + } else { + statusforimage[0] = 0; + } + if (statusforimage[0] == 0) { + pd.dismiss(); + AlertandMessages.showAlertlogin((Activity) context, "Image not uploaded.Please try again." + "\n" + uploadedFiles + " images uploaded out of " + totalFiles); + + } else { + if (totalFiles == uploadedFiles[0]) { + pd.dismiss(); + clicked_flag = false; + AlertandMessages.showAlertlogin((Activity) context, "All images upload successfully"); + + } else { + UploadImageRecursive(pd); + } + } + } catch (Exception e) { + e.fillInStackTrace(); + statusforimage[0] = -1; + pd.dismiss(); + AlertandMessages.showAlertlogin((Activity) context, "Image not uploaded.Please try again." + "\n" + uploadedFiles + " images uploaded out of " + totalFiles); + + } catch (OutOfMemoryError error) { + statusforimage[0] = -1; + error.fillInStackTrace(); + pd.dismiss(); + AlertandMessages.showAlertlogin((Activity) context, "Image not uploaded.Please try again." + "\n" + uploadedFiles + " images uploaded out of " + totalFiles); + } + } + + @Override + public void onFailure(Throwable t) { + if (t instanceof IOException) { + statusforimage[0] = -1; + pd.dismiss(); + AlertandMessages.showAlertlogin((Activity) context, "Image not uploaded.Please try again." + "\n" + uploadedFiles + " images uploaded out of " + totalFiles); + + } + } + }); + } + } catch (Exception e) { + pd.dismiss(); + e.fillInStackTrace(); + AlertandMessages.showAlertlogin((Activity) context, "Image not uploaded.Please try again." + "\n" + uploadedFiles + " images uploaded out of " + totalFiles); + + } + } + + @Override + protected void onResume() { + super.onResume(); + db.open(); + + } + + @Override + public void onBackPressed() { + if (clicked_flag) { + AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle(R.string.parinaam).setMessage(CommonString.UPLOAD_PONBACK_ALERT_MESSAGE).setCancelable(false).setPositiveButton("Ok", + (dialog, id) -> { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + UploadKeyData.this.finish(); + }).setNegativeButton("Cancel", (dialog, id) -> dialog.cancel()); + + AlertDialog alert = builder.create(); + alert.show(); + } else { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + UploadKeyData.this.finish(); + } + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + int id = item.getItemId(); + if (id == android.R.id.home) { + if (clicked_flag) { + AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle(R.string.parinaam).setMessage(CommonString.UPLOAD_PONBACK_ALERT_MESSAGE).setCancelable(false).setPositiveButton("Ok", + (dialog, id1) -> { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + UploadKeyData.this.finish(); + }).setNegativeButton("Cancel", (dialog, id12) -> dialog.cancel()); + + AlertDialog alert = builder.create(); + alert.show(); + } else { + overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out); + UploadKeyData.this.finish(); + } + } + + return super.onOptionsItemSelected(item); + } + + @Override + protected void onDestroy() { + super.onDestroy(); + if (pd != null && pd.isShowing()) { + pd.dismiss(); + } + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/utils/ActionEditText.java b/app/src/main/java/com/cpm/lorealbaautomation/utils/ActionEditText.java new file mode 100644 index 0000000..d7d9c22 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/utils/ActionEditText.java @@ -0,0 +1,30 @@ +package com.cpm.lorealbaautomation.utils; + +import android.content.Context; +import android.util.AttributeSet; +import android.view.inputmethod.EditorInfo; +import android.view.inputmethod.InputConnection; + +import androidx.annotation.NonNull; + +public class ActionEditText extends androidx.appcompat.widget.AppCompatEditText { + public ActionEditText(Context context) { + super(context); + } + + public ActionEditText(Context context, AttributeSet attrs) { + super(context, attrs); + } + + public ActionEditText(Context context, AttributeSet attrs, int defStyle) { + super(context, attrs, defStyle); + } + + @Override + public InputConnection onCreateInputConnection(@NonNull EditorInfo outAttrs) { + InputConnection conn = super.onCreateInputConnection(outAttrs); + outAttrs.imeOptions &= ~EditorInfo.IME_FLAG_NO_ENTER_ACTION; + return conn; + } +} + diff --git a/app/src/main/java/com/cpm/lorealbaautomation/utils/AppUtils.java b/app/src/main/java/com/cpm/lorealbaautomation/utils/AppUtils.java new file mode 100644 index 0000000..3f988f4 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/utils/AppUtils.java @@ -0,0 +1,46 @@ +package com.cpm.lorealbaautomation.utils; + +import android.content.Context; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; + +public class AppUtils { + public static File getInternalDirectory(Context context, String folderName) { + File dir = context.getExternalFilesDir(""); + File file = new File(dir, folderName); + if (!file.exists()) { + file.mkdirs(); + } + return file; + } + + public static File getFile(Context context, String fileName, String folderName) { + File dir = getInternalDirectory(context, folderName); + if (fileName == null || fileName.isEmpty()) { + return dir; + } else { + return new File(dir, fileName); + } + } + + public static void saveByteArrayToFile(byte[] byteArray, String fileName) throws IOException { + try (FileOutputStream fileOutputStream = new FileOutputStream(fileName)) { + fileOutputStream.write(byteArray); + } + } + public static void clearMyFiles(Context activity, String folderName) { + File[] files = getInternalDirectory(activity, folderName).listFiles(); + if (files != null) { + for (File file : files) { + file.delete(); + } + } + } + + public static File getExterDir(Context context) { + return context.getExternalFilesDir(""); + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/utils/BarChartCustomRenderer.java b/app/src/main/java/com/cpm/lorealbaautomation/utils/BarChartCustomRenderer.java new file mode 100644 index 0000000..f356387 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/utils/BarChartCustomRenderer.java @@ -0,0 +1,29 @@ +package com.cpm.lorealbaautomation.utils; + +import android.graphics.Canvas; +import android.graphics.Color; +import android.graphics.Paint; +import android.graphics.Typeface; + +import com.github.mikephil.charting.animation.ChartAnimator; +import com.github.mikephil.charting.interfaces.dataprovider.BarDataProvider; +import com.github.mikephil.charting.renderer.BarChartRenderer; +import com.github.mikephil.charting.utils.MPPointF; +import com.github.mikephil.charting.utils.Utils; +import com.github.mikephil.charting.utils.ViewPortHandler; + +public class BarChartCustomRenderer extends BarChartRenderer { + public BarChartCustomRenderer(BarDataProvider chart, ChartAnimator animator, ViewPortHandler viewPortHandler) { + super(chart, animator, viewPortHandler); + } + + @Override + public void drawValue(Canvas c, String valueText, float x, float y, int color) { + Paint paint=super.mDrawPaint; + paint.setTextSize(18f); + paint.setTextAlign(Paint.Align.CENTER); + paint.setColor(Color.WHITE); + paint.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.BOLD)); + Utils.drawXAxisValue(c,valueText,x,y,paint, MPPointF.getInstance(),270); + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/utils/CustomEditText.java b/app/src/main/java/com/cpm/lorealbaautomation/utils/CustomEditText.java new file mode 100644 index 0000000..226be70 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/utils/CustomEditText.java @@ -0,0 +1,179 @@ +package com.cpm.lorealbaautomation.utils; + +import android.content.Context; +import android.graphics.Canvas; +import android.graphics.Rect; +import android.graphics.drawable.Drawable; +import android.util.AttributeSet; +import android.view.MotionEvent; + + +public class CustomEditText extends androidx.appcompat.widget.AppCompatEditText { + private Drawable drawableRight; + private Drawable drawableLeft; + private Drawable drawableTop; + private Drawable drawableBottom; + + int actionX, actionY; + + private DrawableClickListener clickListener; + + public CustomEditText (Context context, AttributeSet attrs) { + super(context, attrs); + // this Contructure required when you are using this view in xml + } + + public CustomEditText(Context context, AttributeSet attrs, int defStyle) { + super(context, attrs, defStyle); + } + + protected void onDraw(Canvas canvas) { + super.onDraw(canvas); + } + + @Override + protected void onSizeChanged(int w, int h, int oldw, int oldh) { + super.onSizeChanged(w, h, oldw, oldh); + } + + @Override + public void setCompoundDrawables(Drawable left, Drawable top, + Drawable right, Drawable bottom) { + if (left != null) { + drawableLeft = left; + } + if (right != null) { + drawableRight = right; + } + if (top != null) { + drawableTop = top; + } + if (bottom != null) { + drawableBottom = bottom; + } + super.setCompoundDrawables(left, top, right, bottom); + } + + @Override + public boolean onTouchEvent(MotionEvent event) { + Rect bounds; + if (event.getAction() == MotionEvent.ACTION_DOWN) { + actionX = (int) event.getX(); + actionY = (int) event.getY(); + if (drawableBottom != null + && drawableBottom.getBounds().contains(actionX, actionY)) { + clickListener.onClick(DrawableClickListener.DrawablePosition.BOTTOM); + return super.onTouchEvent(event); + } + + if (drawableTop != null + && drawableTop.getBounds().contains(actionX, actionY)) { + clickListener.onClick(DrawableClickListener.DrawablePosition.TOP); + return super.onTouchEvent(event); + } + + // this works for left since container shares 0,0 origin with bounds + if (drawableLeft != null) { + bounds = null; + bounds = drawableLeft.getBounds(); + + int x, y; + int extraTapArea = (int) (13 * getResources().getDisplayMetrics().density + 0.5); + + x = actionX; + y = actionY; + + if (!bounds.contains(actionX, actionY)) { + /** Gives the +20 area for tapping. */ + x = (int) (actionX - extraTapArea); + y = (int) (actionY - extraTapArea); + + if (x <= 0) + x = actionX; + if (y <= 0) + y = actionY; + + /** Creates square from the smallest value */ + if (x < y) { + y = x; + } + } + + if (bounds.contains(x, y) && clickListener != null) { + clickListener + .onClick(DrawableClickListener.DrawablePosition.LEFT); + event.setAction(MotionEvent.ACTION_CANCEL); + return false; + + } + } + + if (drawableRight != null) { + + bounds = null; + bounds = drawableRight.getBounds(); + + int x, y; + int extraTapArea = 13; + + /** + * IF USER CLICKS JUST OUT SIDE THE RECTANGLE OF THE DRAWABLE + * THAN ADD X AND SUBTRACT THE Y WITH SOME VALUE SO THAT AFTER + * CALCULATING X AND Y CO-ORDINATE LIES INTO THE DRAWBABLE + * BOUND. - this process help to increase the tappable area of + * the rectangle. + */ + x = (int) (actionX + extraTapArea); + y = (int) (actionY - extraTapArea); + + /**Since this is right drawable subtract the value of x from the width + * of view. so that width - tappedarea will result in x co-ordinate in drawable bound. + */ + x = getWidth() - x; + + /*x can be negative if user taps at x co-ordinate just near the width. + * e.g views width = 300 and user taps 290. Then as per previous calculation + * 290 + 13 = 303. So subtract X from getWidth() will result in negative value. + * So to avoid this add the value previous added when x goes negative. + */ + + if(x <= 0){ + x += extraTapArea; + } + + /* If result after calculating for extra tappable area is negative. + * assign the original value so that after subtracting + * extratapping area value doesn't go into negative value. + */ + + if (y <= 0) + y = actionY; + + /**If drawble bounds contains the x and y points then move ahead.*/ + if (bounds.contains(x, y) && clickListener != null) { + clickListener + .onClick(DrawableClickListener.DrawablePosition.RIGHT); + event.setAction(MotionEvent.ACTION_CANCEL); + return false; + } + return super.onTouchEvent(event); + } + + } + return super.onTouchEvent(event); + } + + @Override + protected void finalize() throws Throwable { + drawableRight = null; + drawableBottom = null; + drawableLeft = null; + drawableTop = null; + super.finalize(); + } + + public void setDrawableClickListener(DrawableClickListener listener) { + this.clickListener = listener; + } + +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/utils/DistanceUtils.java b/app/src/main/java/com/cpm/lorealbaautomation/utils/DistanceUtils.java new file mode 100644 index 0000000..3f6cf30 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/utils/DistanceUtils.java @@ -0,0 +1,26 @@ +package com.cpm.lorealbaautomation.utils; + +import android.location.Location; + +public class DistanceUtils { + /// /using location api for distance calculation + public static int calculateDistanceInMeters(double startLat, double startLng, double endLat, double endLng) { + float[] results = new float[1]; + Location.distanceBetween(startLat, startLng, endLat, endLng, results); + return (int) results[0]; // Distance in meters + } + + // Radius of the Earth in meters + private static final double R = 6371000; + /// using pure java method for distance calculation + public static double haversine(double lat1, double lon1, double lat2, double lon2) { + double dLat = Math.toRadians(lat2 - lat1); + double dLon = Math.toRadians(lon2 - lon1); + lat1 = Math.toRadians(lat1); + lat2 = Math.toRadians(lat2); + double a = Math.pow(Math.sin(dLat / 2), 2) + Math.cos(lat1) * Math.cos(lat2) + * Math.pow(Math.sin(dLon / 2), 2); + double c = 2 * Math.asin(Math.sqrt(a)); + return R * c; // Distance in meters + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/utils/DrawableClickListener.java b/app/src/main/java/com/cpm/lorealbaautomation/utils/DrawableClickListener.java new file mode 100644 index 0000000..a9027ee --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/utils/DrawableClickListener.java @@ -0,0 +1,6 @@ +package com.cpm.lorealbaautomation.utils; + +public interface DrawableClickListener { + public static enum DrawablePosition { TOP, BOTTOM, LEFT, RIGHT }; + public void onClick(DrawablePosition target); +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/utils/EmulatorCheck.java b/app/src/main/java/com/cpm/lorealbaautomation/utils/EmulatorCheck.java new file mode 100644 index 0000000..fb2f40d --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/utils/EmulatorCheck.java @@ -0,0 +1,23 @@ +package com.cpm.lorealbaautomation.utils; +public class EmulatorCheck { + + public static boolean isProbablyEmulator() { + String fingerprint = android.os.Build.FINGERPRINT; + String model = android.os.Build.MODEL; + String manufacturer = android.os.Build.MANUFACTURER; + String brand = android.os.Build.BRAND; + String device = android.os.Build.DEVICE; + String product = android.os.Build.PRODUCT; + String tags = android.os.Build.TAGS; + + return ( + fingerprint != null && (fingerprint.startsWith("generic") || fingerprint.contains("test-keys")) || + model != null && (model.contains("Emulator") || model.contains("Android SDK built for x86")) || + manufacturer != null && (manufacturer.contains("Genymotion") || manufacturer.contains("unknown")) || + brand != null && brand.startsWith("generic") && device != null && device.startsWith("generic") || + product != null && (product.contains("sdk") || product.contains("emulator")) || + tags != null && tags.contains("test-keys") + ); + } +} + diff --git a/app/src/main/java/com/cpm/lorealbaautomation/utils/GradientBarChartRenderer.java b/app/src/main/java/com/cpm/lorealbaautomation/utils/GradientBarChartRenderer.java new file mode 100644 index 0000000..ab45b79 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/utils/GradientBarChartRenderer.java @@ -0,0 +1,38 @@ +package com.cpm.lorealbaautomation.utils; + +import android.graphics.Canvas; +import android.graphics.drawable.Drawable; +import com.github.mikephil.charting.charts.BarChart; +import com.github.mikephil.charting.interfaces.datasets.IBarDataSet; +import com.github.mikephil.charting.renderer.BarChartRenderer; +import com.github.mikephil.charting.utils.ViewPortHandler; + +public class GradientBarChartRenderer extends BarChartRenderer { + private Drawable targetDrawable; + private Drawable actualDrawable; + + public GradientBarChartRenderer(BarChart chart, ViewPortHandler viewPortHandler, Drawable targetDrawable, Drawable actualDrawable) { + super(chart, chart.getAnimator(), viewPortHandler); + this.targetDrawable = targetDrawable; + this.actualDrawable = actualDrawable; + } + + @Override + protected void drawDataSet(Canvas c, IBarDataSet dataSet, int index) { + float[] buffer = mBarBuffers[index].buffer; + for (int j = 0; j < buffer.length; j += 4) { + float left = buffer[j]; + float top = buffer[j + 1]; + float right = buffer[j + 2]; + float bottom = buffer[j + 3]; + + if (j % 8 == 0) { // Target segment + targetDrawable.setBounds((int) left, (int) top, (int) right, (int) bottom); + targetDrawable.draw(c); + } else { // Actual segment + actualDrawable.setBounds((int) left, (int) top, (int) right, (int) bottom); + actualDrawable.draw(c); + } + } + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/utils/RoundLinerLayoutNormal.java b/app/src/main/java/com/cpm/lorealbaautomation/utils/RoundLinerLayoutNormal.java new file mode 100644 index 0000000..6645938 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/utils/RoundLinerLayoutNormal.java @@ -0,0 +1,32 @@ +package com.cpm.lorealbaautomation.utils; + +import android.content.Context; +import android.util.AttributeSet; +import android.view.Gravity; +import android.widget.LinearLayout; + +import androidx.annotation.Nullable; + +import com.cpm.lorealbaautomation.R; + +public class RoundLinerLayoutNormal extends LinearLayout { + public RoundLinerLayoutNormal(Context context) { + super(context); + initBackground(); + } + + public RoundLinerLayoutNormal(Context context, @Nullable AttributeSet attrs) { + super(context, attrs); + initBackground(); + } + + public RoundLinerLayoutNormal(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { + super(context, attrs, defStyleAttr); + initBackground(); + } + + private void initBackground() { + setBackground(ViewUtils.generateBackgroundWithShadow(this, R.color.white, + R.dimen.padding_10dp,R.color.gray,R.dimen.appbar_padding_top, Gravity.BOTTOM)); + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/utils/RoundedBarChart.java b/app/src/main/java/com/cpm/lorealbaautomation/utils/RoundedBarChart.java new file mode 100644 index 0000000..7f6024b --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/utils/RoundedBarChart.java @@ -0,0 +1,232 @@ +package com.cpm.lorealbaautomation.utils; + +import android.content.Context; +import android.graphics.Canvas; +import android.graphics.LinearGradient; +import android.graphics.RectF; +import android.util.AttributeSet; + +import com.github.mikephil.charting.animation.ChartAnimator; +import com.github.mikephil.charting.buffer.BarBuffer; +import com.github.mikephil.charting.charts.BarChart; +import com.github.mikephil.charting.data.BarData; +import com.github.mikephil.charting.data.BarEntry; +import com.github.mikephil.charting.highlight.Highlight; +import com.github.mikephil.charting.highlight.Range; +import com.github.mikephil.charting.interfaces.dataprovider.BarDataProvider; +import com.github.mikephil.charting.interfaces.datasets.IBarDataSet; +import com.github.mikephil.charting.model.GradientColor; +import com.github.mikephil.charting.renderer.BarChartRenderer; +import com.github.mikephil.charting.utils.Transformer; +import com.github.mikephil.charting.utils.Utils; +import com.github.mikephil.charting.utils.ViewPortHandler; + +public class RoundedBarChart extends BarChart { + public RoundedBarChart(Context context) { + super(context); + } + + public RoundedBarChart(Context context, AttributeSet attrs) { + super(context, attrs); + readRadiusAttr(context, attrs); + } + + public RoundedBarChart(Context context, AttributeSet attrs, int defStyle) { + super(context, attrs, defStyle); + readRadiusAttr(context, attrs); + } + + private void readRadiusAttr(Context context, AttributeSet attrs){ + // TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.CustomBarChart, 0, 0); + //TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.RoundedBarChart, 0, 0); + try { + // setRadius(a.getDimensionPixelSize(R.styleable.CustomBarChart_radius, 0)); + setRadius(20); + } finally { + //a.recycle(); + } + } + + public void setRadius(int radius) { + setRenderer(new RoundedBarChartRenderer(this, getAnimator(), getViewPortHandler(), radius)); + } + + private class RoundedBarChartRenderer extends BarChartRenderer { + private int mRadius; + private RectF mBarShadowRectBuffer = new RectF(); + + RoundedBarChartRenderer(BarDataProvider chart, ChartAnimator animator, ViewPortHandler viewPortHandler, int mRadius) { + super(chart, animator, viewPortHandler); + this.mRadius = mRadius; + } + + @Override + public void drawHighlighted(Canvas c, Highlight[] indices) { + BarData barData = mChart.getBarData(); + + for (Highlight high : indices) { + + IBarDataSet set = barData.getDataSetByIndex(high.getDataSetIndex()); + + if (set == null || !set.isHighlightEnabled()) + continue; + + BarEntry e = set.getEntryForXValue(high.getX(), high.getY()); + + if (!isInBoundsX(e, set)) + continue; + + Transformer trans = mChart.getTransformer(set.getAxisDependency()); + + mHighlightPaint.setColor(set.getHighLightColor()); + mHighlightPaint.setAlpha(set.getHighLightAlpha()); + + boolean isStack = high.getStackIndex() >= 0 && e.isStacked(); + + final float y1; + final float y2; + + if (isStack) { + + if (mChart.isHighlightFullBarEnabled()) { + + y1 = e.getPositiveSum(); + y2 = -e.getNegativeSum(); + + } else { + + Range range = e.getRanges()[high.getStackIndex()]; + + y1 = range.from; + y2 = range.to; + } + + } else { + y1 = e.getY(); + y2 = 0.f; + } + + prepareBarHighlight(e.getX(), y1, y2, barData.getBarWidth() / 2f, trans); + + setHighlightDrawPos(high, mBarRect); + + c.drawRoundRect(mBarRect, mRadius, mRadius, mHighlightPaint); + } + } + + @Override + protected void drawDataSet(Canvas c, IBarDataSet dataSet, int index) { + Transformer trans = mChart.getTransformer(dataSet.getAxisDependency()); + + mBarBorderPaint.setColor(dataSet.getBarBorderColor()); + mBarBorderPaint.setStrokeWidth(Utils.convertDpToPixel(dataSet.getBarBorderWidth())); + + final boolean drawBorder = dataSet.getBarBorderWidth() > 0.f; + + float phaseX = mAnimator.getPhaseX(); + float phaseY = mAnimator.getPhaseY(); + + // draw the bar shadow before the values + if (mChart.isDrawBarShadowEnabled()) { + mShadowPaint.setColor(dataSet.getBarShadowColor()); + + BarData barData = mChart.getBarData(); + + final float barWidth = barData.getBarWidth(); + final float barWidthHalf = barWidth / 2.0f; + float x; + + for (int i = 0, count = Math.min((int) (Math.ceil((float) (dataSet.getEntryCount()) * phaseX)), dataSet.getEntryCount()); + i < count; + i++) { + + BarEntry e = dataSet.getEntryForIndex(i); + + x = e.getX(); + + mBarShadowRectBuffer.left = x - barWidthHalf; + mBarShadowRectBuffer.right = x + barWidthHalf; + + trans.rectValueToPixel(mBarShadowRectBuffer); + + if (!mViewPortHandler.isInBoundsLeft(mBarShadowRectBuffer.right)) + continue; + + if (!mViewPortHandler.isInBoundsRight(mBarShadowRectBuffer.left)) + break; + + mBarShadowRectBuffer.top = mViewPortHandler.contentTop(); + mBarShadowRectBuffer.bottom = mViewPortHandler.contentBottom(); + + c.drawRoundRect(mBarShadowRectBuffer, mRadius, mRadius, mShadowPaint); + } + } + + // initialize the buffer + BarBuffer buffer = mBarBuffers[index]; + buffer.setPhases(phaseX, phaseY); + buffer.setDataSet(index); + buffer.setInverted(mChart.isInverted(dataSet.getAxisDependency())); + buffer.setBarWidth(mChart.getBarData().getBarWidth()); + + buffer.feed(dataSet); + + trans.pointValuesToPixel(buffer.buffer); + + final boolean isSingleColor = dataSet.getColors().size() == 1; + + if (isSingleColor) { + mRenderPaint.setColor(dataSet.getColor()); + } + + for (int j = 0; j < buffer.size(); j += 4) { + + if (!mViewPortHandler.isInBoundsLeft(buffer.buffer[j + 2])) + continue; + + if (!mViewPortHandler.isInBoundsRight(buffer.buffer[j])) + break; + + if (!isSingleColor) { + // Set the color for the currently drawn value. If the index + // is out of bounds, reuse colors. + mRenderPaint.setColor(dataSet.getColor(j / 4)); + } + + if (dataSet.getGradientColor() != null) { + GradientColor gradientColor = dataSet.getGradientColor(); + mRenderPaint.setShader( + new LinearGradient( + buffer.buffer[j], + buffer.buffer[j + 3], + buffer.buffer[j], + buffer.buffer[j + 1], + gradientColor.getStartColor(), + gradientColor.getEndColor(), + android.graphics.Shader.TileMode.MIRROR)); + } + + if (dataSet.getGradientColors() != null) { + mRenderPaint.setShader( + new LinearGradient( + buffer.buffer[j], + buffer.buffer[j + 3], + buffer.buffer[j], + buffer.buffer[j + 1], + dataSet.getGradientColor(j / 4).getStartColor(), + dataSet.getGradientColor(j / 4).getEndColor(), + android.graphics.Shader.TileMode.MIRROR)); + } + + + c.drawRoundRect(buffer.buffer[j], buffer.buffer[j + 1], buffer.buffer[j + 2], + buffer.buffer[j + 3], mRadius, mRadius, mRenderPaint); + + if (drawBorder) { + c.drawRoundRect(buffer.buffer[j], buffer.buffer[j + 1], buffer.buffer[j + 2], + buffer.buffer[j + 3], mRadius, mRadius, mBarBorderPaint); + } + } + } + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/utils/Spinner.java b/app/src/main/java/com/cpm/lorealbaautomation/utils/Spinner.java new file mode 100644 index 0000000..2dbae18 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/utils/Spinner.java @@ -0,0 +1,99 @@ +package com.cpm.lorealbaautomation.utils; + +import android.content.Context; +import android.util.AttributeSet; +import android.view.View; +import android.widget.AdapterView; + +/** + * Used this to differentiate between user selected and prorammatically selected + * Call {@link Spinner#programmaticallySetPosition} to use this feature. + * Created by vedant on 6/1/15. + */ +public class Spinner extends androidx.appcompat.widget.AppCompatSpinner implements AdapterView.OnItemSelectedListener { + + OnItemSelectedListener mListener; + + /** + * used to ascertain whether the user selected an item on spinner (and not programmatically) + */ + private boolean mUserActionOnSpinner = true; + + @Override + public void onItemSelected(AdapterView parent, View view, int position, long id) { + + if (mListener != null) { + + mListener.onItemSelected(parent, view, position, id, mUserActionOnSpinner); + } + // reset variable, so that it will always be true unless tampered with + mUserActionOnSpinner = true; + } + + @Override + public void onNothingSelected(AdapterView parent) { + if (mListener != null) + mListener.onNothingSelected(parent); + } + + public interface OnItemSelectedListener { + /** + *

Callback method to be invoked when an item in this view has been + * selected. This callback is invoked only when the newly selected + * position is different from the previously selected position or if + * there was no selected item.

+ * + * Impelmenters can call getItemAtPosition(position) if they need to access the + * data associated with the selected item. + * + * @param parent The AdapterView where the selection happened + * @param view The view within the AdapterView that was clicked + * @param position The position of the view in the adapter + * @param id The row id of the item that is selected + */ + void onItemSelected(AdapterView parent, View view, int position, long id, boolean userSelected); + + /** + * Callback method to be invoked when the selection disappears from this + * view. The selection can disappear for instance when touch is activated + * or when the adapter becomes empty. + * + * @param parent The AdapterView that now contains no selected item. + */ + void onNothingSelected(AdapterView parent); + } + + public void programmaticallySetPosition(int pos, boolean animate) { + mUserActionOnSpinner = false; + setSelection(pos, animate); + } + + public void setOnItemSelectedListener (OnItemSelectedListener listener) { + mListener = listener; + } + + public Spinner(Context context) { + super(context); + super.setOnItemSelectedListener(this); + } + + public Spinner(Context context, int mode) { + super(context, mode); + super.setOnItemSelectedListener(this); + } + + public Spinner(Context context, AttributeSet attrs) { + super(context, attrs); + super.setOnItemSelectedListener(this); + } + + public Spinner(Context context, AttributeSet attrs, int defStyle) { + super(context, attrs, defStyle); + super.setOnItemSelectedListener(this); + } + + public Spinner(Context context, AttributeSet attrs, int defStyle, int mode) { + super(context, attrs, defStyle, mode); + super.setOnItemSelectedListener(this); + } +} \ No newline at end of file diff --git a/app/src/main/java/com/cpm/lorealbaautomation/utils/VerticalValueFormatter.java b/app/src/main/java/com/cpm/lorealbaautomation/utils/VerticalValueFormatter.java new file mode 100644 index 0000000..a9e4349 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/utils/VerticalValueFormatter.java @@ -0,0 +1,18 @@ +package com.cpm.lorealbaautomation.utils; + +import com.github.mikephil.charting.data.BarEntry; +import com.github.mikephil.charting.formatter.ValueFormatter; + +public class VerticalValueFormatter extends ValueFormatter { + @Override + public String getBarLabel(BarEntry barEntry) { + String value = String.valueOf((int) barEntry.getY()); + StringBuilder verticalText = new StringBuilder(); + + for (char c : value.toCharArray()) { + verticalText.append(c).append("\n"); + } + + return verticalText.toString().trim(); // Trim to remove the last newline + } +} \ No newline at end of file diff --git a/app/src/main/java/com/cpm/lorealbaautomation/utils/ViewUtils.java b/app/src/main/java/com/cpm/lorealbaautomation/utils/ViewUtils.java new file mode 100644 index 0000000..5987d12 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/utils/ViewUtils.java @@ -0,0 +1,77 @@ +package com.cpm.lorealbaautomation.utils; + +import static android.view.View.LAYER_TYPE_SOFTWARE; + +import android.graphics.Paint; +import android.graphics.Rect; +import android.graphics.drawable.Drawable; +import android.graphics.drawable.LayerDrawable; +import android.graphics.drawable.ShapeDrawable; +import android.graphics.drawable.shapes.RoundRectShape; +import android.view.Gravity; +import android.view.View; + +import androidx.annotation.ColorRes; +import androidx.annotation.DimenRes; +import androidx.core.content.ContextCompat; + +public class ViewUtils { + public static Drawable generateBackgroundWithShadow(View view, @ColorRes int backgroundColor, + @DimenRes int cornerRadius, + @ColorRes int shadowColor, + @DimenRes int elevation, + int shadowGravity) { + float cornerRadiusValue = view.getContext().getResources().getDimension(cornerRadius); + int elevationValue = (int) view.getContext().getResources().getDimension(elevation); + int shadowColorValue = ContextCompat.getColor(view.getContext(),shadowColor); + int backgroundColorValue = ContextCompat.getColor(view.getContext(),backgroundColor); + + float[] outerRadius = {cornerRadiusValue, cornerRadiusValue, cornerRadiusValue, + cornerRadiusValue, cornerRadiusValue, cornerRadiusValue, cornerRadiusValue, + cornerRadiusValue}; + + Paint backgroundPaint = new Paint(); + backgroundPaint.setStyle(Paint.Style.FILL); + backgroundPaint.setShadowLayer(cornerRadiusValue, 0, 0, 0); + + Rect shapeDrawablePadding = new Rect(); + shapeDrawablePadding.left = elevationValue; + shapeDrawablePadding.right = elevationValue; + + int DY; + switch (shadowGravity) { + case Gravity.CENTER: + shapeDrawablePadding.top = elevationValue; + shapeDrawablePadding.bottom = elevationValue; + DY = 0; + break; + case Gravity.TOP: + shapeDrawablePadding.top = elevationValue*2; + shapeDrawablePadding.bottom = elevationValue; + DY = -1*elevationValue/3; + break; + default: + case Gravity.BOTTOM: + shapeDrawablePadding.top = elevationValue; + shapeDrawablePadding.bottom = elevationValue*2; + DY = elevationValue/3; + break; + } + + ShapeDrawable shapeDrawable = new ShapeDrawable(); + shapeDrawable.setPadding(shapeDrawablePadding); + + shapeDrawable.getPaint().setColor(backgroundColorValue); + shapeDrawable.getPaint().setShadowLayer(cornerRadiusValue/3, 0, DY, shadowColorValue); + + view.setLayerType(LAYER_TYPE_SOFTWARE, shapeDrawable.getPaint()); + + shapeDrawable.setShape(new RoundRectShape(outerRadius, null, null)); + + LayerDrawable drawable = new LayerDrawable(new Drawable[]{shapeDrawable}); + drawable.setLayerInset(0, elevationValue, elevationValue*2, elevationValue, elevationValue*2); + + return drawable; + + } +} diff --git a/app/src/main/java/com/cpm/lorealbaautomation/viewModel/MyCountViewModel.java b/app/src/main/java/com/cpm/lorealbaautomation/viewModel/MyCountViewModel.java new file mode 100644 index 0000000..f875c70 --- /dev/null +++ b/app/src/main/java/com/cpm/lorealbaautomation/viewModel/MyCountViewModel.java @@ -0,0 +1,19 @@ +package com.cpm.lorealbaautomation.viewModel; + +import androidx.lifecycle.MutableLiveData; +import androidx.lifecycle.ViewModel; + +public class MyCountViewModel extends ViewModel { + + public MutableLiveData count; + + public MutableLiveData getCount() { + + if(count==null){ + count = new MutableLiveData<>(); + count.setValue("0"); + } + return count; + } +} + diff --git a/app/src/main/res/anim/activity_back_in.xml b/app/src/main/res/anim/activity_back_in.xml new file mode 100644 index 0000000..c1704a7 --- /dev/null +++ b/app/src/main/res/anim/activity_back_in.xml @@ -0,0 +1,7 @@ + + + + \ No newline at end of file diff --git a/app/src/main/res/anim/activity_back_out.xml b/app/src/main/res/anim/activity_back_out.xml new file mode 100644 index 0000000..2d13167 --- /dev/null +++ b/app/src/main/res/anim/activity_back_out.xml @@ -0,0 +1,7 @@ + + + + \ No newline at end of file diff --git a/app/src/main/res/anim/activity_in.xml b/app/src/main/res/anim/activity_in.xml new file mode 100644 index 0000000..54cc7ae --- /dev/null +++ b/app/src/main/res/anim/activity_in.xml @@ -0,0 +1,7 @@ + + + + \ No newline at end of file diff --git a/app/src/main/res/anim/activity_out.xml b/app/src/main/res/anim/activity_out.xml new file mode 100644 index 0000000..4af3c86 --- /dev/null +++ b/app/src/main/res/anim/activity_out.xml @@ -0,0 +1,7 @@ + + + + \ No newline at end of file diff --git a/app/src/main/res/anim/alpha.xml b/app/src/main/res/anim/alpha.xml new file mode 100644 index 0000000..62f84a6 --- /dev/null +++ b/app/src/main/res/anim/alpha.xml @@ -0,0 +1,6 @@ + + \ No newline at end of file diff --git a/app/src/main/res/anim/bounce.xml b/app/src/main/res/anim/bounce.xml new file mode 100644 index 0000000..17635aa --- /dev/null +++ b/app/src/main/res/anim/bounce.xml @@ -0,0 +1,8 @@ + + + + \ No newline at end of file diff --git a/app/src/main/res/anim/bounce_with_zoom.xml b/app/src/main/res/anim/bounce_with_zoom.xml new file mode 100644 index 0000000..39defda --- /dev/null +++ b/app/src/main/res/anim/bounce_with_zoom.xml @@ -0,0 +1,27 @@ + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/anim/fab2_hide.xml b/app/src/main/res/anim/fab2_hide.xml new file mode 100644 index 0000000..e85bcbf --- /dev/null +++ b/app/src/main/res/anim/fab2_hide.xml @@ -0,0 +1,21 @@ + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/anim/fab2_show.xml b/app/src/main/res/anim/fab2_show.xml new file mode 100644 index 0000000..eef4b68 --- /dev/null +++ b/app/src/main/res/anim/fab2_show.xml @@ -0,0 +1,32 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/anim/fab_hide.xml b/app/src/main/res/anim/fab_hide.xml new file mode 100644 index 0000000..d533454 --- /dev/null +++ b/app/src/main/res/anim/fab_hide.xml @@ -0,0 +1,21 @@ + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/anim/fab_show.xml b/app/src/main/res/anim/fab_show.xml new file mode 100644 index 0000000..2473127 --- /dev/null +++ b/app/src/main/res/anim/fab_show.xml @@ -0,0 +1,32 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/anim/slide_in_bottom.xml b/app/src/main/res/anim/slide_in_bottom.xml new file mode 100644 index 0000000..e1d5802 --- /dev/null +++ b/app/src/main/res/anim/slide_in_bottom.xml @@ -0,0 +1,19 @@ + + + + + + \ No newline at end of file diff --git a/app/src/main/res/anim/translate.xml b/app/src/main/res/anim/translate.xml new file mode 100644 index 0000000..53b20fe --- /dev/null +++ b/app/src/main/res/anim/translate.xml @@ -0,0 +1,14 @@ + + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable-v21/ic_menu_camera.xml b/app/src/main/res/drawable-v21/ic_menu_camera.xml new file mode 100644 index 0000000..634fe92 --- /dev/null +++ b/app/src/main/res/drawable-v21/ic_menu_camera.xml @@ -0,0 +1,12 @@ + + + + diff --git a/app/src/main/res/drawable-v21/ic_menu_gallery.xml b/app/src/main/res/drawable-v21/ic_menu_gallery.xml new file mode 100644 index 0000000..03c7709 --- /dev/null +++ b/app/src/main/res/drawable-v21/ic_menu_gallery.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable-v21/ic_menu_manage.xml b/app/src/main/res/drawable-v21/ic_menu_manage.xml new file mode 100644 index 0000000..aeb047d --- /dev/null +++ b/app/src/main/res/drawable-v21/ic_menu_manage.xml @@ -0,0 +1,9 @@ + + + \ No newline at end of file diff --git a/app/src/main/res/drawable-v21/ic_menu_send.xml b/app/src/main/res/drawable-v21/ic_menu_send.xml new file mode 100644 index 0000000..fdf1c90 --- /dev/null +++ b/app/src/main/res/drawable-v21/ic_menu_send.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable-v21/ic_menu_share.xml b/app/src/main/res/drawable-v21/ic_menu_share.xml new file mode 100644 index 0000000..338d95a --- /dev/null +++ b/app/src/main/res/drawable-v21/ic_menu_share.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable-v21/ic_menu_slideshow.xml b/app/src/main/res/drawable-v21/ic_menu_slideshow.xml new file mode 100644 index 0000000..5e9e163 --- /dev/null +++ b/app/src/main/res/drawable-v21/ic_menu_slideshow.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable-v24/ic_launcher_foreground.xml b/app/src/main/res/drawable-v24/ic_launcher_foreground.xml new file mode 100644 index 0000000..1f6bb29 --- /dev/null +++ b/app/src/main/res/drawable-v24/ic_launcher_foreground.xml @@ -0,0 +1,34 @@ + + + + + + + + + + + diff --git a/app/src/main/res/drawable/ach_fill.xml b/app/src/main/res/drawable/ach_fill.xml new file mode 100644 index 0000000..69e35ea --- /dev/null +++ b/app/src/main/res/drawable/ach_fill.xml @@ -0,0 +1,7 @@ + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/add.png b/app/src/main/res/drawable/add.png new file mode 100644 index 0000000..fe41302 Binary files /dev/null and b/app/src/main/res/drawable/add.png differ diff --git a/app/src/main/res/drawable/badge_background.xml b/app/src/main/res/drawable/badge_background.xml new file mode 100644 index 0000000..4e2380c --- /dev/null +++ b/app/src/main/res/drawable/badge_background.xml @@ -0,0 +1,11 @@ + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/bck_attendance.xml b/app/src/main/res/drawable/bck_attendance.xml new file mode 100644 index 0000000..b9e5ba8 --- /dev/null +++ b/app/src/main/res/drawable/bck_attendance.xml @@ -0,0 +1,13 @@ + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/big_button_background.xml b/app/src/main/res/drawable/big_button_background.xml new file mode 100644 index 0000000..2ca2531 --- /dev/null +++ b/app/src/main/res/drawable/big_button_background.xml @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/big_button_effect.xml b/app/src/main/res/drawable/big_button_effect.xml new file mode 100644 index 0000000..cbaad8d --- /dev/null +++ b/app/src/main/res/drawable/big_button_effect.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/blank_screen.jpg b/app/src/main/res/drawable/blank_screen.jpg new file mode 100644 index 0000000..b824082 Binary files /dev/null and b/app/src/main/res/drawable/blank_screen.jpg differ diff --git a/app/src/main/res/drawable/button_background.xml b/app/src/main/res/drawable/button_background.xml new file mode 100644 index 0000000..c61a1b5 --- /dev/null +++ b/app/src/main/res/drawable/button_background.xml @@ -0,0 +1,14 @@ + + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/cancel.png b/app/src/main/res/drawable/cancel.png new file mode 100644 index 0000000..05251d5 Binary files /dev/null and b/app/src/main/res/drawable/cancel.png differ diff --git a/app/src/main/res/drawable/cancel_image.png b/app/src/main/res/drawable/cancel_image.png new file mode 100644 index 0000000..754f468 Binary files /dev/null and b/app/src/main/res/drawable/cancel_image.png differ diff --git a/app/src/main/res/drawable/card_bg.xml b/app/src/main/res/drawable/card_bg.xml new file mode 100644 index 0000000..7f96df0 --- /dev/null +++ b/app/src/main/res/drawable/card_bg.xml @@ -0,0 +1,13 @@ + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/circle_black.xml b/app/src/main/res/drawable/circle_black.xml new file mode 100644 index 0000000..6da0ad6 --- /dev/null +++ b/app/src/main/res/drawable/circle_black.xml @@ -0,0 +1,6 @@ + + + + + + diff --git a/app/src/main/res/drawable/complete_icon.png b/app/src/main/res/drawable/complete_icon.png new file mode 100644 index 0000000..25f299d Binary files /dev/null and b/app/src/main/res/drawable/complete_icon.png differ diff --git a/app/src/main/res/drawable/cross.png b/app/src/main/res/drawable/cross.png new file mode 100644 index 0000000..11d95bc Binary files /dev/null and b/app/src/main/res/drawable/cross.png differ diff --git a/app/src/main/res/drawable/dailog_background.xml b/app/src/main/res/drawable/dailog_background.xml new file mode 100644 index 0000000..47b2827 --- /dev/null +++ b/app/src/main/res/drawable/dailog_background.xml @@ -0,0 +1,10 @@ + + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/draft_icon.png b/app/src/main/res/drawable/draft_icon.png new file mode 100644 index 0000000..f017938 Binary files /dev/null and b/app/src/main/res/drawable/draft_icon.png differ diff --git a/app/src/main/res/drawable/edit_icon_white.png b/app/src/main/res/drawable/edit_icon_white.png new file mode 100644 index 0000000..c08531f Binary files /dev/null and b/app/src/main/res/drawable/edit_icon_white.png differ diff --git a/app/src/main/res/drawable/edit_text_border.xml b/app/src/main/res/drawable/edit_text_border.xml new file mode 100644 index 0000000..2fa7643 --- /dev/null +++ b/app/src/main/res/drawable/edit_text_border.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/edit_txt.png b/app/src/main/res/drawable/edit_txt.png new file mode 100644 index 0000000..fd5cdb6 Binary files /dev/null and b/app/src/main/res/drawable/edit_txt.png differ diff --git a/app/src/main/res/drawable/example_drawable.xml b/app/src/main/res/drawable/example_drawable.xml new file mode 100644 index 0000000..e06220b --- /dev/null +++ b/app/src/main/res/drawable/example_drawable.xml @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/drawable/example_drawable_with_grey_disabled.xml b/app/src/main/res/drawable/example_drawable_with_grey_disabled.xml new file mode 100644 index 0000000..ff1aa70 --- /dev/null +++ b/app/src/main/res/drawable/example_drawable_with_grey_disabled.xml @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/drawable/filter_icon.png b/app/src/main/res/drawable/filter_icon.png new file mode 100644 index 0000000..9223d42 Binary files /dev/null and b/app/src/main/res/drawable/filter_icon.png differ diff --git a/app/src/main/res/drawable/gradient_bsg.xml b/app/src/main/res/drawable/gradient_bsg.xml new file mode 100644 index 0000000..cb51c77 --- /dev/null +++ b/app/src/main/res/drawable/gradient_bsg.xml @@ -0,0 +1,15 @@ + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/home_icon.png b/app/src/main/res/drawable/home_icon.png new file mode 100644 index 0000000..b1e7171 Binary files /dev/null and b/app/src/main/res/drawable/home_icon.png differ diff --git a/app/src/main/res/drawable/ic_circle_applied_leave.xml b/app/src/main/res/drawable/ic_circle_applied_leave.xml new file mode 100644 index 0000000..08f37c9 --- /dev/null +++ b/app/src/main/res/drawable/ic_circle_applied_leave.xml @@ -0,0 +1,6 @@ + + + + + + diff --git a/app/src/main/res/drawable/ic_circle_approved_leave.xml b/app/src/main/res/drawable/ic_circle_approved_leave.xml new file mode 100644 index 0000000..c7fa3fb --- /dev/null +++ b/app/src/main/res/drawable/ic_circle_approved_leave.xml @@ -0,0 +1,6 @@ + + + + + + diff --git a/app/src/main/res/drawable/ic_circle_gov_leave.xml b/app/src/main/res/drawable/ic_circle_gov_leave.xml new file mode 100644 index 0000000..5772db2 --- /dev/null +++ b/app/src/main/res/drawable/ic_circle_gov_leave.xml @@ -0,0 +1,6 @@ + + + + + + diff --git a/app/src/main/res/drawable/ic_gradient_approved.xml b/app/src/main/res/drawable/ic_gradient_approved.xml new file mode 100644 index 0000000..8b4b163 --- /dev/null +++ b/app/src/main/res/drawable/ic_gradient_approved.xml @@ -0,0 +1,6 @@ + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/ic_imageupload.xml b/app/src/main/res/drawable/ic_imageupload.xml new file mode 100644 index 0000000..2552983 --- /dev/null +++ b/app/src/main/res/drawable/ic_imageupload.xml @@ -0,0 +1,42 @@ + + + + + + + + + + + + + + diff --git a/app/src/main/res/drawable/ic_launcher_background.xml b/app/src/main/res/drawable/ic_launcher_background.xml new file mode 100644 index 0000000..0d025f9 --- /dev/null +++ b/app/src/main/res/drawable/ic_launcher_background.xml @@ -0,0 +1,170 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/drawable/ic_round_corner.xml b/app/src/main/res/drawable/ic_round_corner.xml new file mode 100644 index 0000000..736ba40 --- /dev/null +++ b/app/src/main/res/drawable/ic_round_corner.xml @@ -0,0 +1,12 @@ + + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/incomplete_icon.png b/app/src/main/res/drawable/incomplete_icon.png new file mode 100644 index 0000000..58da548 Binary files /dev/null and b/app/src/main/res/drawable/incomplete_icon.png differ diff --git a/app/src/main/res/drawable/indicator_background.xml b/app/src/main/res/drawable/indicator_background.xml new file mode 100644 index 0000000..5e86ce0 --- /dev/null +++ b/app/src/main/res/drawable/indicator_background.xml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/indicator_effect.xml b/app/src/main/res/drawable/indicator_effect.xml new file mode 100644 index 0000000..d5ccf14 --- /dev/null +++ b/app/src/main/res/drawable/indicator_effect.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/notifications.png b/app/src/main/res/drawable/notifications.png new file mode 100644 index 0000000..debfb8c Binary files /dev/null and b/app/src/main/res/drawable/notifications.png differ diff --git a/app/src/main/res/drawable/ok_btn.png b/app/src/main/res/drawable/ok_btn.png new file mode 100644 index 0000000..98d40c0 Binary files /dev/null and b/app/src/main/res/drawable/ok_btn.png differ diff --git a/app/src/main/res/drawable/out_line_border.xml b/app/src/main/res/drawable/out_line_border.xml new file mode 100644 index 0000000..42f0cf2 --- /dev/null +++ b/app/src/main/res/drawable/out_line_border.xml @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/profile_bg.xml b/app/src/main/res/drawable/profile_bg.xml new file mode 100644 index 0000000..d2388c4 --- /dev/null +++ b/app/src/main/res/drawable/profile_bg.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/rouded_corner.xml b/app/src/main/res/drawable/rouded_corner.xml new file mode 100644 index 0000000..3735456 --- /dev/null +++ b/app/src/main/res/drawable/rouded_corner.xml @@ -0,0 +1,9 @@ + + + + + diff --git a/app/src/main/res/drawable/rouded_corner_btn_cons.xml b/app/src/main/res/drawable/rouded_corner_btn_cons.xml new file mode 100644 index 0000000..a4cb255 --- /dev/null +++ b/app/src/main/res/drawable/rouded_corner_btn_cons.xml @@ -0,0 +1,9 @@ + + + + + diff --git a/app/src/main/res/drawable/rouded_corner_edittaxt.xml b/app/src/main/res/drawable/rouded_corner_edittaxt.xml new file mode 100644 index 0000000..ad77dbb --- /dev/null +++ b/app/src/main/res/drawable/rouded_corner_edittaxt.xml @@ -0,0 +1,10 @@ + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/rouded_corner_edt.xml b/app/src/main/res/drawable/rouded_corner_edt.xml new file mode 100644 index 0000000..6bbe9df --- /dev/null +++ b/app/src/main/res/drawable/rouded_corner_edt.xml @@ -0,0 +1,14 @@ + + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/rouded_corner_gray.xml b/app/src/main/res/drawable/rouded_corner_gray.xml new file mode 100644 index 0000000..b3cb024 --- /dev/null +++ b/app/src/main/res/drawable/rouded_corner_gray.xml @@ -0,0 +1,9 @@ + + + + + diff --git a/app/src/main/res/drawable/rouded_corner_green.xml b/app/src/main/res/drawable/rouded_corner_green.xml new file mode 100644 index 0000000..626ca4e --- /dev/null +++ b/app/src/main/res/drawable/rouded_corner_green.xml @@ -0,0 +1,9 @@ + + + + + diff --git a/app/src/main/res/drawable/rouded_corner_pinki.xml b/app/src/main/res/drawable/rouded_corner_pinki.xml new file mode 100644 index 0000000..af2960f --- /dev/null +++ b/app/src/main/res/drawable/rouded_corner_pinki.xml @@ -0,0 +1,14 @@ + + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/rouded_corner_white.xml b/app/src/main/res/drawable/rouded_corner_white.xml new file mode 100644 index 0000000..c710a4a --- /dev/null +++ b/app/src/main/res/drawable/rouded_corner_white.xml @@ -0,0 +1,12 @@ + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/round_btn_color_primary.xml b/app/src/main/res/drawable/round_btn_color_primary.xml new file mode 100644 index 0000000..6bbe9df --- /dev/null +++ b/app/src/main/res/drawable/round_btn_color_primary.xml @@ -0,0 +1,14 @@ + + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/round_button.xml b/app/src/main/res/drawable/round_button.xml new file mode 100644 index 0000000..826343a --- /dev/null +++ b/app/src/main/res/drawable/round_button.xml @@ -0,0 +1,9 @@ + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/round_corner_grey.xml b/app/src/main/res/drawable/round_corner_grey.xml new file mode 100644 index 0000000..6ae1b54 --- /dev/null +++ b/app/src/main/res/drawable/round_corner_grey.xml @@ -0,0 +1,10 @@ + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/round_corner_parent.xml b/app/src/main/res/drawable/round_corner_parent.xml new file mode 100644 index 0000000..8fe2ae6 --- /dev/null +++ b/app/src/main/res/drawable/round_corner_parent.xml @@ -0,0 +1,16 @@ + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/round_layout.xml b/app/src/main/res/drawable/round_layout.xml new file mode 100644 index 0000000..dd8c151 --- /dev/null +++ b/app/src/main/res/drawable/round_layout.xml @@ -0,0 +1,11 @@ + + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/rounded_corner_delete.xml b/app/src/main/res/drawable/rounded_corner_delete.xml new file mode 100644 index 0000000..64cda10 --- /dev/null +++ b/app/src/main/res/drawable/rounded_corner_delete.xml @@ -0,0 +1,9 @@ + + + + + diff --git a/app/src/main/res/drawable/rounded_corner_leave.xml b/app/src/main/res/drawable/rounded_corner_leave.xml new file mode 100644 index 0000000..ea8889e --- /dev/null +++ b/app/src/main/res/drawable/rounded_corner_leave.xml @@ -0,0 +1,9 @@ + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/save_icon.png b/app/src/main/res/drawable/save_icon.png new file mode 100644 index 0000000..6ce2526 Binary files /dev/null and b/app/src/main/res/drawable/save_icon.png differ diff --git a/app/src/main/res/drawable/search.png b/app/src/main/res/drawable/search.png new file mode 100644 index 0000000..a2d05f5 Binary files /dev/null and b/app/src/main/res/drawable/search.png differ diff --git a/app/src/main/res/drawable/side_nav_bar.xml b/app/src/main/res/drawable/side_nav_bar.xml new file mode 100644 index 0000000..0534fdb --- /dev/null +++ b/app/src/main/res/drawable/side_nav_bar.xml @@ -0,0 +1,9 @@ + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/sliding_square_loader_view.gif b/app/src/main/res/drawable/sliding_square_loader_view.gif new file mode 100644 index 0000000..021ee62 Binary files /dev/null and b/app/src/main/res/drawable/sliding_square_loader_view.gif differ diff --git a/app/src/main/res/drawable/small_button_background.xml b/app/src/main/res/drawable/small_button_background.xml new file mode 100644 index 0000000..a467b7c --- /dev/null +++ b/app/src/main/res/drawable/small_button_background.xml @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/small_button_effect.xml b/app/src/main/res/drawable/small_button_effect.xml new file mode 100644 index 0000000..cbaad8d --- /dev/null +++ b/app/src/main/res/drawable/small_button_effect.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/smartphone_drib.gif b/app/src/main/res/drawable/smartphone_drib.gif new file mode 100644 index 0000000..4089171 Binary files /dev/null and b/app/src/main/res/drawable/smartphone_drib.gif differ diff --git a/app/src/main/res/drawable/submit.png b/app/src/main/res/drawable/submit.png new file mode 100644 index 0000000..640a7eb Binary files /dev/null and b/app/src/main/res/drawable/submit.png differ diff --git a/app/src/main/res/drawable/target_fill.xml b/app/src/main/res/drawable/target_fill.xml new file mode 100644 index 0000000..808354a --- /dev/null +++ b/app/src/main/res/drawable/target_fill.xml @@ -0,0 +1,7 @@ + + + + \ No newline at end of file diff --git a/app/src/main/res/layout-sw600dp/activity_ba_survey.xml b/app/src/main/res/layout-sw600dp/activity_ba_survey.xml new file mode 100644 index 0000000..0bb711b --- /dev/null +++ b/app/src/main/res/layout-sw600dp/activity_ba_survey.xml @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout-sw600dp/activity_ba_survey_list.xml b/app/src/main/res/layout-sw600dp/activity_ba_survey_list.xml new file mode 100644 index 0000000..54afabe --- /dev/null +++ b/app/src/main/res/layout-sw600dp/activity_ba_survey_list.xml @@ -0,0 +1,25 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout-sw600dp/activity_baprofile.xml b/app/src/main/res/layout-sw600dp/activity_baprofile.xml new file mode 100644 index 0000000..cdca012 --- /dev/null +++ b/app/src/main/res/layout-sw600dp/activity_baprofile.xml @@ -0,0 +1,35 @@ + + + + + + + + + + + + + diff --git a/app/src/main/res/layout-sw600dp/activity_consumer_return.xml b/app/src/main/res/layout-sw600dp/activity_consumer_return.xml new file mode 100644 index 0000000..c46080d --- /dev/null +++ b/app/src/main/res/layout-sw600dp/activity_consumer_return.xml @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout-sw600dp/activity_counter.xml b/app/src/main/res/layout-sw600dp/activity_counter.xml new file mode 100644 index 0000000..eda083a --- /dev/null +++ b/app/src/main/res/layout-sw600dp/activity_counter.xml @@ -0,0 +1,40 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout-sw600dp/activity_counter_image.xml b/app/src/main/res/layout-sw600dp/activity_counter_image.xml new file mode 100644 index 0000000..e1bfc98 --- /dev/null +++ b/app/src/main/res/layout-sw600dp/activity_counter_image.xml @@ -0,0 +1,39 @@ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout-sw600dp/activity_counter_login.xml b/app/src/main/res/layout-sw600dp/activity_counter_login.xml new file mode 100644 index 0000000..c439720 --- /dev/null +++ b/app/src/main/res/layout-sw600dp/activity_counter_login.xml @@ -0,0 +1,41 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout-sw600dp/activity_counter_profile.xml b/app/src/main/res/layout-sw600dp/activity_counter_profile.xml new file mode 100644 index 0000000..4cadd46 --- /dev/null +++ b/app/src/main/res/layout-sw600dp/activity_counter_profile.xml @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + diff --git a/app/src/main/res/layout-sw600dp/activity_download.xml b/app/src/main/res/layout-sw600dp/activity_download.xml new file mode 100644 index 0000000..099fee1 --- /dev/null +++ b/app/src/main/res/layout-sw600dp/activity_download.xml @@ -0,0 +1,55 @@ + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/layout-sw600dp/activity_groomed.xml b/app/src/main/res/layout-sw600dp/activity_groomed.xml new file mode 100644 index 0000000..a47fa5d --- /dev/null +++ b/app/src/main/res/layout-sw600dp/activity_groomed.xml @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + diff --git a/app/src/main/res/layout-sw600dp/activity_in_ward_stock.xml b/app/src/main/res/layout-sw600dp/activity_in_ward_stock.xml new file mode 100644 index 0000000..2fa2051 --- /dev/null +++ b/app/src/main/res/layout-sw600dp/activity_in_ward_stock.xml @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/layout-sw600dp/activity_inward_stock_details.xml b/app/src/main/res/layout-sw600dp/activity_inward_stock_details.xml new file mode 100644 index 0000000..07ee021 --- /dev/null +++ b/app/src/main/res/layout-sw600dp/activity_inward_stock_details.xml @@ -0,0 +1,49 @@ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout-sw600dp/activity_leave_calender.xml b/app/src/main/res/layout-sw600dp/activity_leave_calender.xml new file mode 100644 index 0000000..1fb24fa --- /dev/null +++ b/app/src/main/res/layout-sw600dp/activity_leave_calender.xml @@ -0,0 +1,97 @@ + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/layout-sw600dp/content_promo_offer_details.xml b/app/src/main/res/layout-sw600dp/content_promo_offer_details.xml new file mode 100644 index 0000000..d981bf9 --- /dev/null +++ b/app/src/main/res/layout-sw600dp/content_promo_offer_details.xml @@ -0,0 +1,195 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/layout-sw600dp/content_promo_offers.xml b/app/src/main/res/layout-sw600dp/content_promo_offers.xml new file mode 100644 index 0000000..8e18c04 --- /dev/null +++ b/app/src/main/res/layout-sw600dp/content_promo_offers.xml @@ -0,0 +1,19 @@ + + + + + + diff --git a/app/src/main/res/layout-sw600dp/content_report.xml b/app/src/main/res/layout-sw600dp/content_report.xml new file mode 100644 index 0000000..b6b5d84 --- /dev/null +++ b/app/src/main/res/layout-sw600dp/content_report.xml @@ -0,0 +1,134 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/layout-sw600dp/content_report_attendance.xml b/app/src/main/res/layout-sw600dp/content_report_attendance.xml new file mode 100644 index 0000000..0785259 --- /dev/null +++ b/app/src/main/res/layout-sw600dp/content_report_attendance.xml @@ -0,0 +1,159 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/layout-sw600dp/content_report_ba_availability.xml b/app/src/main/res/layout-sw600dp/content_report_ba_availability.xml new file mode 100644 index 0000000..db1f7a6 --- /dev/null +++ b/app/src/main/res/layout-sw600dp/content_report_ba_availability.xml @@ -0,0 +1,102 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/layout-sw600dp/content_report_consumer_product_wise.xml b/app/src/main/res/layout-sw600dp/content_report_consumer_product_wise.xml new file mode 100644 index 0000000..2fea889 --- /dev/null +++ b/app/src/main/res/layout-sw600dp/content_report_consumer_product_wise.xml @@ -0,0 +1,113 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/layout-sw600dp/content_report_consumer_wise.xml b/app/src/main/res/layout-sw600dp/content_report_consumer_wise.xml new file mode 100644 index 0000000..48cdddf --- /dev/null +++ b/app/src/main/res/layout-sw600dp/content_report_consumer_wise.xml @@ -0,0 +1,125 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/layout-sw600dp/content_report_daily_tva.xml b/app/src/main/res/layout-sw600dp/content_report_daily_tva.xml new file mode 100644 index 0000000..37bbbff --- /dev/null +++ b/app/src/main/res/layout-sw600dp/content_report_daily_tva.xml @@ -0,0 +1,241 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/layout-sw600dp/content_report_damagedstockhistory.xml b/app/src/main/res/layout-sw600dp/content_report_damagedstockhistory.xml new file mode 100644 index 0000000..41e8388 --- /dev/null +++ b/app/src/main/res/layout-sw600dp/content_report_damagedstockhistory.xml @@ -0,0 +1,146 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/layout-sw600dp/content_report_daywise.xml b/app/src/main/res/layout-sw600dp/content_report_daywise.xml new file mode 100644 index 0000000..6881c14 --- /dev/null +++ b/app/src/main/res/layout-sw600dp/content_report_daywise.xml @@ -0,0 +1,164 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/layout-sw600dp/content_report_inword.xml b/app/src/main/res/layout-sw600dp/content_report_inword.xml new file mode 100644 index 0000000..382a718 --- /dev/null +++ b/app/src/main/res/layout-sw600dp/content_report_inword.xml @@ -0,0 +1,165 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/layout-sw600dp/content_report_me_sale.xml b/app/src/main/res/layout-sw600dp/content_report_me_sale.xml new file mode 100644 index 0000000..21ddbe7 --- /dev/null +++ b/app/src/main/res/layout-sw600dp/content_report_me_sale.xml @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/layout-sw600dp/content_report_proforma_invoice.xml b/app/src/main/res/layout-sw600dp/content_report_proforma_invoice.xml new file mode 100644 index 0000000..a04affc --- /dev/null +++ b/app/src/main/res/layout-sw600dp/content_report_proforma_invoice.xml @@ -0,0 +1,238 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/layout-sw600dp/content_report_sale_details.xml b/app/src/main/res/layout-sw600dp/content_report_sale_details.xml new file mode 100644 index 0000000..6ba5d3f --- /dev/null +++ b/app/src/main/res/layout-sw600dp/content_report_sale_details.xml @@ -0,0 +1,544 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/layout-sw600dp/content_report_tester.xml b/app/src/main/res/layout-sw600dp/content_report_tester.xml new file mode 100644 index 0000000..e66ec9b --- /dev/null +++ b/app/src/main/res/layout-sw600dp/content_report_tester.xml @@ -0,0 +1,184 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/layout-sw600dp/content_reports_list.xml b/app/src/main/res/layout-sw600dp/content_reports_list.xml new file mode 100644 index 0000000..cf5f438 --- /dev/null +++ b/app/src/main/res/layout-sw600dp/content_reports_list.xml @@ -0,0 +1,20 @@ + + + + + + + diff --git a/app/src/main/res/layout-sw600dp/content_retail_excellence.xml b/app/src/main/res/layout-sw600dp/content_retail_excellence.xml new file mode 100644 index 0000000..c7e568b --- /dev/null +++ b/app/src/main/res/layout-sw600dp/content_retail_excellence.xml @@ -0,0 +1,21 @@ + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout-sw600dp/content_returns_history.xml b/app/src/main/res/layout-sw600dp/content_returns_history.xml new file mode 100644 index 0000000..86baef0 --- /dev/null +++ b/app/src/main/res/layout-sw600dp/content_returns_history.xml @@ -0,0 +1,19 @@ + + + + + + diff --git a/app/src/main/res/layout-sw600dp/content_sales_report.xml b/app/src/main/res/layout-sw600dp/content_sales_report.xml new file mode 100644 index 0000000..ac39d4c --- /dev/null +++ b/app/src/main/res/layout-sw600dp/content_sales_report.xml @@ -0,0 +1,98 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout-sw600dp/content_skin_genius_category.xml b/app/src/main/res/layout-sw600dp/content_skin_genius_category.xml new file mode 100644 index 0000000..e3b462d --- /dev/null +++ b/app/src/main/res/layout-sw600dp/content_skin_genius_category.xml @@ -0,0 +1,174 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout-sw600dp/content_skin_genius_screenshots.xml b/app/src/main/res/layout-sw600dp/content_skin_genius_screenshots.xml new file mode 100644 index 0000000..056bcfb --- /dev/null +++ b/app/src/main/res/layout-sw600dp/content_skin_genius_screenshots.xml @@ -0,0 +1,75 @@ + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout-sw600dp/content_stock_check.xml b/app/src/main/res/layout-sw600dp/content_stock_check.xml new file mode 100644 index 0000000..41f5db0 --- /dev/null +++ b/app/src/main/res/layout-sw600dp/content_stock_check.xml @@ -0,0 +1,226 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout-sw600dp/content_store_image.xml b/app/src/main/res/layout-sw600dp/content_store_image.xml new file mode 100644 index 0000000..bd90734 --- /dev/null +++ b/app/src/main/res/layout-sw600dp/content_store_image.xml @@ -0,0 +1,68 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/layout/activity_invoice_report_proforma.xml b/app/src/main/res/layout/activity_invoice_report_proforma.xml new file mode 100644 index 0000000..7845b18 --- /dev/null +++ b/app/src/main/res/layout/activity_invoice_report_proforma.xml @@ -0,0 +1,56 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/layout/activity_inward_stock_details.xml b/app/src/main/res/layout/activity_inward_stock_details.xml new file mode 100644 index 0000000..b061605 --- /dev/null +++ b/app/src/main/res/layout/activity_inward_stock_details.xml @@ -0,0 +1,49 @@ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/activity_kpi_tracker.xml b/app/src/main/res/layout/activity_kpi_tracker.xml new file mode 100644 index 0000000..03af6ae --- /dev/null +++ b/app/src/main/res/layout/activity_kpi_tracker.xml @@ -0,0 +1,40 @@ + + + + + + + + + + + + diff --git a/app/src/main/res/layout/activity_leave_calender.xml b/app/src/main/res/layout/activity_leave_calender.xml new file mode 100644 index 0000000..f65d6c0 --- /dev/null +++ b/app/src/main/res/layout/activity_leave_calender.xml @@ -0,0 +1,97 @@ + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/layout/content_promo_offer_details.xml b/app/src/main/res/layout/content_promo_offer_details.xml new file mode 100644 index 0000000..daaabe0 --- /dev/null +++ b/app/src/main/res/layout/content_promo_offer_details.xml @@ -0,0 +1,193 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/layout/content_promo_offers.xml b/app/src/main/res/layout/content_promo_offers.xml new file mode 100644 index 0000000..8e18c04 --- /dev/null +++ b/app/src/main/res/layout/content_promo_offers.xml @@ -0,0 +1,19 @@ + + + + + + diff --git a/app/src/main/res/layout/content_report.xml b/app/src/main/res/layout/content_report.xml new file mode 100644 index 0000000..beea740 --- /dev/null +++ b/app/src/main/res/layout/content_report.xml @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/layout/content_report_attendance.xml b/app/src/main/res/layout/content_report_attendance.xml new file mode 100644 index 0000000..b88245b --- /dev/null +++ b/app/src/main/res/layout/content_report_attendance.xml @@ -0,0 +1,158 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/layout/content_report_ba_availability.xml b/app/src/main/res/layout/content_report_ba_availability.xml new file mode 100644 index 0000000..c9ce27e --- /dev/null +++ b/app/src/main/res/layout/content_report_ba_availability.xml @@ -0,0 +1,100 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/layout/content_report_consumer_product_wise.xml b/app/src/main/res/layout/content_report_consumer_product_wise.xml new file mode 100644 index 0000000..c59fcb7 --- /dev/null +++ b/app/src/main/res/layout/content_report_consumer_product_wise.xml @@ -0,0 +1,115 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/layout/content_report_consumer_wise.xml b/app/src/main/res/layout/content_report_consumer_wise.xml new file mode 100644 index 0000000..ccc34ca --- /dev/null +++ b/app/src/main/res/layout/content_report_consumer_wise.xml @@ -0,0 +1,125 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/layout/content_report_daily_tva.xml b/app/src/main/res/layout/content_report_daily_tva.xml new file mode 100644 index 0000000..6600560 --- /dev/null +++ b/app/src/main/res/layout/content_report_daily_tva.xml @@ -0,0 +1,240 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/layout/content_report_damagedstockhistory.xml b/app/src/main/res/layout/content_report_damagedstockhistory.xml new file mode 100644 index 0000000..3360288 --- /dev/null +++ b/app/src/main/res/layout/content_report_damagedstockhistory.xml @@ -0,0 +1,147 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/layout/content_report_daywise.xml b/app/src/main/res/layout/content_report_daywise.xml new file mode 100644 index 0000000..26aca8e --- /dev/null +++ b/app/src/main/res/layout/content_report_daywise.xml @@ -0,0 +1,164 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/layout/content_report_inword.xml b/app/src/main/res/layout/content_report_inword.xml new file mode 100644 index 0000000..dc5fbbd --- /dev/null +++ b/app/src/main/res/layout/content_report_inword.xml @@ -0,0 +1,156 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/layout/content_report_me_sale.xml b/app/src/main/res/layout/content_report_me_sale.xml new file mode 100644 index 0000000..b8eba93 --- /dev/null +++ b/app/src/main/res/layout/content_report_me_sale.xml @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/layout/content_report_proforma_invoice.xml b/app/src/main/res/layout/content_report_proforma_invoice.xml new file mode 100644 index 0000000..9403d85 --- /dev/null +++ b/app/src/main/res/layout/content_report_proforma_invoice.xml @@ -0,0 +1,243 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/layout/content_report_sale_details.xml b/app/src/main/res/layout/content_report_sale_details.xml new file mode 100644 index 0000000..dd3fb2f --- /dev/null +++ b/app/src/main/res/layout/content_report_sale_details.xml @@ -0,0 +1,543 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/layout/content_report_tester.xml b/app/src/main/res/layout/content_report_tester.xml new file mode 100644 index 0000000..b814d07 --- /dev/null +++ b/app/src/main/res/layout/content_report_tester.xml @@ -0,0 +1,175 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/layout/content_reports_list.xml b/app/src/main/res/layout/content_reports_list.xml new file mode 100644 index 0000000..cf5f438 --- /dev/null +++ b/app/src/main/res/layout/content_reports_list.xml @@ -0,0 +1,20 @@ + + + + + + + diff --git a/app/src/main/res/layout/content_retail_excellence.xml b/app/src/main/res/layout/content_retail_excellence.xml new file mode 100644 index 0000000..b010527 --- /dev/null +++ b/app/src/main/res/layout/content_retail_excellence.xml @@ -0,0 +1,25 @@ + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/content_returns_history.xml b/app/src/main/res/layout/content_returns_history.xml new file mode 100644 index 0000000..86baef0 --- /dev/null +++ b/app/src/main/res/layout/content_returns_history.xml @@ -0,0 +1,19 @@ + + + + + + diff --git a/app/src/main/res/layout/content_sales_check.xml b/app/src/main/res/layout/content_sales_check.xml new file mode 100644 index 0000000..15c4ff2 --- /dev/null +++ b/app/src/main/res/layout/content_sales_check.xml @@ -0,0 +1,231 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/content_sales_report.xml b/app/src/main/res/layout/content_sales_report.xml new file mode 100644 index 0000000..bbb9a8d --- /dev/null +++ b/app/src/main/res/layout/content_sales_report.xml @@ -0,0 +1,98 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/content_sample_stock.xml b/app/src/main/res/layout/content_sample_stock.xml new file mode 100644 index 0000000..a3776c2 --- /dev/null +++ b/app/src/main/res/layout/content_sample_stock.xml @@ -0,0 +1,11 @@ + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/content_skin_genius_category.xml b/app/src/main/res/layout/content_skin_genius_category.xml new file mode 100644 index 0000000..42bb7e7 --- /dev/null +++ b/app/src/main/res/layout/content_skin_genius_category.xml @@ -0,0 +1,173 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/content_skin_genius_screenshots.xml b/app/src/main/res/layout/content_skin_genius_screenshots.xml new file mode 100644 index 0000000..3c1dffa --- /dev/null +++ b/app/src/main/res/layout/content_skin_genius_screenshots.xml @@ -0,0 +1,73 @@ + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/content_stock_check.xml b/app/src/main/res/layout/content_stock_check.xml new file mode 100644 index 0000000..87b1c1b --- /dev/null +++ b/app/src/main/res/layout/content_stock_check.xml @@ -0,0 +1,230 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/content_store_image.xml b/app/src/main/res/layout/content_store_image.xml new file mode 100644 index 0000000..85706f9 --- /dev/null +++ b/app/src/main/res/layout/content_store_image.xml @@ -0,0 +1,70 @@ + + + + + + + + + + + + + + + + + + + +