From 45e424b8a122968700d0553d7b975ca79280042c Mon Sep 17 00:00:00 2001 From: ahsan Date: Thu, 24 May 2018 11:16:24 +0530 Subject: [PATCH] rentnride source file committed --- .bowerrc | 3 + .env.example | 26 + .gitignore | 17 + Gruntfile.js | 726 ++ README.md | 108 +- app/ApiRequest.php | 75 + app/Attachment.php | 40 + app/City.php | 116 + app/Console/Commands/.gitkeep | 0 app/Console/Commands/CurrencyCron.php | 47 + app/Console/Commands/GeoIpCron.php | 93 + app/Console/Commands/StatusUpdateCron.php | 59 + app/Console/Kernel.php | 45 + app/Country.php | 117 + app/Currency.php | 97 + app/DiscountType.php | 35 + app/DurationType.php | 51 + app/EmailTemplate.php | 75 + app/Events/Event.php | 23 + app/Exceptions/Handler.php | 63 + .../Admin/AdminApiRequestsController.php | 105 + .../Admin/AdminCitiesController.php | 216 + .../Admin/AdminCountriesController.php | 209 + .../Admin/AdminCurrenciesController.php | 185 + .../Admin/AdminDashboardsController.php | 131 + .../Admin/AdminEmailTemplatesController.php | 112 + .../Controllers/Admin/AdminIpsController.php | 106 + .../Admin/AdminLanguagesController.php | 161 + .../Admin/AdminMessagesController.php | 186 + .../Admin/AdminRolesController.php | 62 + .../AdminSettingCategoriesController.php | 109 + .../Admin/AdminSettingsController.php | 308 + .../Admin/AdminStatesController.php | 208 + .../Admin/AdminTransactionTypesController.php | 129 + .../Admin/AdminTransactionsController.php | 76 + .../Admin/AdminUserLoginsController.php | 121 + .../Admin/AdminUsersController.php | 314 + .../AdminWalletTransactionLogsController.php | 79 + app/Http/Controllers/AssetsController.php | 88 + app/Http/Controllers/CitiesController.php | 43 + app/Http/Controllers/Controller.php | 25 + app/Http/Controllers/CountriesController.php | 54 + app/Http/Controllers/CurrenciesController.php | 46 + app/Http/Controllers/ImagesController.php | 62 + app/Http/Controllers/LanguagesController.php | 41 + app/Http/Controllers/MessagesController.php | 352 + .../Controllers/PaymentGatewaysController.php | 135 + app/Http/Controllers/SettingsController.php | 67 + app/Http/Controllers/StatesController.php | 46 + .../TransactionTypesController.php | 55 + .../Controllers/TransactionsController.php | 66 + .../Controllers/UserProfilesController.php | 129 + app/Http/Controllers/UsersController.php | 358 + app/Http/Controllers/WalletsController.php | 140 + app/Http/Middleware/Authenticate.php | 55 + app/Http/Middleware/AuthenticateRole.php | 42 + app/Http/Middleware/Tracking.php | 79 + app/Http/Requests/CreateUserRequest.php | 70 + app/Http/Requests/Request.php | 23 + app/Http/routes.php | 230 + app/Ip.php | 109 + app/ItemUserStatus.php | 28 + app/Jobs/Job.php | 37 + app/Language.php | 98 + app/Message.php | 128 + app/MessageContent.php | 39 + app/Plugins/Analytics/plugin.json | 9 + app/Plugins/Banner/plugin.json | 9 + .../Admin/AdminContactsController.php | 100 + .../Controllers/ContactsController.php | 103 + app/Plugins/Contacts/Model/Contact.php | 114 + .../Providers/ContactServiceProvider.php | 43 + .../Contacts/Services/ContactService.php | 71 + .../Transformers/ContactTransformer.php | 76 + app/Plugins/Contacts/plugin.json | 9 + app/Plugins/Contacts/routes.php | 37 + ...nCurrencyConversionHistoriesController.php | 67 + .../AdminCurrencyConversionsController.php | 64 + .../Model/CurrencyConversion.php | 105 + .../Model/CurrencyConversionHistory.php | 106 + .../CurrencyConversionServiceProvider.php | 42 + .../Services/CurrencyConversionService.php | 84 + .../CurrencyConversionHistoryTransformer.php | 59 + .../CurrencyConversionTransformer.php | 74 + app/Plugins/CurrencyConversions/plugin.json | 9 + app/Plugins/CurrencyConversions/routes.php | 34 + .../Admin/AdminPagesController.php | 186 + .../Pages/Controllers/PagesController.php | 84 + app/Plugins/Pages/Model/Page.php | 106 + .../Pages/Providers/PageServiceProvider.php | 43 + .../Transformers/PageLanguageTransformer.php | 37 + .../Pages/Transformers/PageTransformer.php | 60 + app/Plugins/Pages/plugin.json | 9 + app/Plugins/Pages/routes.php | 41 + .../AdminPaypalTransactionLogsController.php | 82 + .../Paypal/Controllers/PaypalController.php | 84 + .../Paypal/Model/PaypalTransactionLog.php | 60 + .../Providers/PaypalServiceProvider.php | 44 + app/Plugins/Paypal/Services/PayPalService.php | 307 + .../Services/PaypalTransactionLogService.php | 52 + .../PaypalTransactionLogTransformer.php | 37 + app/Plugins/Paypal/plugin.json | 9 + app/Plugins/Paypal/routes.php | 36 + app/Plugins/PluginServiceProvider.php | 49 + .../Admin/AdminProvidersController.php | 135 + .../Controllers/ProvidersController.php | 53 + .../Controllers/SocialLoginsController.php | 666 ++ app/Plugins/SocialLogins/Model/Provider.php | 81 + .../SocialLogins/Model/ProviderUser.php | 39 + .../Providers/SocialLoginServiceProvider.php | 51 + .../Services/SocialLoginService.php | 80 + .../Transformers/ProviderTransformer.php | 37 + .../Transformers/ProviderUserTransformer.php | 62 + app/Plugins/SocialLogins/plugin.json | 9 + app/Plugins/SocialLogins/routes.php | 52 + .../Admin/AdminSudopayIpnLogsController.php | 82 + .../AdminSudopayTransactionLogsController.php | 80 + .../Admin/AdminSudopaysController.php | 110 + .../Controllers/SudopaysController.php | 118 + app/Plugins/Sudopays/Model/SudopayIpnLog.php | 38 + .../Sudopays/Model/SudopayPaymentGateway.php | 33 + .../Sudopays/Model/SudopayPaymentGroup.php | 33 + .../Sudopays/Model/SudopayTransactionLog.php | 65 + .../Providers/SudopayServiceProvider.php | 47 + .../Sudopays/Services/SudopayAPIService.php | 386 + .../Sudopays/Services/SudopayIpnService.php | 56 + .../Sudopays/Services/SudopayService.php | 347 + .../Services/SudopayTransactionLogService.php | 52 + .../Transformers/SudopayIpnLogTransformer.php | 38 + .../SudopayTransactionLogTransformer.php | 36 + app/Plugins/Sudopays/plugin.json | 9 + app/Plugins/Sudopays/routes.php | 41 + app/Plugins/Translations/plugin.json | 9 + .../Admin/AdminVehicleCouponsController.php | 226 + .../Controllers/VehicleCouponsController.php | 106 + .../VehicleCoupons/Model/VehicleCoupon.php | 123 + .../VehicleCouponServiceProvider.php | 45 + .../Services/VehicleCouponService.php | 31 + .../Transformers/VehicleCouponTransformer.php | 60 + app/Plugins/VehicleCoupons/plugin.json | 9 + app/Plugins/VehicleCoupons/routes.php | 42 + ...minVehicleDisputeClosedTypesController.php | 111 + .../AdminVehicleDisputeTypesController.php | 107 + .../Admin/AdminVehicleDisputesController.php | 165 + .../VehicleDisputeClosedTypesController.php | 55 + .../VehicleDisputeTypesController.php | 56 + .../Controllers/VehicleDisputesController.php | 227 + .../VehicleDisputes/Model/VehicleDispute.php | 161 + .../Model/VehicleDisputeClosedType.php | 104 + .../Model/VehicleDisputeStatus.php | 44 + .../Model/VehicleDisputeType.php | 97 + .../VehicleDisputeServiceProvider.php | 50 + .../VehicleDisputeClosedTypeService.php | 59 + .../Services/VehicleDisputeService.php | 496 ++ .../VehicleDisputeClosedTypeTransformer.php | 53 + .../VehicleDisputeStatusTransformer.php | 29 + .../VehicleDisputeTransformer.php | 146 + .../VehicleDisputeTypeTransformer.php | 31 + app/Plugins/VehicleDisputes/plugin.json | 9 + app/Plugins/VehicleDisputes/routes.php | 53 + ...AdminVehicleExtraAccessoriesController.php | 190 + ...nVehicleTypeExtraAccessoriesController.php | 188 + .../VehicleExtraAccessoriesController.php | 58 + .../VehicleTypeExtraAccessoriesController.php | 59 + .../Model/VehicleExtraAccessory.php | 101 + .../Model/VehicleTypeExtraAccessory.php | 151 + .../VehicleExtraAccessoryServiceProvider.php | 44 + .../Services/VehicleExtraAccessoryService.php | 67 + .../AdminVehicleExtraAccessoryTransformer.php | 40 + .../VehicleExtraAccessoryTransformer.php | 37 + .../VehicleTypeExtraAccessoryTransformer.php | 104 + .../VehicleExtraAccessories/plugin.json | 9 + .../VehicleExtraAccessories/routes.php | 51 + .../Admin/AdminVehicleFeedbacksController.php | 170 + .../VehicleFeedbacksController.php | 301 + .../Model/VehicleFeedback.php | 117 + .../VehicleFeedbackServiceProvider.php | 51 + .../Services/VehicleFeedbackService.php | 142 + .../VehicleFeedbackTransformer.php | 113 + app/Plugins/VehicleFeedbacks/plugin.json | 9 + app/Plugins/VehicleFeedbacks/routes.php | 44 + .../AdminVehicleFuelOptionsController.php | 190 + .../AdminVehicleTypeFuelOptionsController.php | 187 + .../VehicleFuelOptionsController.php | 58 + .../VehicleTypeFuelOptionsController.php | 59 + .../Model/VehicleFuelOption.php | 101 + .../Model/VehicleTypeFuelOption.php | 152 + .../VehicleFuelOptionServiceProvider.php | 44 + .../Services/VehicleFuelOptionService.php | 72 + .../AdminVehicleFuelOptionTransformer.php | 39 + .../VehicleFuelOptionTransformer.php | 37 + .../VehicleTypeFuelOptionTransformer.php | 104 + app/Plugins/VehicleFuelOptions/plugin.json | 9 + app/Plugins/VehicleFuelOptions/routes.php | 51 + .../AdminVehicleInsurancesController.php | 190 + .../AdminVehicleTypeInsurancesController.php | 196 + .../VehicleInsurancesController.php | 58 + .../VehicleTypeInsurancesController.php | 59 + .../Model/VehicleInsurance.php | 101 + .../Model/VehicleTypeInsurance.php | 160 + .../VehicleInsuranceServiceProvider.php | 44 + .../Services/VehicleInsuranceService.php | 71 + .../AdminVehicleInsuranceTransformer.php | 39 + .../VehicleInsuranceTransformer.php | 37 + .../VehicleTypeInsuranceTransformer.php | 104 + app/Plugins/VehicleInsurances/plugin.json | 9 + app/Plugins/VehicleInsurances/routes.php | 51 + .../AdminVehicleRentalStatusesController.php | 63 + .../Admin/AdminVehicleRentalsController.php | 280 + .../VehicleRentalStatusesController.php | 98 + .../Controllers/VehicleRentalsController.php | 859 ++ .../VehicleRentals/Model/VehicleRental.php | 319 + .../Model/VehicleRentalAdditionalCharge.php | 58 + .../Model/VehicleRentalBookerDetail.php | 79 + .../Model/VehicleRentalLatePaymentDetail.php | 50 + .../Model/VehicleRentalStatus.php | 55 + .../VehicleRentalServiceProvider.php | 64 + .../VehicleRentalBookerDetailService.php | 60 + .../VehicleRentalLatePaymentDetailService.php | 49 + .../Services/VehicleRentalService.php | 927 ++ ...hicleRentalAdditionalChargeTransformer.php | 45 + .../VehicleRentalBookerDetailTransformer.php | 38 + ...icleRentalLatePaymentDetailTransformer.php | 38 + .../VehicleRentalStatusTransformer.php | 44 + .../Transformers/VehicleRentalTransformer.php | 245 + app/Plugins/VehicleRentals/plugin.json | 9 + app/Plugins/VehicleRentals/routes.php | 53 + .../AdminVehicleSurchargesController.php | 190 + .../AdminVehicleTypeSurchargesController.php | 187 + .../VehicleSurchargesController.php | 58 + .../VehicleTypeSurchargesController.php | 59 + .../Model/VehicleSurcharge.php | 101 + .../Model/VehicleTypeSurcharge.php | 151 + .../VehicleSurchargeServiceProvider.php | 44 + .../Services/VehicleSurchargeService.php | 73 + .../AdminVehicleSurchargeTransformer.php | 40 + .../VehicleSurchargeTransformer.php | 36 + .../VehicleTypeSurchargeTransformer.php | 104 + app/Plugins/VehicleSurcharges/plugin.json | 9 + app/Plugins/VehicleSurcharges/routes.php | 51 + .../Admin/AdminVehicleTaxesController.php | 191 + .../Admin/AdminVehicleTypeTaxesController.php | 188 + .../Controllers/VehicleTaxesController.php | 58 + .../VehicleTypeTaxesController.php | 59 + app/Plugins/VehicleTaxes/Model/VehicleTax.php | 101 + .../VehicleTaxes/Model/VehicleTypeTax.php | 151 + .../Providers/VehicleTaxServiceProvider.php | 44 + .../Services/VehicleTaxService.php | 73 + .../AdminVehicleTaxTransformer.php | 40 + .../Transformers/VehicleTaxTransformer.php | 37 + .../VehicleTypeTaxTransformer.php | 104 + app/Plugins/VehicleTaxes/plugin.json | 9 + app/Plugins/VehicleTaxes/routes.php | 51 + .../Admin/AdminCounterLocationsController.php | 205 + .../Admin/AdminFuelTypesController.php | 183 + .../AdminUnavailableVehiclesController.php | 261 + .../Admin/AdminVehicleCompaniesController.php | 266 + .../Admin/AdminVehicleMakesController.php | 197 + .../Admin/AdminVehicleModelsController.php | 211 + .../AdminVehicleSpecialPricesController.php | 245 + .../AdminVehicleTypePricesController.php | 232 + .../Admin/AdminVehicleTypesController.php | 210 + .../Admin/AdminVehiclesController.php | 473 + .../CounterLocationsController.php | 63 + .../Controllers/FuelTypesController.php | 61 + .../UnavailableVehiclesController.php | 241 + .../VehicleCompaniesController.php | 167 + .../Controllers/VehicleMakesController.php | 61 + .../Controllers/VehicleModelsController.php | 62 + .../VehicleSpecialPricesController.php | 96 + .../VehicleTypePricesController.php | 96 + .../Controllers/VehicleTypesController.php | 79 + .../Controllers/VehiclesController.php | 571 ++ .../Vehicles/Model/CounterLocation.php | 94 + app/Plugins/Vehicles/Model/FuelType.php | 47 + .../Vehicles/Model/UnavailableVehicle.php | 113 + app/Plugins/Vehicles/Model/Vehicle.php | 411 + app/Plugins/Vehicles/Model/VehicleCompany.php | 127 + app/Plugins/Vehicles/Model/VehicleMake.php | 92 + app/Plugins/Vehicles/Model/VehicleModel.php | 110 + .../Vehicles/Model/VehicleSpecialPrice.php | 111 + app/Plugins/Vehicles/Model/VehicleType.php | 180 + .../Vehicles/Model/VehicleTypePrice.php | 108 + .../Providers/VehicleServiceProvider.php | 61 + .../Services/CounterLocationService.php | 64 + .../Vehicles/Services/FuelTypeService.php | 40 + .../Services/UnavailableVehicleService.php | 65 + .../Services/VehicleCompanyService.php | 40 + .../Vehicles/Services/VehicleMakeService.php | 40 + .../Vehicles/Services/VehicleModelService.php | 53 + .../Vehicles/Services/VehicleService.php | 406 + .../Services/VehicleSpecialPriceService.php | 58 + .../Services/VehicleTypePriceService.php | 60 + .../Vehicles/Services/VehicleTypeService.php | 56 + .../AdminCounterLocationTransformer.php | 40 + .../Transformers/AdminFuelTypeTransformer.php | 39 + .../AdminVehicleCompanyTransformer.php | 66 + .../AdminVehicleMakeTransformer.php | 41 + .../AdminVehicleModelTransformer.php | 59 + .../AdminVehicleSpecialPriceTransformer.php | 63 + .../Transformers/AdminVehicleTransformer.php | 192 + .../AdminVehicleTypePriceTransformer.php | 61 + .../AdminVehicleTypeTransformer.php | 114 + .../CounterLocationTransformer.php | 40 + .../Transformers/FuelTypeTransformer.php | 39 + .../UnavailableVehicleTransformer.php | 58 + .../VehicleCompanyTransformer.php | 58 + .../Transformers/VehicleMakeTransformer.php | 40 + .../Transformers/VehicleModelTransformer.php | 57 + .../Transformers/VehicleSimpleTransformer.php | 38 + .../VehicleSpecialPriceTransformer.php | 63 + .../Transformers/VehicleTransformer.php | 226 + .../VehicleTypePriceTransformer.php | 61 + .../VehicleTypeSimpleTransformer.php | 38 + .../Transformers/VehicleTypeTransformer.php | 136 + app/Plugins/Vehicles/plugin.json | 9 + app/Plugins/Vehicles/routes.php | 152 + .../AdminUserCashWithdrawalsController.php | 187 + .../AdminWithdrawalStatusesController.php | 62 + .../MoneyTransferAccountsController.php | 118 + .../UserCashWithdrawalsController.php | 122 + .../WithdrawalStatusesController.php | 59 + .../Model/MoneyTransferAccount.php | 67 + .../Withdrawals/Model/UserCashWithdrawal.php | 146 + .../Withdrawals/Model/WithdrawalStatus.php | 48 + .../Providers/WithdrawServiceProvider.php | 44 + .../Services/MoneyTransferAccountService.php | 34 + .../Services/UserCashWithdrawalService.php | 74 + .../MoneyTransferAccountTransformer.php | 52 + .../UserCashWithdrawalTransformer.php | 92 + .../WithdrawalStatusTransformer.php | 30 + app/Plugins/Withdrawals/plugin.json | 9 + app/Plugins/Withdrawals/routes.php | 48 + app/Plugins/composer.json | 8 + app/Providers/AppServiceProvider.php | 31 + app/Providers/AuthServiceProvider.php | 53 + app/Providers/EventServiceProvider.php | 32 + app/Providers/MessageServiceProvider.php | 53 + app/Providers/SettingsServiceProvider.php | 49 + app/Providers/TransactionServiceProvider.php | 55 + app/Role.php | 34 + app/Services/AttachmentService.php | 121 + app/Services/CityService.php | 36 + app/Services/CountryService.php | 36 + app/Services/IpService.php | 58 + app/Services/MailService.php | 75 + app/Services/MessageService.php | 134 + app/Services/TokenService.php | 44 + app/Services/TransactionService.php | 178 + app/Services/UserLoginService.php | 70 + app/Services/UserService.php | 323 + app/Services/WalletService.php | 216 + app/Services/WalletTransactionLogService.php | 34 + app/Setting.php | 84 + app/SettingCategory.php | 73 + app/State.php | 110 + app/Transaction.php | 142 + app/TransactionType.php | 76 + app/Transformers/ApiRequestTransformer.php | 73 + app/Transformers/AttachmentTransformer.php | 41 + app/Transformers/CityTransformer.php | 74 + app/Transformers/CountryTransformer.php | 37 + app/Transformers/CurrencyTransformer.php | 37 + app/Transformers/DiscountTypeTransformer.php | 28 + app/Transformers/DurationTypeTransformer.php | 28 + app/Transformers/EmailTemplateTransformer.php | 36 + app/Transformers/IpTransformer.php | 86 + app/Transformers/LanguageTransformer.php | 37 + .../MessageContentTransformer.php | 36 + app/Transformers/MessageTransformer.php | 137 + app/Transformers/RoleTransformer.php | 28 + .../SettingCategoryTransformer.php | 37 + app/Transformers/SettingTransformer.php | 58 + app/Transformers/StateTransformer.php | 59 + app/Transformers/TransactionTransformer.php | 113 + .../TransactionTypeTransformer.php | 37 + .../UploadAttachmentTransformer.php | 41 + app/Transformers/UserAuthTransformer.php | 101 + app/Transformers/UserLoginTransformer.php | 88 + app/Transformers/UserProfileTransformer.php | 62 + .../UserSimpleFeedbackTransformer.php | 59 + app/Transformers/UserSimpleTransformer.php | 57 + app/Transformers/UserTransformer.php | 129 + .../WalletTransactionLogTransformer.php | 60 + app/User.php | 246 + app/UserLogin.php | 88 + app/UserProfile.php | 75 + app/Wallet.php | 86 + app/WalletTransactionLog.php | 60 + app/helpers.php | 253 + artisan | 35 + bootstrap/app.php | 203 + bower.json | 51 + client/.npmignore | 32 + client/.yo-rc.json | 6 + client/README.md | 7 + client/src/README.md | 47 + client/src/ag-admin/index.html | 33 + client/src/ag-admin/js/ng-admin.app.js | 7709 +++++++++++++++++ client/src/ag-admin/js/ng-admin.jwt-auth.js | 256 + .../src/ag-admin/tpl/changePassword.tpl.html | 35 + .../ag-admin/tpl/counterLocationAdd.tpl.html | 69 + .../ag-admin/tpl/counterLocationEdit.tpl.html | 69 + client/src/ag-admin/tpl/customHeader.tpl.html | 18 + .../src/ag-admin/tpl/customLoginTemplate.html | 27 + .../ag-admin/tpl/dashboardSummary.tpl.html | 253 + client/src/ag-admin/tpl/pages.tpl.html | 42 + client/src/ag-admin/tpl/plugins.tpl.html | 149 + client/src/ag-admin/tpl/trip_detail.tpl.html | 99 + client/src/ag-admin/tpl/vehicle.tpl.html | 105 + client/src/ag-admin/tpl/vehicleAdd.tpl.html | 308 + .../ag-admin/tpl/vehicleCompaniesAdd.tpl.html | 100 + .../tpl/vehicleCompaniesEdit.tpl.html | 101 + client/src/ag-admin/tpl/vehicleEdit.tpl.html | 284 + .../ag-admin/tpl/vehicleTypePrice.tpl.html | 99 + client/src/ag-admin/tpl/vehicleView.tpl.html | 215 + .../ag-admin/tpl/vehicle_calendar.tpl.html | 45 + .../src/ag-admin/tpl/vehiclecheckOut.tpl.html | 74 + client/src/app/App.js | 343 + client/src/app/Common/404.tpl.html | 5 + client/src/app/Common/Common.module.js | 45 + client/src/app/Common/Footer.js | 14 + client/src/app/Common/Header.js | 98 + client/src/app/Common/footer.tpl.html | 98 + client/src/app/Common/gateway.tpl.html | 101 + client/src/app/Common/header.tpl.html | 119 + client/src/app/Common/how_it_works.tpl.html | 104 + client/src/app/Constant.js | 72 + client/src/app/Home/Home.js | 42 + client/src/app/Home/Home.module.js | 52 + client/src/app/Home/home.tpl.html | 77 + client/src/app/Message/Message.js | 163 + client/src/app/Message/Message.module.js | 67 + client/src/app/Message/MessageService.js | 71 + client/src/app/Message/message_list.tpl.html | 48 + .../src/app/Message/message_sidebar.tpl.html | 5 + client/src/app/Message/message_view.tpl.html | 39 + client/src/app/Plugins/Analytics/Analytics.js | 130 + client/src/app/Plugins/Banner/Banner.js | 63 + client/src/app/Plugins/Banner/banner.tpl.html | 10 + client/src/app/Plugins/Contacts/Contacts.js | 103 + .../app/Plugins/Contacts/Contacts.module.js | 63 + .../app/Plugins/Contacts/ContactsService.js | 25 + .../Plugins/Contacts/contact_links.tpl.html | 1 + .../app/Plugins/Contacts/contacts.tpl.html | 77 + .../CurrencyConversions/CurrencyConversion.js | 46 + .../CurrencyConversion.module.js | 36 + .../currency_conversion.tpl.html | 4 + client/src/app/Plugins/Pages/Pages.js | 76 + client/src/app/Plugins/Pages/Pages.module.js | 60 + client/src/app/Plugins/Pages/Pages.spec.js | 0 client/src/app/Plugins/Pages/PagesService.js | 28 + .../src/app/Plugins/Pages/page_links.tpl.html | 15 + client/src/app/Plugins/Pages/pages.tpl.html | 13 + .../src/app/Plugins/Paypal/Paypal.module.js | 28 + .../Plugins/SocialLogins/SocialConnection.js | 128 + .../app/Plugins/SocialLogins/SocialLogin.js | 208 + .../SocialLogins/SocialLogin.module.js | 89 + .../SocialLogins/SocialLoginService.js | 77 + .../app/Plugins/SocialLogins/SocialProfile.js | 132 + .../SocialLogins/get_email_from_user.tpl.html | 24 + .../SocialLogins/my_connection.tpl.html | 88 + .../SocialLogins/profile_image.tpl.html | 86 + .../SocialLogins/social_login.tpl.html | 15 + .../SocialLogins/social_login_share.tpl.html | 52 + .../app/Plugins/Sudopays/Sudopay.module.js | 33 + .../src/app/Plugins/Sudopays/buyer.tpl.html | 45 + .../app/Plugins/Sudopays/credit_card.tpl.html | 45 + .../src/app/Plugins/Sudopays/manual.tpl.html | 7 + .../app/Plugins/Translations/Translations.js | 176 + .../Translations/language_translate.tpl.html | 5 + .../VehicleCoupons/VehicleCoupons.module.js | 49 + .../VehicleCoupons/vehicle_coupon.tpl.html | 22 + .../Plugins/VehicleDisputes/VehicleDispute.js | 108 + .../VehicleDisputes/VehicleDisputeService.js | 67 + .../VehicleDisputes/VehicleDisputes.module.js | 27 + .../VehicleDisputes/vehicle_dispute.tpl.html | 115 + .../VehicleExtraAccessories.module.js | 36 + .../VehicleFeedbacks/FeedbackService.js | 138 + .../VehicleFeedbacks.module.js | 102 + .../VehicleFeedbacks/edit_feedback.tpl.html | 15 + .../app/Plugins/VehicleFeedbacks/feedback.js | 226 + .../VehicleFeedbacks/feedback.tpl.html | 15 + .../Plugins/VehicleFeedbacks/rating.tpl.html | 6 + .../VehicleFeedbacks/user_feedbacks.tpl.html | 36 + .../vehicle_feedbacks.tpl.html | 42 + .../VehicleFuelOptions.module.js | 36 + .../VehicleInsurances.module.js | 36 + .../Plugins/VehicleRentals/BookingCalendar.js | 85 + .../Plugins/VehicleRentals/OrderCalendar.js | 94 + .../app/Plugins/VehicleRentals/OrderLists.js | 181 + .../Plugins/VehicleRentals/VehicleCheckout.js | 154 + .../VehicleRentals/VehicleRentalActivity.js | 121 + .../VehicleRentals/VehicleRentalOrder.js | 292 + .../VehicleRentals/VehicleRentalService.js | 406 + .../Plugins/VehicleRentals/VehicleRentals.js | 268 + .../VehicleRentals/VehicleRentals.module.js | 183 + .../VehicleRentals/order_lists.tpl.html | 91 + .../VehicleRentals/vehicle_checkout.tpl.html | 76 + .../vehicle_rental_activity.tpl.html | 85 + .../vehicle_rental_add.tpl.html | 52 + .../vehicle_rental_calendar.tpl.html | 45 + .../vehicle_rental_list.tpl.html | 85 + .../vehicle_rental_order.tpl.html | 23 + .../VehicleSurcharges.module.js | 36 + .../VehicleTaxes/VehicleTaxes.module.js | 36 + .../Plugins/Vehicles/MaintenanaceVehicles.js | 183 + client/src/app/Plugins/Vehicles/MyVehicles.js | 102 + .../Plugins/Vehicles/VehicleBookItModal.js | 112 + .../app/Plugins/Vehicles/VehicleDetails.js | 194 + .../src/app/Plugins/Vehicles/VehicleLists.js | 412 + .../src/app/Plugins/Vehicles/VehicleModal.js | 63 + .../src/app/Plugins/Vehicles/VehicleSearch.js | 78 + .../app/Plugins/Vehicles/VehicleService.js | 432 + .../src/app/Plugins/Vehicles/VehicleView.js | 115 + client/src/app/Plugins/Vehicles/Vehicles.js | 206 + .../app/Plugins/Vehicles/Vehicles.module.js | 388 + .../app/Plugins/Vehicles/VehiclesAllLists.js | 389 + .../Plugins/Vehicles/all_vehicles.tpl.html | 273 + .../Vehicles/maintenance_vehicle_add.tpl.html | 37 + .../maintenance_vehicle_edit.tpl.html | 37 + .../Vehicles/maintenance_vehicles.tpl.html | 55 + .../app/Plugins/Vehicles/my_vehicles.tpl.html | 95 + .../app/Plugins/Vehicles/trip_detail.tpl.html | 124 + .../src/app/Plugins/Vehicles/vehicle.tpl.html | 70 + client/src/app/Plugins/Vehicles/vehicleAdd.js | 241 + .../app/Plugins/Vehicles/vehicleCompany.js | 112 + .../Plugins/Vehicles/vehicleCompany.tpl.html | 101 + .../src/app/Plugins/Vehicles/vehicleEdit.js | 290 + .../app/Plugins/Vehicles/vehicle_add.tpl.html | 326 + .../Plugins/Vehicles/vehicle_bookit.tpl.html | 52 + .../Plugins/Vehicles/vehicle_details.tpl.html | 154 + .../Plugins/Vehicles/vehicle_edit.tpl.html | 298 + .../Vehicles/vehicle_feedback_modal.tpl.html | 46 + .../Plugins/Vehicles/vehicle_list.tpl.html | 305 + .../Vehicles/vehicle_list_home.tpl.html | 72 + .../Plugins/Vehicles/vehicle_payment.tpl.html | 27 + .../Plugins/Vehicles/vehicle_search.tpl.html | 51 + .../Plugins/Vehicles/vehicle_view.tpl.html | 256 + .../Withdrawals/MoneyTransferAccount.js | 82 + .../Withdrawals/UserCashWithdrawals.js | 128 + .../Withdrawals/UserCashWithdrawals.module.js | 70 + .../Plugins/Withdrawals/WithdrawalService.js | 104 + .../money_transfer_account.tpl.html | 48 + .../Withdrawals/user_cashWithdrawals.tpl.html | 105 + client/src/app/README.md | 94 + client/src/app/Transactions/Transaction.js | 105 + .../app/Transactions/Transaction.module.js | 62 + .../app/Transactions/TransactionService.js | 21 + .../Transactions/transaction_list.tpl.html | 61 + client/src/app/User/ChangePassword.js | 63 + client/src/app/User/Dashboard.js | 85 + client/src/app/User/ForgetPassword.js | 37 + client/src/app/User/Login.js | 96 + client/src/app/User/Register.js | 116 + client/src/app/User/User.js | 50 + client/src/app/User/User.module.js | 166 + client/src/app/User/UserActivate.js | 44 + client/src/app/User/UserProfile.js | 107 + client/src/app/User/UsersService.js | 161 + client/src/app/User/change_password.tpl.html | 47 + client/src/app/User/dashboard.tpl.html | 107 + .../src/app/User/dashboard_settings.tpl.html | 29 + client/src/app/User/forgot_password.tpl.html | 21 + client/src/app/User/login.tpl.html | 33 + client/src/app/User/register.tpl.html | 63 + client/src/app/User/user_profile.tpl.html | 125 + client/src/app/User/user_view.tpl.html | 67 + client/src/app/Wallets/Wallet.js | 190 + client/src/app/Wallets/Wallet.module.js | 65 + client/src/app/Wallets/WalletService.js | 52 + client/src/app/Wallets/wallet.tpl.html | 58 + client/src/assets/README.md | 4 + .../src/assets/apple-touch-icon-114x114.png | Bin 0 -> 12053 bytes client/src/assets/apple-touch-icon-57x57.png | Bin 0 -> 4942 bytes client/src/assets/apple-touch-icon-72x72.png | Bin 0 -> 6399 bytes client/src/assets/apple-touch-icon.png | Bin 0 -> 1994 bytes client/src/assets/css/loader.css | 29 + client/src/assets/favicon.ico | Bin 0 -> 4286 bytes client/src/assets/fonts/Avenir.ttf | Bin 0 -> 91500 bytes client/src/assets/fonts/FontAwesome.otf | Bin 0 -> 109688 bytes .../src/assets/fonts/PlayfairDisplay-Bold.eot | Bin 0 -> 220374 bytes .../src/assets/fonts/PlayfairDisplay-Bold.otf | Bin 0 -> 158148 bytes .../src/assets/fonts/PlayfairDisplay-Bold.ttf | Bin 0 -> 220072 bytes .../assets/fonts/PlayfairDisplay-Bold.woff | Bin 0 -> 91924 bytes .../assets/fonts/PlayfairDisplay-Regular.eot | Bin 0 -> 215186 bytes .../assets/fonts/PlayfairDisplay-Regular.otf | Bin 0 -> 148580 bytes .../assets/fonts/PlayfairDisplay-Regular.ttf | Bin 0 -> 214888 bytes .../assets/fonts/PlayfairDisplay-Regular.woff | Bin 0 -> 84712 bytes client/src/assets/fonts/ProximaNova-Bold.eot | Bin 0 -> 129754 bytes client/src/assets/fonts/ProximaNova-Bold.otf | Bin 0 -> 96640 bytes client/src/assets/fonts/ProximaNova-Bold.svg | 570 ++ client/src/assets/fonts/ProximaNova-Bold.ttf | Bin 0 -> 129556 bytes client/src/assets/fonts/ProximaNova-Bold.woff | Bin 0 -> 57804 bytes client/src/assets/fonts/ProximaNova-Light.eot | Bin 0 -> 90712 bytes client/src/assets/fonts/ProximaNova-Light.otf | Bin 0 -> 23572 bytes client/src/assets/fonts/ProximaNova-Light.svg | 543 ++ client/src/assets/fonts/ProximaNova-Light.ttf | Bin 0 -> 90452 bytes .../src/assets/fonts/ProximaNova-Light.woff | Bin 0 -> 40336 bytes .../src/assets/fonts/ProximaNova-Regular.eot | Bin 0 -> 28326 bytes .../src/assets/fonts/ProximaNova-Regular.otf | Bin 0 -> 23472 bytes .../src/assets/fonts/ProximaNova-Regular.svg | 545 ++ .../src/assets/fonts/ProximaNova-Regular.ttf | Bin 0 -> 28100 bytes .../src/assets/fonts/ProximaNova-Regular.woff | Bin 0 -> 16372 bytes .../src/assets/fonts/ProximaNova-Semibold.eot | Bin 0 -> 90388 bytes .../src/assets/fonts/ProximaNova-Semibold.otf | Bin 0 -> 63116 bytes .../src/assets/fonts/ProximaNova-Semibold.svg | 570 ++ .../src/assets/fonts/ProximaNova-Semibold.ttf | Bin 0 -> 90132 bytes .../assets/fonts/ProximaNova-Semibold.woff | Bin 0 -> 42056 bytes client/src/assets/fonts/Raleway-Regular.ttf | Bin 0 -> 178520 bytes client/src/assets/fonts/Roboto-Regular.woff | Bin 0 -> 61736 bytes .../src/assets/fonts/fontawesome-webfont.eot | Bin 0 -> 70807 bytes .../src/assets/fonts/fontawesome-webfont.svg | 655 ++ .../src/assets/fonts/fontawesome-webfont.ttf | Bin 0 -> 142072 bytes .../src/assets/fonts/fontawesome-webfont.woff | Bin 0 -> 83588 bytes .../assets/fonts/fontawesome-webfont.woff2 | Bin 0 -> 66624 bytes .../fonts/glyphicons-halflings-regular.eot | Bin 0 -> 20127 bytes .../fonts/glyphicons-halflings-regular.svg | 288 + .../fonts/glyphicons-halflings-regular.ttf | Bin 0 -> 45404 bytes .../fonts/glyphicons-halflings-regular.woff | Bin 0 -> 23424 bytes .../fonts/glyphicons-halflings-regular.woff2 | Bin 0 -> 18028 bytes .../fonts/proximanova-light-webfont.eot | Bin 0 -> 23379 bytes .../fonts/proximanova-light-webfont.svg | 542 ++ .../fonts/proximanova-light-webfont.ttf | Bin 0 -> 51292 bytes .../fonts/proximanova-light-webfont.woff | Bin 0 -> 26408 bytes .../fonts/proximanova-light-webfont.woff2 | Bin 0 -> 20420 bytes .../fonts/proximanova-regitalic-webfont.eot | Bin 0 -> 25921 bytes .../fonts/proximanova-regitalic-webfont.svg | 528 ++ .../fonts/proximanova-regitalic-webfont.ttf | Bin 0 -> 60452 bytes .../fonts/proximanova-regitalic-webfont.woff | Bin 0 -> 29168 bytes .../fonts/proximanova-regitalic-webfont.woff2 | Bin 0 -> 22504 bytes .../fonts/proximanova-regular-webfont.eot | Bin 0 -> 23471 bytes .../fonts/proximanova-regular-webfont.svg | 544 ++ .../fonts/proximanova-regular-webfont.ttf | Bin 0 -> 51708 bytes .../fonts/proximanova-regular-webfont.woff | Bin 0 -> 26648 bytes .../fonts/proximanova-regular-webfont.woff2 | Bin 0 -> 20500 bytes .../fonts/proximanova-semibold-webfont.eot | Bin 0 -> 23684 bytes .../fonts/proximanova-semibold-webfont.svg | 535 ++ .../fonts/proximanova-semibold-webfont.ttf | Bin 0 -> 51556 bytes .../fonts/proximanova-semibold-webfont.woff | Bin 0 -> 26740 bytes .../fonts/proximanova-semibold-webfont.woff2 | Bin 0 -> 20664 bytes .../proximanova-semibolditalic-webfont.eot | Bin 0 -> 26093 bytes .../proximanova-semibolditalic-webfont.svg | 530 ++ .../proximanova-semibolditalic-webfont.ttf | Bin 0 -> 60380 bytes .../proximanova-semibolditalic-webfont.woff | Bin 0 -> 29316 bytes .../proximanova-semibolditalic-webfont.woff2 | Bin 0 -> 22580 bytes client/src/assets/img/activities.icon.png | Bin 0 -> 3481 bytes client/src/assets/img/air.png | Bin 0 -> 511 bytes client/src/assets/img/app-store.png | Bin 0 -> 6706 bytes client/src/assets/img/arrow.png | Bin 0 -> 226 bytes client/src/assets/img/automatic.png | Bin 0 -> 1070 bytes client/src/assets/img/bag.png | Bin 0 -> 584 bytes client/src/assets/img/banner.jpg | Bin 0 -> 822000 bytes client/src/assets/img/car-icon.png | Bin 0 -> 4729 bytes client/src/assets/img/check-circle.png | Bin 0 -> 1451 bytes client/src/assets/img/clock.png | Bin 0 -> 1238 bytes client/src/assets/img/customer.png | Bin 0 -> 1700 bytes client/src/assets/img/customers-bg.png | Bin 0 -> 3255 bytes client/src/assets/img/diesel.png | Bin 0 -> 601 bytes client/src/assets/img/drive.png | Bin 0 -> 5268 bytes client/src/assets/img/envelop.png | Bin 0 -> 1243 bytes client/src/assets/img/key-icon.png | Bin 0 -> 1266 bytes client/src/assets/img/loader.gif | Bin 0 -> 6462 bytes client/src/assets/img/login-bg.jpg | Bin 0 -> 789033 bytes client/src/assets/img/logo-white.png | Bin 0 -> 4991 bytes client/src/assets/img/logo.png | Bin 0 -> 7230 bytes client/src/assets/img/luggage.png | Bin 0 -> 467 bytes client/src/assets/img/make-payment.png | Bin 0 -> 3884 bytes client/src/assets/img/manual.png | Bin 0 -> 539 bytes client/src/assets/img/paypal.png | Bin 0 -> 11060 bytes client/src/assets/img/play-store.png | Bin 0 -> 6865 bytes client/src/assets/img/powered-by-agriya.png | Bin 0 -> 474 bytes client/src/assets/img/quote.png | Bin 0 -> 1451 bytes client/src/assets/img/rental-bg.png | Bin 0 -> 4815 bytes client/src/assets/img/rental.png | Bin 0 -> 1950 bytes client/src/assets/img/revenue-bg.png | Bin 0 -> 4481 bytes client/src/assets/img/revenue.png | Bin 0 -> 1908 bytes client/src/assets/img/road-view.jpg | Bin 0 -> 149818 bytes client/src/assets/img/search-car.png | Bin 0 -> 1790 bytes client/src/assets/img/seats.png | Bin 0 -> 537 bytes client/src/assets/img/site-settings.png | Bin 0 -> 14613 bytes client/src/assets/img/static-bg.jpg | Bin 0 -> 58749 bytes client/src/assets/img/sudopay-icon.png | Bin 0 -> 1533 bytes client/src/assets/img/user-icon.png | Bin 0 -> 434 bytes client/src/assets/img/user-list.png | Bin 0 -> 1486 bytes client/src/assets/img/user.png | Bin 0 -> 38514 bytes client/src/assets/img/vehicle-bg.png | Bin 0 -> 2886 bytes client/src/assets/img/vehicle.png | Bin 0 -> 1656 bytes client/src/assets/img/wallet-icon.png | Bin 0 -> 1909 bytes client/src/assets/js/ag-admin/loader.js | 75 + client/src/assets/js/ag-admin/loader_build.js | 82 + client/src/assets/js/l10n/en.json | 716 ++ client/src/assets/js/l10n/es.json | 712 ++ client/src/assets/js/loader.js | 60 + client/src/assets/js/loader_build.js | 118 + client/src/index.html | 113 + client/src/less/README.md | 28 + client/src/less/admin/bootstrap.less | 16 + client/src/less/admin/code.less | 63 + client/src/less/admin/main.less | 23 + client/src/less/admin/mixins.less | 413 + client/src/less/admin/morris.css | 2 + client/src/less/admin/ngadmin-responsive.less | 365 + client/src/less/admin/ngadmin.less | 1875 ++++ client/src/less/admin/timeline.css | 180 + client/src/less/admin/variables.less | 924 ++ client/src/less/bootstrap-social.less | 113 + client/src/less/bootstrap.less | 16 + client/src/less/custom-responsive.less | 592 ++ client/src/less/custom.less | 3433 ++++++++ client/src/less/font-awesome.less | 1643 ++++ client/src/less/forms.less | 437 + client/src/less/main.less | 34 + client/src/less/mixins.less | 195 + client/src/less/variables.less | 943 ++ composer.json | 57 + config/api.php | 235 + config/app.php | 34 + config/auth.php | 84 + config/cache.php | 92 + config/constants.php | 209 + config/database.php | 138 + config/filesystems.php | 84 + config/jwt.php | 173 + config/mail.php | 124 + config/paypal.php | 55 + config/services.php | 51 + config/session.php | 166 + config/sudopay.php | 24 + database/factories/ModelFactory.php | 32 + database/migrations/.gitkeep | 0 ..._23_000001_create_discount_types_table.php | 31 + ...16_03_24_000001_create_countries_table.php | 34 + .../2016_03_24_000002_create_states_table.php | 36 + .../2016_03_24_000003_create_cities_table.php | 42 + .../2016_03_24_000004_create_ips_table.php | 49 + .../2016_03_24_000005_create_roles_table.php | 31 + .../2016_03_24_000006_create_users_table.php | 60 + ...3_24_000007_create_user_profiles_table.php | 43 + ...016_03_24_000008_create_contacts_table.php | 44 + ...16_03_24_000009_create_languages_table.php | 34 + .../2016_03_24_000010_create_pages_table.php | 38 + ..._03_24_000011_create_user_logins_table.php | 43 + ...16_03_24_000012_create_providers_table.php | 37 + ..._24_000013_create_provider_users_table.php | 41 + ...4_create_money_transfer_accounts_table.php | 36 + ...00015_create_withdrawal_statuses_table.php | 31 + ...016_create_user_cash_withdrawals_table.php | 43 + ...000017_create_setting_categories_table.php | 33 + ...016_03_24_000018_create_settings_table.php | 39 + ...6_03_24_000019_create_currencies_table.php | 41 + ...0020_create_currency_conversions_table.php | 35 + ...te_currency_conversion_histories_table.php | 32 + .../2016_03_24_000022_create_items_table.php | 40 + ...000023_create_item_user_statuses_table.php | 36 + ...2016_03_24_000024_create_coupons_table.php | 48 + ...000025_create_cancellation_types_table.php | 35 + ..._000026_create_transaction_types_table.php | 39 + ..._000027_create_counter_locations_table.php | 37 + ...4_000028_create_dispute_statuses_table.php | 31 + ...6_03_24_000029_create_item_users_table.php | 86 + ...24_000030_create_email_templates_table.php | 37 + ..._03_24_000031_create_attachments_table.php | 38 + ...03_24_000032_create_transactions_table.php | 48 + ...4_000035_create_message_contents_table.php | 35 + ...016_03_24_000036_create_messages_table.php | 66 + ..._create_sudopay_transaction_logs_table.php | 44 + ...38_create_sudopay_payment_groups_table.php | 33 + ..._create_sudopay_payment_gateways_table.php | 52 + ...e_sudopay_payment_gateways_users_table.php | 38 + ...0_000041_create_sudopay_ipn_logs_table.php | 32 + ...3_create_paypal_transaction_logs_table.php | 44 + ...16_05_10_000044_create_feedbacks_table.php | 49 + .../2016_05_10_000045_apirequests.php | 41 + ...6_create_user_add_wallet_amounts_table.php | 45 + ..._11_000047_create_duration_types_table.php | 31 + ...5_17_000048_create_dispute_types_table.php | 33 + ...0049_create_dispute_closed_types_table.php | 38 + ...000050_create_item_user_disputes_table.php | 59 + ...1_create_wallet_transaction_logs_table.php | 35 + ..._000052_create_vehicle_companies_table.php | 45 + ...6_02_000053_create_vehicle_types_table.php | 46 + ...6_02_000054_create_vehicle_makes_table.php | 35 + ..._02_000055_create_vehicle_models_table.php | 38 + ...00056_create_vehicle_type_prices_table.php | 38 + ...6_06_02_000057_create_fuel_types_table.php | 31 + ...016_06_02_000058_create_vehicles_table.php | 78 + ...60_create_vehicle_special_prices_table.php | 38 + ...ate_item_user_additional_charges_table.php | 37 + ...6_06_02_000062_create_surcharges_table.php | 35 + ...3_create_vehicle_type_surcharges_table.php | 49 + .../2016_06_02_000064_create_taxes_table.php | 35 + ...000065_create_vehicle_type_taxes_table.php | 49 + ..._000066_create_extra_accessories_table.php | 35 + ...e_vehicle_type_extra_accessories_table.php | 50 + ...6_06_02_000068_create_insurances_table.php | 35 + ...9_create_vehicle_type_insurances_table.php | 49 + ...06_02_000070_create_fuel_options_table.php | 35 + ...create_vehicle_type_fuel_options_table.php | 49 + ..._create_counter_location_vehicle_table.php | 40 + ...0073_create_unavailable_vehicles_table.php | 41 + ...0074_create_late_payment_details_table.php | 41 + ..._16_000075_create_booker_details_table.php | 39 + database/seeds/AttachmentTableSeeder.php | 50 + .../seeds/CounterLocationsTableSeeder.php | 94 + database/seeds/CountriesTableSeeder.php | 2300 +++++ database/seeds/CurrenciesTableSeeder.php | 380 + database/seeds/DatabaseSeeder.php | 115 + database/seeds/DiscountTypeSeeder.php | 39 + database/seeds/DisputeStatusesTableSeeder.php | 47 + database/seeds/DisputeTypesTableSeeder.php | 114 + database/seeds/DurationTypesTableSeeder.php | 39 + database/seeds/EmailTemplatesTableSeeder.php | 297 + .../seeds/ExtraAccessoriesTableSeeder.php | 86 + database/seeds/FuelOptionsTableSeeder.php | 59 + database/seeds/FuelTypesTableSeeder.php | 51 + database/seeds/InsurancesTableSeeder.php | 109 + database/seeds/IpsTableSeeder.php | 45 + .../seeds/ItemUserStatusesTableSeeder.php | 129 + database/seeds/LanguagesTableSeeder.php | 1235 +++ database/seeds/ProvidersTableSeeder.php | 74 + database/seeds/RolesTableSeeder.php | 37 + database/seeds/SettingCategoryTableSeeder.php | 956 ++ database/seeds/SurchargesTableSeeder.php | 185 + database/seeds/TaxesTableSeeder.php | 73 + .../seeds/TransactionTypesTableSeeder.php | 371 + database/seeds/UsersTableSeeder.php | 87 + .../seeds/VehicleCompaniesTableSeeder.php | 59 + database/seeds/VehicleMakesTableSeeder.php | 202 + database/seeds/VehicleTypesTableSeeder.php | 79 + .../seeds/WithdrawalStatusesTableSeeder.php | 43 + grunt-config/dev1.json | 10 + package.json | 28 + phpunit.xml | 26 + public/.htaccess | 47 + .../api_explorer/DSL/admin_api_requests.dsl | 35 + .../DSL/admin_cancellation_types.dsl | 67 + public/api_explorer/DSL/admin_cities.dsl | 70 + public/api_explorer/DSL/admin_contacts.dsl | 26 + .../DSL/admin_counter_locations.dsl | 78 + public/api_explorer/DSL/admin_countries.dsl | 66 + public/api_explorer/DSL/admin_currencies.dsl | 90 + .../admin_currency_conversion_histories.dsl | 15 + .../DSL/admin_currency_conversions.dsl | 15 + public/api_explorer/DSL/admin_dashboard.dsl | 12 + .../DSL/admin_email_templates.dsl | 38 + public/api_explorer/DSL/admin_fuel_types.dsl | 65 + public/api_explorer/DSL/admin_ips.dsl | 33 + public/api_explorer/DSL/admin_languages.dsl | 69 + public/api_explorer/DSL/admin_messages.dsl | 58 + public/api_explorer/DSL/admin_pages.dsl | 84 + .../DSL/admin_paypal_transaction_logs.dsl | 21 + public/api_explorer/DSL/admin_providers.dsl | 53 + public/api_explorer/DSL/admin_roles.dsl | 15 + .../DSL/admin_setting_categories.dsl | 23 + public/api_explorer/DSL/admin_settings.dsl | 77 + public/api_explorer/DSL/admin_states.dsl | 64 + public/api_explorer/DSL/admin_sudopay.dsl | 10 + .../DSL/admin_sudopay_ipn_logs.dsl | 21 + .../DSL/admin_sudopay_transaction_logs.dsl | 21 + .../DSL/admin_transaction_types.dsl | 47 + .../api_explorer/DSL/admin_transactions.dsl | 19 + .../DSL/admin_unavailable_vehicles.dsl | 68 + .../DSL/admin_user_cash_withdrawals.dsl | 49 + public/api_explorer/DSL/admin_user_logins.dsl | 33 + public/api_explorer/DSL/admin_users.dsl | 112 + .../DSL/admin_vehicle_companies.dsl | 109 + .../admin_vehicle_dispute_closed_types.dsl | 43 + .../DSL/admin_vehicle_dispute_types.dsl | 43 + .../DSL/admin_vehicle_disputes.dsl | 34 + .../DSL/admin_vehicle_extra_accessories.dsl | 75 + .../DSL/admin_vehicle_feedbacks.dsl | 59 + .../DSL/admin_vehicle_fuel_options.dsl | 75 + .../DSL/admin_vehicle_insurances.dsl | 75 + .../api_explorer/DSL/admin_vehicle_makes.dsl | 67 + .../api_explorer/DSL/admin_vehicle_models.dsl | 69 + .../DSL/admin_vehicle_rentals.dsl | 58 + .../DSL/admin_vehicle_special_prices.dsl | 73 + .../DSL/admin_vehicle_surcharges.dsl | 75 + .../api_explorer/DSL/admin_vehicle_taxes.dsl | 75 + .../admin_vehicle_type_extra_accessories.dsl | 79 + .../DSL/admin_vehicle_type_fuel_options.dsl | 79 + .../DSL/admin_vehicle_type_insurances.dsl | 79 + .../DSL/admin_vehicle_type_prices.dsl | 73 + .../DSL/admin_vehicle_type_surcharges.dsl | 79 + .../DSL/admin_vehicle_type_taxes.dsl | 79 + .../api_explorer/DSL/admin_vehicle_types.dsl | 81 + public/api_explorer/DSL/admin_vehicles.dsl | 142 + .../DSL/admin_wallet_transaction_logs.dsl | 21 + .../DSL/admin_withdrawal_statuses.dsl | 15 + .../api_explorer/DSL/cancellation_types.dsl | 15 + public/api_explorer/DSL/cities.dsl | 18 + public/api_explorer/DSL/contacts.dsl | 21 + public/api_explorer/DSL/counter_locations.dsl | 16 + public/api_explorer/DSL/countries.dsl | 18 + public/api_explorer/DSL/currencies.dsl | 20 + public/api_explorer/DSL/fuel_types.dsl | 16 + public/api_explorer/DSL/images.dsl | 13 + public/api_explorer/DSL/languages.dsl | 19 + public/api_explorer/DSL/messages.dsl | 92 + .../DSL/money_transfer_accounts.dsl | 31 + public/api_explorer/DSL/pages.dsl | 17 + public/api_explorer/DSL/payment_gateways.dsl | 13 + public/api_explorer/DSL/providers.dsl | 16 + public/api_explorer/DSL/settings.dsl | 15 + public/api_explorer/DSL/social_logins.dsl | 126 + public/api_explorer/DSL/states.dsl | 19 + public/api_explorer/DSL/transaction_types.dsl | 15 + public/api_explorer/DSL/transactions.dsl | 16 + .../api_explorer/DSL/unavailable_vehicles.dsl | 60 + .../DSL/user_cash_withdrawals.dsl | 30 + public/api_explorer/DSL/user_profiles.dsl | 34 + public/api_explorer/DSL/user_views.dsl | 27 + public/api_explorer/DSL/users.dsl | 103 + public/api_explorer/DSL/vehicle_companies.dsl | 55 + public/api_explorer/DSL/vehicle_disputes.dsl | 40 + .../DSL/vehicle_extra_accessories.dsl | 16 + public/api_explorer/DSL/vehicle_feedbacks.dsl | 49 + .../api_explorer/DSL/vehicle_fuel_options.dsl | 16 + .../api_explorer/DSL/vehicle_insurances.dsl | 16 + public/api_explorer/DSL/vehicle_makes.dsl | 16 + public/api_explorer/DSL/vehicle_models.dsl | 16 + public/api_explorer/DSL/vehicle_rentals.dsl | 161 + .../DSL/vehicle_special_prices.dsl | 32 + .../api_explorer/DSL/vehicle_surcharges.dsl | 16 + public/api_explorer/DSL/vehicle_taxes.dsl | 16 + .../DSL/vehicle_type_extra_accessories.dsl | 16 + .../DSL/vehicle_type_fuel_options.dsl | 16 + .../DSL/vehicle_type_insurances.dsl | 16 + .../api_explorer/DSL/vehicle_type_prices.dsl | 31 + .../DSL/vehicle_type_surcharges.dsl | 16 + .../api_explorer/DSL/vehicle_type_taxes.dsl | 16 + public/api_explorer/DSL/vehicle_types.dsl | 24 + public/api_explorer/DSL/vehicles.dsl | 179 + public/api_explorer/DSL/wallets.dsl | 15 + .../api_explorer/DSL/withdrawal_statuses.dsl | 15 + .../api-docs/admin_api_requests.json | 130 + .../api-docs/admin_cancellation_types.json | 266 + .../api_explorer/api-docs/admin_cities.json | 294 + .../api_explorer/api-docs/admin_contacts.json | 102 + .../api-docs/admin_counter_locations.json | 318 + .../api-docs/admin_countries.json | 261 + .../api-docs/admin_currencies.json | 371 + .../admin_currency_conversion_histories.json | 69 + .../api-docs/admin_currency_conversions.json | 69 + .../api-docs/admin_dashboard.json | 47 + .../api-docs/admin_email_templates.json | 158 + .../api-docs/admin_fuel_types.json | 248 + public/api_explorer/api-docs/admin_ips.json | 130 + .../api-docs/admin_languages.json | 256 + .../api_explorer/api-docs/admin_messages.json | 227 + public/api_explorer/api-docs/admin_pages.json | 333 + .../admin_paypal_transaction_logs.json | 86 + .../api-docs/admin_providers.json | 219 + public/api_explorer/api-docs/admin_roles.json | 69 + .../api-docs/admin_setting_categories.json | 94 + .../api_explorer/api-docs/admin_settings.json | 289 + .../api_explorer/api-docs/admin_states.json | 253 + .../api_explorer/api-docs/admin_sudopay.json | 27 + .../api-docs/admin_sudopay_ipn_logs.json | 86 + .../admin_sudopay_transaction_logs.json | 86 + .../api-docs/admin_transaction_types.json | 178 + .../api-docs/admin_transactions.json | 108 + .../api-docs/admin_unavailable_vehicles.json | 260 + .../api-docs/admin_user_cash_withdrawals.json | 191 + .../api-docs/admin_user_logins.json | 122 + public/api_explorer/api-docs/admin_users.json | 465 + .../api-docs/admin_vehicle_companies.json | 431 + .../admin_vehicle_dispute_closed_types.json | 163 + .../api-docs/admin_vehicle_dispute_types.json | 165 + .../api-docs/admin_vehicle_disputes.json | 144 + .../admin_vehicle_extra_accessories.json | 290 + .../api-docs/admin_vehicle_feedbacks.json | 233 + .../api-docs/admin_vehicle_fuel_options.json | 290 + .../api-docs/admin_vehicle_insurances.json | 290 + .../api-docs/admin_vehicle_makes.json | 260 + .../api-docs/admin_vehicle_models.json | 270 + .../api-docs/admin_vehicle_rentals.json | 258 + .../admin_vehicle_special_prices.json | 294 + .../api-docs/admin_vehicle_surcharges.json | 290 + .../api-docs/admin_vehicle_taxes.json | 290 + .../admin_vehicle_type_extra_accessories.json | 314 + .../admin_vehicle_type_fuel_options.json | 314 + .../admin_vehicle_type_insurances.json | 314 + .../api-docs/admin_vehicle_type_prices.json | 298 + .../admin_vehicle_type_surcharges.json | 314 + .../api-docs/admin_vehicle_type_taxes.json | 314 + .../api-docs/admin_vehicle_types.json | 344 + .../api_explorer/api-docs/admin_vehicles.json | 508 ++ .../admin_wallet_transaction_logs.json | 86 + .../api-docs/admin_withdrawal_statuses.json | 69 + .../api-docs/cancellation_types.json | 69 + public/api_explorer/api-docs/cities.json | 85 + public/api_explorer/api-docs/contacts.json | 77 + .../api-docs/counter_locations.json | 77 + public/api_explorer/api-docs/countries.json | 85 + public/api_explorer/api-docs/currencies.json | 93 + public/api_explorer/api-docs/fuel_types.json | 77 + public/api_explorer/api-docs/images.json | 57 + public/api_explorer/api-docs/index.php | 391 + public/api_explorer/api-docs/languages.json | 93 + public/api_explorer/api-docs/messages.json | 367 + .../api-docs/money_transfer_accounts.json | 104 + public/api_explorer/api-docs/pages.json | 54 + .../api-docs/payment_gateways.json | 57 + public/api_explorer/api-docs/providers.json | 81 + public/api_explorer/api-docs/settings.json | 69 + .../api_explorer/api-docs/social_logins.json | 478 + public/api_explorer/api-docs/states.json | 75 + .../api-docs/transaction_types.json | 61 + .../api_explorer/api-docs/transactions.json | 83 + .../api-docs/unavailable_vehicles.json | 236 + .../api-docs/user_cash_withdrawals.json | 119 + .../api_explorer/api-docs/user_profiles.json | 133 + public/api_explorer/api-docs/user_views.json | 102 + public/api_explorer/api-docs/users.json | 375 + .../api-docs/vehicle_companies.json | 218 + .../api-docs/vehicle_disputes.json | 167 + .../api-docs/vehicle_extra_accessories.json | 81 + .../api-docs/vehicle_feedbacks.json | 205 + .../api-docs/vehicle_fuel_options.json | 81 + .../api-docs/vehicle_insurances.json | 81 + .../api_explorer/api-docs/vehicle_makes.json | 77 + .../api_explorer/api-docs/vehicle_models.json | 77 + .../api-docs/vehicle_rentals.json | 687 ++ .../api-docs/vehicle_special_prices.json | 135 + .../api-docs/vehicle_surcharges.json | 81 + .../api_explorer/api-docs/vehicle_taxes.json | 81 + .../vehicle_type_extra_accessories.json | 69 + .../api-docs/vehicle_type_fuel_options.json | 69 + .../api-docs/vehicle_type_insurances.json | 69 + .../api-docs/vehicle_type_prices.json | 135 + .../api-docs/vehicle_type_surcharges.json | 69 + .../api-docs/vehicle_type_taxes.json | 69 + .../api_explorer/api-docs/vehicle_types.json | 106 + public/api_explorer/api-docs/vehicles.json | 838 ++ public/api_explorer/api-docs/wallets.json | 52 + .../api-docs/withdrawal_statuses.json | 69 + public/api_explorer/css/highlight.default.css | 135 + public/api_explorer/css/screen.css | 1070 +++ public/api_explorer/images/logo_small.png | Bin 0 -> 770 bytes public/api_explorer/images/pet_store_api.png | Bin 0 -> 824 bytes public/api_explorer/images/throbber.gif | Bin 0 -> 9257 bytes public/api_explorer/images/wordnik_api.png | Bin 0 -> 980 bytes public/api_explorer/index.html | 85 + public/api_explorer/lib/backbone-min.js | 38 + public/api_explorer/lib/handlebars-1.0.0.js | 2278 +++++ public/api_explorer/lib/highlight.7.3.pack.js | 1 + public/api_explorer/lib/jquery-1.8.0.min.js | 2 + public/api_explorer/lib/jquery.ba-bbq.min.js | 18 + public/api_explorer/lib/jquery.slideto.min.js | 1 + public/api_explorer/lib/jquery.wiggle.min.js | 8 + public/api_explorer/lib/shred.bundle.js | 2765 ++++++ public/api_explorer/lib/shred/content.js | 193 + public/api_explorer/lib/swagger.js | 1291 +++ public/api_explorer/lib/underscore-min.js | 32 + public/api_explorer/swagger-ui.js | 2119 +++++ public/api_explorer/swagger-ui.min.js | 2858 ++++++ public/index.php | 41 + resources/views/emails/mailContent.php | 16 + storage/app/.gitignore | 2 + storage/framework/views/.gitignore | 2 + storage/logs/.gitignore | 2 + tests/ExampleTest.php | 33 + tests/TestCase.php | 27 + 1065 files changed, 132856 insertions(+), 1 deletion(-) create mode 100644 .bowerrc create mode 100644 .env.example create mode 100644 .gitignore create mode 100644 Gruntfile.js create mode 100644 app/ApiRequest.php create mode 100644 app/Attachment.php create mode 100644 app/City.php create mode 100644 app/Console/Commands/.gitkeep create mode 100644 app/Console/Commands/CurrencyCron.php create mode 100644 app/Console/Commands/GeoIpCron.php create mode 100644 app/Console/Commands/StatusUpdateCron.php create mode 100644 app/Console/Kernel.php create mode 100644 app/Country.php create mode 100644 app/Currency.php create mode 100644 app/DiscountType.php create mode 100644 app/DurationType.php create mode 100644 app/EmailTemplate.php create mode 100644 app/Events/Event.php create mode 100644 app/Exceptions/Handler.php create mode 100644 app/Http/Controllers/Admin/AdminApiRequestsController.php create mode 100644 app/Http/Controllers/Admin/AdminCitiesController.php create mode 100644 app/Http/Controllers/Admin/AdminCountriesController.php create mode 100644 app/Http/Controllers/Admin/AdminCurrenciesController.php create mode 100644 app/Http/Controllers/Admin/AdminDashboardsController.php create mode 100644 app/Http/Controllers/Admin/AdminEmailTemplatesController.php create mode 100644 app/Http/Controllers/Admin/AdminIpsController.php create mode 100644 app/Http/Controllers/Admin/AdminLanguagesController.php create mode 100644 app/Http/Controllers/Admin/AdminMessagesController.php create mode 100644 app/Http/Controllers/Admin/AdminRolesController.php create mode 100644 app/Http/Controllers/Admin/AdminSettingCategoriesController.php create mode 100644 app/Http/Controllers/Admin/AdminSettingsController.php create mode 100644 app/Http/Controllers/Admin/AdminStatesController.php create mode 100644 app/Http/Controllers/Admin/AdminTransactionTypesController.php create mode 100644 app/Http/Controllers/Admin/AdminTransactionsController.php create mode 100644 app/Http/Controllers/Admin/AdminUserLoginsController.php create mode 100644 app/Http/Controllers/Admin/AdminUsersController.php create mode 100644 app/Http/Controllers/Admin/AdminWalletTransactionLogsController.php create mode 100644 app/Http/Controllers/AssetsController.php create mode 100644 app/Http/Controllers/CitiesController.php create mode 100644 app/Http/Controllers/Controller.php create mode 100644 app/Http/Controllers/CountriesController.php create mode 100644 app/Http/Controllers/CurrenciesController.php create mode 100644 app/Http/Controllers/ImagesController.php create mode 100644 app/Http/Controllers/LanguagesController.php create mode 100644 app/Http/Controllers/MessagesController.php create mode 100644 app/Http/Controllers/PaymentGatewaysController.php create mode 100644 app/Http/Controllers/SettingsController.php create mode 100644 app/Http/Controllers/StatesController.php create mode 100644 app/Http/Controllers/TransactionTypesController.php create mode 100644 app/Http/Controllers/TransactionsController.php create mode 100644 app/Http/Controllers/UserProfilesController.php create mode 100644 app/Http/Controllers/UsersController.php create mode 100644 app/Http/Controllers/WalletsController.php create mode 100644 app/Http/Middleware/Authenticate.php create mode 100644 app/Http/Middleware/AuthenticateRole.php create mode 100644 app/Http/Middleware/Tracking.php create mode 100644 app/Http/Requests/CreateUserRequest.php create mode 100644 app/Http/Requests/Request.php create mode 100644 app/Http/routes.php create mode 100644 app/Ip.php create mode 100644 app/ItemUserStatus.php create mode 100644 app/Jobs/Job.php create mode 100644 app/Language.php create mode 100644 app/Message.php create mode 100644 app/MessageContent.php create mode 100644 app/Plugins/Analytics/plugin.json create mode 100644 app/Plugins/Banner/plugin.json create mode 100644 app/Plugins/Contacts/Controllers/Admin/AdminContactsController.php create mode 100644 app/Plugins/Contacts/Controllers/ContactsController.php create mode 100644 app/Plugins/Contacts/Model/Contact.php create mode 100644 app/Plugins/Contacts/Providers/ContactServiceProvider.php create mode 100644 app/Plugins/Contacts/Services/ContactService.php create mode 100644 app/Plugins/Contacts/Transformers/ContactTransformer.php create mode 100644 app/Plugins/Contacts/plugin.json create mode 100644 app/Plugins/Contacts/routes.php create mode 100644 app/Plugins/CurrencyConversions/Controllers/Admin/AdminCurrencyConversionHistoriesController.php create mode 100644 app/Plugins/CurrencyConversions/Controllers/Admin/AdminCurrencyConversionsController.php create mode 100644 app/Plugins/CurrencyConversions/Model/CurrencyConversion.php create mode 100644 app/Plugins/CurrencyConversions/Model/CurrencyConversionHistory.php create mode 100644 app/Plugins/CurrencyConversions/Providers/CurrencyConversionServiceProvider.php create mode 100644 app/Plugins/CurrencyConversions/Services/CurrencyConversionService.php create mode 100644 app/Plugins/CurrencyConversions/Transformers/CurrencyConversionHistoryTransformer.php create mode 100644 app/Plugins/CurrencyConversions/Transformers/CurrencyConversionTransformer.php create mode 100644 app/Plugins/CurrencyConversions/plugin.json create mode 100644 app/Plugins/CurrencyConversions/routes.php create mode 100644 app/Plugins/Pages/Controllers/Admin/AdminPagesController.php create mode 100644 app/Plugins/Pages/Controllers/PagesController.php create mode 100644 app/Plugins/Pages/Model/Page.php create mode 100644 app/Plugins/Pages/Providers/PageServiceProvider.php create mode 100644 app/Plugins/Pages/Transformers/PageLanguageTransformer.php create mode 100644 app/Plugins/Pages/Transformers/PageTransformer.php create mode 100644 app/Plugins/Pages/plugin.json create mode 100644 app/Plugins/Pages/routes.php create mode 100644 app/Plugins/Paypal/Controllers/Admin/AdminPaypalTransactionLogsController.php create mode 100644 app/Plugins/Paypal/Controllers/PaypalController.php create mode 100644 app/Plugins/Paypal/Model/PaypalTransactionLog.php create mode 100644 app/Plugins/Paypal/Providers/PaypalServiceProvider.php create mode 100644 app/Plugins/Paypal/Services/PayPalService.php create mode 100644 app/Plugins/Paypal/Services/PaypalTransactionLogService.php create mode 100644 app/Plugins/Paypal/Transformers/PaypalTransactionLogTransformer.php create mode 100644 app/Plugins/Paypal/plugin.json create mode 100644 app/Plugins/Paypal/routes.php create mode 100644 app/Plugins/PluginServiceProvider.php create mode 100644 app/Plugins/SocialLogins/Controllers/Admin/AdminProvidersController.php create mode 100644 app/Plugins/SocialLogins/Controllers/ProvidersController.php create mode 100644 app/Plugins/SocialLogins/Controllers/SocialLoginsController.php create mode 100644 app/Plugins/SocialLogins/Model/Provider.php create mode 100644 app/Plugins/SocialLogins/Model/ProviderUser.php create mode 100644 app/Plugins/SocialLogins/Providers/SocialLoginServiceProvider.php create mode 100644 app/Plugins/SocialLogins/Services/SocialLoginService.php create mode 100644 app/Plugins/SocialLogins/Transformers/ProviderTransformer.php create mode 100644 app/Plugins/SocialLogins/Transformers/ProviderUserTransformer.php create mode 100644 app/Plugins/SocialLogins/plugin.json create mode 100644 app/Plugins/SocialLogins/routes.php create mode 100644 app/Plugins/Sudopays/Controllers/Admin/AdminSudopayIpnLogsController.php create mode 100644 app/Plugins/Sudopays/Controllers/Admin/AdminSudopayTransactionLogsController.php create mode 100644 app/Plugins/Sudopays/Controllers/Admin/AdminSudopaysController.php create mode 100644 app/Plugins/Sudopays/Controllers/SudopaysController.php create mode 100644 app/Plugins/Sudopays/Model/SudopayIpnLog.php create mode 100644 app/Plugins/Sudopays/Model/SudopayPaymentGateway.php create mode 100644 app/Plugins/Sudopays/Model/SudopayPaymentGroup.php create mode 100644 app/Plugins/Sudopays/Model/SudopayTransactionLog.php create mode 100644 app/Plugins/Sudopays/Providers/SudopayServiceProvider.php create mode 100644 app/Plugins/Sudopays/Services/SudopayAPIService.php create mode 100644 app/Plugins/Sudopays/Services/SudopayIpnService.php create mode 100644 app/Plugins/Sudopays/Services/SudopayService.php create mode 100644 app/Plugins/Sudopays/Services/SudopayTransactionLogService.php create mode 100644 app/Plugins/Sudopays/Transformers/SudopayIpnLogTransformer.php create mode 100644 app/Plugins/Sudopays/Transformers/SudopayTransactionLogTransformer.php create mode 100644 app/Plugins/Sudopays/plugin.json create mode 100644 app/Plugins/Sudopays/routes.php create mode 100644 app/Plugins/Translations/plugin.json create mode 100644 app/Plugins/VehicleCoupons/Controllers/Admin/AdminVehicleCouponsController.php create mode 100644 app/Plugins/VehicleCoupons/Controllers/VehicleCouponsController.php create mode 100644 app/Plugins/VehicleCoupons/Model/VehicleCoupon.php create mode 100644 app/Plugins/VehicleCoupons/Providers/VehicleCouponServiceProvider.php create mode 100644 app/Plugins/VehicleCoupons/Services/VehicleCouponService.php create mode 100644 app/Plugins/VehicleCoupons/Transformers/VehicleCouponTransformer.php create mode 100644 app/Plugins/VehicleCoupons/plugin.json create mode 100644 app/Plugins/VehicleCoupons/routes.php create mode 100644 app/Plugins/VehicleDisputes/Controllers/Admin/AdminVehicleDisputeClosedTypesController.php create mode 100644 app/Plugins/VehicleDisputes/Controllers/Admin/AdminVehicleDisputeTypesController.php create mode 100644 app/Plugins/VehicleDisputes/Controllers/Admin/AdminVehicleDisputesController.php create mode 100644 app/Plugins/VehicleDisputes/Controllers/VehicleDisputeClosedTypesController.php create mode 100644 app/Plugins/VehicleDisputes/Controllers/VehicleDisputeTypesController.php create mode 100644 app/Plugins/VehicleDisputes/Controllers/VehicleDisputesController.php create mode 100644 app/Plugins/VehicleDisputes/Model/VehicleDispute.php create mode 100644 app/Plugins/VehicleDisputes/Model/VehicleDisputeClosedType.php create mode 100644 app/Plugins/VehicleDisputes/Model/VehicleDisputeStatus.php create mode 100644 app/Plugins/VehicleDisputes/Model/VehicleDisputeType.php create mode 100644 app/Plugins/VehicleDisputes/Providers/VehicleDisputeServiceProvider.php create mode 100644 app/Plugins/VehicleDisputes/Services/VehicleDisputeClosedTypeService.php create mode 100644 app/Plugins/VehicleDisputes/Services/VehicleDisputeService.php create mode 100644 app/Plugins/VehicleDisputes/Transformers/VehicleDisputeClosedTypeTransformer.php create mode 100644 app/Plugins/VehicleDisputes/Transformers/VehicleDisputeStatusTransformer.php create mode 100644 app/Plugins/VehicleDisputes/Transformers/VehicleDisputeTransformer.php create mode 100644 app/Plugins/VehicleDisputes/Transformers/VehicleDisputeTypeTransformer.php create mode 100644 app/Plugins/VehicleDisputes/plugin.json create mode 100644 app/Plugins/VehicleDisputes/routes.php create mode 100644 app/Plugins/VehicleExtraAccessories/Controllers/Admin/AdminVehicleExtraAccessoriesController.php create mode 100644 app/Plugins/VehicleExtraAccessories/Controllers/Admin/AdminVehicleTypeExtraAccessoriesController.php create mode 100644 app/Plugins/VehicleExtraAccessories/Controllers/VehicleExtraAccessoriesController.php create mode 100644 app/Plugins/VehicleExtraAccessories/Controllers/VehicleTypeExtraAccessoriesController.php create mode 100644 app/Plugins/VehicleExtraAccessories/Model/VehicleExtraAccessory.php create mode 100644 app/Plugins/VehicleExtraAccessories/Model/VehicleTypeExtraAccessory.php create mode 100644 app/Plugins/VehicleExtraAccessories/Providers/VehicleExtraAccessoryServiceProvider.php create mode 100644 app/Plugins/VehicleExtraAccessories/Services/VehicleExtraAccessoryService.php create mode 100644 app/Plugins/VehicleExtraAccessories/Transformers/AdminVehicleExtraAccessoryTransformer.php create mode 100644 app/Plugins/VehicleExtraAccessories/Transformers/VehicleExtraAccessoryTransformer.php create mode 100644 app/Plugins/VehicleExtraAccessories/Transformers/VehicleTypeExtraAccessoryTransformer.php create mode 100644 app/Plugins/VehicleExtraAccessories/plugin.json create mode 100644 app/Plugins/VehicleExtraAccessories/routes.php create mode 100644 app/Plugins/VehicleFeedbacks/Controllers/Admin/AdminVehicleFeedbacksController.php create mode 100644 app/Plugins/VehicleFeedbacks/Controllers/VehicleFeedbacksController.php create mode 100644 app/Plugins/VehicleFeedbacks/Model/VehicleFeedback.php create mode 100644 app/Plugins/VehicleFeedbacks/Providers/VehicleFeedbackServiceProvider.php create mode 100644 app/Plugins/VehicleFeedbacks/Services/VehicleFeedbackService.php create mode 100644 app/Plugins/VehicleFeedbacks/Transformers/VehicleFeedbackTransformer.php create mode 100644 app/Plugins/VehicleFeedbacks/plugin.json create mode 100644 app/Plugins/VehicleFeedbacks/routes.php create mode 100644 app/Plugins/VehicleFuelOptions/Controllers/Admin/AdminVehicleFuelOptionsController.php create mode 100644 app/Plugins/VehicleFuelOptions/Controllers/Admin/AdminVehicleTypeFuelOptionsController.php create mode 100644 app/Plugins/VehicleFuelOptions/Controllers/VehicleFuelOptionsController.php create mode 100644 app/Plugins/VehicleFuelOptions/Controllers/VehicleTypeFuelOptionsController.php create mode 100644 app/Plugins/VehicleFuelOptions/Model/VehicleFuelOption.php create mode 100644 app/Plugins/VehicleFuelOptions/Model/VehicleTypeFuelOption.php create mode 100644 app/Plugins/VehicleFuelOptions/Providers/VehicleFuelOptionServiceProvider.php create mode 100644 app/Plugins/VehicleFuelOptions/Services/VehicleFuelOptionService.php create mode 100644 app/Plugins/VehicleFuelOptions/Transformers/AdminVehicleFuelOptionTransformer.php create mode 100644 app/Plugins/VehicleFuelOptions/Transformers/VehicleFuelOptionTransformer.php create mode 100644 app/Plugins/VehicleFuelOptions/Transformers/VehicleTypeFuelOptionTransformer.php create mode 100644 app/Plugins/VehicleFuelOptions/plugin.json create mode 100644 app/Plugins/VehicleFuelOptions/routes.php create mode 100644 app/Plugins/VehicleInsurances/Controllers/Admin/AdminVehicleInsurancesController.php create mode 100644 app/Plugins/VehicleInsurances/Controllers/Admin/AdminVehicleTypeInsurancesController.php create mode 100644 app/Plugins/VehicleInsurances/Controllers/VehicleInsurancesController.php create mode 100644 app/Plugins/VehicleInsurances/Controllers/VehicleTypeInsurancesController.php create mode 100644 app/Plugins/VehicleInsurances/Model/VehicleInsurance.php create mode 100644 app/Plugins/VehicleInsurances/Model/VehicleTypeInsurance.php create mode 100644 app/Plugins/VehicleInsurances/Providers/VehicleInsuranceServiceProvider.php create mode 100644 app/Plugins/VehicleInsurances/Services/VehicleInsuranceService.php create mode 100644 app/Plugins/VehicleInsurances/Transformers/AdminVehicleInsuranceTransformer.php create mode 100644 app/Plugins/VehicleInsurances/Transformers/VehicleInsuranceTransformer.php create mode 100644 app/Plugins/VehicleInsurances/Transformers/VehicleTypeInsuranceTransformer.php create mode 100644 app/Plugins/VehicleInsurances/plugin.json create mode 100644 app/Plugins/VehicleInsurances/routes.php create mode 100644 app/Plugins/VehicleRentals/Controllers/Admin/AdminVehicleRentalStatusesController.php create mode 100644 app/Plugins/VehicleRentals/Controllers/Admin/AdminVehicleRentalsController.php create mode 100644 app/Plugins/VehicleRentals/Controllers/VehicleRentalStatusesController.php create mode 100644 app/Plugins/VehicleRentals/Controllers/VehicleRentalsController.php create mode 100644 app/Plugins/VehicleRentals/Model/VehicleRental.php create mode 100644 app/Plugins/VehicleRentals/Model/VehicleRentalAdditionalCharge.php create mode 100644 app/Plugins/VehicleRentals/Model/VehicleRentalBookerDetail.php create mode 100644 app/Plugins/VehicleRentals/Model/VehicleRentalLatePaymentDetail.php create mode 100644 app/Plugins/VehicleRentals/Model/VehicleRentalStatus.php create mode 100644 app/Plugins/VehicleRentals/Providers/VehicleRentalServiceProvider.php create mode 100644 app/Plugins/VehicleRentals/Services/VehicleRentalBookerDetailService.php create mode 100644 app/Plugins/VehicleRentals/Services/VehicleRentalLatePaymentDetailService.php create mode 100644 app/Plugins/VehicleRentals/Services/VehicleRentalService.php create mode 100644 app/Plugins/VehicleRentals/Transformers/VehicleRentalAdditionalChargeTransformer.php create mode 100644 app/Plugins/VehicleRentals/Transformers/VehicleRentalBookerDetailTransformer.php create mode 100644 app/Plugins/VehicleRentals/Transformers/VehicleRentalLatePaymentDetailTransformer.php create mode 100644 app/Plugins/VehicleRentals/Transformers/VehicleRentalStatusTransformer.php create mode 100644 app/Plugins/VehicleRentals/Transformers/VehicleRentalTransformer.php create mode 100644 app/Plugins/VehicleRentals/plugin.json create mode 100644 app/Plugins/VehicleRentals/routes.php create mode 100644 app/Plugins/VehicleSurcharges/Controllers/Admin/AdminVehicleSurchargesController.php create mode 100644 app/Plugins/VehicleSurcharges/Controllers/Admin/AdminVehicleTypeSurchargesController.php create mode 100644 app/Plugins/VehicleSurcharges/Controllers/VehicleSurchargesController.php create mode 100644 app/Plugins/VehicleSurcharges/Controllers/VehicleTypeSurchargesController.php create mode 100644 app/Plugins/VehicleSurcharges/Model/VehicleSurcharge.php create mode 100644 app/Plugins/VehicleSurcharges/Model/VehicleTypeSurcharge.php create mode 100644 app/Plugins/VehicleSurcharges/Providers/VehicleSurchargeServiceProvider.php create mode 100644 app/Plugins/VehicleSurcharges/Services/VehicleSurchargeService.php create mode 100644 app/Plugins/VehicleSurcharges/Transformers/AdminVehicleSurchargeTransformer.php create mode 100644 app/Plugins/VehicleSurcharges/Transformers/VehicleSurchargeTransformer.php create mode 100644 app/Plugins/VehicleSurcharges/Transformers/VehicleTypeSurchargeTransformer.php create mode 100644 app/Plugins/VehicleSurcharges/plugin.json create mode 100644 app/Plugins/VehicleSurcharges/routes.php create mode 100644 app/Plugins/VehicleTaxes/Controllers/Admin/AdminVehicleTaxesController.php create mode 100644 app/Plugins/VehicleTaxes/Controllers/Admin/AdminVehicleTypeTaxesController.php create mode 100644 app/Plugins/VehicleTaxes/Controllers/VehicleTaxesController.php create mode 100644 app/Plugins/VehicleTaxes/Controllers/VehicleTypeTaxesController.php create mode 100644 app/Plugins/VehicleTaxes/Model/VehicleTax.php create mode 100644 app/Plugins/VehicleTaxes/Model/VehicleTypeTax.php create mode 100644 app/Plugins/VehicleTaxes/Providers/VehicleTaxServiceProvider.php create mode 100644 app/Plugins/VehicleTaxes/Services/VehicleTaxService.php create mode 100644 app/Plugins/VehicleTaxes/Transformers/AdminVehicleTaxTransformer.php create mode 100644 app/Plugins/VehicleTaxes/Transformers/VehicleTaxTransformer.php create mode 100644 app/Plugins/VehicleTaxes/Transformers/VehicleTypeTaxTransformer.php create mode 100644 app/Plugins/VehicleTaxes/plugin.json create mode 100644 app/Plugins/VehicleTaxes/routes.php create mode 100644 app/Plugins/Vehicles/Controllers/Admin/AdminCounterLocationsController.php create mode 100644 app/Plugins/Vehicles/Controllers/Admin/AdminFuelTypesController.php create mode 100644 app/Plugins/Vehicles/Controllers/Admin/AdminUnavailableVehiclesController.php create mode 100644 app/Plugins/Vehicles/Controllers/Admin/AdminVehicleCompaniesController.php create mode 100644 app/Plugins/Vehicles/Controllers/Admin/AdminVehicleMakesController.php create mode 100644 app/Plugins/Vehicles/Controllers/Admin/AdminVehicleModelsController.php create mode 100644 app/Plugins/Vehicles/Controllers/Admin/AdminVehicleSpecialPricesController.php create mode 100644 app/Plugins/Vehicles/Controllers/Admin/AdminVehicleTypePricesController.php create mode 100644 app/Plugins/Vehicles/Controllers/Admin/AdminVehicleTypesController.php create mode 100644 app/Plugins/Vehicles/Controllers/Admin/AdminVehiclesController.php create mode 100644 app/Plugins/Vehicles/Controllers/CounterLocationsController.php create mode 100644 app/Plugins/Vehicles/Controllers/FuelTypesController.php create mode 100644 app/Plugins/Vehicles/Controllers/UnavailableVehiclesController.php create mode 100644 app/Plugins/Vehicles/Controllers/VehicleCompaniesController.php create mode 100644 app/Plugins/Vehicles/Controllers/VehicleMakesController.php create mode 100644 app/Plugins/Vehicles/Controllers/VehicleModelsController.php create mode 100644 app/Plugins/Vehicles/Controllers/VehicleSpecialPricesController.php create mode 100644 app/Plugins/Vehicles/Controllers/VehicleTypePricesController.php create mode 100644 app/Plugins/Vehicles/Controllers/VehicleTypesController.php create mode 100644 app/Plugins/Vehicles/Controllers/VehiclesController.php create mode 100644 app/Plugins/Vehicles/Model/CounterLocation.php create mode 100644 app/Plugins/Vehicles/Model/FuelType.php create mode 100644 app/Plugins/Vehicles/Model/UnavailableVehicle.php create mode 100644 app/Plugins/Vehicles/Model/Vehicle.php create mode 100644 app/Plugins/Vehicles/Model/VehicleCompany.php create mode 100644 app/Plugins/Vehicles/Model/VehicleMake.php create mode 100644 app/Plugins/Vehicles/Model/VehicleModel.php create mode 100644 app/Plugins/Vehicles/Model/VehicleSpecialPrice.php create mode 100644 app/Plugins/Vehicles/Model/VehicleType.php create mode 100644 app/Plugins/Vehicles/Model/VehicleTypePrice.php create mode 100644 app/Plugins/Vehicles/Providers/VehicleServiceProvider.php create mode 100644 app/Plugins/Vehicles/Services/CounterLocationService.php create mode 100644 app/Plugins/Vehicles/Services/FuelTypeService.php create mode 100644 app/Plugins/Vehicles/Services/UnavailableVehicleService.php create mode 100644 app/Plugins/Vehicles/Services/VehicleCompanyService.php create mode 100644 app/Plugins/Vehicles/Services/VehicleMakeService.php create mode 100644 app/Plugins/Vehicles/Services/VehicleModelService.php create mode 100644 app/Plugins/Vehicles/Services/VehicleService.php create mode 100644 app/Plugins/Vehicles/Services/VehicleSpecialPriceService.php create mode 100644 app/Plugins/Vehicles/Services/VehicleTypePriceService.php create mode 100644 app/Plugins/Vehicles/Services/VehicleTypeService.php create mode 100644 app/Plugins/Vehicles/Transformers/AdminCounterLocationTransformer.php create mode 100644 app/Plugins/Vehicles/Transformers/AdminFuelTypeTransformer.php create mode 100644 app/Plugins/Vehicles/Transformers/AdminVehicleCompanyTransformer.php create mode 100644 app/Plugins/Vehicles/Transformers/AdminVehicleMakeTransformer.php create mode 100644 app/Plugins/Vehicles/Transformers/AdminVehicleModelTransformer.php create mode 100644 app/Plugins/Vehicles/Transformers/AdminVehicleSpecialPriceTransformer.php create mode 100644 app/Plugins/Vehicles/Transformers/AdminVehicleTransformer.php create mode 100644 app/Plugins/Vehicles/Transformers/AdminVehicleTypePriceTransformer.php create mode 100644 app/Plugins/Vehicles/Transformers/AdminVehicleTypeTransformer.php create mode 100644 app/Plugins/Vehicles/Transformers/CounterLocationTransformer.php create mode 100644 app/Plugins/Vehicles/Transformers/FuelTypeTransformer.php create mode 100644 app/Plugins/Vehicles/Transformers/UnavailableVehicleTransformer.php create mode 100644 app/Plugins/Vehicles/Transformers/VehicleCompanyTransformer.php create mode 100644 app/Plugins/Vehicles/Transformers/VehicleMakeTransformer.php create mode 100644 app/Plugins/Vehicles/Transformers/VehicleModelTransformer.php create mode 100644 app/Plugins/Vehicles/Transformers/VehicleSimpleTransformer.php create mode 100644 app/Plugins/Vehicles/Transformers/VehicleSpecialPriceTransformer.php create mode 100644 app/Plugins/Vehicles/Transformers/VehicleTransformer.php create mode 100644 app/Plugins/Vehicles/Transformers/VehicleTypePriceTransformer.php create mode 100644 app/Plugins/Vehicles/Transformers/VehicleTypeSimpleTransformer.php create mode 100644 app/Plugins/Vehicles/Transformers/VehicleTypeTransformer.php create mode 100644 app/Plugins/Vehicles/plugin.json create mode 100644 app/Plugins/Vehicles/routes.php create mode 100644 app/Plugins/Withdrawals/Controllers/Admin/AdminUserCashWithdrawalsController.php create mode 100644 app/Plugins/Withdrawals/Controllers/Admin/AdminWithdrawalStatusesController.php create mode 100644 app/Plugins/Withdrawals/Controllers/MoneyTransferAccountsController.php create mode 100644 app/Plugins/Withdrawals/Controllers/UserCashWithdrawalsController.php create mode 100644 app/Plugins/Withdrawals/Controllers/WithdrawalStatusesController.php create mode 100644 app/Plugins/Withdrawals/Model/MoneyTransferAccount.php create mode 100644 app/Plugins/Withdrawals/Model/UserCashWithdrawal.php create mode 100644 app/Plugins/Withdrawals/Model/WithdrawalStatus.php create mode 100644 app/Plugins/Withdrawals/Providers/WithdrawServiceProvider.php create mode 100644 app/Plugins/Withdrawals/Services/MoneyTransferAccountService.php create mode 100644 app/Plugins/Withdrawals/Services/UserCashWithdrawalService.php create mode 100644 app/Plugins/Withdrawals/Transformers/MoneyTransferAccountTransformer.php create mode 100644 app/Plugins/Withdrawals/Transformers/UserCashWithdrawalTransformer.php create mode 100644 app/Plugins/Withdrawals/Transformers/WithdrawalStatusTransformer.php create mode 100644 app/Plugins/Withdrawals/plugin.json create mode 100644 app/Plugins/Withdrawals/routes.php create mode 100644 app/Plugins/composer.json create mode 100644 app/Providers/AppServiceProvider.php create mode 100644 app/Providers/AuthServiceProvider.php create mode 100644 app/Providers/EventServiceProvider.php create mode 100644 app/Providers/MessageServiceProvider.php create mode 100644 app/Providers/SettingsServiceProvider.php create mode 100644 app/Providers/TransactionServiceProvider.php create mode 100644 app/Role.php create mode 100644 app/Services/AttachmentService.php create mode 100644 app/Services/CityService.php create mode 100644 app/Services/CountryService.php create mode 100644 app/Services/IpService.php create mode 100644 app/Services/MailService.php create mode 100644 app/Services/MessageService.php create mode 100644 app/Services/TokenService.php create mode 100644 app/Services/TransactionService.php create mode 100644 app/Services/UserLoginService.php create mode 100644 app/Services/UserService.php create mode 100644 app/Services/WalletService.php create mode 100644 app/Services/WalletTransactionLogService.php create mode 100644 app/Setting.php create mode 100644 app/SettingCategory.php create mode 100644 app/State.php create mode 100644 app/Transaction.php create mode 100644 app/TransactionType.php create mode 100644 app/Transformers/ApiRequestTransformer.php create mode 100644 app/Transformers/AttachmentTransformer.php create mode 100644 app/Transformers/CityTransformer.php create mode 100644 app/Transformers/CountryTransformer.php create mode 100644 app/Transformers/CurrencyTransformer.php create mode 100644 app/Transformers/DiscountTypeTransformer.php create mode 100644 app/Transformers/DurationTypeTransformer.php create mode 100644 app/Transformers/EmailTemplateTransformer.php create mode 100644 app/Transformers/IpTransformer.php create mode 100644 app/Transformers/LanguageTransformer.php create mode 100644 app/Transformers/MessageContentTransformer.php create mode 100644 app/Transformers/MessageTransformer.php create mode 100644 app/Transformers/RoleTransformer.php create mode 100644 app/Transformers/SettingCategoryTransformer.php create mode 100644 app/Transformers/SettingTransformer.php create mode 100644 app/Transformers/StateTransformer.php create mode 100644 app/Transformers/TransactionTransformer.php create mode 100644 app/Transformers/TransactionTypeTransformer.php create mode 100644 app/Transformers/UploadAttachmentTransformer.php create mode 100644 app/Transformers/UserAuthTransformer.php create mode 100644 app/Transformers/UserLoginTransformer.php create mode 100644 app/Transformers/UserProfileTransformer.php create mode 100644 app/Transformers/UserSimpleFeedbackTransformer.php create mode 100644 app/Transformers/UserSimpleTransformer.php create mode 100644 app/Transformers/UserTransformer.php create mode 100644 app/Transformers/WalletTransactionLogTransformer.php create mode 100644 app/User.php create mode 100644 app/UserLogin.php create mode 100644 app/UserProfile.php create mode 100644 app/Wallet.php create mode 100644 app/WalletTransactionLog.php create mode 100644 app/helpers.php create mode 100644 artisan create mode 100644 bootstrap/app.php create mode 100644 bower.json create mode 100644 client/.npmignore create mode 100644 client/.yo-rc.json create mode 100644 client/README.md create mode 100644 client/src/README.md create mode 100644 client/src/ag-admin/index.html create mode 100644 client/src/ag-admin/js/ng-admin.app.js create mode 100644 client/src/ag-admin/js/ng-admin.jwt-auth.js create mode 100644 client/src/ag-admin/tpl/changePassword.tpl.html create mode 100644 client/src/ag-admin/tpl/counterLocationAdd.tpl.html create mode 100644 client/src/ag-admin/tpl/counterLocationEdit.tpl.html create mode 100644 client/src/ag-admin/tpl/customHeader.tpl.html create mode 100644 client/src/ag-admin/tpl/customLoginTemplate.html create mode 100644 client/src/ag-admin/tpl/dashboardSummary.tpl.html create mode 100644 client/src/ag-admin/tpl/pages.tpl.html create mode 100644 client/src/ag-admin/tpl/plugins.tpl.html create mode 100644 client/src/ag-admin/tpl/trip_detail.tpl.html create mode 100644 client/src/ag-admin/tpl/vehicle.tpl.html create mode 100644 client/src/ag-admin/tpl/vehicleAdd.tpl.html create mode 100644 client/src/ag-admin/tpl/vehicleCompaniesAdd.tpl.html create mode 100644 client/src/ag-admin/tpl/vehicleCompaniesEdit.tpl.html create mode 100644 client/src/ag-admin/tpl/vehicleEdit.tpl.html create mode 100644 client/src/ag-admin/tpl/vehicleTypePrice.tpl.html create mode 100644 client/src/ag-admin/tpl/vehicleView.tpl.html create mode 100644 client/src/ag-admin/tpl/vehicle_calendar.tpl.html create mode 100644 client/src/ag-admin/tpl/vehiclecheckOut.tpl.html create mode 100644 client/src/app/App.js create mode 100644 client/src/app/Common/404.tpl.html create mode 100644 client/src/app/Common/Common.module.js create mode 100644 client/src/app/Common/Footer.js create mode 100644 client/src/app/Common/Header.js create mode 100644 client/src/app/Common/footer.tpl.html create mode 100644 client/src/app/Common/gateway.tpl.html create mode 100644 client/src/app/Common/header.tpl.html create mode 100644 client/src/app/Common/how_it_works.tpl.html create mode 100644 client/src/app/Constant.js create mode 100644 client/src/app/Home/Home.js create mode 100644 client/src/app/Home/Home.module.js create mode 100644 client/src/app/Home/home.tpl.html create mode 100644 client/src/app/Message/Message.js create mode 100644 client/src/app/Message/Message.module.js create mode 100644 client/src/app/Message/MessageService.js create mode 100644 client/src/app/Message/message_list.tpl.html create mode 100644 client/src/app/Message/message_sidebar.tpl.html create mode 100644 client/src/app/Message/message_view.tpl.html create mode 100644 client/src/app/Plugins/Analytics/Analytics.js create mode 100644 client/src/app/Plugins/Banner/Banner.js create mode 100644 client/src/app/Plugins/Banner/banner.tpl.html create mode 100644 client/src/app/Plugins/Contacts/Contacts.js create mode 100644 client/src/app/Plugins/Contacts/Contacts.module.js create mode 100644 client/src/app/Plugins/Contacts/ContactsService.js create mode 100644 client/src/app/Plugins/Contacts/contact_links.tpl.html create mode 100644 client/src/app/Plugins/Contacts/contacts.tpl.html create mode 100644 client/src/app/Plugins/CurrencyConversions/CurrencyConversion.js create mode 100644 client/src/app/Plugins/CurrencyConversions/CurrencyConversion.module.js create mode 100644 client/src/app/Plugins/CurrencyConversions/currency_conversion.tpl.html create mode 100644 client/src/app/Plugins/Pages/Pages.js create mode 100644 client/src/app/Plugins/Pages/Pages.module.js create mode 100644 client/src/app/Plugins/Pages/Pages.spec.js create mode 100644 client/src/app/Plugins/Pages/PagesService.js create mode 100644 client/src/app/Plugins/Pages/page_links.tpl.html create mode 100644 client/src/app/Plugins/Pages/pages.tpl.html create mode 100644 client/src/app/Plugins/Paypal/Paypal.module.js create mode 100644 client/src/app/Plugins/SocialLogins/SocialConnection.js create mode 100644 client/src/app/Plugins/SocialLogins/SocialLogin.js create mode 100644 client/src/app/Plugins/SocialLogins/SocialLogin.module.js create mode 100644 client/src/app/Plugins/SocialLogins/SocialLoginService.js create mode 100644 client/src/app/Plugins/SocialLogins/SocialProfile.js create mode 100644 client/src/app/Plugins/SocialLogins/get_email_from_user.tpl.html create mode 100644 client/src/app/Plugins/SocialLogins/my_connection.tpl.html create mode 100644 client/src/app/Plugins/SocialLogins/profile_image.tpl.html create mode 100644 client/src/app/Plugins/SocialLogins/social_login.tpl.html create mode 100644 client/src/app/Plugins/SocialLogins/social_login_share.tpl.html create mode 100644 client/src/app/Plugins/Sudopays/Sudopay.module.js create mode 100644 client/src/app/Plugins/Sudopays/buyer.tpl.html create mode 100644 client/src/app/Plugins/Sudopays/credit_card.tpl.html create mode 100644 client/src/app/Plugins/Sudopays/manual.tpl.html create mode 100644 client/src/app/Plugins/Translations/Translations.js create mode 100644 client/src/app/Plugins/Translations/language_translate.tpl.html create mode 100644 client/src/app/Plugins/VehicleCoupons/VehicleCoupons.module.js create mode 100644 client/src/app/Plugins/VehicleCoupons/vehicle_coupon.tpl.html create mode 100644 client/src/app/Plugins/VehicleDisputes/VehicleDispute.js create mode 100644 client/src/app/Plugins/VehicleDisputes/VehicleDisputeService.js create mode 100644 client/src/app/Plugins/VehicleDisputes/VehicleDisputes.module.js create mode 100644 client/src/app/Plugins/VehicleDisputes/vehicle_dispute.tpl.html create mode 100644 client/src/app/Plugins/VehicleExtraAccessories/VehicleExtraAccessories.module.js create mode 100644 client/src/app/Plugins/VehicleFeedbacks/FeedbackService.js create mode 100644 client/src/app/Plugins/VehicleFeedbacks/VehicleFeedbacks.module.js create mode 100644 client/src/app/Plugins/VehicleFeedbacks/edit_feedback.tpl.html create mode 100644 client/src/app/Plugins/VehicleFeedbacks/feedback.js create mode 100644 client/src/app/Plugins/VehicleFeedbacks/feedback.tpl.html create mode 100644 client/src/app/Plugins/VehicleFeedbacks/rating.tpl.html create mode 100644 client/src/app/Plugins/VehicleFeedbacks/user_feedbacks.tpl.html create mode 100644 client/src/app/Plugins/VehicleFeedbacks/vehicle_feedbacks.tpl.html create mode 100644 client/src/app/Plugins/VehicleFuelOptions/VehicleFuelOptions.module.js create mode 100644 client/src/app/Plugins/VehicleInsurances/VehicleInsurances.module.js create mode 100644 client/src/app/Plugins/VehicleRentals/BookingCalendar.js create mode 100644 client/src/app/Plugins/VehicleRentals/OrderCalendar.js create mode 100644 client/src/app/Plugins/VehicleRentals/OrderLists.js create mode 100644 client/src/app/Plugins/VehicleRentals/VehicleCheckout.js create mode 100644 client/src/app/Plugins/VehicleRentals/VehicleRentalActivity.js create mode 100644 client/src/app/Plugins/VehicleRentals/VehicleRentalOrder.js create mode 100644 client/src/app/Plugins/VehicleRentals/VehicleRentalService.js create mode 100644 client/src/app/Plugins/VehicleRentals/VehicleRentals.js create mode 100644 client/src/app/Plugins/VehicleRentals/VehicleRentals.module.js create mode 100644 client/src/app/Plugins/VehicleRentals/order_lists.tpl.html create mode 100644 client/src/app/Plugins/VehicleRentals/vehicle_checkout.tpl.html create mode 100644 client/src/app/Plugins/VehicleRentals/vehicle_rental_activity.tpl.html create mode 100644 client/src/app/Plugins/VehicleRentals/vehicle_rental_add.tpl.html create mode 100644 client/src/app/Plugins/VehicleRentals/vehicle_rental_calendar.tpl.html create mode 100644 client/src/app/Plugins/VehicleRentals/vehicle_rental_list.tpl.html create mode 100644 client/src/app/Plugins/VehicleRentals/vehicle_rental_order.tpl.html create mode 100644 client/src/app/Plugins/VehicleSurcharges/VehicleSurcharges.module.js create mode 100644 client/src/app/Plugins/VehicleTaxes/VehicleTaxes.module.js create mode 100644 client/src/app/Plugins/Vehicles/MaintenanaceVehicles.js create mode 100644 client/src/app/Plugins/Vehicles/MyVehicles.js create mode 100644 client/src/app/Plugins/Vehicles/VehicleBookItModal.js create mode 100644 client/src/app/Plugins/Vehicles/VehicleDetails.js create mode 100644 client/src/app/Plugins/Vehicles/VehicleLists.js create mode 100644 client/src/app/Plugins/Vehicles/VehicleModal.js create mode 100644 client/src/app/Plugins/Vehicles/VehicleSearch.js create mode 100644 client/src/app/Plugins/Vehicles/VehicleService.js create mode 100644 client/src/app/Plugins/Vehicles/VehicleView.js create mode 100644 client/src/app/Plugins/Vehicles/Vehicles.js create mode 100644 client/src/app/Plugins/Vehicles/Vehicles.module.js create mode 100644 client/src/app/Plugins/Vehicles/VehiclesAllLists.js create mode 100644 client/src/app/Plugins/Vehicles/all_vehicles.tpl.html create mode 100644 client/src/app/Plugins/Vehicles/maintenance_vehicle_add.tpl.html create mode 100644 client/src/app/Plugins/Vehicles/maintenance_vehicle_edit.tpl.html create mode 100644 client/src/app/Plugins/Vehicles/maintenance_vehicles.tpl.html create mode 100644 client/src/app/Plugins/Vehicles/my_vehicles.tpl.html create mode 100644 client/src/app/Plugins/Vehicles/trip_detail.tpl.html create mode 100644 client/src/app/Plugins/Vehicles/vehicle.tpl.html create mode 100644 client/src/app/Plugins/Vehicles/vehicleAdd.js create mode 100644 client/src/app/Plugins/Vehicles/vehicleCompany.js create mode 100644 client/src/app/Plugins/Vehicles/vehicleCompany.tpl.html create mode 100644 client/src/app/Plugins/Vehicles/vehicleEdit.js create mode 100644 client/src/app/Plugins/Vehicles/vehicle_add.tpl.html create mode 100644 client/src/app/Plugins/Vehicles/vehicle_bookit.tpl.html create mode 100644 client/src/app/Plugins/Vehicles/vehicle_details.tpl.html create mode 100644 client/src/app/Plugins/Vehicles/vehicle_edit.tpl.html create mode 100644 client/src/app/Plugins/Vehicles/vehicle_feedback_modal.tpl.html create mode 100644 client/src/app/Plugins/Vehicles/vehicle_list.tpl.html create mode 100644 client/src/app/Plugins/Vehicles/vehicle_list_home.tpl.html create mode 100644 client/src/app/Plugins/Vehicles/vehicle_payment.tpl.html create mode 100644 client/src/app/Plugins/Vehicles/vehicle_search.tpl.html create mode 100644 client/src/app/Plugins/Vehicles/vehicle_view.tpl.html create mode 100644 client/src/app/Plugins/Withdrawals/MoneyTransferAccount.js create mode 100644 client/src/app/Plugins/Withdrawals/UserCashWithdrawals.js create mode 100644 client/src/app/Plugins/Withdrawals/UserCashWithdrawals.module.js create mode 100644 client/src/app/Plugins/Withdrawals/WithdrawalService.js create mode 100644 client/src/app/Plugins/Withdrawals/money_transfer_account.tpl.html create mode 100644 client/src/app/Plugins/Withdrawals/user_cashWithdrawals.tpl.html create mode 100644 client/src/app/README.md create mode 100644 client/src/app/Transactions/Transaction.js create mode 100644 client/src/app/Transactions/Transaction.module.js create mode 100644 client/src/app/Transactions/TransactionService.js create mode 100644 client/src/app/Transactions/transaction_list.tpl.html create mode 100644 client/src/app/User/ChangePassword.js create mode 100644 client/src/app/User/Dashboard.js create mode 100644 client/src/app/User/ForgetPassword.js create mode 100644 client/src/app/User/Login.js create mode 100644 client/src/app/User/Register.js create mode 100644 client/src/app/User/User.js create mode 100644 client/src/app/User/User.module.js create mode 100644 client/src/app/User/UserActivate.js create mode 100644 client/src/app/User/UserProfile.js create mode 100644 client/src/app/User/UsersService.js create mode 100644 client/src/app/User/change_password.tpl.html create mode 100644 client/src/app/User/dashboard.tpl.html create mode 100644 client/src/app/User/dashboard_settings.tpl.html create mode 100644 client/src/app/User/forgot_password.tpl.html create mode 100644 client/src/app/User/login.tpl.html create mode 100644 client/src/app/User/register.tpl.html create mode 100644 client/src/app/User/user_profile.tpl.html create mode 100644 client/src/app/User/user_view.tpl.html create mode 100644 client/src/app/Wallets/Wallet.js create mode 100644 client/src/app/Wallets/Wallet.module.js create mode 100644 client/src/app/Wallets/WalletService.js create mode 100644 client/src/app/Wallets/wallet.tpl.html create mode 100644 client/src/assets/README.md create mode 100644 client/src/assets/apple-touch-icon-114x114.png create mode 100644 client/src/assets/apple-touch-icon-57x57.png create mode 100644 client/src/assets/apple-touch-icon-72x72.png create mode 100644 client/src/assets/apple-touch-icon.png create mode 100644 client/src/assets/css/loader.css create mode 100644 client/src/assets/favicon.ico create mode 100644 client/src/assets/fonts/Avenir.ttf create mode 100644 client/src/assets/fonts/FontAwesome.otf create mode 100644 client/src/assets/fonts/PlayfairDisplay-Bold.eot create mode 100644 client/src/assets/fonts/PlayfairDisplay-Bold.otf create mode 100644 client/src/assets/fonts/PlayfairDisplay-Bold.ttf create mode 100644 client/src/assets/fonts/PlayfairDisplay-Bold.woff create mode 100644 client/src/assets/fonts/PlayfairDisplay-Regular.eot create mode 100644 client/src/assets/fonts/PlayfairDisplay-Regular.otf create mode 100644 client/src/assets/fonts/PlayfairDisplay-Regular.ttf create mode 100644 client/src/assets/fonts/PlayfairDisplay-Regular.woff create mode 100644 client/src/assets/fonts/ProximaNova-Bold.eot create mode 100644 client/src/assets/fonts/ProximaNova-Bold.otf create mode 100644 client/src/assets/fonts/ProximaNova-Bold.svg create mode 100644 client/src/assets/fonts/ProximaNova-Bold.ttf create mode 100644 client/src/assets/fonts/ProximaNova-Bold.woff create mode 100644 client/src/assets/fonts/ProximaNova-Light.eot create mode 100644 client/src/assets/fonts/ProximaNova-Light.otf create mode 100644 client/src/assets/fonts/ProximaNova-Light.svg create mode 100644 client/src/assets/fonts/ProximaNova-Light.ttf create mode 100644 client/src/assets/fonts/ProximaNova-Light.woff create mode 100644 client/src/assets/fonts/ProximaNova-Regular.eot create mode 100644 client/src/assets/fonts/ProximaNova-Regular.otf create mode 100644 client/src/assets/fonts/ProximaNova-Regular.svg create mode 100644 client/src/assets/fonts/ProximaNova-Regular.ttf create mode 100644 client/src/assets/fonts/ProximaNova-Regular.woff create mode 100644 client/src/assets/fonts/ProximaNova-Semibold.eot create mode 100644 client/src/assets/fonts/ProximaNova-Semibold.otf create mode 100644 client/src/assets/fonts/ProximaNova-Semibold.svg create mode 100644 client/src/assets/fonts/ProximaNova-Semibold.ttf create mode 100644 client/src/assets/fonts/ProximaNova-Semibold.woff create mode 100644 client/src/assets/fonts/Raleway-Regular.ttf create mode 100644 client/src/assets/fonts/Roboto-Regular.woff create mode 100644 client/src/assets/fonts/fontawesome-webfont.eot create mode 100644 client/src/assets/fonts/fontawesome-webfont.svg create mode 100644 client/src/assets/fonts/fontawesome-webfont.ttf create mode 100644 client/src/assets/fonts/fontawesome-webfont.woff create mode 100644 client/src/assets/fonts/fontawesome-webfont.woff2 create mode 100644 client/src/assets/fonts/glyphicons-halflings-regular.eot create mode 100644 client/src/assets/fonts/glyphicons-halflings-regular.svg create mode 100644 client/src/assets/fonts/glyphicons-halflings-regular.ttf create mode 100644 client/src/assets/fonts/glyphicons-halflings-regular.woff create mode 100644 client/src/assets/fonts/glyphicons-halflings-regular.woff2 create mode 100644 client/src/assets/fonts/proximanova-light-webfont.eot create mode 100644 client/src/assets/fonts/proximanova-light-webfont.svg create mode 100644 client/src/assets/fonts/proximanova-light-webfont.ttf create mode 100644 client/src/assets/fonts/proximanova-light-webfont.woff create mode 100644 client/src/assets/fonts/proximanova-light-webfont.woff2 create mode 100644 client/src/assets/fonts/proximanova-regitalic-webfont.eot create mode 100644 client/src/assets/fonts/proximanova-regitalic-webfont.svg create mode 100644 client/src/assets/fonts/proximanova-regitalic-webfont.ttf create mode 100644 client/src/assets/fonts/proximanova-regitalic-webfont.woff create mode 100644 client/src/assets/fonts/proximanova-regitalic-webfont.woff2 create mode 100644 client/src/assets/fonts/proximanova-regular-webfont.eot create mode 100644 client/src/assets/fonts/proximanova-regular-webfont.svg create mode 100644 client/src/assets/fonts/proximanova-regular-webfont.ttf create mode 100644 client/src/assets/fonts/proximanova-regular-webfont.woff create mode 100644 client/src/assets/fonts/proximanova-regular-webfont.woff2 create mode 100644 client/src/assets/fonts/proximanova-semibold-webfont.eot create mode 100644 client/src/assets/fonts/proximanova-semibold-webfont.svg create mode 100644 client/src/assets/fonts/proximanova-semibold-webfont.ttf create mode 100644 client/src/assets/fonts/proximanova-semibold-webfont.woff create mode 100644 client/src/assets/fonts/proximanova-semibold-webfont.woff2 create mode 100644 client/src/assets/fonts/proximanova-semibolditalic-webfont.eot create mode 100644 client/src/assets/fonts/proximanova-semibolditalic-webfont.svg create mode 100644 client/src/assets/fonts/proximanova-semibolditalic-webfont.ttf create mode 100644 client/src/assets/fonts/proximanova-semibolditalic-webfont.woff create mode 100644 client/src/assets/fonts/proximanova-semibolditalic-webfont.woff2 create mode 100644 client/src/assets/img/activities.icon.png create mode 100644 client/src/assets/img/air.png create mode 100644 client/src/assets/img/app-store.png create mode 100644 client/src/assets/img/arrow.png create mode 100644 client/src/assets/img/automatic.png create mode 100644 client/src/assets/img/bag.png create mode 100644 client/src/assets/img/banner.jpg create mode 100644 client/src/assets/img/car-icon.png create mode 100644 client/src/assets/img/check-circle.png create mode 100644 client/src/assets/img/clock.png create mode 100644 client/src/assets/img/customer.png create mode 100644 client/src/assets/img/customers-bg.png create mode 100644 client/src/assets/img/diesel.png create mode 100644 client/src/assets/img/drive.png create mode 100644 client/src/assets/img/envelop.png create mode 100644 client/src/assets/img/key-icon.png create mode 100644 client/src/assets/img/loader.gif create mode 100644 client/src/assets/img/login-bg.jpg create mode 100644 client/src/assets/img/logo-white.png create mode 100644 client/src/assets/img/logo.png create mode 100644 client/src/assets/img/luggage.png create mode 100644 client/src/assets/img/make-payment.png create mode 100644 client/src/assets/img/manual.png create mode 100644 client/src/assets/img/paypal.png create mode 100644 client/src/assets/img/play-store.png create mode 100644 client/src/assets/img/powered-by-agriya.png create mode 100644 client/src/assets/img/quote.png create mode 100644 client/src/assets/img/rental-bg.png create mode 100644 client/src/assets/img/rental.png create mode 100644 client/src/assets/img/revenue-bg.png create mode 100644 client/src/assets/img/revenue.png create mode 100644 client/src/assets/img/road-view.jpg create mode 100644 client/src/assets/img/search-car.png create mode 100644 client/src/assets/img/seats.png create mode 100644 client/src/assets/img/site-settings.png create mode 100644 client/src/assets/img/static-bg.jpg create mode 100644 client/src/assets/img/sudopay-icon.png create mode 100644 client/src/assets/img/user-icon.png create mode 100644 client/src/assets/img/user-list.png create mode 100644 client/src/assets/img/user.png create mode 100644 client/src/assets/img/vehicle-bg.png create mode 100644 client/src/assets/img/vehicle.png create mode 100644 client/src/assets/img/wallet-icon.png create mode 100644 client/src/assets/js/ag-admin/loader.js create mode 100644 client/src/assets/js/ag-admin/loader_build.js create mode 100644 client/src/assets/js/l10n/en.json create mode 100644 client/src/assets/js/l10n/es.json create mode 100644 client/src/assets/js/loader.js create mode 100644 client/src/assets/js/loader_build.js create mode 100644 client/src/index.html create mode 100644 client/src/less/README.md create mode 100644 client/src/less/admin/bootstrap.less create mode 100644 client/src/less/admin/code.less create mode 100644 client/src/less/admin/main.less create mode 100644 client/src/less/admin/mixins.less create mode 100644 client/src/less/admin/morris.css create mode 100644 client/src/less/admin/ngadmin-responsive.less create mode 100644 client/src/less/admin/ngadmin.less create mode 100644 client/src/less/admin/timeline.css create mode 100644 client/src/less/admin/variables.less create mode 100644 client/src/less/bootstrap-social.less create mode 100644 client/src/less/bootstrap.less create mode 100644 client/src/less/custom-responsive.less create mode 100644 client/src/less/custom.less create mode 100644 client/src/less/font-awesome.less create mode 100644 client/src/less/forms.less create mode 100644 client/src/less/main.less create mode 100644 client/src/less/mixins.less create mode 100644 client/src/less/variables.less create mode 100644 composer.json create mode 100644 config/api.php create mode 100644 config/app.php create mode 100644 config/auth.php create mode 100644 config/cache.php create mode 100644 config/constants.php create mode 100644 config/database.php create mode 100644 config/filesystems.php create mode 100644 config/jwt.php create mode 100644 config/mail.php create mode 100644 config/paypal.php create mode 100644 config/services.php create mode 100644 config/session.php create mode 100644 config/sudopay.php create mode 100644 database/factories/ModelFactory.php create mode 100644 database/migrations/.gitkeep create mode 100644 database/migrations/2016_03_23_000001_create_discount_types_table.php create mode 100644 database/migrations/2016_03_24_000001_create_countries_table.php create mode 100644 database/migrations/2016_03_24_000002_create_states_table.php create mode 100644 database/migrations/2016_03_24_000003_create_cities_table.php create mode 100644 database/migrations/2016_03_24_000004_create_ips_table.php create mode 100644 database/migrations/2016_03_24_000005_create_roles_table.php create mode 100644 database/migrations/2016_03_24_000006_create_users_table.php create mode 100644 database/migrations/2016_03_24_000007_create_user_profiles_table.php create mode 100644 database/migrations/2016_03_24_000008_create_contacts_table.php create mode 100644 database/migrations/2016_03_24_000009_create_languages_table.php create mode 100644 database/migrations/2016_03_24_000010_create_pages_table.php create mode 100644 database/migrations/2016_03_24_000011_create_user_logins_table.php create mode 100644 database/migrations/2016_03_24_000012_create_providers_table.php create mode 100644 database/migrations/2016_03_24_000013_create_provider_users_table.php create mode 100644 database/migrations/2016_03_24_000014_create_money_transfer_accounts_table.php create mode 100644 database/migrations/2016_03_24_000015_create_withdrawal_statuses_table.php create mode 100644 database/migrations/2016_03_24_000016_create_user_cash_withdrawals_table.php create mode 100644 database/migrations/2016_03_24_000017_create_setting_categories_table.php create mode 100644 database/migrations/2016_03_24_000018_create_settings_table.php create mode 100644 database/migrations/2016_03_24_000019_create_currencies_table.php create mode 100644 database/migrations/2016_03_24_000020_create_currency_conversions_table.php create mode 100644 database/migrations/2016_03_24_000021_create_currency_conversion_histories_table.php create mode 100644 database/migrations/2016_03_24_000022_create_items_table.php create mode 100644 database/migrations/2016_03_24_000023_create_item_user_statuses_table.php create mode 100644 database/migrations/2016_03_24_000024_create_coupons_table.php create mode 100644 database/migrations/2016_03_24_000025_create_cancellation_types_table.php create mode 100644 database/migrations/2016_03_24_000026_create_transaction_types_table.php create mode 100644 database/migrations/2016_03_24_000027_create_counter_locations_table.php create mode 100644 database/migrations/2016_03_24_000028_create_dispute_statuses_table.php create mode 100644 database/migrations/2016_03_24_000029_create_item_users_table.php create mode 100644 database/migrations/2016_03_24_000030_create_email_templates_table.php create mode 100644 database/migrations/2016_03_24_000031_create_attachments_table.php create mode 100644 database/migrations/2016_03_24_000032_create_transactions_table.php create mode 100644 database/migrations/2016_03_24_000035_create_message_contents_table.php create mode 100644 database/migrations/2016_03_24_000036_create_messages_table.php create mode 100644 database/migrations/2016_04_28_000037_create_sudopay_transaction_logs_table.php create mode 100644 database/migrations/2016_04_28_000038_create_sudopay_payment_groups_table.php create mode 100644 database/migrations/2016_04_28_000039_create_sudopay_payment_gateways_table.php create mode 100644 database/migrations/2016_04_28_000040_create_sudopay_payment_gateways_users_table.php create mode 100644 database/migrations/2016_05_10_000041_create_sudopay_ipn_logs_table.php create mode 100644 database/migrations/2016_05_10_000043_create_paypal_transaction_logs_table.php create mode 100644 database/migrations/2016_05_10_000044_create_feedbacks_table.php create mode 100644 database/migrations/2016_05_10_000045_apirequests.php create mode 100644 database/migrations/2016_05_11_000046_create_user_add_wallet_amounts_table.php create mode 100644 database/migrations/2016_05_11_000047_create_duration_types_table.php create mode 100644 database/migrations/2016_05_17_000048_create_dispute_types_table.php create mode 100644 database/migrations/2016_05_17_000049_create_dispute_closed_types_table.php create mode 100644 database/migrations/2016_05_17_000050_create_item_user_disputes_table.php create mode 100644 database/migrations/2016_05_18_000051_create_wallet_transaction_logs_table.php create mode 100644 database/migrations/2016_06_02_000052_create_vehicle_companies_table.php create mode 100644 database/migrations/2016_06_02_000053_create_vehicle_types_table.php create mode 100644 database/migrations/2016_06_02_000054_create_vehicle_makes_table.php create mode 100644 database/migrations/2016_06_02_000055_create_vehicle_models_table.php create mode 100644 database/migrations/2016_06_02_000056_create_vehicle_type_prices_table.php create mode 100644 database/migrations/2016_06_02_000057_create_fuel_types_table.php create mode 100644 database/migrations/2016_06_02_000058_create_vehicles_table.php create mode 100644 database/migrations/2016_06_02_000060_create_vehicle_special_prices_table.php create mode 100644 database/migrations/2016_06_02_000061_create_item_user_additional_charges_table.php create mode 100644 database/migrations/2016_06_02_000062_create_surcharges_table.php create mode 100644 database/migrations/2016_06_02_000063_create_vehicle_type_surcharges_table.php create mode 100644 database/migrations/2016_06_02_000064_create_taxes_table.php create mode 100644 database/migrations/2016_06_02_000065_create_vehicle_type_taxes_table.php create mode 100644 database/migrations/2016_06_02_000066_create_extra_accessories_table.php create mode 100644 database/migrations/2016_06_02_000067_create_vehicle_type_extra_accessories_table.php create mode 100644 database/migrations/2016_06_02_000068_create_insurances_table.php create mode 100644 database/migrations/2016_06_02_000069_create_vehicle_type_insurances_table.php create mode 100644 database/migrations/2016_06_02_000070_create_fuel_options_table.php create mode 100644 database/migrations/2016_06_02_000071_create_vehicle_type_fuel_options_table.php create mode 100644 database/migrations/2016_06_02_000072_create_counter_location_vehicle_table.php create mode 100644 database/migrations/2016_06_10_000073_create_unavailable_vehicles_table.php create mode 100644 database/migrations/2016_06_10_000074_create_late_payment_details_table.php create mode 100644 database/migrations/2016_06_16_000075_create_booker_details_table.php create mode 100644 database/seeds/AttachmentTableSeeder.php create mode 100644 database/seeds/CounterLocationsTableSeeder.php create mode 100644 database/seeds/CountriesTableSeeder.php create mode 100644 database/seeds/CurrenciesTableSeeder.php create mode 100644 database/seeds/DatabaseSeeder.php create mode 100644 database/seeds/DiscountTypeSeeder.php create mode 100644 database/seeds/DisputeStatusesTableSeeder.php create mode 100644 database/seeds/DisputeTypesTableSeeder.php create mode 100644 database/seeds/DurationTypesTableSeeder.php create mode 100644 database/seeds/EmailTemplatesTableSeeder.php create mode 100644 database/seeds/ExtraAccessoriesTableSeeder.php create mode 100644 database/seeds/FuelOptionsTableSeeder.php create mode 100644 database/seeds/FuelTypesTableSeeder.php create mode 100644 database/seeds/InsurancesTableSeeder.php create mode 100644 database/seeds/IpsTableSeeder.php create mode 100644 database/seeds/ItemUserStatusesTableSeeder.php create mode 100644 database/seeds/LanguagesTableSeeder.php create mode 100644 database/seeds/ProvidersTableSeeder.php create mode 100644 database/seeds/RolesTableSeeder.php create mode 100644 database/seeds/SettingCategoryTableSeeder.php create mode 100644 database/seeds/SurchargesTableSeeder.php create mode 100644 database/seeds/TaxesTableSeeder.php create mode 100644 database/seeds/TransactionTypesTableSeeder.php create mode 100644 database/seeds/UsersTableSeeder.php create mode 100644 database/seeds/VehicleCompaniesTableSeeder.php create mode 100644 database/seeds/VehicleMakesTableSeeder.php create mode 100644 database/seeds/VehicleTypesTableSeeder.php create mode 100644 database/seeds/WithdrawalStatusesTableSeeder.php create mode 100644 grunt-config/dev1.json create mode 100644 package.json create mode 100644 phpunit.xml create mode 100644 public/.htaccess create mode 100644 public/api_explorer/DSL/admin_api_requests.dsl create mode 100644 public/api_explorer/DSL/admin_cancellation_types.dsl create mode 100644 public/api_explorer/DSL/admin_cities.dsl create mode 100644 public/api_explorer/DSL/admin_contacts.dsl create mode 100644 public/api_explorer/DSL/admin_counter_locations.dsl create mode 100644 public/api_explorer/DSL/admin_countries.dsl create mode 100644 public/api_explorer/DSL/admin_currencies.dsl create mode 100644 public/api_explorer/DSL/admin_currency_conversion_histories.dsl create mode 100644 public/api_explorer/DSL/admin_currency_conversions.dsl create mode 100644 public/api_explorer/DSL/admin_dashboard.dsl create mode 100644 public/api_explorer/DSL/admin_email_templates.dsl create mode 100644 public/api_explorer/DSL/admin_fuel_types.dsl create mode 100644 public/api_explorer/DSL/admin_ips.dsl create mode 100644 public/api_explorer/DSL/admin_languages.dsl create mode 100644 public/api_explorer/DSL/admin_messages.dsl create mode 100644 public/api_explorer/DSL/admin_pages.dsl create mode 100644 public/api_explorer/DSL/admin_paypal_transaction_logs.dsl create mode 100644 public/api_explorer/DSL/admin_providers.dsl create mode 100644 public/api_explorer/DSL/admin_roles.dsl create mode 100644 public/api_explorer/DSL/admin_setting_categories.dsl create mode 100644 public/api_explorer/DSL/admin_settings.dsl create mode 100644 public/api_explorer/DSL/admin_states.dsl create mode 100644 public/api_explorer/DSL/admin_sudopay.dsl create mode 100644 public/api_explorer/DSL/admin_sudopay_ipn_logs.dsl create mode 100644 public/api_explorer/DSL/admin_sudopay_transaction_logs.dsl create mode 100644 public/api_explorer/DSL/admin_transaction_types.dsl create mode 100644 public/api_explorer/DSL/admin_transactions.dsl create mode 100644 public/api_explorer/DSL/admin_unavailable_vehicles.dsl create mode 100644 public/api_explorer/DSL/admin_user_cash_withdrawals.dsl create mode 100644 public/api_explorer/DSL/admin_user_logins.dsl create mode 100644 public/api_explorer/DSL/admin_users.dsl create mode 100644 public/api_explorer/DSL/admin_vehicle_companies.dsl create mode 100644 public/api_explorer/DSL/admin_vehicle_dispute_closed_types.dsl create mode 100644 public/api_explorer/DSL/admin_vehicle_dispute_types.dsl create mode 100644 public/api_explorer/DSL/admin_vehicle_disputes.dsl create mode 100644 public/api_explorer/DSL/admin_vehicle_extra_accessories.dsl create mode 100644 public/api_explorer/DSL/admin_vehicle_feedbacks.dsl create mode 100644 public/api_explorer/DSL/admin_vehicle_fuel_options.dsl create mode 100644 public/api_explorer/DSL/admin_vehicle_insurances.dsl create mode 100644 public/api_explorer/DSL/admin_vehicle_makes.dsl create mode 100644 public/api_explorer/DSL/admin_vehicle_models.dsl create mode 100644 public/api_explorer/DSL/admin_vehicle_rentals.dsl create mode 100644 public/api_explorer/DSL/admin_vehicle_special_prices.dsl create mode 100644 public/api_explorer/DSL/admin_vehicle_surcharges.dsl create mode 100644 public/api_explorer/DSL/admin_vehicle_taxes.dsl create mode 100644 public/api_explorer/DSL/admin_vehicle_type_extra_accessories.dsl create mode 100644 public/api_explorer/DSL/admin_vehicle_type_fuel_options.dsl create mode 100644 public/api_explorer/DSL/admin_vehicle_type_insurances.dsl create mode 100644 public/api_explorer/DSL/admin_vehicle_type_prices.dsl create mode 100644 public/api_explorer/DSL/admin_vehicle_type_surcharges.dsl create mode 100644 public/api_explorer/DSL/admin_vehicle_type_taxes.dsl create mode 100644 public/api_explorer/DSL/admin_vehicle_types.dsl create mode 100644 public/api_explorer/DSL/admin_vehicles.dsl create mode 100644 public/api_explorer/DSL/admin_wallet_transaction_logs.dsl create mode 100644 public/api_explorer/DSL/admin_withdrawal_statuses.dsl create mode 100644 public/api_explorer/DSL/cancellation_types.dsl create mode 100644 public/api_explorer/DSL/cities.dsl create mode 100644 public/api_explorer/DSL/contacts.dsl create mode 100644 public/api_explorer/DSL/counter_locations.dsl create mode 100644 public/api_explorer/DSL/countries.dsl create mode 100644 public/api_explorer/DSL/currencies.dsl create mode 100644 public/api_explorer/DSL/fuel_types.dsl create mode 100644 public/api_explorer/DSL/images.dsl create mode 100644 public/api_explorer/DSL/languages.dsl create mode 100644 public/api_explorer/DSL/messages.dsl create mode 100644 public/api_explorer/DSL/money_transfer_accounts.dsl create mode 100644 public/api_explorer/DSL/pages.dsl create mode 100644 public/api_explorer/DSL/payment_gateways.dsl create mode 100644 public/api_explorer/DSL/providers.dsl create mode 100644 public/api_explorer/DSL/settings.dsl create mode 100644 public/api_explorer/DSL/social_logins.dsl create mode 100644 public/api_explorer/DSL/states.dsl create mode 100644 public/api_explorer/DSL/transaction_types.dsl create mode 100644 public/api_explorer/DSL/transactions.dsl create mode 100644 public/api_explorer/DSL/unavailable_vehicles.dsl create mode 100644 public/api_explorer/DSL/user_cash_withdrawals.dsl create mode 100644 public/api_explorer/DSL/user_profiles.dsl create mode 100644 public/api_explorer/DSL/user_views.dsl create mode 100644 public/api_explorer/DSL/users.dsl create mode 100644 public/api_explorer/DSL/vehicle_companies.dsl create mode 100644 public/api_explorer/DSL/vehicle_disputes.dsl create mode 100644 public/api_explorer/DSL/vehicle_extra_accessories.dsl create mode 100644 public/api_explorer/DSL/vehicle_feedbacks.dsl create mode 100644 public/api_explorer/DSL/vehicle_fuel_options.dsl create mode 100644 public/api_explorer/DSL/vehicle_insurances.dsl create mode 100644 public/api_explorer/DSL/vehicle_makes.dsl create mode 100644 public/api_explorer/DSL/vehicle_models.dsl create mode 100644 public/api_explorer/DSL/vehicle_rentals.dsl create mode 100644 public/api_explorer/DSL/vehicle_special_prices.dsl create mode 100644 public/api_explorer/DSL/vehicle_surcharges.dsl create mode 100644 public/api_explorer/DSL/vehicle_taxes.dsl create mode 100644 public/api_explorer/DSL/vehicle_type_extra_accessories.dsl create mode 100644 public/api_explorer/DSL/vehicle_type_fuel_options.dsl create mode 100644 public/api_explorer/DSL/vehicle_type_insurances.dsl create mode 100644 public/api_explorer/DSL/vehicle_type_prices.dsl create mode 100644 public/api_explorer/DSL/vehicle_type_surcharges.dsl create mode 100644 public/api_explorer/DSL/vehicle_type_taxes.dsl create mode 100644 public/api_explorer/DSL/vehicle_types.dsl create mode 100644 public/api_explorer/DSL/vehicles.dsl create mode 100644 public/api_explorer/DSL/wallets.dsl create mode 100644 public/api_explorer/DSL/withdrawal_statuses.dsl create mode 100644 public/api_explorer/api-docs/admin_api_requests.json create mode 100644 public/api_explorer/api-docs/admin_cancellation_types.json create mode 100644 public/api_explorer/api-docs/admin_cities.json create mode 100644 public/api_explorer/api-docs/admin_contacts.json create mode 100644 public/api_explorer/api-docs/admin_counter_locations.json create mode 100644 public/api_explorer/api-docs/admin_countries.json create mode 100644 public/api_explorer/api-docs/admin_currencies.json create mode 100644 public/api_explorer/api-docs/admin_currency_conversion_histories.json create mode 100644 public/api_explorer/api-docs/admin_currency_conversions.json create mode 100644 public/api_explorer/api-docs/admin_dashboard.json create mode 100644 public/api_explorer/api-docs/admin_email_templates.json create mode 100644 public/api_explorer/api-docs/admin_fuel_types.json create mode 100644 public/api_explorer/api-docs/admin_ips.json create mode 100644 public/api_explorer/api-docs/admin_languages.json create mode 100644 public/api_explorer/api-docs/admin_messages.json create mode 100644 public/api_explorer/api-docs/admin_pages.json create mode 100644 public/api_explorer/api-docs/admin_paypal_transaction_logs.json create mode 100644 public/api_explorer/api-docs/admin_providers.json create mode 100644 public/api_explorer/api-docs/admin_roles.json create mode 100644 public/api_explorer/api-docs/admin_setting_categories.json create mode 100644 public/api_explorer/api-docs/admin_settings.json create mode 100644 public/api_explorer/api-docs/admin_states.json create mode 100644 public/api_explorer/api-docs/admin_sudopay.json create mode 100644 public/api_explorer/api-docs/admin_sudopay_ipn_logs.json create mode 100644 public/api_explorer/api-docs/admin_sudopay_transaction_logs.json create mode 100644 public/api_explorer/api-docs/admin_transaction_types.json create mode 100644 public/api_explorer/api-docs/admin_transactions.json create mode 100644 public/api_explorer/api-docs/admin_unavailable_vehicles.json create mode 100644 public/api_explorer/api-docs/admin_user_cash_withdrawals.json create mode 100644 public/api_explorer/api-docs/admin_user_logins.json create mode 100644 public/api_explorer/api-docs/admin_users.json create mode 100644 public/api_explorer/api-docs/admin_vehicle_companies.json create mode 100644 public/api_explorer/api-docs/admin_vehicle_dispute_closed_types.json create mode 100644 public/api_explorer/api-docs/admin_vehicle_dispute_types.json create mode 100644 public/api_explorer/api-docs/admin_vehicle_disputes.json create mode 100644 public/api_explorer/api-docs/admin_vehicle_extra_accessories.json create mode 100644 public/api_explorer/api-docs/admin_vehicle_feedbacks.json create mode 100644 public/api_explorer/api-docs/admin_vehicle_fuel_options.json create mode 100644 public/api_explorer/api-docs/admin_vehicle_insurances.json create mode 100644 public/api_explorer/api-docs/admin_vehicle_makes.json create mode 100644 public/api_explorer/api-docs/admin_vehicle_models.json create mode 100644 public/api_explorer/api-docs/admin_vehicle_rentals.json create mode 100644 public/api_explorer/api-docs/admin_vehicle_special_prices.json create mode 100644 public/api_explorer/api-docs/admin_vehicle_surcharges.json create mode 100644 public/api_explorer/api-docs/admin_vehicle_taxes.json create mode 100644 public/api_explorer/api-docs/admin_vehicle_type_extra_accessories.json create mode 100644 public/api_explorer/api-docs/admin_vehicle_type_fuel_options.json create mode 100644 public/api_explorer/api-docs/admin_vehicle_type_insurances.json create mode 100644 public/api_explorer/api-docs/admin_vehicle_type_prices.json create mode 100644 public/api_explorer/api-docs/admin_vehicle_type_surcharges.json create mode 100644 public/api_explorer/api-docs/admin_vehicle_type_taxes.json create mode 100644 public/api_explorer/api-docs/admin_vehicle_types.json create mode 100644 public/api_explorer/api-docs/admin_vehicles.json create mode 100644 public/api_explorer/api-docs/admin_wallet_transaction_logs.json create mode 100644 public/api_explorer/api-docs/admin_withdrawal_statuses.json create mode 100644 public/api_explorer/api-docs/cancellation_types.json create mode 100644 public/api_explorer/api-docs/cities.json create mode 100644 public/api_explorer/api-docs/contacts.json create mode 100644 public/api_explorer/api-docs/counter_locations.json create mode 100644 public/api_explorer/api-docs/countries.json create mode 100644 public/api_explorer/api-docs/currencies.json create mode 100644 public/api_explorer/api-docs/fuel_types.json create mode 100644 public/api_explorer/api-docs/images.json create mode 100644 public/api_explorer/api-docs/index.php create mode 100644 public/api_explorer/api-docs/languages.json create mode 100644 public/api_explorer/api-docs/messages.json create mode 100644 public/api_explorer/api-docs/money_transfer_accounts.json create mode 100644 public/api_explorer/api-docs/pages.json create mode 100644 public/api_explorer/api-docs/payment_gateways.json create mode 100644 public/api_explorer/api-docs/providers.json create mode 100644 public/api_explorer/api-docs/settings.json create mode 100644 public/api_explorer/api-docs/social_logins.json create mode 100644 public/api_explorer/api-docs/states.json create mode 100644 public/api_explorer/api-docs/transaction_types.json create mode 100644 public/api_explorer/api-docs/transactions.json create mode 100644 public/api_explorer/api-docs/unavailable_vehicles.json create mode 100644 public/api_explorer/api-docs/user_cash_withdrawals.json create mode 100644 public/api_explorer/api-docs/user_profiles.json create mode 100644 public/api_explorer/api-docs/user_views.json create mode 100644 public/api_explorer/api-docs/users.json create mode 100644 public/api_explorer/api-docs/vehicle_companies.json create mode 100644 public/api_explorer/api-docs/vehicle_disputes.json create mode 100644 public/api_explorer/api-docs/vehicle_extra_accessories.json create mode 100644 public/api_explorer/api-docs/vehicle_feedbacks.json create mode 100644 public/api_explorer/api-docs/vehicle_fuel_options.json create mode 100644 public/api_explorer/api-docs/vehicle_insurances.json create mode 100644 public/api_explorer/api-docs/vehicle_makes.json create mode 100644 public/api_explorer/api-docs/vehicle_models.json create mode 100644 public/api_explorer/api-docs/vehicle_rentals.json create mode 100644 public/api_explorer/api-docs/vehicle_special_prices.json create mode 100644 public/api_explorer/api-docs/vehicle_surcharges.json create mode 100644 public/api_explorer/api-docs/vehicle_taxes.json create mode 100644 public/api_explorer/api-docs/vehicle_type_extra_accessories.json create mode 100644 public/api_explorer/api-docs/vehicle_type_fuel_options.json create mode 100644 public/api_explorer/api-docs/vehicle_type_insurances.json create mode 100644 public/api_explorer/api-docs/vehicle_type_prices.json create mode 100644 public/api_explorer/api-docs/vehicle_type_surcharges.json create mode 100644 public/api_explorer/api-docs/vehicle_type_taxes.json create mode 100644 public/api_explorer/api-docs/vehicle_types.json create mode 100644 public/api_explorer/api-docs/vehicles.json create mode 100644 public/api_explorer/api-docs/wallets.json create mode 100644 public/api_explorer/api-docs/withdrawal_statuses.json create mode 100644 public/api_explorer/css/highlight.default.css create mode 100644 public/api_explorer/css/screen.css create mode 100644 public/api_explorer/images/logo_small.png create mode 100644 public/api_explorer/images/pet_store_api.png create mode 100644 public/api_explorer/images/throbber.gif create mode 100644 public/api_explorer/images/wordnik_api.png create mode 100644 public/api_explorer/index.html create mode 100644 public/api_explorer/lib/backbone-min.js create mode 100644 public/api_explorer/lib/handlebars-1.0.0.js create mode 100644 public/api_explorer/lib/highlight.7.3.pack.js create mode 100644 public/api_explorer/lib/jquery-1.8.0.min.js create mode 100644 public/api_explorer/lib/jquery.ba-bbq.min.js create mode 100644 public/api_explorer/lib/jquery.slideto.min.js create mode 100644 public/api_explorer/lib/jquery.wiggle.min.js create mode 100644 public/api_explorer/lib/shred.bundle.js create mode 100644 public/api_explorer/lib/shred/content.js create mode 100644 public/api_explorer/lib/swagger.js create mode 100644 public/api_explorer/lib/underscore-min.js create mode 100644 public/api_explorer/swagger-ui.js create mode 100644 public/api_explorer/swagger-ui.min.js create mode 100644 public/index.php create mode 100644 resources/views/emails/mailContent.php create mode 100644 storage/app/.gitignore create mode 100644 storage/framework/views/.gitignore create mode 100644 storage/logs/.gitignore create mode 100644 tests/ExampleTest.php create mode 100644 tests/TestCase.php diff --git a/.bowerrc b/.bowerrc new file mode 100644 index 0000000..25c9a0f --- /dev/null +++ b/.bowerrc @@ -0,0 +1,3 @@ +{ + "directory": "vendor" +} \ No newline at end of file diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..8bb7f62 --- /dev/null +++ b/.env.example @@ -0,0 +1,26 @@ +APP_ENV=local +APP_DEBUG=true +APP_KEY=12345678901234567890123456789012 + +APP_LOCALE=en +APP_FALLBACK_LOCALE=en + +DB_CONNECTION=mysql +DB_HOST=localhost +DB_PORT=3306 +DB_DATABASE=lumen +DB_USERNAME=root +DB_PASSWORD= + +CACHE_DRIVER=file +QUEUE_DRIVER=sync + +JWT_SECRET=aaaabbbbccccddddeeeeffffgggghhhh + +API_STANDARDS_TREE=vnd +API_SUBTYPE=bookorrent +API_NAME="Book or Rent" +API_PREFIX=api +API_VERSION=v1 +API_DEBUG=true +API_STRICT=false \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..13ff70b --- /dev/null +++ b/.gitignore @@ -0,0 +1,17 @@ +.env +.idea +.phpstorm.meta.php +_ide_helper.php +composer.lock +/vendor +/node_modules +/public/ag-admin +/public/vendor +/public/client +/public/assets +/public/api +/public/Plugins +/public/index.html +/public/karma-unit.js +/public/templates-app.js +/public/templates-common.js diff --git a/Gruntfile.js b/Gruntfile.js new file mode 100644 index 0000000..03948b3 --- /dev/null +++ b/Gruntfile.js @@ -0,0 +1,726 @@ +var taskName = ''; +module.exports = function (grunt) { + var _ = require('lodash'); + // Load required Grunt tasks. These are installed based on the versions listed + // * in 'package.json' when you do 'npm install' in this directory. + grunt.loadNpmTasks('grunt-contrib-clean'); + grunt.loadNpmTasks('grunt-contrib-copy'); + grunt.loadNpmTasks('grunt-contrib-jshint'); + grunt.loadNpmTasks('grunt-contrib-concat'); + grunt.loadNpmTasks('grunt-contrib-uglify'); + grunt.loadNpmTasks('grunt-contrib-less'); + grunt.loadNpmTasks('grunt-ng-annotate'); + grunt.loadNpmTasks('grunt-html2js'); + grunt.loadNpmTasks('grunt-angular-translate'); + grunt.loadNpmTasks('grunt-regex-replace'); + grunt.loadNpmTasks('grunt-zip'); + grunt.loadNpmTasks('grunt-ssh'); + grunt.loadNpmTasks('grunt-parallel'); + grunt.loadNpmTasks('grunt-exec'); + grunt.loadNpmTasks('grunt-ngdocs'); + /** ********************************************************************************* */ + /** **************************** File Config **************************************** */ + var fileConfig = { + build_dir: 'public', + compile_dir: 'public', + /** + * This is a collection of file patterns for our app code (the + * stuff in 'src/'). These paths are used in the configuration of + * build tasks. 'js' is all project javascript, except tests. + * template HTML files, while 'appTemplates' contains the templates for + * our app's code. 'html' is just our main HTML file. 'less' is our main + * stylesheet, and 'unit' contains our app's unit tests. + */ + app_files: { + js: ['./client/src/assets/js/loader_build.js', '/client/src/assets/js/loader.js', 'vendor/jquery/dist/jquery.min.js', '/client/src/assets/js/ag-admin/loader_build.js', '/client/src/assets/js/ag-admin/loader.js'], + copy_js: [ + './client/src/app/App.js', + 'client/src/app/Constant.js', + 'client/src/app/Common/*.module.js', + 'client/src/app/User/*.module.js', + 'client/src/app/Wallets/*.module.js', + 'client/src/app/Home/*.module.js', + 'client/src/app/Message/*.module.js', + 'client/src/app/Transactions/*.module.js', + 'client/src/app/Common/*.js', + 'client/src/app/User/*.js', + 'client/src/app/Wallets/*.js', + 'client/src/app/Home/*.js', + 'client/src/app/Message/*.js', + 'client/src/app/Transactions/*.js' + ], + appTemplates: [ + 'client/src/app/Common/*.tpl.html', + 'client/src/app/User/*.tpl.html', + 'client/src/app/Wallets/*.tpl.html', + 'client/src/app/Home/*.tpl.html', + 'client/src/app/Message/*.tpl.html', + 'client/src/app/Transactions/*.tpl.html' + ], + html: ['client/src/index.html'], + less: ['client/src/less/main.less'] + }, + /** + * This is a collection of files used during admin pages. + */ + admin_files: { + js: ['client/src/ag-admin/js/ng-admin.jwt-auth.js', 'client/src/ag-admin/js/ng-admin.app.js'], + appTemplates: ['client/src/ag-admin/tpl/*.html'], + less: [ + 'client/src/less/admin/main.less' + ] + }, + /** + * This is the same as 'app_files', except it contains patterns that + * reference vendor code ('vendor/') that we need to place into the build + * process somewhere. While the 'app_files' property ensures all + * standardized files are collected for compilation, it is the user's job + * to ensure non-standardized (i.e. vendor-related) files are handled + * appropriately in 'vendor_files.js'. + * + * The 'vendor_files.js' property holds files to be automatically + * concatenated and minified with our project source files. + * + * The 'vendor_files.css' property holds any CSS files to be automatically + * included in our app. + * + * The 'vendor_files.assets' property holds any assets to be copied along + * with our app's assets. This structure is flattened, so it is not + * recommended that you use wildcards. + */ + vendor_files: { + js: [ + 'vendor/moment/min/moment-with-locales.min.js', + 'vendor/jquery/dist/jquery.min.js', + 'vendor/angular/angular.js', + 'vendor/angular-moment/angular-moment.js', + 'vendor/angular-sanitize/angular-sanitize.js', + 'vendor/angular-resource/angular-resource.js', + 'vendor/angular-bootstrap/ui-bootstrap-tpls.min.js', + 'vendor/ng-file-upload-shim/angular-file-upload-shim.min.js', + 'vendor/ng-file-upload/ng-file-upload.min.js', + 'vendor/angular-ui-router/release/angular-ui-router.js', + 'vendor/angular-animate/angular-animate.js', + 'vendor/angular-translate/angular-translate.min.js', + 'vendor/satellizer/satellizer.js', + 'vendor/angular-growl-v2/build/angular-growl.js', + 'vendor/angular-translate-loader-static-files/angular-translate-loader-static-files.min.js', + 'vendor/angular-dynamic-locale/tmhDynamicLocale.min.js', + 'vendor/angular-translate-storage-cookie/angular-translate-storage-cookie.js', + 'vendor/angular-translate-handler-log/angular-translate-handler-log.js', + 'vendor/angular-translate-storage-local/angular-translate-storage-local.min.js', + 'vendor/angular-cookies/angular-cookies.js', + 'vendor/angular-slugify/angular-slugify.js', + 'vendor/bootstrap/dist/js/bootstrap.min.js', + 'vendor/angulartics/dist/angulartics.min.js', + 'vendor/angulartics-google-analytics/dist/angulartics-google-analytics.min.js', + 'vendor/angulartics-facebook-pixel/dist/angulartics-facebook-pixel.min.js', + 'vendor/angular-recaptcha/release/angular-recaptcha.min.js', + 'vendor/angular-credit-cards/release/angular-credit-cards.js', + 'vendor/angular-loading-bar/build/loading-bar.min.js', + 'vendor/bootstrap-ui-datetime-picker/dist/datetime-picker.js', + 'vendor/accounting/accounting.js', + 'vendor/angularjs-slider/dist/rzslider.js', + 'vendor/angular-google-places-autocomplete/src/autocomplete.js', + 'vendor/angular-bootstrap-calendar/dist/js/angular-bootstrap-calendar-tpls.min.js', + 'vendor/angularjs-socialshare/dist/angular-socialshare.js' + ], + css: [ + 'vendor/angular-growl-v2/build/angular-growl.min.css', + 'vendor/angular-loading-bar/build/loading-bar.min.css', + 'vendor/angularjs-slider/dist/rzslider.css', + 'vendor/angular-google-places-autocomplete/src/autocomplete.css', + 'vendor/angular-bootstrap-calendar/dist/css/angular-bootstrap-calendar.min.css' + ], + assets: ['vendor/angular-i18n/*.*'], + moment_assets: ['vendor/moment/locale/*.*'] + }, + admin_vendor_files: { + js: [ + 'vendor/moment/min/moment-with-locales.min.js', + 'vendor/jquery/dist/jquery.min.js', + 'vendor/ng-admin/build/ng-admin.min.js', + 'vendor/angular-google-places-autocomplete/src/autocomplete.js', + 'vendor/bootstrap/dist/js/bootstrap.min.js', + 'vendor/ng-file-upload/ng-file-upload.min.js', + 'vendor/angular-bootstrap-calendar/dist/js/angular-bootstrap-calendar-tpls.min.js' + ], + css: [ + 'client/src/less/admin/ng-admin.min.css', + 'client/src/less/admin/timeline.css', + 'vendor/angular-google-places-autocomplete/src/autocomplete.css', + 'vendor/angular-bootstrap-calendar/dist/css/angular-bootstrap-calendar.min.css' + ], + assets: [] + } + }; + /** ********************************************************************************* */ + /** **************************** Task Config **************************************** */ + var taskConfig = { + pkg: grunt.file.readJSON("package.json"), + /** + * The banner is the comment that is placed at the top of our compiled + * source files. It is first processed as a Grunt template, where the 'less than percent equals' + * pairs are evaluated based on this very configuration object. + */ + meta: { + banner: '/**\n' + + ' * <%= pkg.name %> - v<%= pkg.version %> - <%= grunt.template.today("yyyy-mm-dd") %>\n' + + ' *\n' + + ' * Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author %>\n' + + ' */\n' + }, + /** + * The directories to delete when 'grunt clean' is executed. + */ + clean: { + all: [ + '<%= build_dir %>/index.html', + '<%= build_dir %>/assets/', + '<%= build_dir %>/api/assets/js/', + '<%= build_dir %>/Plugins/', + '<%= build_dir %>/vendor/', + '<%= build_dir %>/client/', + '<%= build_dir %>/ag-admin/', + '!<%= build_dir %>/api_explorer/**', + '!<%= build_dir %>/.htaccess', + '!<%= build_dir %>/index.php' + ], + compile: [ + '<%= build_dir %>/ag-admin/js/', + '<%= build_dir %>/ag-admin/css/', + '<%= build_dir %>/vendor/', + '<%= build_dir %>/client/src/app/' + ], + vendor: [ + '<%= build_dir %>/vendor/' + ], + index: ['<%= build_dir %>/index.html'] + }, + 'regex-replace': { + 'api-config': { + src: ['public/api_explorer/index.html', 'public/api_explorer/api-docs/*.json', 'client/src/**/*.js'], + actions: [{ + name: 'Domain Replace', + search: '/bookorrent/public', + replace: '<%= config.api_url %>', + flags: 'g' + }] + } + }, + zip: { + 'using-cwd': { + cwd: './', + src: [ + 'app/**', + 'bootstrap/**', + 'config/**', + 'client/**', + 'database/**', + 'public/**', + 'resources/**', + 'storage/**', + 'tests/**', + '.env.example', + 'artisan', + 'composer.json', + 'phpunit.xml', + 'readme.md' + ], + dest: 'bookorrent.zip' + } + }, + sftp: { + dev1: { + files: { + "./": 'bookorrent.zip' + }, + options: { + path: '<%= config.upload_path %>', + host: '<%= config.host %>', + username: '<%= config.host_username %>', + password: '<%= config.host_password %>' + } + } + }, + sshexec: { + dev1: { + command: ['unzip -o -d <%= config.upload_path %> <%= config.upload_path %>/bookorrent.zip', 'rm <%= config.upload_path %>/bookorrent.zip'], + options: { + host: '<%= config.host %>', + username: '<%= config.host_username %>', + password: '<%= config.host_password %>' + } + } + }, + /** + * The 'copy' task just copies files from A to B. We use it here to copy + * our project assets (images, fonts, etc.) and javascripts into + * 'build_dir', and then to copy the assets to 'compile_dir'. + */ + copy: { + build_app_assets: { + files: [ + { + src: ['**'], + dest: '<%= build_dir %>/assets/', + cwd: 'client/src/assets', + expand: true + } + ] + }, + build_app_assets_js: { + files: [ + { + src: ['<%= app_files.js %>'], + dest: '<%= build_dir %>/assets/js/', + cwd: '.', + expand: true, + flatten: true + } + ] + }, + build_vendor_assets: { + files: [ + { + src: ['<%= vendor_files.assets %>'], + dest: '<%= build_dir %>/assets/js/angular-i18n/', + cwd: '.', + expand: true, + flatten: true + } + ] + }, + build_vendor_moment: { + files: [ + { + src: ['<%= vendor_files.moment_assets %>'], + dest: '<%= build_dir %>/assets/js/moment/locale', + cwd: '.', + expand: true, + flatten: true + } + ] + }, + build_ngadmin: { + files: [ + { + src: ['<%= admin_files.js %>'], + dest: '<%= build_dir %>/ag-admin/js/', + cwd: '.', + expand: true, + flatten: true + } + ] + }, + build_ngadmin_tpl: { + files: [ + { + src: ['<%= admin_files.appTemplates %>'], + dest: '<%= build_dir %>/ag-admin/tpl/', + cwd: '.', + expand: true, + flatten: true + } + ] + }, + build_appjs: { + files: [ + { + src: ['<%= app_files.copy_js %>'], + dest: '<%= build_dir %>/', + cwd: '.', + expand: true + } + ] + }, + build_vendorjs: { + files: [ + { + src: ['<%= vendor_files.js %>', '<%= admin_vendor_files.js %>'], + dest: '<%= build_dir %>/', + cwd: '.', + expand: true + } + ] + } + }, + /** + * 'grunt concat' concatenates multiple source files into a single file. + */ + concat: { + // The 'build_css' target concatenates compiled CSS and vendor CSS together. + build_css: { + src: [ + '<%= build_dir %>/assets/css/<%= pkg.name %>-<%= pkg.version %>.css', + '<%= vendor_files.css %>' + ], + dest: '<%= build_dir %>/assets/css/<%= pkg.name %>-<%= pkg.version %>.css' + }, + // The 'build_admin_css' target concatenates compiled CSS and vendor CSS together. + build_admin_css: { + src: [ + '<%= build_dir %>/assets/css/<%= pkg.name %>-admin-<%= pkg.version %>.css', + '<%= admin_vendor_files.css %>' + ], + dest: '<%= build_dir %>/assets/css/<%= pkg.name %>-admin-<%= pkg.version %>.css' + }, + // The 'compile_js' target concatenates app and vendor js code together. + compile_js: { + options: { + banner: '<%= meta.banner %>' + }, + src: [ + '<%= vendor_files.js %>', + 'module.prefix', + '<%= build_dir %>/client/src/**/*.module.js', + '<%= build_dir %>/client/src/**/*.js', + '<%= html2js.app.dest %>', + 'module.suffix' + ], + dest: '<%= compile_dir %>/assets/js/<%= pkg.name %>-<%= pkg.version %>.js' + }, + compile_admin_js: { + options: { + banner: '<%= meta.banner %>' + }, + src: [ + '<%= admin_vendor_files.js %>', + '<%= admin_files.js %>' + ], + dest: '<%= compile_dir %>/assets/js/<%= pkg.name %>-admin-<%= pkg.version %>.js' + } + }, + /** + * 'ng-annotate' annotates the sources for safe minification. That is, it allows us + * to code without the array syntax. + */ + ngAnnotate: { + options: { + singleQuotes: true + }, + build: { + files: [ + { + src: ['<%= app_files.copy_js %>'], + cwd: '<%= build_dir %>', + dest: '<%= build_dir %>', + expand: true + } + ] + } + }, + /** + * Minify the sources! + */ + uglify: { + compile: { + options: { + banner: '<%= meta.banner %>', + mangle: false + }, + files: { + '<%= concat.compile_js.dest %>': '<%= concat.compile_js.dest %>' + } + }, + admin_compile: { + options: { + banner: '<%= meta.banner %>', + mangle: false //minified JS not working in admin side. So we added this option. (It works for front end compressed js) + }, + files: { + '<%= concat.compile_admin_js.dest %>': '<%= concat.compile_admin_js.dest %>' + } + } + }, + /** + * `grunt-contrib-less` handles our LESS compilation and uglification automatically. + * Only our 'main.less' file is included in compilation; all other files + * must be imported from this file. + */ + less: { + build: { + files: { + '<%= build_dir %>/assets/css/<%= pkg.name %>-<%= pkg.version %>.css': '<%= app_files.less %>' + } + }, + admin_build: { + files: { + '<%= build_dir %>/assets/css/<%= pkg.name %>-admin-<%= pkg.version %>.css': '<%= admin_files.less %>' + } + }, + compile: { + files: { + '<%= build_dir %>/assets/css/<%= pkg.name %>-<%= pkg.version %>.css': '<%= app_files.less %>' + }, + options: { + cleancss: true, + compress: true + } + }, + admin_compile: { + files: { + '<%= build_dir %>/assets/css/<%= pkg.name %>-admin-<%= pkg.version %>.css': '<%= admin_files.less %>' + }, + options: { + cleancss: true, + compress: true + } + } + }, + /** + * 'jshint' defines the rules of our linter as well as which files we + * should check. This file, all javascript sources, and all our unit tests + * are linted based on the policies listed in 'options'. But we can also + * specify exclusionary patterns by prefixing them with an exclamation + * point (!); this is useful when code comes from a third party but is + * nonetheless inside 'src/'. + */ + jshint: { + src: [ + '<%= app_files.copy_js %>' + ], + gruntfile: [ + 'Gruntfile.js' + ], + options: { + curly: true, + immed: true, + newcap: true, + noarg: true, + sub: true, + boss: true, + eqnull: true + }, + globals: {} + }, + /** + * HTML2JS is a Grunt plugin that takes all of your template files and + * places them into JavaScript files as strings that are added to + * AngularJS's template cache. This means that the templates too become + * part of the initial payload as one JavaScript file. Neat! + */ + html2js: { + // These are the templates from 'src/app'. + app: { + options: { + base: 'client/src/app' + }, + src: ['<%= app_files.appTemplates %>'], + dest: '<%= build_dir %>/assets/js/templates-app.js' + } + }, + /** + * The 'index' task compiles the 'index.html' file as a Grunt template. CSS + * and JS files co-exist here but they get split apart later. + */ + index: { + /** + * During development, we don't want to have wait for compilation, + * concatenation, minification, etc. So to avoid these steps, we simply + * add all script files directly to the '' of 'index.html'. The + * 'src' property contains the list of included files. + */ + build: { + appName: 'BookorRent', + dir: '<%= build_dir %>', + src: [ + '<%= build_dir %>/assets/js/jquery.min.js', + '<%= build_dir %>/assets/js/loader_build.js', + '<%= build_dir %>/assets/css/<%= pkg.name %>-<%= pkg.version %>.css' + ] + }, + /** + * When it is time to have a completely compiled application, we can + * alter the above to include only a single JavaScript and a single CSS + * file. Now we're back! + */ + compile: { + appName: 'BookorRent', + dir: '<%= compile_dir %>', + src: [ + '<%= build_dir %>/assets/js/jquery.min.js', + '<%= build_dir %>/assets/js/loader.js', + '<%= build_dir %>/assets/css/<%= pkg.name %>-<%= pkg.version %>.css' + ] + } + }, + /** + * The ng-admin 'index' task compiles the 'ng-admin/index.html' file as a Grunt template. CSS + * and JS files co-exist here but they get split apart later. + */ + admin_index: { + /** + * During development, we don't want to have wait for compilation, + * concatenation, minification, etc. So to avoid these steps, we simply + * add all script files directly to the '' of 'index.html'. The + * 'src' property contains the list of included files. + */ + build: { + appName: 'BookorRent', + dir: '<%= build_dir %>', + src: [ + '<%= build_dir %>/assets/js/jquery.min.js', + '<%= build_dir %>/assets/js/ag-admin/loader_build.js', + '<%= build_dir %>/assets/css/<%= pkg.name %>-admin-<%= pkg.version %>.css' + ] + }, + compile_admin: { + appName: 'BookorRent', + dir: '<%= compile_dir %>', + src: [ + '<%= build_dir %>/assets/js/jquery.min.js', + '<%= build_dir %>/assets/js/ag-admin/loader.js', + '<%= build_dir %>/assets/css/<%= pkg.name %>-admin-<%= pkg.version %>.css' + ] + } + }, + /** + * i18nextract build json lang files + */ + i18nextract: { + // Getting all translate key to json files + default_language: { + suffix: '.json', + src: ['client/src/index.html', 'client/src/app/**/*.js', 'client/src/app/**/*.html'], + lang: ['en', 'es'], + defaultLang: 'en', + dest: 'client/src/assets/js/l10n' + }, + // For filling dafault english value to fr_FR and ja-JP's value + default_exists_i18n: { + suffix: '.json', + nullEmpty: true, + src: ['client/src/index.html', 'client/src/app/**/*.js', 'client/src/app/**/*.html'], + lang: ['es'], + dest: 'client/src/assets/js/l10n/', + source: 'client/src/assets/js/l10n/en.json' // Use to generate different output file + } + }, + ngdocs: { + all: ['client/src/app/**/*.js'], + } + }; + /** ********************************************************************************* */ + /** **************************** Project Configuration ****************************** */ + // The following chooses some watch tasks based on whether we're running in mock mode or not. + // Our watch (delta above) needs to run a different index task and copyVendorJs task + // in several places if "grunt watchmock" is run. + taskName = grunt.cli.tasks[0]; // the name of the task from the command line (e.g. "grunt watch" => "watch") + // Take the big config objects we defined above, combine them, and feed them into grunt + grunt.initConfig(_.assign(taskConfig, fileConfig)); + grunt.registerTask('build', [ + 'clean:all', + 'html2js', + 'jshint', + 'less:build', 'less:admin_build', 'concat:build_css', 'concat:build_admin_css', + 'copy:build_app_assets', 'copy:build_app_assets_js', 'copy:build_ngadmin', 'copy:build_ngadmin_tpl', 'copy:build_vendor_assets', 'copy:build_vendor_moment', 'copy:build_appjs', 'copy:build_vendorjs', + 'ngAnnotate:build', + 'index:build', + 'admin_index:build' + ]); + // 'coffeelint', 'coffee', 'copy:build_vendorcss', 'copy:build_admin_vendorcss', + // The 'compile' task gets your app ready for deployment by concatenating and minifying your code. + // Note - compile builds off of the build dir (look at concat:compile_js), so run grunt build before grunt compile + grunt.registerTask('compile', 'compile task', function (env) { + if (env === undefined) { + grunt.task.run(['clean:all', 'html2js', 'jshint', 'less:compile', 'less:admin_compile', 'concat:build_css', 'concat:build_admin_css', + 'copy:build_app_assets', 'copy:build_app_assets_js', 'copy:build_ngadmin', 'copy:build_ngadmin_tpl', 'copy:build_vendor_assets', 'copy:build_vendor_moment', 'copy:build_appjs', 'copy:build_vendorjs', + 'ngAnnotate:build', 'concat:compile_js', 'concat:compile_admin_js', 'uglify', 'index:compile', + 'admin_index:compile_admin', 'clean:compile']); + } else { + grunt.config.set('config', grunt.file.readJSON('grunt-config/' + env + '.json')); + grunt.task.run(['clean:all', 'html2js', 'jshint', 'less:compile', 'less:admin_compile', 'concat:build_css', 'concat:build_admin_css', + 'copy:build_app_assets', 'copy:build_app_assets_js', 'copy:build_ngadmin', 'copy:build_ngadmin_tpl', 'copy:build_vendor_assets', 'copy:build_vendor_moment', 'copy:build_appjs', 'copy:build_vendorjs', + 'ngAnnotate:build', 'concat:compile_js', 'concat:compile_admin_js', 'uglify', + 'index:compile', 'admin_index:compile_admin', 'clean:compile']); + } + }); + grunt.registerTask('upload', 'Upload task', function (env) { + if (env === undefined) { + grunt.warn('Theme must be specified, like default:udemy.'); + } + grunt.config.set('config', grunt.file.readJSON('grunt-config/' + env + '.json')); + grunt.task.run(['regex-replace', 'compile:' + env, 'zip', 'sftp', 'sshexec']); + }); + // A utility function to get all app JavaScript sources. + function filterForJS(files) { + return files.filter(function (file) { + return file.match(/\.js$/); + }); + } + + // A utility function to get all app CSS sources. + function filterForCSS(files) { + return files.filter(function (file) { + return file.match(/\.css$/); + }); + } + + // The index.html template includes the stylesheet and javascript sources + // based on dynamic names calculated in this Gruntfile. This task assembles + // the list into variables for the template to use and then runs the + // compilation. + grunt.registerMultiTask('index', 'Process index.html template', function () { + var dirRE = new RegExp('^(' + grunt.config('build_dir') + '|' + grunt.config('compile_dir') + ')\/', 'g'); + // this.fileSrc comes from either build:src, compile:src, or karmaconfig:src in the index config defined above + // see - http://gruntjs.com/api/inside-tasks#this.filessrc for documentation + var jsFiles = filterForJS(this.filesSrc).map(function (file) { + return file.replace(dirRE, ''); + }); + var cssFiles = filterForCSS(this.filesSrc).map(function (file) { + return file.replace(dirRE, ''); + }); + var app = this.data.appName; + // this.data.dir comes from either build:dir, compile:dir, or karmaconfig:dir in the index config defined above + // see - http://gruntjs.com/api/inside-tasks#this.data for documentation + grunt.file.copy('client/src/index.html', this.data.dir + '/index.html', { + process: function (contents, path) { + // These are the variables looped over in our index.html exposed as "scripts", "styles", and "version" + return grunt.template.process(contents, { + data: { + appName: app, + scripts: jsFiles, + styles: cssFiles, + version: grunt.config('pkg.version'), + author: grunt.config('pkg.author'), + date: grunt.template.today("yyyy") + } + }); + } + }); + }); + // The index.html template includes the stylesheet and javascript sources + // based on dynamic names calculated in this Gruntfile. This task assembles + // the list into variables for the template to use and then runs the + // compilation. + grunt.registerMultiTask('admin_index', 'Process ag-admin/index.html template', function () { + var dirRE = new RegExp('^(' + grunt.config('build_dir') + '|' + grunt.config('compile_dir') + ')\/', 'g'); + // this.fileSrc comes from either build:src, compile:src, or karmaconfig:src in the index config defined above + // see - http://gruntjs.com/api/inside-tasks#this.filessrc for documentation + var jsNgAdminFiles = filterForJS(this.filesSrc).map(function (file) { + return file.replace(dirRE, ''); + }); + var cssAdminFiles = filterForCSS(this.filesSrc).map(function (file) { + return file.replace(dirRE, ''); + }); + var app = this.data.appName; + // this.data.dir comes from either build:dir, compile:dir, or karmaconfig:dir in the index config defined above + // see - http://gruntjs.com/api/inside-tasks#this.data for documentation + grunt.file.copy('client/src/ag-admin/index.html', this.data.dir + '/ag-admin/index.html', { + process: function (contents, path) { + // These are the variables looped over in our index.html exposed as "scripts", "styles", and "version" + return grunt.template.process(contents, { + data: { + appName: app, + ngAdminScripts: jsNgAdminFiles, + styles: cssAdminFiles, + version: grunt.config('pkg.version'), + author: grunt.config('pkg.author'), + date: grunt.template.today("yyyy") + } + }); + } + }); + }); +}; diff --git a/README.md b/README.md index bcd94e3..39d0407 100644 --- a/README.md +++ b/README.md @@ -1 +1,107 @@ -# rentnride \ No newline at end of file +# Lumen 5.2 & Angular Base Script + +* Lumen: 5.2 +* Angularjs: 1.5.2 + +## Requirements: + +* PHP >= 5.5.9 +* Enable extensions in **php.ini** file(OpenSSL PHP Extension, PDO PHP Extension, Mbstring PHP Extension) +* Nodejs +* Composer +* Bower +* Grunt + +First you should set "**\trunk\lumen**" path as your root path. + +## Server Side: +### Composer Updation: + +* To Update the Composer, please run the below command in your Project Path. + + composer update + +* The above Updation doesn't work to you, need to install Composer, please refer this link **https://getcomposer.org/** for "**How to install Composer**". + +### Environmental Settings: + +* In the root path "**\trunk\lumen**", you can find the "**.env.example**" file. +* Rename the file **.env.example** -> **.env** for further environmental changes. +* The **.env** contain below lines + + * APP_DEBUG=true + * DB_CONNECTION=mysql + * DB_HOST=localhost + * DB_PORT=3306 + * DB_DATABASE=lumen + * DB_USERNAME=root + * DB_PASSWORD= + +* Make changes in the file as you need, set DB_CONNECTION, DB_HOST, DB_DATABASE.. etc, +* Now create Database for your project. +* open command prompt and go to exact path "**\trunk\lumen**" then run the below command(imports all tables into the database). + + php artisan migrate +* Run the below command, which is used to imports the all values into the tables. + + php artisan db:seed + +## Front Side: + +* You need to install nodejs, bower, grunt. + +* Go to "**\trunk\lumen**" path in command prompt. +* Run the below command, the bower used to download and installed all front-end development libraries. + + bower install + +* The npm used to install the all dependencies in the local node_modules folder. + + npm install + +* In "**public/.htaccess**" you can change the project base url in **RewriteBase /lumen/public** as you need. + +* Also change the project base url in **\client\src\ag-admin\js\ng-admin.app.js**, here find **admin_api_url** variable and change as you need. + +* Also change the project base url in **\client\src\app\Constant.js**, here find **GENERAL_CONFIG** constant and change as you need. + +* The build task used to execute particular tasks which is build with grunt. +* If modify the files in local, you should run the below command for further updation. + + grunt build + +* The compile task used to concatenating and minifying your code. + + grunt compile + +* If you want to upload files to dev1 server, you have to run the below command with server name. + + grunt upload:dev1 + +### Cron updates on local: + +* To check curreny conversion from one country to another country, run below command. + + php artisan currency:cron + +* To update all booking status manually, run below command. + + php artisan status_update:cron + +### Cron updates on server: + +* To update curreny conversion, you have set like below with server url. + + 0 0 * * * php /server URL/artisan currency:cron + Eg: 0 0 * * * php /home/spgsql/html/lumenbase/artisan currency:cron + +* To update project status, you have set like below with server url. + + 0 0 * * * php /server URL/artisan status_update:cron + Eg: 0 0 * * * php /home/spgsql/html/lumenbase/artisan status_update:cron + + +### FAQ +1. If facing any problem(values not imports into table properly) while run the "**db:seed**" command, run the below command and again run the "**db:seed**" command for futher imports. + + composer dump-autoload diff --git a/app/ApiRequest.php b/app/ApiRequest.php new file mode 100644 index 0000000..10a53ad --- /dev/null +++ b/app/ApiRequest.php @@ -0,0 +1,75 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ +namespace App; + +use Illuminate\Http\Request; +use Illuminate\Database\Eloquent\Model; + +class ApiRequest extends Model +{ + /** + * @var string + */ + protected $table = "api_requests"; + + /** + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function ip() + { + return $this->belongsTo(Ip::class); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function user() + { + return $this->belongsTo(User::class); + } + + + /** + * @param $query + * @param Request $request + * @return mixed + */ + public function scopeFilterByRequest($query, Request $request) + { + if($request->input('sort', 'id') == 'User.username') { + $query->orderBy('username', $request->input('sortby', 'desc')); + }elseif($request->input('sort', 'id') == 'Ip.ip'){ + $query->orderBy('ip', $request->input('sortby', 'desc')); + }else{ + $query->orderBy($request->input('sort', 'id'), $request->input('sortby', 'desc')); + } + if ($request->has('q')) { + $query->where('path', 'LIKE', '%' . $request->input('q') . '%') + ->orWhere('method', 'LIKE', '%' . $request->input('q') . '%') + ->orWhere('http_response_code', 'LIKE', '%' . $request->input('q') . '%'); + $query->orWhereHas('Ip', function ($q) use ($request) { + $q->Where('ip', 'like', '%' . $request->input('q') . '%'); + }); + $query->orWhereHas('User', function ($q) use ($request) { + $q->Where('username', 'like', '%' . $request->input('q') . '%'); + }); + } + if ($request->has('filter')) { + $query->where('method', '=', $request->input('filter')); + } + return $query; + } + +} diff --git a/app/Attachment.php b/app/Attachment.php new file mode 100644 index 0000000..4a54f6f --- /dev/null +++ b/app/Attachment.php @@ -0,0 +1,40 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ +namespace App; + +use Illuminate\Http\Request; +use Illuminate\Database\Eloquent\Model; + +class Attachment extends Model +{ + /** + * @var string + */ + protected $table = "attachments"; + + protected $fillable = [ + 'filename', 'dir', 'mimetype', 'filesize', 'height', 'width' + ]; + + + /** + * Get all of the owning likeable models. + */ + public function attachmentable() + { + return $this->morphTo(); + } + +} diff --git a/app/City.php b/app/City.php new file mode 100644 index 0000000..b181c90 --- /dev/null +++ b/app/City.php @@ -0,0 +1,116 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App; + +use Illuminate\Http\Request; +use Illuminate\Database\Eloquent\Model; + +class City extends Model +{ + /** + * @var string + */ + protected $table = "cities"; + + protected $fillable = [ + 'name', 'state_id', 'country_id', 'latitude', 'longitude', 'is_active' + ]; + + + /** + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function state() + { + return $this->belongsTo(State::class); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function country() + { + return $this->belongsTo(Country::class); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\HasMany + */ + public function ip() + { + return $this->hasMany(Ip::class); + } + + /** + * @param $query + * @param Request $request + * @return mixed + */ + public function scopeFilterByRequest($query, Request $request) + { + if ($request->input('sort', 'id') == 'State.name') { + $query->orderBy('state_name', $request->input('sortby', 'desc')); + } elseif ($request->input('sort', 'id') == 'Country.name') { + $query->orderBy('country_name', $request->input('sortby', 'desc')); + } else { + $query->orderBy($request->input('sort', 'id'), $request->input('sortby', 'desc')); + } + if ($request->has('filter')) { + $filter = false; + if ($request->input('filter') == 'active') { + $filter = true; + } + $query->where('is_active', '=', $filter); + } + if ($request->has('q')) { + $query->where('name', 'LIKE', '%' . $request->input('q') . '%'); + $query->orWhereHas('State', function ($q) use ($request) { + $q->Where('name', 'like', '%' . $request->input('q') . '%'); + }); + $query->orWhereHas('Country', function ($q) use ($request) { + $q->Where('name', 'like', '%' . $request->input('q') . '%'); + }); + } + return $query; + } + + /** + * @return array + */ + public function scopeGetValidationRule() + { + return [ + 'name' => 'required|min:2', + 'state_id' => 'required|integer|exists:states,id', + 'country_id' => 'required|integer|exists:countries,id' + ]; + } + + public function scopeGetValidationMessage() + { + return [ + 'name.required' => 'Required', + 'name.min' => 'Name - minimum length is 2!', + 'state_id.required' => 'Required', + 'state_id.integer' => 'State id must be a number!', + 'state_id.exists' => 'Invalid state id', + 'country_id.required' => 'Required', + 'country_id.integer' => 'Country id must be a number!', + 'country_id.exists' => 'Invalid country id', + ]; + } + +} diff --git a/app/Console/Commands/.gitkeep b/app/Console/Commands/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/app/Console/Commands/CurrencyCron.php b/app/Console/Commands/CurrencyCron.php new file mode 100644 index 0000000..7c568f7 --- /dev/null +++ b/app/Console/Commands/CurrencyCron.php @@ -0,0 +1,47 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Console\Commands; + +use Illuminate\Console\Command; + +class CurrencyCron extends Command +{ + /** + * The name and signature of the console command. + * + * @var string + */ + protected $signature = 'currency:cron'; + + + /** + * The console command description. + * + * @var string + */ + protected $description = 'Cron command to update daily currency rates'; + + /** + * Execute the console command. + */ + public function handle() + { + if (isPluginEnabled('CurrencyConversions')) { + $currencyService = new \Plugins\CurrencyConversions\Services\CurrencyConversionService(); + $currencyService->currencyconversion(); + } + } +} \ No newline at end of file diff --git a/app/Console/Commands/GeoIpCron.php b/app/Console/Commands/GeoIpCron.php new file mode 100644 index 0000000..7a2e558 --- /dev/null +++ b/app/Console/Commands/GeoIpCron.php @@ -0,0 +1,93 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Console\Commands; + +use Illuminate\Console\Command; +use League\Flysystem\Exception; +use Log; + +class GeoIpCron extends Command +{ + /** + * The name and signature of the console command. + * + * @var string + */ + protected $signature = 'ip:cron'; + + + /** + * The console command description. + * + * @var string + */ + protected $description = 'Cron command to update the ip table'; + /** + * @var + */ + protected $countryService; + /** + * @var + */ + protected $cityService; + /** + * @var + */ + protected $ipService; + + + /** + * Execute the console command. + */ + public function handle() + { + + $ips = \App\Ip::where('is_checked', false)->take(5)->get(); + $client = new \GuzzleHttp\Client(); + try { + foreach ($ips as $ip) { + $res = $client->request('GET', 'geoip.nekudo.com/api/'.$ip->ip); + $code = $res->getStatusCode(); + if($code == 200) { + $body = $res->getBody(); + $content = $body->getContents(); + $response = json_decode($content); + if (isset($response->country) && isset($response->country->code)) { + $countryService = new \App\Services\CountryService(); + $country_id = $countryService->getCountryId($response->country->code, $response->country->name); + $ip_arr['country_id'] = $country_id; + if (isset($response->city)) { + $cityService = new \App\Services\CityService(); + $city_id = $cityService->getCityId($response->city, $country_id); + $ip_arr['city_id'] = $city_id; + } + } + if (isset($response->location)) { + $ip_arr['latitude'] = $response->location->latitude; + $ip_arr['longitude'] = $response->location->longitude; + } + $ip_arr['is_checked'] = true; + $ipService = new \App\Services\IpService(); + $ipService->updateIpById($ip->id, $ip_arr); + } else { + Log::info("error"); + } + } + } catch(Exception $e) { + Log::info("message", array($e->getMessage())); + } + } +} \ No newline at end of file diff --git a/app/Console/Commands/StatusUpdateCron.php b/app/Console/Commands/StatusUpdateCron.php new file mode 100644 index 0000000..22c58b3 --- /dev/null +++ b/app/Console/Commands/StatusUpdateCron.php @@ -0,0 +1,59 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Console\Commands; + +use Illuminate\Console\Command; + +class StatusUpdateCron extends Command +{ + /** + * The name and signature of the console command. + * + * @var string + */ + protected $signature = 'status_update:cron'; + + /** + * @var + */ + protected $VehicleRentalService; + + /** + * The console command description. + * + * @var string + */ + protected $description = 'Cron command to update daily status updates'; + + /** + * StatusUpdateCron constructor. + */ + public function __construct() + { + parent::__construct(); + } + + /** + * Execute the console command. + */ + public function handle() + { + if (isPluginEnabled('VehicleRentals')) { + $VehicleRentalService = new \Plugins\VehicleRentals\Services\VehicleRentalService; + $VehicleRentalService->autoUpdateStatus(); + } + } +} \ No newline at end of file diff --git a/app/Console/Kernel.php b/app/Console/Kernel.php new file mode 100644 index 0000000..b078310 --- /dev/null +++ b/app/Console/Kernel.php @@ -0,0 +1,45 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Console; + +use Illuminate\Console\Scheduling\Schedule; +use Laravel\Lumen\Console\Kernel as ConsoleKernel; + +class Kernel extends ConsoleKernel +{ + /** + * The Artisan commands provided by your application. + * + * @var array + */ + protected $commands = [ + Commands\CurrencyCron::class, + Commands\StatusUpdateCron::class, + Commands\GeoIpCron::class + ]; + + /** + * Define the application's command schedule. + * + * @param \Illuminate\Console\Scheduling\Schedule $schedule + */ + protected function schedule(Schedule $schedule) + { + $schedule->command("currency:cron")->daily(); + $schedule->command("status_update:cron")->daily(); + $schedule->command("ip:cron")->daily(); + } +} diff --git a/app/Country.php b/app/Country.php new file mode 100644 index 0000000..9e92e45 --- /dev/null +++ b/app/Country.php @@ -0,0 +1,117 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App; + +use Illuminate\Http\Request; +use Illuminate\Database\Eloquent\Model; + +/** + * Class Country + * @package App + */ +class Country extends Model +{ + /** + * @var string + */ + protected $table = "countries"; + + /** + * The attributes that are mass assignable. + * + * @var array + */ + protected $fillable = [ + 'name', 'iso2', 'iso3', 'is_active' + ]; + + /** + * @return \Illuminate\Database\Eloquent\Relations\HasMany + */ + public function state() + { + return $this->hasMany(State::class); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\HasMany + */ + public function city() + { + return $this->hasMany(City::class); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\HasMany + */ + public function ip() + { + return $this->hasMany(ip::class); + } + + /** + * @param $query + * @param Request $request + * @return mixed + */ + public function scopeFilterByRequest($query, Request $request) + { + $query->orderBy($request->input('sort', 'id'), $request->input('sortby', 'desc')); + if ($request->has('filter')) { + $filter = false; + if ($request->input('filter') == 'active') { + $filter = true; + } + $query->where('is_active', '=', $filter); + } + if ($request->has('q')) { + $query->where('name', 'LIKE', '%' . $request->input('q') . '%') + ->orWhere('iso2', 'LIKE', '%' . $request->input('q') . '%'); + } + if ($request->has('name')) { + $query->where('name', 'LIKE', '%' . $request->input('name') . '%'); + } + return $query; + + + } + + /** + * @return array + */ + public function scopeGetValidationRule() + { + return [ + 'name' => 'required|min:2', + 'iso2' => 'required|min:2|max:2', + 'iso3' => 'required|min:3|max:3' + ]; + } + + public function scopeGetValidationMessage() + { + return [ + 'name.required' => 'Required', + 'name.min' => 'Name - minimum length is 2', + 'iso2.required' => 'Required', + 'iso2.min' => 'iso2 - minimum length is 2', + 'iso2.max' => 'iso2 - maximum length is 2', + 'iso3.required' => 'Required', + 'iso3.min' => 'iso3 - minimum length is 2', + 'iso3.max' => 'iso3 - maximum length is 2', + ]; + } +} diff --git a/app/Currency.php b/app/Currency.php new file mode 100644 index 0000000..9a15e8d --- /dev/null +++ b/app/Currency.php @@ -0,0 +1,97 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App; + +use Illuminate\Http\Request; +use Illuminate\Database\Eloquent\Model; + +class Currency extends Model +{ + protected $table = "currencies"; + + /** + * The attributes that are mass assignable. + * + * @var array + */ + protected $fillable = [ + 'name', 'code', 'symbol', 'prefix', 'suffix', 'decimals', 'dec_point', 'thousands_sep', 'is_prefix_display_on_left', 'is_use_graphic_symbol', 'is_active' + ]; + + /** + * @param $query + * @param Request $request + * @return mixed + */ + public function scopeFilterByRequest($query, Request $request) + { + $query->orderBy($request->input('sort', 'id'), $request->input('sortby', 'desc')); + if ($request->has('filter')) { + $filter = false; + if ($request->input('filter') == 'active') { + $filter = true; + } + $query->where('is_active', '=', $filter); + } + if ($request->has('q')) { + $query->where('name', 'LIKE', '%' . $request->input('q') . '%') + ->orWhere('code', 'LIKE', '%' . $request->input('q') . '%'); + } + return $query; + + + } + + /** + * @return array + */ + public function scopeGetValidationRule() + { + return [ + 'name' => 'required|min:2', + 'code' => 'required|min:2', + 'symbol' => 'required', + 'decimals' => 'required|integer', + 'dec_point' => 'required|max:1', + 'thousands_sep' => 'required|max:1', + 'is_prefix_display_on_left' => 'required|integer|max:1', + 'is_use_graphic_symbol' => 'required|integer|max:1' + ]; + } + + public function scopeGetValidationMessage() + { + return [ + 'name.required' => 'Required', + 'name.min' => 'Name - minimum length is 2', + 'code.required' => 'Required', + 'code.min' => 'Code - minimum length is 2', + 'symbol.required' => 'Required', + 'decimals.required' => 'Required', + 'decimals.integer' => 'Decimals must be a number', + 'dec_point.required' => 'Required', + 'dec_point.max' => 'dec_point - maximum length is 1', + 'thousands_sep.required' => 'Required', + 'thousands_sep.max' => 'thousand_sep - maximum length is 1', + 'is_prefix_display_on_left.required' => 'Required', + 'is_prefix_display_on_left.integer' => 'is_prefix_display_on_left must be a number', + 'is_prefix_display_on_left.max' => 'is_prefix_display_on_left - maximum length is 1', + 'is_use_graphic_symbol.required' => 'Required', + 'is_use_graphic_symbol.integer' => 'is_use_graphic_symbol must be a number', + 'is_use_graphic_symbol.max' => 'is_use_graphic_symbol - maximum length is 1', + ]; + } +} diff --git a/app/DiscountType.php b/app/DiscountType.php new file mode 100644 index 0000000..5d2e102 --- /dev/null +++ b/app/DiscountType.php @@ -0,0 +1,35 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App; + +use Illuminate\Database\Eloquent\Model; + +class DiscountType extends Model +{ + /** + * @var string + */ + protected $table = "discount_types"; + + /** + * @return \Illuminate\Database\Eloquent\Relations\HasOne + */ + public function vehicle_type_surcharge() + { + return $this->hasMany(\Plugins\VehicleSurcharges\Model\VehicleTypeSurcharge::class); + } + +} diff --git a/app/DurationType.php b/app/DurationType.php new file mode 100644 index 0000000..4c2a680 --- /dev/null +++ b/app/DurationType.php @@ -0,0 +1,51 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App; + +use Illuminate\Http\Request; +use Illuminate\Database\Eloquent\Model; + +class DurationType extends Model +{ + /** + * @var string + */ + protected $table = "duration_types"; + + public function scopeFilterByRequest($query, Request $request) + { + $query->orderBy($request->input('sort', 'id'), $request->input('sortby', 'desc')); + return $query; + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\HasOne + */ + public function vehicle_type_surcharge() + { + return $this->hasMany(\Plugins\VehicleSurcharges\Model\VehicleTypeSurcharge::class); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\HasOne + */ + public function vehicle_type() + { + return $this->hasMany(\Plugins\Vehicles\Model\VehicleType::class); + } + + +} diff --git a/app/EmailTemplate.php b/app/EmailTemplate.php new file mode 100644 index 0000000..1729a9b --- /dev/null +++ b/app/EmailTemplate.php @@ -0,0 +1,75 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App; + +use Illuminate\Http\Request; +use Illuminate\Database\Eloquent\Model; + +class EmailTemplate extends Model +{ + protected $table = "email_templates"; + + /** + * The attributes that are mass assignable. + * + * @var array + */ + protected $fillable = [ + 'name', 'subject', 'body_content', 'from_name', 'reply_to' + ]; + + + /** + * @param $query + * @param Request $request + * @return mixed + */ + public function scopeFilterByRequest($query, Request $request) + { + $query->orderBy($request->input('sort', 'id'), $request->input('sortby', 'desc')); + if ($request->has('q')) { + $query->where('name', 'like', '%' . $request->input('q') . '%'); + $query->orWhere('body_content', 'like', '%' . $request->input('q') . '%'); + $query->orWhere('subject', 'like', '%' . $request->input('q') . '%'); + $query->orWhere('from_name', 'like', '%' . $request->input('q') . '%'); + } + return $query; + } + + /** + * @return array + */ + public function scopeGetValidationRule() + { + return [ + 'name' => 'required', + 'subject' => 'required', + 'body_content' => 'required', + 'from_name' => 'required' + ]; + } + + public function scopeGetValidationMessage() + { + return [ + 'name.required' => 'Required', + 'subject.required' => 'Required', + 'body_content.required' => 'Required', + 'from_name.required' => 'Required', + ]; + } + +} diff --git a/app/Events/Event.php b/app/Events/Event.php new file mode 100644 index 0000000..6ca06c7 --- /dev/null +++ b/app/Events/Event.php @@ -0,0 +1,23 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Events; + +use Illuminate\Queue\SerializesModels; + +abstract class Event +{ + use SerializesModels; +} diff --git a/app/Exceptions/Handler.php b/app/Exceptions/Handler.php new file mode 100644 index 0000000..8708776 --- /dev/null +++ b/app/Exceptions/Handler.php @@ -0,0 +1,63 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Exceptions; + +use Exception; +use Illuminate\Validation\ValidationException; +use Illuminate\Auth\Access\AuthorizationException; +use Illuminate\Database\Eloquent\ModelNotFoundException; +use Symfony\Component\HttpKernel\Exception\HttpException; +use Laravel\Lumen\Exceptions\Handler as ExceptionHandler; + +class Handler extends ExceptionHandler +{ + /** + * A list of the exception types that should not be reported. + * + * @var array + */ + protected $dontReport = [ + AuthorizationException::class, + HttpException::class, + ModelNotFoundException::class, + ValidationException::class, + ]; + + /** + * Report or log an exception. + * + * This is a great spot to send exceptions to Sentry, Bugsnag, etc. + * + * @param \Exception $e + * @return void + */ + public function report(Exception $e) + { + parent::report($e); + } + + /** + * Render an exception into an HTTP response. + * + * @param \Illuminate\Http\Request $request + * @param \Exception $e + * @return \Illuminate\Http\Response + */ + public function render($request, Exception $e) + { + return parent::render($request, $e); + } +} diff --git a/app/Http/Controllers/Admin/AdminApiRequestsController.php b/app/Http/Controllers/Admin/AdminApiRequestsController.php new file mode 100644 index 0000000..0c62f36 --- /dev/null +++ b/app/Http/Controllers/Admin/AdminApiRequestsController.php @@ -0,0 +1,105 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + + +namespace App\Http\Controllers\Admin; + +use Illuminate\Http\Request; + + +use App\Http\Controllers\Controller; + +use App\ApiRequest; + +use JWTAuth; +use Validator; +use App\Transformers\ApiRequestTransformer; +use DB; + +/** + * ApiRequests resource representation. + * @Resource("Admin/AdminApiRequests") + */ +class AdminApiRequestsController extends Controller +{ + public function __construct() + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth'); + // Check the logged user role. + $this->middleware('role'); + } + + /** + * Show all api requests. + * Get a JSON representation of all the api requests. + * + * @Get("/api_requests?sort={sort}&sortby={sortby}") + * @Parameters({ + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1), + * @Parameter("sort", type="string", required=false, description="Sort the api requests list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort api requests by Ascending / Descending Order.", default=null), + * }) + */ + public function index(Request $request) + { + $api_requests = ApiRequest::select(DB::raw('api_requests.*')) + ->leftJoin(DB::raw('(select id,username from users) as users'), 'users.id', '=', 'api_requests.user_id') + ->leftJoin(DB::raw('(select id,ip from ips) as ips'), 'ips.id', '=', 'api_requests.ip_id') + ->filterByRequest($request) + ->paginate(config('constants.ConstPageLimit')); + return $this->response->paginator($api_requests, (new ApiRequestTransformer)->setDefaultIncludes(['User', 'Ip'])); + } + + /** + * Show the specified api requests. + * Show the api requests with a `id`. + * @Get("/api_requests/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"id": 1, "created_at": "2016-05-11 16:37:50", "path": "http://localhost/bookorrent/public/api/admin/api_requests", "method": "GET", "http_response_code": "200", "user_id": 1, "ip_id": 2, "User": {}, "Ip": {}}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function show($id) + { + $api_request = ApiRequest::with('User', 'Ip')->find($id); + if (!$api_request) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($api_request, (new ApiRequestTransformer)->setDefaultIncludes(['User', 'Ip'])); + } + + /** + * Delete the specified api requests. + * Delete the api requests with a `id`. + * @Delete("/api_requests/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"success": "Record Deleted."}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function destroy($id) + { + $api_request = ApiRequest::find($id); + if (!$api_request) { + return $this->response->errorNotFound("Invalid Request"); + } else { + $api_request->delete(); + } + return response()->json(['Success' => 'Api Request deleted'], 200); + } +} \ No newline at end of file diff --git a/app/Http/Controllers/Admin/AdminCitiesController.php b/app/Http/Controllers/Admin/AdminCitiesController.php new file mode 100644 index 0000000..b9563d0 --- /dev/null +++ b/app/Http/Controllers/Admin/AdminCitiesController.php @@ -0,0 +1,216 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Http\Controllers\Admin; + +use Illuminate\Http\Request; +use App\Http\Controllers\Controller; +use App\City; +use JWTAuth; +use Validator; +use App\Transformers\CityTransformer; +use App\State; +use App\Country; +use DB; + +/** + * Cities resource representation. + * @Resource("Admin/AdminCities") + */ +class AdminCitiesController extends Controller +{ + /** + * AdminCitiesController constructor. + */ + public function __construct() + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth'); + // Check the logged user role. + $this->middleware('role'); + } + + /** + * Show all cities. + * Get a JSON representation of all the cities. + * + * @Get("/cities?filter={filter}&sort={sort}&sortby={sortby}&q={q}") + * @Parameters({ + * @Parameter("filter", type="integer", required=false, description="Filter the cities list by type.", default=null), + * @Parameter("sort", type="string", required=false, description="Sort the cities list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort cities by Ascending / Descending Order.", default=null), + * @Parameter("q", type="string", required=false, description="Search Cities.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1) + * }) + */ + public function index(Request $request) + { + $cities = City::select(DB::raw('cities.*')) + ->leftJoin(DB::raw('(select id,name as state_name from states) as states'), 'states.id', '=', 'cities.state_id') + ->leftJoin(DB::raw('(select id,name as country_name from countries) as countries'), 'countries.id', '=', 'cities.country_id') + ->filterByRequest($request) + ->paginate(config('constants.ConstPageLimit')); + return $this->response->paginator($cities, (new CityTransformer)->setDefaultIncludes(['State', 'Country'])); + } + + /** + * Store a new city. + * Store a new city with a `name`, `state_id`, `country_id`, `latitude` and `longitude`. + * @Post("/cities") + * @Transaction({ + * @Request({"name": "chennai", "state_id": 1, "country_id": 1, "latitude": 10.10, "longitude": 12.12}), + * @Response(200, body={"success": "Record has been added."}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {"name": {}}, "status_code": 422}) + * }) + */ + public function store(Request $request) + { + $city_data = $request->only('name', 'state_id', 'country_id', 'latitude', 'longitude'); + $validator = Validator::make($city_data, City::GetValidationRule(), City::GetValidationMessage()); + $state = State::find($city_data['state_id']); + if (!$state) { + return $this->response->errorNotFound("Invalid State Id"); + } + $country = Country::find($city_data['country_id']); + if (!$country) { + return $this->response->errorNotFound("Invalid Country Id"); + } + if ($validator->passes()) { + $city_data['is_active'] = true; + $city = City::create($city_data); + if ($city) { + return response()->json(['Success' => 'City has been added'], 200); + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('City could not be updated. Please, try again.'); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('City could not be updated. Please, try again.', $validator->errors()); + } + } + + /** + * Edit the specified city. + * Edit the city with a `id`. + * @Get("/cities/{id}/edit") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"id": 1, "name": "chennai", "state_id": 1, "country_id": 1, "latitude": 10.10, "longitude": 12.12, "is_active": 1, "State": {}, "Country": {} }), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function edit($id) + { + $city = City::with('State', 'Country')->find($id); + if (!$city) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($city, (new CityTransformer)->setDefaultIncludes(['State', 'Country'])); + } + + /** + * Update the specified city. + * Update the city with a `id`. + * @Put("/cities/{id}") + * @Transaction({ + * @Request({"id": 1, "name": "chennai", "state_id": 1, "country_id": 1, "latitude": 10.10, "longitude": 12.12, "is_active": 1}), + * @Response(200, body={"success": "Record has been updated."}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {"name": {}}, "status_code": 422}) + * }) + */ + public function update(Request $request, $id) + { + $city_data = $request->only('name', 'state_id', 'country_id', 'latitude', 'longitude', 'is_active'); + $validator = Validator::make($city_data, City::GetValidationRule(), City::GetValidationMessage()); + $city = false; + if ($request->has('id')) { + $city = City::find($id); + $city = ($request->id != $id) ? false : $city; + } + if ($validator->passes() && $city) { + try { + $city->update($city_data); + return response()->json(['Success' => 'City has been updated'], 200); + } catch (\Exception $e) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('City could not be updated. Please, try again.'); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('City could not be updated. Please, try again.', $validator->errors()); + } + } + + /** + * Delete the specified city. + * Delete the city with a `id`. + * @Delete("/cities/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"success": "Record Deleted."}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function destroy($id) + { + $city = City::find($id); + if (!$city) { + return $this->response->errorNotFound("Invalid Request"); + } else { + $city->delete(); + } + return response()->json(['Success' => 'City deleted'], 200); + } + /** + * Deactivate the city. + * @Put("/cities/{id}/deactive") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"success": "Record has been deactivated!."}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}), + * }) + */ + public function deactive(Request $request, $id) + { + $city = City::find($id); + if (!$city) { + return $this->response->errorNotFound("Invalid Request"); + } else { + $city_data['is_active'] = false; + if ($city->update($city_data)) { + return response()->json(['Success' => 'Record has been deactivated!'], 200); + } + } + } + + /** + * Activate the city. + * @Put("/cities/{id}/active") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"success": "Record has been activated!."}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}), + * }) + */ + public function active(Request $request, $id) + { + $city = City::find($id); + if (!$city) { + return $this->response->errorNotFound("Invalid Request"); + } else { + $city_data['is_active'] = true; + if ($city->update($city_data)) { + return response()->json(['Success' => 'Record has been activated!'], 200); + } + } + } +} diff --git a/app/Http/Controllers/Admin/AdminCountriesController.php b/app/Http/Controllers/Admin/AdminCountriesController.php new file mode 100644 index 0000000..3a45937 --- /dev/null +++ b/app/Http/Controllers/Admin/AdminCountriesController.php @@ -0,0 +1,209 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Http\Controllers\Admin; + +use Illuminate\Http\Request; + + +use App\Http\Controllers\Controller; +use App\Country; + +use JWTAuth; +use Validator; +use App\Transformers\CountryTransformer; + +/** + * Countries resource representation. + * @Resource("Admin/AdminCountries") + */ +class AdminCountriesController extends Controller +{ + + /** + * AdminCountriesController constructor. + */ + public function __construct() + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth'); + // Check the logged user role. + $this->middleware('role'); + } + + /** + * Show all countries + * Get a JSON representation of all the countries. + * + * @Get("/countries?filter={filter}&sort={sort}&sortby={sortby}&q={q}") + * @Parameters({ + * @Parameter("filter", type="integer", required=false, description="Filter the countries list by type.", default=null), + * @Parameter("sort", type="string", required=false, description="Sort the countries list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort countries by Ascending / Descending Order.", default=null), + * @Parameter("q", type="string", required=false, description="Search countries.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1) + * }) + */ + public function index(Request $request) + { + $country_count = config('constants.ConstPageLimit'); + if ($request->has('limit') && $request->limit == 'all') { + $country_count = Country::count(); + } + $countries = Country::filterByRequest($request)->paginate($country_count); + return $this->response->paginator($countries, new CountryTransformer); + } + + /** + * Store a new country. + * Store a new country with a `name`, `iso2`, and `iso3`. + * @Post("/countries") + * @Transaction({ + * @Request({"name": "india", "iso2": "IN", "iso3": "IND"}), + * @Response(200, body={"success": "Record has been added."}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {"name": {}}, "status_code": 422}) + * }) + */ + public function store(Request $request) + { + $country_data = $request->only('name', 'iso2', 'iso3'); + $validator = Validator::make($country_data, Country::GetValidationRule(), Country::GetValidationMessage()); + if ($validator->passes()) { + $country_data['is_active'] = true; + $country = Country::create($country_data); + if ($country) { + return response()->json(['Success' => 'Country has been added'], 200); + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Country could not be updated. Please, try again.'); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Country could not be updated. Please, try again.', $validator->errors()); + } + } + + /** + * Edit the specified country. + * Edit the country with a `id`. + * @Get("/countries/{id}/edit") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"id": 1, "name": "india", "iso2": "IN", "iso3": "IND", "is_active": 1}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function edit($id) + { + $country = Country::find($id); + if (!$country) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($country, new CountryTransformer); + } + + /** + * Update the specified country + * Update the country with a `id`. + * @Put("/countries/{id}") + * @Transaction({ + * @Request({"id": 1, "name": "india", "iso2": "IN", "iso3": "IND", "is_active": 1}), + * @Response(200, body={"success": "Record has been updated."}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {"name": {}}, "status_code": 422}) + * }) + */ + public function update(Request $request, $id) + { + $country_data = $request->only('name', 'iso2', 'iso3', 'is_active'); + $validator = Validator::make($country_data, Country::GetValidationRule(), Country::GetValidationMessage()); + $country = false; + if ($request->has('id')) { + $country = Country::find($id); + $country = ($request->id != $id) ? false : $country; + } + if ($validator->passes() && $country) { + try { + $country->update($country_data); + return response()->json(['Success' => 'Country has been updated'], 200); + } catch (\Exception $e) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Country could not be updated. Please, try again.'); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Country could not be updated. Please, try again.', $validator->errors()); + } + } + + /** + * Delete the specified country + * Delete the country with a `id`. + * @Delete("/countries/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"success": "Record Deleted."}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function destroy($id) + { + $country = Country::find($id); + if (!$country) { + return $this->response->errorNotFound("Invalid Request"); + } else { + $country->delete(); + } + return response()->json(['Success' => 'Country deleted'], 200); + } + /** + * Deactivate the country. + * @Put("/countries/{id}/deactive") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"success": "Record has been deactivated!."}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}), + * }) + */ + public function deactive(Request $request, $id) + { + $country = Country::find($id); + if (!$country) { + return $this->response->errorNotFound("Invalid Request"); + } else { + $country_data['is_active'] = false; + if ($country->update($country_data)) { + return response()->json(['Success' => 'Record has been deactivated!'], 200); + } + } + } + + /** + * Activate the country. + * @Put("/countries/{id}/active") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"success": "Record has been activated!."}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}), + * }) + */ + public function active(Request $request, $id) + { + $country = Country::find($id); + if (!$country) { + return $this->response->errorNotFound("Invalid Request"); + } else { + $country_data['is_active'] = true; + if ($country->update($country_data)) { + return response()->json(['Success' => 'Record has been activated!'], 200); + } + } + } +} diff --git a/app/Http/Controllers/Admin/AdminCurrenciesController.php b/app/Http/Controllers/Admin/AdminCurrenciesController.php new file mode 100644 index 0000000..a03a2e5 --- /dev/null +++ b/app/Http/Controllers/Admin/AdminCurrenciesController.php @@ -0,0 +1,185 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Http\Controllers\Admin; + +use Illuminate\Http\Request; + + +use App\Http\Controllers\Controller; +use App\Currency; + +use JWTAuth; +use Validator; +use App\Transformers\CurrencyTransformer; + +/** + * Currencies resource representation. + * @Resource("Admin/AdminCurrencies") + */ +class AdminCurrenciesController extends Controller +{ + /** + * AdminCurrenciesController constructor. + */ + public function __construct() + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth'); + // Check the logged user role. + $this->middleware('role'); + } + + /** + * Show all currencies + * Get a JSON representation of all the currencies. + * + * @Get("/currencies?filter={filter}&sort={sort}&sortby={sortby}&type={type}&field={field}&q={q}") + * @Parameters({ + * @Parameter("filter", type="integer", required=false, description="Filter the currencies list by type.", default=null), + * @Parameter("sort", type="string", required=false, description="Sort the currencies list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort currencies by Ascending / Descending Order.", default=null), + * @Parameter("q", type="string", required=false, description="Search currencies.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1) + * }) + */ + public function index(Request $request) + { + $currency_count = config('constants.ConstPageLimit'); + if ($request->has('type') && $request->type == 'list') { + $currency_count = Currency::count(); + } + $currencies = Currency::filterByRequest($request)->paginate($currency_count); + return $this->response->paginator($currencies, new CurrencyTransformer); + } + + /** + * Store a new currency. + * Store a new currency with a `name`, `code`, `symbol`, `prefix`, `suffix`, `decimals` ,`dec_point`, `thousands_sep`, `is_prefix_display_on_left` and `is_use_graphic_symbol`. + * @Post("/currencies") + * @Transaction({ + * @Request({"name": "Dollar", "code": "USD", "symbol": "$", "prefix" : "$", "suffix":"", "decimals":"0.00", "dec_point":"2", "thousands_sep":"4", "is_prefix_display_on_left":1, "is_use_graphic_symbol":1 }), + * @Response(200, body={"success": "Record has been added."}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {"name": {}}, "status_code": 422}) + * }) + */ + public function store(Request $request) + { + $currency_data = $request->only('name', 'code', 'symbol', 'prefix', 'suffix', 'decimals', 'dec_point', 'thousands_sep', 'is_prefix_display_on_left', 'is_use_graphic_symbol'); + $validator = Validator::make($currency_data, Currency::GetValidationRule(), Currency::GetValidationMessage()); + if ($validator->passes()) { + $currency_data['is_active'] = true; + $currency = Currency::create($currency_data); + if ($currency) { + return response()->json(['Success' => 'Currency has been added'], 200); + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Currency could not be updated. Please, try again.'); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Currency could not be updated. Please, try again.', $validator->errors()); + } + } + + /** + * Edit the specified currency. + * Edit the currency with a `id`. + * @Get("/currencies/{id}/edit") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"id": 1, "name": "Dollar", "code": "USD", "symbol": "$", "prefix" : "$", "suffix":"", "decimals":"0.00", "dec_point":"2", "thousands_sep":"4", "is_prefix_display_on_left":1, "is_use_graphic_symbol":1, "is_active": 1}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function edit($id) + { + $currency = Currency::find($id); + if (!$currency) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($currency, new CurrencyTransformer); + } + + /** + * Show the specified currency. + * show the currency with a `id`. + * @Get("/currencies/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"id": 1, "name": "Dollar", "code": "USD", "symbol": "$", "prefix" : "$", "suffix":"USD", "decimals":"2", "dec_point":".", "thousands_sep":",", "is_prefix_display_on_left":1, "is_use_graphic_symbol":1, "is_active": 1}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function show($id) + { + $currency = Currency::find($id); + if (!$currency) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($currency, new CurrencyTransformer); + } + + /** + * Update the specified currency + * Update the currency with a `id`. + * @Put("/currencies/{id}") + * @Transaction({ + * @Request({"id": 1, "name": "Dollar", "code": "USD", "symbol": "$", "prefix" : "$", "suffix":"", "decimals":"0.00", "dec_point":"2", "thousands_sep":"4", "is_prefix_display_on_left":1, "is_use_graphic_symbol":1, "is_active": 1}), + * @Response(200, body={"success": "Record has been updated."}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {"name": {}}, "status_code": 422}) + * }) + */ + public function update(Request $request, $id) + { + $currency_data = $request->only('name', 'code', 'symbol', 'prefix', 'suffix', 'decimals', 'dec_point', 'thousands_sep', 'is_prefix_display_on_left', 'is_use_graphic_symbol', 'is_active'); + $validator = Validator::make($currency_data, Currency::GetValidationRule(), Currency::GetValidationMessage()); + $currency = false; + if ($request->has('id')) { + $currency = Currency::find($id); + $currency = ($request->id != $id) ? false : $currency; + } + if ($validator->passes() && $currency) { + try { + $currency->update($currency_data); + return response()->json(['Success' => 'Currency has been updated'], 200); + } catch (\Exception $e) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Currency could not be updated. Please, try again.'); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Currency could not be updated. Please, try again.', $validator->errors()); + } + + } + + /** + * Delete the specified currency + * Delete the currency with a `id`. + * @Delete("/currencies/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"success": "Record Deleted."}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function destroy($id) + { + $currency = Currency::find($id); + if (!$currency) { + return $this->response->errorNotFound("Invalid Request"); + } else { + $currency->delete(); + } + return response()->json(['Success' => 'Currency deleted'], 200); + } +} diff --git a/app/Http/Controllers/Admin/AdminDashboardsController.php b/app/Http/Controllers/Admin/AdminDashboardsController.php new file mode 100644 index 0000000..0156e1f --- /dev/null +++ b/app/Http/Controllers/Admin/AdminDashboardsController.php @@ -0,0 +1,131 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Http\Controllers\Admin; + +use Illuminate\Http\Request; + + +use App\Http\Controllers\Controller; + +use App\Dashboard; + +use JWTAuth; + +use App\Services\UserService; +use App\Services\UserLoginService; +use App\Services\TransactionService; + +/** + * Dashboards resource representation. + * @Resource("Admin/AdminDashboards") + */ +class AdminDashboardsController extends Controller +{ + /** + * @var UserService + */ + protected $UserService; + /** + * @var UserLoginService + */ + protected $UserLoginService; + /** + * @var + */ + protected $transactionService; + + /** + * AdminDashboardsController constructor. + */ + public function __construct(UserService $user_service) + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth'); + // Check the logged user role. + $this->middleware('role'); + $this->UserService = $user_service; + $this->setUserLoginService(); + $this->setTransactionService(); + } + + public function setUserLoginService() + { + $this->UserLoginService = new UserLoginService(); + } + + public function setTransactionService() + { + $this->transactionService = new TransactionService(); + } + + /** + * Show all Dashboards stats + * Get a JSON representation of all the Dashboards statistics. + * + * @Get("/stats") + * @Parameters({ + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1) + * }) + */ + public function stats(Request $request) + { + if (!$request->has('filter')) { + $last_user_login = $this->UserLoginService->getLastLogin(); + $last_register = $this->UserService->getLastRegistered(); + $total_users = $this->UserService->getTotalUsers(); + $site_version = config('site.version'); + if (isPluginEnabled('VehicleRentals')) { + $this->VehicleRentalService = new \Plugins\VehicleRentals\Services\VehicleRentalService(); + $last_vehicle_rental = $this->VehicleRentalService->getLastVehicleRental(); + $total_booking_count = $this->VehicleRentalService->getVehicleRentalCount($request, 'total'); + $total_revenue = $this->transactionService->getAdminTotalRevenue(); + } + if (isPluginEnabled('Vehicles')) { + $this->vehicleService = new \Plugins\Vehicles\Services\VehicleService(); + $last_item = $this->vehicleService->getLastAddVehicle(); + $total_vehicle_count = $this->vehicleService->getVehicleCount($request, 'total'); + } + if (isPluginEnabled('VehicleFeedbacks')) { + $this->feedbackService = new \Plugins\VehicleFeedbacks\Services\VehicleFeedbackService(); + $last_feedback = $this->feedbackService->getLastFeedback(); + $total_feedback_count = $this->feedbackService->getFeedbackCount($request, 'total'); + } + + } + $user_login = $this->UserService->getLoginCount($request); + $user_register = $this->UserService->getRegisterCount($request); + $transaction_count = $this->transactionService->getTranactionCount($request); + if (isPluginEnabled('VehicleRentals')) { + $this->VehicleRentalService = new \Plugins\VehicleRentals\Services\VehicleRentalService(); + $booking_count = $this->VehicleRentalService->getVehicleRentalCount($request); + } + if (isPluginEnabled('Vehicles')) { + $this->vehicleService = new \Plugins\Vehicles\Services\VehicleService(); + $vehicle_count = $this->vehicleService->getVehicleCount($request); + } + if (isPluginEnabled('VehicleFeedbacks')) { + $this->feedbackService = new \Plugins\VehicleFeedbacks\Services\VehicleFeedbackService(); + $feedback_count = $this->feedbackService->getFeedbackCount($request); + } + + if (!$request->has('filter')) { + return response()->json(compact('user_login', 'user_register', 'last_user_login', 'last_register', 'total_users', 'site_version', 'last_vehicle_rental', 'last_item', 'last_feedback', 'total_booking_count', 'booking_count', 'vehicle_count', 'total_vehicle_count', 'total_feedback_count', 'feedback_count', 'transaction_count', 'total_revenue')); + } else { + return response()->json(compact('user_login', 'user_register', 'booking_count', 'vehicle_count', 'feedback_count', 'transaction_count')); + } + + } +} \ No newline at end of file diff --git a/app/Http/Controllers/Admin/AdminEmailTemplatesController.php b/app/Http/Controllers/Admin/AdminEmailTemplatesController.php new file mode 100644 index 0000000..bee4f6b --- /dev/null +++ b/app/Http/Controllers/Admin/AdminEmailTemplatesController.php @@ -0,0 +1,112 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ +namespace App\Http\Controllers\Admin; + +use Illuminate\Http\Request; + + +use App\Http\Controllers\Controller; + +use App\EmailTemplate; + +use JWTAuth; +use Validator; +use App\Transformers\EmailTemplateTransformer; + +/** + * EmailTemplates resource representation. + * @Resource("Admin/AdminEmailTemplates") + */ +class AdminEmailTemplatesController extends Controller +{ + /** + * AdminEmailTemplatesController constructor. + */ + public function __construct() + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth'); + // Check the logged user role. + $this->middleware('role'); + } + + /** + * Show all email templates. + * Get a JSON representation of all the EmailTemplates. + * + * @Get("/email_templates?sort={sort}&sortby={sortby}&page={page}") + * @Parameters({ + * @Parameter("sort", type="string", required=false, description="Sort the email templates list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort email templates by Ascending / Descending Order.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1) + * }) + */ + public function index(Request $request) + { + $email_templates = EmailTemplate::filterByRequest($request)->paginate(config('constants.ConstPageLimit')); + return $this->response->paginator($email_templates, new EmailTemplateTransformer); + } + + /** + * Edit the specified email template. + * Edit the email template with a `id`. + * @Get("/email_templates/{id}/edit") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"id": 1, "name": "XXXXXX", "subject": "XXXXXX", "body_content": "XXXXXX", "from_name": "XXXXXX", "info": "XXXXXX", "reply_to": "XXXXXX"}), + * @Response(404, body={"message": "Invalid Request", "errors": {"name":{}}, "status_code": 404}) + * }) + */ + public function edit($id) + { + $email_template = EmailTemplate::find($id); + if (!$email_template) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($email_template, new EmailTemplateTransformer); + } + + /** + * Update the specified email template. + * Update the email template with a `id`. + * @Put("/email_templates/{id}") + * @Transaction({ + * @Request({"id": 1, "name": "XXXXXX", "subject": "XXXXXX", "body_content": "XXXXXX", "from_name": "XXXXXX", "info": "XXXXXX", "reply_to": "XXXXXX"}), + * @Response(200, body={"success": "Record has been updated."}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {"name":{}}, "status_code": 422}) + * }) + */ + public function update(Request $request, $id) + { + $email_template_data = $request->only('name', 'subject', 'body_content', 'from_name', 'reply_to'); + $validator = Validator::make($email_template_data, EmailTemplate::GetValidationRule(), EmailTemplate::GetValidationMessage()); + $email_template = false; + if ($request->has('id')) { + $email_template = EmailTemplate::find($id); + $email_template = ($request->id != $id) ? false : $email_template; + } + if ($validator->passes() && $email_template) { + try { + $email_template->update($email_template_data); + return response()->json(['Success' => 'EmailTemplate has been updated'], 200); + } catch (\Exception $e) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('EmailTemplate could not be updated. Please, try again.'); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('EmailTemplate could not be updated. Please, try again.', $validator->errors()); + } + + } +} \ No newline at end of file diff --git a/app/Http/Controllers/Admin/AdminIpsController.php b/app/Http/Controllers/Admin/AdminIpsController.php new file mode 100644 index 0000000..dc6a320 --- /dev/null +++ b/app/Http/Controllers/Admin/AdminIpsController.php @@ -0,0 +1,106 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Http\Controllers\Admin; + +use Illuminate\Http\Request; + + +use App\Http\Controllers\Controller; + +use App\Ip; +use App\Transformers\IpTransformer; +use DB; + +/** + * Ips resource representation. + * @Resource("Admin/AdminIps") + */ +class AdminIpsController extends Controller +{ + /** + * AdminIpsController constructor. + */ + public function __construct() + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth'); + // Check the logged user role. + $this->middleware('role'); + } + + /** + * Show all Ips + * Get a JSON representation of all the Ips. + * + * @Get("/ips?sort={sort}&sortby={sortby}&page={page}&q={q}") + * @Parameters({ + * @Parameter("sort", type="string", required=false, description="Sort the states list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort states by Ascending / Descending Order.", default=null), + * @Parameter("q", type="string", required=false, description="Search Ips.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1) + * }) + */ + public function index(Request $request) + { + $ips = Ip::select(DB::raw('ips.*')) + ->leftJoin(DB::raw('(select id,name as city_name from cities) as cities'), 'cities.id', '=', 'ips.city_id') + ->leftJoin(DB::raw('(select id,name as state_name from states) as states'), 'states.id', '=', 'ips.state_id') + ->leftJoin(DB::raw('(select id,name as country_name from countries) as countries'), 'countries.id', '=', 'ips.country_id') + ->filterByRequest($request) + ->paginate(config('constants.ConstPageLimit')); + return $this->response->paginator($ips, (new IpTransformer)->setDefaultIncludes(['City', 'State', 'Country'])); + } + + /** + * Show the specified ip. + * Show the ip with a `id`. + * @Get("/ips/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body= {"id": 1, "city_id": 1, "state_id": 1, "country_id": 1, "ip": "::1", "latitude": 0, "longitude": 0, "City": {}, "State": {}, "Country": {}}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function show($id) + { + $ips = Ip::with('City', 'State', 'Country')->find($id); + if (!$ips) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($ips, (new IpTransformer)->setDefaultIncludes(['City', 'State', 'Country'])); + } + + /** + * Delete the specified ip. + * Delete the ip with a `id`. + * @Delete("/ips/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"success": "Record Deleted."}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function destroy($id) + { + $ips = Ip::find($id); + if (!$ips) { + return $this->response->errorNotFound("Invalid Request"); + } else { + $ips->delete(); + } + return response()->json(['Success' => 'Ip deleted'], 200); + } +} \ No newline at end of file diff --git a/app/Http/Controllers/Admin/AdminLanguagesController.php b/app/Http/Controllers/Admin/AdminLanguagesController.php new file mode 100644 index 0000000..7122b73 --- /dev/null +++ b/app/Http/Controllers/Admin/AdminLanguagesController.php @@ -0,0 +1,161 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Http\Controllers\Admin; + +use Illuminate\Http\Request; + + +use App\Http\Controllers\Controller; +use App\Language; + +use JWTAuth; +use Validator; +use App\Transformers\LanguageTransformer; + +/** + * Languages resource representation. + * @Resource("Admin/AdminLanguages") + */ +class AdminLanguagesController extends Controller +{ + /** + * AdminLanguagesController constructor. + */ + public function __construct() + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth'); + // Check the logged user role. + $this->middleware('role'); + } + + /** + * Show all languages + * Get a JSON representation of all the languages. + * + * @Get("/languages?filter={filter}&sort={sort}&sortby={sortby}&q={q}") + * @Parameters({ + * @Parameter("filter", type="integer", required=false, description="Filter the languages list by type.", default=null), + * @Parameter("sort", type="string", required=false, description="Sort the languages list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort languages by Ascending / Descending Order.", default=null), + * @Parameter("q", type="string", required=false, description="Search languages.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1) + * }) + */ + public function index(Request $request) + { + $languages = Language::filterByRequest($request)->paginate(config('constants.ConstPageLimit')); + return $this->response->paginator($languages, new LanguageTransformer); + } + + /** + * Store a new language. + * Store a new language with a `name`, iso2, and `iso3`. + * @Post("/languages") + * @Transaction({ + * @Request({"name": "English", "iso2": "EN", "iso3": "ENG"}), + * @Response(200, body={"success": "Record has been added."}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {"name": {}}, "status_code": 422}) + * }) + */ + public function store(Request $request) + { + $language_data = $request->only('name', 'iso2', 'iso3'); + $validator = Validator::make($language_data, Language::GetValidationRule(), Language::GetValidationMessage()); + if ($validator->passes()) { + $language_data['is_active'] = true; + $language = Language::create($language_data); + if ($language) { + return response()->json(['Success' => 'Language has been added'], 200); + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Language could not be updated. Please, try again.'); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Language could not be updated. Please, try again.', $validator->errors()); + } + } + + /** + * Edit the specified language. + * Edit the language with a `id`. + * @Get("/languages/{id}/edit") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"id": 1, "name": "English", "iso2": "EN", "iso3": "ENG", "is_active": 1}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function edit($id) + { + $language = Language::find($id); + if (!$language) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($language, new LanguageTransformer); + } + + /** + * Update the specified language. + * Update the language with a `id`. + * @Put("/languages/{id}") + * @Transaction({ + * @Request({"id": 1, "name": "English", "iso2": "EN", "iso3": "ENG", "is_active": 1}), + * @Response(200, body={"success": "Record has been updated."}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {"name": {}}, "status_code": 422}) + * }) + */ + public function update(Request $request, $id) + { + $language_data = $request->only('name', 'iso2', 'iso3', 'is_active'); + $validator = Validator::make($language_data, Language::GetValidationRule(), Language::GetValidationMessage()); + $language = false; + if ($request->has('id')) { + $language = Language::find($id); + $language = ($request->id != $id) ? false : $language; + } + if ($validator->passes() && $language) { + try { + $language->update($language_data); + return response()->json(['Success' => 'Language has been updated'], 200); + } catch (\Exception $e) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Language could not be updated. Please, try again.'); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Language could not be updated. Please, try again.', $validator->errors()); + } + } + + /** + * Delete the specified language. + * Delete the language with a `id`. + * @Delete("/languages/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"success": "Record Deleted."}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function destroy($id) + { + $language = Language::find($id); + if (!$language) { + return $this->response->errorNotFound("Invalid Request"); + } else { + $language->delete(); + } + return response()->json(['Success' => 'Language deleted'], 200); + } +} diff --git a/app/Http/Controllers/Admin/AdminMessagesController.php b/app/Http/Controllers/Admin/AdminMessagesController.php new file mode 100644 index 0000000..766c97c --- /dev/null +++ b/app/Http/Controllers/Admin/AdminMessagesController.php @@ -0,0 +1,186 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Http\Controllers\Admin; + +use Illuminate\Http\Request; + +use App\Http\Controllers\Controller; +use JWTAuth; +use App\Message; +use Validator; +use App\Transformers\MessageTransformer; +use DB; + +/** + * AdminMessages resource representation. + * @Resource("Admin/AdminMessages") + */ +class AdminMessagesController extends Controller +{ + /** + * AdminMessagesController constructor. + */ + public function __construct() + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth'); + // Check the logged user role. + $this->middleware('role'); + } + + /** + * Show all Messages + * Get a JSON representation of all the Messages. + * + * @Get("/admin/messages?sort={sort}&sortby={sortby}&page={page}&q={q}") + * @Parameters({ + * @Parameter("sort", type="string", required=false, description="Sort the messages list by sort key.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort messages by Ascending / Descending Order.", default=null), + * @Parameter("q", type="string", required=false, description="Search messages.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1), + * @Parameter("filter", type="string", required=false, description="Filter messages.", default=null) + * }) + */ + public function index(Request $request) + { + /*$enabledIncludes = ""; + // check if plugin enabled and include + (isPluginEnabled('Items')) ? $enabledIncludes[] = 'item' : ''; + (isPluginEnabled('VehicleRentals')) ? $enabledIncludes[] = 'item_users' : '';*/ + $messages = Message::select(DB::raw('messages.*')) + ->leftJoin(DB::raw('(select id,username from users) as from_user'), 'from_user.id', '=', 'messages.user_id') + ->leftJoin(DB::raw('(select id,username from users) as to_user'), 'to_user.id', '=', 'messages.to_user_id') + ->leftJoin(DB::raw('(select id,message, subject from message_contents) as message_content'), 'message_content.id', '=', 'messages.message_content_id') + ->filterByRequest($request) + ->paginate(config('constants.ConstPageLimit')); + return $this->response->paginator($messages, (new MessageTransformer)->setDefaultIncludes(['from_user', 'to_user', 'message_content', 'item_user_status', 'dispute_status', 'messageable'])); + } + + /** + * Get item activities + * + * @Get("/admin/item_messages/{item_id}") + * @Transaction({ + * @Request({"item_id": 1}), + * @Response(200, body={"user_id":1,"item_id":1,"to_user_id":2,"message_content_id":1,"message_folder_id":1,"messageable_id":1,"messageable_type":"App\Model\User","is_sender":1,"is_starred":1,"is_read":1,"is_deleted":1,"is_archived":1,"is_review":1,"is_communication":0,"user":{},"item_user":{},"item":{},"message_content":{}}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + /*public function itemActivities($item_id) + { + $enabledIncludes = array('user', 'message_content'); + // check if plugin enabled and include + (isPluginEnabled('Items')) ? $enabledIncludes[] = 'item' : ''; + (isPluginEnabled('VehicleRentals')) ? $enabledIncludes[] = 'item_users' : ''; + $item_message = Message::with($enabledIncludes)->where('item_id', $item_id)->get(); + if (!$item_message) { + return $this->response->errorNotFound('Invalid Request'); + } + return $this->response->Collection($item_message, (new MessageTransformer)->setDefaultIncludes($enabledIncludes)); + }*/ + + /** + * Get item user activities + * + * @Get("/admin/item_user_messages/{item_user_id}") + * @Transaction({ + * @Request({"item_user_id": 1}), + * @Response(200, body={"user_id":1,"item_id":1,"to_user_id":2,"message_content_id":1,"message_folder_id":1,"messageable_id":1,"messageable_type":"App\Model\User","is_sender":1,"is_starred":1,"is_read":1,"is_deleted":1,"is_archived":1,"is_review":1,"is_communication":0,"user":{},"item_user":{},"item":{},"message_content":{}}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + /*public function bookerActivities($item_user_id) + { + $enabledIncludes = array('user', 'message_content'); + // check if plugin enabled and include + (isPluginEnabled('Items')) ? $enabledIncludes[] = 'item' : ''; + (isPluginEnabled('VehicleRentals')) ? $enabledIncludes[] = 'item_users' : ''; + $item_user_messages = Message::with($enabledIncludes)->where('messageable_id',$item_user_id)->get(); + if(!$item_user_messages) + { + return $this->response->errorNotFound('Invalid Request'); + } + return $this->response->Collection($item_user_messages, (new MessageTransformer)->setDefaultIncludes($enabledIncludes)); + + }*/ + + /** + * Get user activities + * + * @Get("/admin/user_messages/{user_id}") + * @Transaction({ + * @Request({"user_id": 1}), + * @Response(200, body={"user_id":1,"item_id":1,"to_user_id":2,"message_content_id":1,"message_folder_id":1,"messageable_id":1,"messageable_type":"App\Model\User","is_sender":1,"is_starred":1,"is_read":1,"is_deleted":1,"is_archived":1,"is_review":1,"is_communication":0,"user":{},"item_user":{},"item":{},"message_content":{}}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + /*public function userActivities($user_id) + { + $enabledIncludes = array('user', 'message_content'); + // check if plugin enabled and include + (isPluginEnabled('Items')) ? $enabledIncludes[] = 'item' : ''; + (isPluginEnabled('VehicleRentals')) ? $enabledIncludes[] = 'item_users' : ''; + $user_messages = Message::with($enabledIncludes)->where('messageable_id',$user_id)->get(); + if(!$user_messages) + { + return $this->response->errorNotFound('Invalid Request'); + } + return $this->response->Collection($user_messages, (new MessageTransformer)->setDefaultIncludes($enabledIncludes)); + }*/ + + /** + * Show the specified message. + * Show the message with a `id`. + * @Get("/messages/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"id": 1, "created_at": "2016-05-10 13:12:13", "user_id": 4, "to_user_id": 1, "item_id": 1, "user": {}, "message_content": {}, "item": {}, "item_users": {}}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function show($id) + { + $enabledIncludes = array('from_user', 'to_user', 'message_content', 'item_user_status', 'dispute_status'); + $message = Message::with($enabledIncludes)->find($id); + if (!$message) { + return $this->response->errorNotFound("Invalid Request"); + } + $enabledIncludes = array_merge($enabledIncludes, array('messageable')); + return $this->response->item($message, (new MessageTransformer)->setDefaultIncludes($enabledIncludes)); + } + + /** + * Delete the specified message. + * Delete the message with a `id`. + * @Delete("messages/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"success": "Messages Deleted."}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function destroy($id) + { + $message = Message::find($id); + if (!$message) { + return $this->response->errorNotFound("Invalid Request"); + } else { + $message->delete(); + } + return response()->json(['Success' => 'Messages deleted'], 200); + } + +} diff --git a/app/Http/Controllers/Admin/AdminRolesController.php b/app/Http/Controllers/Admin/AdminRolesController.php new file mode 100644 index 0000000..a9c29d9 --- /dev/null +++ b/app/Http/Controllers/Admin/AdminRolesController.php @@ -0,0 +1,62 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Http\Controllers\Admin; + +use Illuminate\Http\Request; + + +use App\Http\Controllers\Controller; + +use App\Role; + +use JWTAuth; +use Validator; +use App\Transformers\RoleTransformer; + +/** + * Roles resource representation. + * @Resource("Admin/AdminRoles") + */ +class AdminRolesController extends Controller +{ + /** + * AdminRolesController constructor. + */ + public function __construct() + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth'); + // Check the logged user role. + $this->middleware('role'); + } + + /** + * Show all roles + * Get a JSON representation of all the roles. + * + * @Get("/roles?sort={sort}&sortby={sortby}&page={page}") + * @Parameters({ + * @Parameter("sort", type="string", required=false, description="Sort the states list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort states by Ascending / Descending Order.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1) + * }) + */ + public function index(Request $request) + { + $roles = Role::filterByRequest($request)->paginate(config('constants.ConstPageLimit')); + return $this->response->paginator($roles, new RoleTransformer); + } +} \ No newline at end of file diff --git a/app/Http/Controllers/Admin/AdminSettingCategoriesController.php b/app/Http/Controllers/Admin/AdminSettingCategoriesController.php new file mode 100644 index 0000000..f822157 --- /dev/null +++ b/app/Http/Controllers/Admin/AdminSettingCategoriesController.php @@ -0,0 +1,109 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Http\Controllers\Admin; + +use Illuminate\Http\Request; + + +use App\Http\Controllers\Controller; + +use App\SettingCategory; +use App\Setting; + +use JWTAuth; +use Validator; +use App\Transformers\SettingCategoryTransformer; + +/** + * SettingCategories resource representation. + * @Resource("Admin/AdminSettingCategories") + */ +class AdminSettingCategoriesController extends Controller +{ + /** + * AdminSettingCategoriesController constructor. + */ + public function __construct() + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth'); + // Check the logged user role. + $this->middleware('role'); + } + + /** + * Show all setting categories. + * Get a JSON representation of all the setting categories. + * + * @Get("/setting_categories?sort={sort}&sortby={sortby}&page={page}") + * @Parameters({ + * @Parameter("sort", type="string", required=false, description="Sort the states list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort states by Ascending / Descending Order.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1) + * }) + */ + public function index(Request $request) + { + $setting_plugin = Setting::select('value')->where('name', 'site.enabled_plugins')->first(); + $notInCategories = array(); + $notInCategories[] = config('constants.ConstSettingCategories.Plugins'); + if (!empty($setting_plugin) && strpos($setting_plugin['value'], 'Analytics') === false) { + $notInCategories[] = config('constants.ConstSettingCategories.Analytics'); + } + if (!empty($setting_plugin) && strpos($setting_plugin['value'], 'Withdrawals') === false) { + $notInCategories[] = config('constants.ConstSettingCategories.Withdrawal'); + } + if (!empty($setting_plugin) && strpos($setting_plugin['value'], 'Banner') === false) { + $notInCategories[] = config('constants.ConstSettingCategories.Banner'); + } + if (!empty($setting_plugin) && strpos($setting_plugin['value'], 'Sudopays') === false) { + $notInCategories[] = config('constants.ConstSettingCategories.Sudopay'); + } + if (!empty($setting_plugin) && strpos($setting_plugin['value'], 'Paypal') === false) { + $notInCategories[] = config('constants.ConstSettingCategories.PayPal'); + } + if (!empty($setting_plugin) && strpos($setting_plugin['value'], 'Vehicles') === false) { + $notInCategories[] = config('constants.ConstSettingCategories.Vehicles'); + } + if (!empty($setting_plugin) && strpos($setting_plugin['value'], 'VehicleRentals') === false) { + $notInCategories[] = config('constants.ConstSettingCategories.VehicleRentals'); + } + if (!empty($setting_plugin) && strpos($setting_plugin['value'], 'VehicleDisputes') === false) { + $notInCategories[] = config('constants.ConstSettingCategories.Disputes'); + } + $setting_categories = SettingCategory::filterByRequest($request, $notInCategories)->paginate(config('constants.ConstPageLimit')); + return $this->response->paginator($setting_categories, new SettingCategoryTransformer); + } + /** + * Show the specified setting category. + * Show the setting category with a `id`. + * @Get("/setting_categories/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"name": "System", "description": "XXX", "parent_id": 1, "display_order": 1, "Setting": {"setting_category_id": 1, "name": "XXX", "value": 1, "label": "XXX", "description": 1, "display_order": 1} }), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function show($id) + { + $setting_category = SettingCategory::find($id); + if(!$setting_category){ + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($setting_category, new SettingCategoryTransformer); + } + +} \ No newline at end of file diff --git a/app/Http/Controllers/Admin/AdminSettingsController.php b/app/Http/Controllers/Admin/AdminSettingsController.php new file mode 100644 index 0000000..2f51eed --- /dev/null +++ b/app/Http/Controllers/Admin/AdminSettingsController.php @@ -0,0 +1,308 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Http\Controllers\Admin; + +use App\Currency; +use Illuminate\Http\Request; + + +use App\Http\Controllers\Controller; +use App\Setting; + +use JWTAuth; +use Validator; +use File; +use Cache; +use App\Transformers\SettingTransformer; + + +/** + * Settings resource representation. + * @Resource("Admin/AdminSettings") + */ +class AdminSettingsController extends Controller +{ + /** + * AdminSettingsController constructor. + */ + public function __construct() + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth', ['except' => [ + 'show' + ]]); + // Check the logged user role. + $this->middleware('role', ['except' => [ + 'show' + ]]); + } + + /** + * Show all settings + * Get a JSON representation of all the settings. + * @Get("/settings?sort={sort}&sortby={sortby}&page={page}&setting_category_id={id}") + * @Parameters({ + * @Parameter("sort", type="string", required=false, description="Sort the settings list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort setting by Ascending / Descending Order.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1), + * @Parameter("setting_category_id", type="integer", required=false, description="Sort setting by category.", default=null) + * }) + */ + public function index(Request $request) + { + $settings = Setting::filterByRequest($request)->paginate(config('constants.ConstPageLimit')); + return $this->response->paginator($settings, new SettingTransformer); + } + + /** + * Show all settings. + * Show the settings with a `id`. + * @Get("/setting_categories/{id}/settings") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"name": "System", "value": 1, "label": "XXX", "description": "XXX", "display_order": 1 }), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function settings($id) + { + $setting = Setting::where('setting_category_id', '=', $id)->get(); + if (!$setting) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($setting, (new SettingTransformer)->setDefaultIncludes(['setting_category'])); + } + + /** + * Edit the specified setting. + * Edit the setting with a `id`. + * @Get("/settings/{id}/edit") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"id": 1, "name": "Site Name", "description": "XXX", "value": 1}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function edit($id) + { + $setting = Setting::find($id); + if (!$setting) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($setting, (new SettingTransformer)->setDefaultIncludes(['setting_category'])); + } + + /** + * Update the specified setting. + * Update the setting with a `id`. + * @Put("/settings/{id}") + * @Transaction({ + * @Request({"id": 1, "value": 1}), + * @Response(200, body={"success": "Record Updated Successfully."}), + * @Response(500, body={"error": "Record not found."}) + * }) + */ + public function update(Request $request, $id) + { + $setting_data = $request->only('id', 'value'); + $validator = Validator::make($setting_data, Setting::GetValidationRule(), Setting::GetValidationMessage()); + $setting = false; + if ($request->has('id')) { + $setting = Setting::find($id); + $setting = ($request->id != $id) ? false : $setting; + if($setting && $setting->name == 'site.currency_code'){ + $currency = Currency::where('code', $setting->value)->where('is_active', 1)->first(); + if(!$currency){ + $setting = false; + } + } + } + if ($validator->passes() && $setting) { + try { + $setting->update($setting_data); + Cache::forget('settings_data'); + return response()->json(['Success' => 'Setting has been updated'], 200); + } catch (\Exception $e) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Setting could not be updated. Please, try again.'); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Setting could not be updated. Please, try again.', $validator->errors()); + } + } + + /** + * Show the specified setting details. + * Show the setting detail with a `name`. + * @Get("/settings/{name}/show") + * @Transaction({ + * @Request({"name": "site.version"}), + * @Response(200, body={"id":2, "setting_category_id":1, "name":"site.version", "value":"v1.0a.01", "label":"Site Version","description":"XXXX", "display_order":2}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function show($name) + { + $setting = Setting::where('name', '=', $name)->get(); + if (!$setting) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($setting, (new SettingTransformer)->setDefaultIncludes(['setting_category'])); + } + + /** + * List out the all plugin and Setting to enable plugin list + * @Get("/plugins") + * @Transaction({ + * @Request({"name": "site.version"}), + * @Response(200, body={"other_plugin":{}, "enabled_plugin":{}}), + * }) + */ + public function getPlugin() + { + $path = app()->basePath('app/Plugins/'); + $directories = array(); + $directories = glob($path . '/*', GLOB_ONLYDIR); + $available_plugin = array(); + $available_plugin_details = array(); + $pluginArray = array(); + + $pluginArray['Vehicles'] = array(); + $pluginArray['VehicleRentals'] = array(); + $pluginArray['PaymentGateways'] = array(); + foreach ($directories as $key => $val) { + $json = file_get_contents($val . '/' . 'plugin.json'); + $data = json_decode($json, true); + + if (!empty($data['dependencies'])) { + $pluginArray[$data['dependencies']]['sub_plugins'][$data['name']] = $data; + } else { + if (!isset($pluginArray[$data['name']])) { + $pluginArray[] = $data; + } else { + $pluginArray[$data['name']]['main'] = $data; + } + } + } + // Creating Payment Gateway plugin + $paymentGatewayPlugins = array(); + if (!empty($pluginArray['PaymentGateways'])) { + $paymentGatewayPlugins = $pluginArray['PaymentGateways']; + } + unset($pluginArray['PaymentGateways']); + // Creating Vehicles Gateway plugin + + $vehicleRentalRelatedPlugins = array(); + $itemRelatedPlugins = array(); + if (!empty($pluginArray['Vehicles'])) { + $itemRelatedPlugins = $pluginArray['Vehicles']; + if (!empty($pluginArray['VehicleRentals'])) { + $pluginArray['VehicleRentals']['sub_plugins'] = collect($pluginArray['VehicleRentals']['sub_plugins'])->sortBy('display_order')->all(); + $itemRelatedPlugins['sub_plugins']['VehicleRentals'] = $itemRelatedPlugins['sub_plugins']['VehicleRentals'] + $pluginArray['VehicleRentals']; + } + } + unset($pluginArray['Vehicles']); + unset($pluginArray['VehicleRentals']); + $otherlugins = array(); + foreach ($pluginArray as $plugin) { + $otherlugins[] = $plugin; + } + $setting_plugin = Setting::where('name', '=', 'site.enabled_plugins')->first(); + $enabled_plugin = explode(",", $setting_plugin['value']); + $enabled_plugin = array_map('trim', $enabled_plugin); + foreach ($enabled_plugin as $key=>$value) { + if($value == 'Sudopays') { + $enabled_plugin[$key] = 'ZazPay'; + } + } + $response['item_plugin'] = $itemRelatedPlugins; + $response['payment_gateway_plugin'] = $paymentGatewayPlugins; + $response['other_plugin'] = $otherlugins; + $response['enabled_plugin'] = $enabled_plugin; + return response()->json($response, 200); + } + + /** + * Update the plugin setting. + * Plugin setting to update enable or disable. + * @Put("/plugins") + * @Transaction({ + * @Request({"is_enabled": 1, "plugin_name": "Wallets"}), + * @Response(200, body={"success": "Record Updated Successfully."}), + * @Response(422, body={"error": "Record could not be updated."}) + * }) + */ + public function updatePlugin(Request $request) + { + $setting = Setting::where('name', '=', 'site.enabled_plugins')->first(); + $pluginStr = $setting->value; + $pluginArray = explode(",", $pluginStr); + $pluginArray = array_map('trim', $pluginArray); + $item_sub_plugin = array('VehicleRentals', 'VehicleCoupons', 'VehicleFeedbacks', 'VehicleDisputes', 'VehicleExtraAccessories', 'VehicleFuelOptions', 'VehicleInsurances', 'VehicleSurcharges', 'VehicleTaxes'); + if ($request->has('is_enabled') && $request->has('plugin_name')) { + if($request->plugin_name == 'ZazPay') { + $request->plugin_name = 'Sudopays'; + } + $path = app()->basePath('app/Plugins/' . $request->plugin_name); + if (File::isDirectory($path)) { + if ($request->is_enabled === 1) { + if (!in_array($request->plugin_name, $pluginArray)) { + $pluginArray[] = $request->plugin_name; + } + $pluginStr = implode(',', $pluginArray); + } else if ($request->is_enabled === 0) { + $key = array_search($request->plugin_name, $pluginArray); + if ($key !== false) { + unset($pluginArray[$key]); + } + if ($request->plugin_name == 'Vehicles') { + foreach ($item_sub_plugin as $key_value) { + $key = array_search($key_value, $pluginArray); + if (!empty($key)) { + unset($pluginArray[$key]); + } + } + } + if ($request->plugin_name == 'VehicleRentals') { + foreach ($item_sub_plugin as $key_value) { + $key = array_search($key_value, $pluginArray); + if (!empty($key)) { + unset($pluginArray[$key]); + } + } + } + $pluginStr = implode(',', $pluginArray); + } + try { + $setting->update(['value' => $pluginStr]); + Cache::forget('settings_data'); + $dest_file = base_path('public/api/assets/js/plugins.js'); + if (File::exists($dest_file)) { + File::delete($dest_file); + } + return response()->json(['Success' => 'Setting has been updated'], 200); + } catch (\Exception $e) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Setting could not be updated. Please, try again.'); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Setting could not be updated. Please, try again.'); + } + + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Setting could not be updated. Please, try again.'); + } + } + +} diff --git a/app/Http/Controllers/Admin/AdminStatesController.php b/app/Http/Controllers/Admin/AdminStatesController.php new file mode 100644 index 0000000..7bde713 --- /dev/null +++ b/app/Http/Controllers/Admin/AdminStatesController.php @@ -0,0 +1,208 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Http\Controllers\Admin; + +use Illuminate\Http\Request; + + +use App\Http\Controllers\Controller; +use App\State; + +use JWTAuth; +use Validator; +use App\Transformers\StateTransformer; +use DB; + +/** + * States resource representation. + ** @Resource("Admin/AdminStates") + */ +class AdminStatesController extends Controller +{ + /** + * AdminStatesController constructor. + */ + public function __construct() + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth'); + // Check the logged user role. + $this->middleware('role'); + } + + /** + * Show all states + * Get a JSON representation of all the states. + * + * @Get("/states?filter={filter}&sort={sort}&sortby={sortby}&q={q}") + * @Parameters({ + * @Parameter("filter", type="integer", required=false, description="Filter the states list by type.", default=null), + * @Parameter("sort", type="string", required=false, description="Sort the states list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort states by Ascending / Descending Order.", default=null), + * @Parameter("q", type="string", required=false, description="Search states.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1) + * }) + */ + public function index(Request $request) + { + $states = State::select(DB::raw('states.*')) + ->leftJoin(DB::raw('(select id,name as country_name from countries) as countries'), 'countries.id', '=', 'states.country_id') + ->filterByRequest($request) + ->paginate(config('constants.ConstPageLimit')); + return $this->response->paginator($states, (new StateTransformer)->setDefaultIncludes(['Country'])); + } + + /** + * Store a new state. + * Store a new state with a `name`, `country_id`. + * @Post("/states") + * @Transaction({ + * @Request({"name": "Tamilnadu", "country_id": 1}), + * @Response(200, body={"success": "Record has been added."}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {"name": {"validation.required"}}, "status_code": 422}) + * }) + */ + public function store(Request $request) + { + $state_data = $request->only('name', 'country_id'); + $validator = Validator::make($state_data, State::GetValidationRule(), State::GetValidationMessage()); + if ($validator->passes()) { + $state_data['is_active'] = true; + $state = State::create($state_data); + if ($state) { + return response()->json(['Success' => 'State has been added'], 200); + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('State could not be updated. Please, try again.'); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('State could not be updated. Please, try again.', $validator->errors()); + } + } + + /** + * Edit the specified state. + * Edit the state with a `id`. + * @Get("/states/{id}/edit") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"id": 1, "name": "Tamilnadu", "country_id": 1, "is_active": 1, "Country": {"id": 1, "name": "India", "iso2": "IN", "iso3": "IND", "is_active": 1}}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function edit($id) + { + $state = State::with('Country')->find($id); + if (!$state) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($state, (new StateTransformer)->setDefaultIncludes(['Country'])); + } + + /** + * Update the specified state + * Update the state with a `id`. + * @Put("/states/{id}") + * @Transaction({ + * @Request({"id": 1, "name": "Tamilnadu", "country_id": 1}), + * @Response(200, body={"success": "Record has been updated."}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {}, "status_code": 422}) + * }) + */ + public function update(Request $request, $id) + { + $state_data = $request->only('id', 'name', 'country_id', 'is_active'); + $validator = Validator::make($state_data, State::GetValidationRule(), State::GetValidationMessage()); + $state = false; + if ($request->has('id')) { + $state = State::find($id); + $state = ($request->id != $id) ? false : $state; + } + if ($validator->passes() && $state) { + try { + $state->update($state_data); + return response()->json(['Success' => 'State has been updated'], 200); + } catch (\Exception $e) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('State could not be updated. Please, try again.'); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('State could not be updated. Please, try again.', $validator->errors()); + } + } + + /** + * Delete the specified state + * Delete the state with a `id`. + * @Delete("/states/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"success": "Record Deleted."}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function destroy($id) + { + $state = State::find($id); + if (!$state) { + return $this->response->errorNotFound("Invalid Request"); + } else { + $state->delete(); + } + return response()->json(['Success' => 'State deleted'], 200); + } + /** + * Deactivate the state. + * @Put("/states/{id}/deactive") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"success": "Record has been deactivated!."}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}), + * }) + */ + public function deactive(Request $request, $id) + { + $state = State::find($id); + if (!$state) { + return $this->response->errorNotFound("Invalid Request"); + } else { + $state_data['is_active'] = false; + if ($state->update($state_data)) { + return response()->json(['Success' => 'Record has been deactivated!'], 200); + } + } + } + + /** + * Activate the state. + * @Put("/states/{id}/active") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"success": "Record has been activated!."}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}), + * }) + */ + public function active(Request $request, $id) + { + $state = State::find($id); + if (!$state) { + return $this->response->errorNotFound("Invalid Request"); + } else { + $state_data['is_active'] = true; + if ($state->update($state_data)) { + return response()->json(['Success' => 'Record has been activated!'], 200); + } + } + } +} diff --git a/app/Http/Controllers/Admin/AdminTransactionTypesController.php b/app/Http/Controllers/Admin/AdminTransactionTypesController.php new file mode 100644 index 0000000..97fb1b6 --- /dev/null +++ b/app/Http/Controllers/Admin/AdminTransactionTypesController.php @@ -0,0 +1,129 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Http\Controllers\Admin; + +use Illuminate\Http\Request; + +use App\Http\Controllers\Controller; +use JWTAuth; +use Validator; +use App\Transformers\TransactionTypeTransformer; +use App\TransactionType; + +/** + * TransactionTypes resource representation. + * @Resource("Admin/AdminTransactionTypes") + */ +class AdminTransactionTypesController extends Controller +{ + /** + * AdminTransactionTypesController constructor. + */ + public function __construct() + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth'); + // Check the logged user role. + $this->middleware('role'); + } + + /** + * Show all transaction types. + * Get a JSON representation of all the transaction types. + * + * @Get("/transaction_types?sort={sort}&sortby={sortby}&page={page}") + * @Parameters({ + * @Parameter("sort", type="string", required=false, description="Sort the transaction types list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort transaction types by Ascending / Descending Order.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1) + * }) + */ + public function index(Request $request) + { + $transaction_types = TransactionType::filterByRequest($request)->paginate(config('constants.ConstPageLimit')); + return $this->response->paginator($transaction_types, (new TransactionTypeTransformer)); + } + + /** + * Show the transaction type. + * Show the transaction type with a `id`. + * @Get("/transaction_types/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"id": 1, "name": "XXXX", "is_credit": 1, "message": "XXXXXX"}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function show($id) + { + $transaction_types = TransactionType::find($id); + if (!$transaction_types) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($transaction_types, (new TransactionTypeTransformer)); + } + + /** + * Edit the specified transaction type. + * Edit the transaction type with a `id`. + * @Get("/transaction_types/{id}/edit") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"id": 1, "message": "XXXXX"}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + + public function edit($id) + { + $transaction_type = TransactionType::find($id); + if (!$transaction_type) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($transaction_type, (new TransactionTypeTransformer)); + } + + /** + * Update the specified transaction type. + * Update the transaction type with a `id`. + * @Put("/transaction_types/{id}") + * @Transaction({ + * @Request({"id": 1, "message": "XXXXX"}), + * @Response(200, body={"success": "Record has been updated."}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {}, "status_code": 422}) + * }) + */ + public function update(Request $request, $id) + { + $transaction_type_data = $request->only('message', 'name', 'is_credit'); + $validator = Validator::make($transaction_type_data, TransactionType::GetValidationRule(), TransactionType::GetValidationMessage()); + $transaction_type = false; + if ($request->has('id')) { + $transaction_type = TransactionType::find($id); + $transaction_type = ($request->id != $id) ? false : $transaction_type; + } + if ($validator->passes() && $transaction_type) { + try { + TransactionType::where('id', '=', $id)->update($transaction_type_data); + return response()->json(['Success' => 'Transaction Type has been updated'], 200); + } catch (\Exception $e) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Transaction Type could not be updated. Please, try again.'); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Transaction Type could not be updated. Please, try again.', $validator->errors()); + } + } +} diff --git a/app/Http/Controllers/Admin/AdminTransactionsController.php b/app/Http/Controllers/Admin/AdminTransactionsController.php new file mode 100644 index 0000000..843533f --- /dev/null +++ b/app/Http/Controllers/Admin/AdminTransactionsController.php @@ -0,0 +1,76 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Http\Controllers\Admin; + +use Illuminate\Http\Request; + +use App\Http\Controllers\Controller; +use JWTAuth; +use Validator; +use App\Transformers\TransactionTransformer; +use App\Transaction; +use App\Services\TransactionService; +use DB; + +/** + * Transactions resource representation. + * @Resource("Admin/AdminTransactions") + */ +class AdminTransactionsController extends Controller +{ + /** + * AdminTransactionsController constructor. + */ + public function __construct() + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth'); + // Check the logged user role. + $this->middleware('role'); + $this->setTransactionService(); + } + + public function setTransactionService() + { + $this->transactionService = new TransactionService(); + } + + /** + * Show all transaction types. + * Get a JSON representation of all the transaction types. + * + * @Get("/transactions?filter={filter}&sort={sort}&sortby={sortby}&page={q}&page={q}") + * @Parameters({ + * @Parameter("sort", type="string", required=false, description="Sort the transactions list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort transactions by Ascending / Descending Order.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1), + * @Parameter("filter", type="integer", required=false, description="Filter transactions list by status.", default=null), + * @Parameter("q", type="string", required=false, description="Search transactions.", default=null) + * }) + */ + public function index(Request $request) + { + $transactions = Transaction::select(DB::raw('transactions.*')) + ->leftJoin(DB::raw('(select id,username from users) as from_user'), 'from_user.id', '=', 'transactions.user_id') + ->leftJoin(DB::raw('(select id,username from users) as to_user'), 'to_user.id', '=', 'transactions.receiver_user_id') + ->leftJoin(DB::raw('(select id,message from transaction_types) as transaction_type'), 'transaction_type.id', '=', 'transactions.transaction_type_id') + ->filterByRequest($request) + ->paginate(config('constants.ConstPageLimit')); + $converted_transactions = $this->transactionService->transactionDescription($transactions); + $transaction_details = $this->response->paginator($converted_transactions, (new TransactionTransformer)->setDefaultIncludes(['from_user', 'to_user', 'transaction_type'])); + return $transaction_details; + } +} diff --git a/app/Http/Controllers/Admin/AdminUserLoginsController.php b/app/Http/Controllers/Admin/AdminUserLoginsController.php new file mode 100644 index 0000000..5eb96ec --- /dev/null +++ b/app/Http/Controllers/Admin/AdminUserLoginsController.php @@ -0,0 +1,121 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Http\Controllers\Admin; + +use Illuminate\Http\Request; + + +use App\Http\Controllers\Controller; + +use App\UserLogin; + +use JWTAuth; +use Validator; +use App\Transformers\UserLoginTransformer; +use App\Services\UserLoginService; +use DB; + +/** + * UserLogins resource representation. + * @Resource("Admin/AdminUserLogins") + */ +class AdminUserLoginsController extends Controller +{ + /** + * @var + */ + protected $UserLoginService; + + /** + * AdminUserLoginsController constructor. + */ + public function __construct() + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth'); + // Check the logged user role. + $this->middleware('role'); + $this->setUserLoginService(); + } + + public function setUserLoginService() + { + $this->UserLoginService = new UserLoginService(); + } + + /** + * Show all user logins. + * Get a JSON representation of all the user logins. + * + * @Get("/user_logins?sort={sort}&sortby={sortby}") + * @Parameters({ + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1), + * @Parameter("sort", type="string", required=false, description="Sort the user logins list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort user logins by Ascending / Descending Order.", default=null), + * }) + */ + public function index(Request $request) + { + $user_logins = UserLogin::select(DB::raw('user_logins.*')) + ->leftJoin(DB::raw('(select id,username from users) as user'), 'user.id', '=', 'user_logins.user_id') + ->leftJoin(DB::raw('(select id,ip from ips) as user_login_ip'), 'user_login_ip.id', '=', 'user_logins.user_login_ip_id') + ->filterByRequest($request) + ->paginate(config('constants.ConstPageLimit')); + return $this->response->paginator($user_logins, (new UserLoginTransformer)->setDefaultIncludes(['user_login_ip', 'user', 'role'])); + } + + /** + * Show the specified user login. + * Show the user login with a `id`. + * @Get("/user_login/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"id": 1, "created_at": "2016-04-15 11:07:42", "user_id": 1, "user_login_ip_id": 4, "role_id": 1, "user_agent": "XXX", "User": {}, "Role": {}}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function show($id) + { + $user_login = UserLogin::with('user_login_ip', 'user', 'role')->find($id); + if (!$user_login) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($user_login, (new UserLoginTransformer)->setDefaultIncludes(['user_login_ip', 'user', 'role'])); + } + + /** + * Delete the specified user logins. + * Delete the user login with a `id`. + * @Delete("/user_login/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"success": "Record Deleted."}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function destroy($id) + { + $user_login = UserLogin::find($id); + if (!$user_login) { + return $this->response->errorNotFound("Invalid Request"); + } else { + $user_login->delete(); + // decrement user login count by 1 in users + $this->UserLoginService->decreaseUserLoginCount($user_login->user_id); + } + return response()->json(['Success' => 'UserLogin deleted'], 200); + } +} \ No newline at end of file diff --git a/app/Http/Controllers/Admin/AdminUsersController.php b/app/Http/Controllers/Admin/AdminUsersController.php new file mode 100644 index 0000000..93fe66f --- /dev/null +++ b/app/Http/Controllers/Admin/AdminUsersController.php @@ -0,0 +1,314 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Http\Controllers\Admin; + +use Illuminate\Http\Request; + +use App\Http\Controllers\Controller; +use App\User; +use JWTAuth; +use Validator; +use App\Transformers\UserTransformer; +use App\Transformers\UserSimpleTransformer; +use Illuminate\Support\Facades\Hash; +use App\Services\UserService; +use App\Services\IpService; +use DB; + +/** + * Users resource representation. + * @Resource("Admin/AdminUsers") + */ +class AdminUsersController extends Controller +{ + /** + * @var UserService + */ + protected $user_service; + /** + * @var IpService + */ + protected $IpService; + + /** + * AdminUsersController constructor. + */ + public function __construct(UserService $user_Service) + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth'); + // Check the logged user role. + $this->middleware('role'); + $this->UserService = $user_Service; + $this->setIpService(); + } + + public function setIpService() + { + $this->IpService = new IpService(); + } + + /** + * Show all users + * Get a JSON representation of all the users. + * + * @Get("/users?filter={filter}&sort={sort}&sortby={sortby}&type={type}&field={field}&q={q}") + * @Parameters({ + * @Parameter("filter", type="integer", required=false, description="Filter the users list by type.", default=null), + * @Parameter("sort", type="string", required=false, description="Sort the users list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort users by Ascending / Descending Order.", default=null), + * @Parameter("type", type="string", required=false, description="Display users By Listing Type.", default=null), + * @Parameter("field", type="string", required=false, description="Give Whatever Fields Needed by Comma Seperator.", default=null), + * @Parameter("q", type="string", required=false, description="Search users.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1) + * }) + */ + public function index(Request $request) + { + if($request->has('limit') && $request->input('limit') == 'all'){ + $users_count = User::where(['is_active' => true, 'is_email_confirmed' => true, 'is_agree_terms_conditions' => true ])->count(); + $users = User::where(['is_active' => true, 'is_email_confirmed' => true, 'is_agree_terms_conditions' => true ])->select('id', 'username')->paginate($users_count); + return $this->response->paginator($users, new UserSimpleTransformer); + } else if($request->has('limit') && $request->input('limit') != 'all'){ + $users_count = $request->input('limit'); + $users = User::select(DB::raw('users.*')) + ->leftJoin(DB::raw('(select id,ip from ips) as last_login_ip'), 'last_login_ip.id', '=', 'users.last_login_ip_id') + ->leftJoin(DB::raw('(select id,ip from ips) as register_ip'), 'register_ip.id', '=', 'users.register_ip_id') + ->filterByRequest($request)->paginate($users_count); + return $this->response->paginator($users, (new UserTransformer)->setDefaultIncludes(['last_login_ip', 'register_ip'])); + } else{ + $users = User::select(DB::raw('users.*')) + ->leftJoin(DB::raw('(select id,ip from ips) as last_login_ip'), 'last_login_ip.id', '=', 'users.last_login_ip_id') + ->leftJoin(DB::raw('(select id,ip from ips) as register_ip'), 'register_ip.id', '=', 'users.register_ip_id') + ->filterByRequest($request) + ->paginate(config('constants.ConstPageLimit')); + return $this->response->paginator($users, (new UserTransformer)->setDefaultIncludes(['last_login_ip', 'register_ip'])); + } + } + + /** + * Store a new user. + * Store a new city with a `role_id`, `username`, `email`, `password`, `is_active` and `is_email_confirmed`. + * @Post("/users") + * @Transaction({ + * @Request({"role_id": 1, "name": "AHSAN", "email": "guest@gmail.com", "password": "XXXXXX", "is_active": 1, "is_email_confirmed": 1 }), + * @Response(200, body={"success": "Record has been added."}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {"name": {}}, "status_code": 422}) + * }) + */ + public function store(Request $request) + { + $user_data = $request->only('username', 'email', 'password', 'role_id', 'is_active', 'is_email_confirmed'); + $validator = Validator::make($user_data, User::GetValidationRule(), User::GetEditValidationRule(), User::GetValidationMessage()); + if ($validator->passes()) { + if ($request->has('password')) { + $user_data['password'] = Hash::make($request->password); + } + $user_data['is_agree_terms_conditions'] = true; + $user_data['register_ip_id'] = $this->IpService->getIpId($request->ip()); + $user = User::create($user_data); + if ($user) { + $this->UserService->sendAdminAddUserMail($user->username, $request->password, $user->email); + return response()->json(['Success' => 'User has been added'], 200); + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('User could not be updated. Please, try again.'); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('User could not be updated. Please, try again.', $validator->errors()); + } + } + + /** + * Edit the specified user. + * Edit the user with a `id`. + * @Get("/users/{id}/edit") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"id": 1, "role_id": 1, "name": "AHSAN", "email": "guest@gmail.com", "password": "XXXXXX", "is_active": 1, "is_email_confirmed": 1}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function edit($id) + { + $user = User::find($id); + if (!$user) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($user, new UserTransformer); + } + + /** + * Show the specified user. + * Show the user with a `id`. + * @Get("/users/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"id": 1, "role_id": 1, "name": "AHSAN", "email": "guest@gmail.com", "password": "XXXXXX", "is_active": 1, "is_email_confirmed": 1}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function show($id) + { + $user = User::with('last_login_ip', 'register_ip', 'attachments')->find($id); + if (!$user) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($user, (new UserTransformer)->setDefaultIncludes(['last_login_ip', 'register_ip', 'attachmentable'])); + } + + /** + * Update User + * Update user with a `id`. + * @Put("/users?id=1") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"success": "Record has been updated."}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {}, "status_code": 422}) + * }) + */ + public function update(Request $request, $id) + { + $user_data = $request->only('username', 'email', 'role_id', 'is_active', 'is_email_confirmed'); + $validator = Validator::make($user_data, array_merge(User::GetValidationRule(), User::GetEditValidationRule()), User::GetValidationMessage()); + $user = false; + if ($request->has('id')) { + $user = User::find($id); + $user = ($request->id != $id) ? false : $user; + $user_is_active = $user->is_active; + } + $check_user = User::where('email', $request->email) + ->where('id', '!=', $id) + ->first(); + if ($check_user) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('User could not be updated. Email already exists.'); + } + if ($validator->passes() && $user) { + try { + $user->update($user_data); + if ($user_is_active !== $request->is_active && $request->is_active === 1) { + // send mail for active + $this->UserService->sendStatusMail($user->username, $user->email, 'Admin User Active'); + } else if ($user_is_active !== $request->is_active && $request->is_active === 0) { + // send mail for deactive + $this->UserService->sendStatusMail($user->username, $user->email, 'Admin User Deactivate'); + } + if($user->user_login_count === 0){ + $this->UserService->sendWelcomeMail($user->id, $user->email, $user->username); + } + return response()->json(['Success' => 'User has been updated'], 200); + } catch (\Exception $e) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('User could not be updated. Please, try again.'); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('User could not be updated. Please, try again.', $validator->errors()); + } + } + + /** + * Delete the specified user. + * Delete the user with a `id`. + * @Delete("/users/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"success": "Record Deleted."}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function destroy($id) + { + $user = User::find($id); + if (!$user) { + return $this->response->errorNotFound("Invalid Request"); + } else { + if ($user->delete()) { + $this->UserService->sendStatusMail($user->username, $user->email, 'Admin User Delete'); + return response()->json(['Success' => 'User deleted'], 200); + } + } + } + + /** + * Change Password. + * @Put("/users/{id}/change_password") + * @Transaction({ + * @Request({"id": 1, "New Password": "XXXXXX", "Confirm Password": "XXXXXX"}), + * @Response(200, body={"success": "Password Changed Successfully."}), + * @Response(422, body={"message": "Could not change password.","errors": {},"status_code": 422}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}), + * }) + */ + public function changePassword(Request $request, $id) + { + $user = User::find($id); + if (!$user) { + return $this->response->errorNotFound("Invalid Request"); + } + $user_data = $request->only('password', 'confirm_password'); + $validator = Validator::make($user_data, User::GetValidationRule()); + if ($validator->passes()) { + $user->password = Hash::make($request->password); + if ($user->save()) { + return response()->json(['Success' => 'Password Changed Successfully.'], 200); + } + } else { + throw new \Dingo\Api\Exception\UpdateResourceFailedException('Could not change password.', $validator->errors()); + } + } + + /** + * Deactivate the user. + * @Put("/users/{id}/deactive") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"success": "Record has been deactivated!."}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}), + * }) + */ + public function deactive(Request $request, $id) + { + $user = User::find($id); + if (!$user) { + return $this->response->errorNotFound("Invalid Request"); + } else { + $user_data['is_active'] = false; + if ($user->update($user_data)) { + return response()->json(['Success' => 'Record has been deactivated!'], 200); + } + } + } + + /** + * Activate the user. + * @Put("/users/{id}/active") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"success": "Record has been activated!."}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}), + * }) + */ + public function active(Request $request, $id) + { + $user = User::find($id); + if (!$user) { + return $this->response->errorNotFound("Invalid Request"); + } else { + $user_data['is_active'] = true; + if ($user->update($user_data)) { + return response()->json(['Success' => 'Record has been activated!'], 200); + } + } + } +} diff --git a/app/Http/Controllers/Admin/AdminWalletTransactionLogsController.php b/app/Http/Controllers/Admin/AdminWalletTransactionLogsController.php new file mode 100644 index 0000000..085ed47 --- /dev/null +++ b/app/Http/Controllers/Admin/AdminWalletTransactionLogsController.php @@ -0,0 +1,79 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Http\Controllers\Admin; + +use Illuminate\Http\Request; + +use App\Http\Controllers\Controller; +use App\WalletTransactionLog; +use JWTAuth; +use Validator; +use App\Transformers\WalletTransactionLogTransformer; + +/** + * Money Transfer Accounts resource representation. + * @Resource("Wallets") + */ +class AdminWalletTransactionLogsController extends Controller +{ + /** + * WalletsController constructor. + */ + public function __construct() + { + // Check the logged user authentication. + $this->middleware('jwt.auth'); + // Check the logged user role. + $this->middleware('role'); + } + + /** + * Show all wallet transaction logs. + * Get a JSON representation of all the wallet transaction logs. + * + * @Get("/wallet_transaction_logs?sort={sort}&sortby={sortby}&page={page}") + * @Parameters({ + * @Parameter("sort", type="string", required=false, description="Sort the wallet transaction log list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort wallet transaction log by Ascending / Descending Order.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1), + * }) + */ + + public function index(Request $request) + { + $wallet_transaction_logs = WalletTransactionLog::filterByRequest($request)->paginate(config('constants.ConstPageLimit')); + return $this->response->paginator($wallet_transaction_logs, (new WalletTransactionLogTransformer)); + } + + /** + * Show the wallet transaction log. + * Show the wallet transaction log with a `id`. + * @Get("/wallet_transaction_logs/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"id": 1, "created_at": "2016-05-19 00:00:00", "amount": 500, "wallet_transaction_logable_type": "Wallet", "wallet_transaction_logable_id": 1, "status": "Capture", "payment_type": "Success"}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function show($id) + { + $wallet_transaction_log = WalletTransactionLog::find($id); + if (!$wallet_transaction_log) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($wallet_transaction_log, (new WalletTransactionLogTransformer)); + } +} \ No newline at end of file diff --git a/app/Http/Controllers/AssetsController.php b/app/Http/Controllers/AssetsController.php new file mode 100644 index 0000000..e537b8e --- /dev/null +++ b/app/Http/Controllers/AssetsController.php @@ -0,0 +1,88 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Http\Controllers; + +use Illuminate\Http\Request; +use File; + +class AssetsController extends Controller +{ + /** Minify all js files and copy plugin template files to public folder + * @get("assets/js/plugins.js") + * @Transaction({ + * @Response(200, body={}), + * @Response(401, body={"message": "Error writing to file", "status_code": 401}) + * }) + */ + public function createJsTplFiles() + { + $dest_path = base_path('public/api/assets/js/'); + if (!File::isDirectory($dest_path)) { + File::makeDirectory($dest_path, 0775, true); + } + $enabled_plugins = enabled_plugins(); + $minifiedCode = ''; + foreach($enabled_plugins as $plugins){ + $plugins = trim($plugins); + if(empty($plugins)) + continue; + //Load js files to public/api/js/plugins.js as minified code + $moduleFileList = glob(base_path("client/src/app/Plugins/$plugins/*.module.js")); + $jsFileList = glob(base_path("client/src/app/Plugins/$plugins/*.js")); + foreach($moduleFileList as $file){ + if(array_search($file, $jsFileList)){ + unset($jsFileList[array_search($file, $jsFileList)]); + } + } + $jsFileList = array_merge($moduleFileList, $jsFileList); + foreach($jsFileList as $jsfiles) { + $contents = File::get($jsfiles); + if(env('APP_DEBUG') == false) { + $contents = \JShrink\Minifier::minify($contents); + } + $minifiedCode .= $contents; + } + if(env('APP_DEBUG') == false) { + $minifiedCode .= \JShrink\Minifier::minify("angular.module('BookorRent').requires.push('BookorRent.".$plugins."');"); + }else{ + $minifiedCode .= "angular.module('BookorRent').requires.push('BookorRent.".$plugins."');"; + } + //Copy Template files from client/src/app/plugins to public/client/src/app/plugins + foreach(glob(base_path("client/src/app/Plugins/$plugins/*.tpl.html")) as $tpl_file) { + $destination = base_path("public/Plugins/$plugins/"); + if (!File::isDirectory($destination)) { + File::makeDirectory($destination, 0777, true); + } + $tpl_name = File::basename($tpl_file); + $dest_file = $destination.$tpl_name; + if(File::exists($dest_file)) { + @chmod($dest_file, 0777); + File::delete($dest_file); + } + File::copy($tpl_file, $dest_file); + @chmod($dest_file, 0777); + } + } + $bytes_written = File::put($dest_path.'plugins.js', $minifiedCode); + @chmod($dest_path.'plugins.js', 0777); + if ($bytes_written === false) + { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Error writing to file.'); + }else { + return redirect(asset('api/assets/js/plugins.js')); + } + } +} diff --git a/app/Http/Controllers/CitiesController.php b/app/Http/Controllers/CitiesController.php new file mode 100644 index 0000000..26adbf9 --- /dev/null +++ b/app/Http/Controllers/CitiesController.php @@ -0,0 +1,43 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Http\Controllers; + +use Illuminate\Http\Request; +use App\City; +use JWTAuth; +use App\Transformers\CityTransformer; + +/** + * Cities resource representation. + * @Resource("Cities") + */ +class CitiesController extends Controller +{ + /** + * Show all cities + * Get a JSON representation of all the cities. + * + * @Get("/cities?sort={sort}") + * @Parameters({ + * @Parameter("sort", type="string", required=false, description="Sort the cities list by sort ley.", default=null), + * }) + */ + public function index(Request $request) + { + $cities = City::filterByRequest($request)->get(); + return $this->response->collection($cities, new CityTransformer); + } +} diff --git a/app/Http/Controllers/Controller.php b/app/Http/Controllers/Controller.php new file mode 100644 index 0000000..27585cd --- /dev/null +++ b/app/Http/Controllers/Controller.php @@ -0,0 +1,25 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Http\Controllers; + +use Laravel\Lumen\Routing\Controller as BaseController; +use Dingo\Api\Routing\Helpers; + +class Controller extends BaseController +{ + // + use Helpers; +} diff --git a/app/Http/Controllers/CountriesController.php b/app/Http/Controllers/CountriesController.php new file mode 100644 index 0000000..1826761 --- /dev/null +++ b/app/Http/Controllers/CountriesController.php @@ -0,0 +1,54 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Http\Controllers; + +use Illuminate\Http\Request; + +use App\Country; +use App\Transformers\CountryTransformer; + +/** + * Countries resource representation. + * @Resource("Countries") + */ +class CountriesController extends Controller +{ + /** + * CountriesController constructor. + */ + public function __construct() + { + // Apply the jwt.auth middleware to all methods in this controller + // except for the authenticate method. We don't want to prevent + // the user from retrieving their token if they don't already have it + // $this->middleware('jwt.auth'); + } + + /** + * Show all countries + * Get a JSON representation of all the countries. + * @Get("/countries?sort={sort}") + * @Parameters({ + * @Parameter("sort", type="string", required=false, description="Sort the countries list by sort ley.", default=null), + * }) + */ + public function index(Request $request) + { + $countries = Country::filterByRequest($request)->get(); + return $this->response->collection($countries, new CountryTransformer); + } + +} diff --git a/app/Http/Controllers/CurrenciesController.php b/app/Http/Controllers/CurrenciesController.php new file mode 100644 index 0000000..7a3d0a9 --- /dev/null +++ b/app/Http/Controllers/CurrenciesController.php @@ -0,0 +1,46 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Http\Controllers; + +use Illuminate\Http\Request; +use App\Currency; +use App\Transformers\CurrencyTransformer; + +/** + * Currencies resource representation. + * @Resource("Currencies") + */ +class CurrenciesController extends Controller +{ + /** + * Show all currencies. + * Get a JSON representation of all the currencies. + * + * @Get("/currencies?filter={filter}&sort={sort}&sortby={sortby}&type={type}&field={field}&q={q}") + * @Parameters({ + * @Parameter("filter", type="integer", required=false, description="Filter the currencies list by type.", default=null), + * @Parameter("sort", type="string", required=false, description="Sort the currencies list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort currencies by Ascending / Descending Order.", default=null), + * @Parameter("q", type="string", required=false, description="Search currencies.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1) + * }) + */ + public function index(Request $request) + { + $currencies = Currency::filterByRequest($request)->get(); + return $this->response->collection($currencies, new CurrencyTransformer); + } +} diff --git a/app/Http/Controllers/ImagesController.php b/app/Http/Controllers/ImagesController.php new file mode 100644 index 0000000..baacb3e --- /dev/null +++ b/app/Http/Controllers/ImagesController.php @@ -0,0 +1,62 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Http\Controllers; + +use Illuminate\Http\Request; +use App\Attachment; +use Image; +use File; + +class ImagesController extends Controller +{ + + /** + * Thumb size based image create + * @Get("/img/{size}/{model}/{file}") + * @Transaction({ + * @Request({"size": "small", "model": "user", "filename": "11.6512bd43d9caa6e02c990b0a82652dca.jpg"}), + * @Response(301), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function create($size, $model, $filename) + { + $file_extract = explode('.', $filename); + if(!empty($file_extract[0])){ + $attachment = Attachment::where('id', '=', $file_extract[0])->first(); + if ($attachment) { + if (md5($file_extract[0] . config('constants.Security.salt') . $attachment->filename) == $file_extract[1]) { + $source_path = storage_path($attachment->dir . $attachment->filename); + $dest_path = base_path('public/api/img/' . $size . '/' . $model . '/'); + if (!File::isDirectory($dest_path)) { + File::makeDirectory($dest_path, 0777, true); + } + $img = Image::make($source_path); + $img->resize(config('constants.thumb.'.$model.'.' . $size . '.width'), config('constants.thumb.'.$model.'.' . $size . '.height')); + $img->save($dest_path . $filename); + @chmod($dest_path . $filename, 0777); + return redirect(asset('api/img/' . $size . '/' . $model . '/' . $filename)); + }else { + return $this->response->errorNotFound("Invalid Request"); + } + }else { + return $this->response->errorNotFound("Invalid Request"); + } + }else { + return $this->response->errorNotFound("Invalid Request"); + } + } +} diff --git a/app/Http/Controllers/LanguagesController.php b/app/Http/Controllers/LanguagesController.php new file mode 100644 index 0000000..7cd6828 --- /dev/null +++ b/app/Http/Controllers/LanguagesController.php @@ -0,0 +1,41 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Http\Controllers; + +use Illuminate\Http\Request; +use App\Language; +use App\Transformers\LanguageTransformer; + +/** + * Contacts resource representation. + * @Resource("Languages") + */ +class LanguagesController extends Controller +{ + /** + * Show all languages + * Get a JSON representation of all the languages. + * @Get("/languages?sort={sort}") + * @Parameters({ + * @Parameter("sort", type="string", required=false, description="Sort the language list by sort ley.", default=null), + * }) + */ + public function index(Request $request) + { + $languages = Language::filterByRequest($request)->get(); + return $this->response->collection($languages, new LanguageTransformer); + } +} \ No newline at end of file diff --git a/app/Http/Controllers/MessagesController.php b/app/Http/Controllers/MessagesController.php new file mode 100644 index 0000000..a9591bc --- /dev/null +++ b/app/Http/Controllers/MessagesController.php @@ -0,0 +1,352 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Http\Controllers; + +use Carbon; +use Illuminate\Http\Request; +use JWTAuth; +use App\Message; +use App\MessageContent; +use Validator; +use App\Transformers\MessageTransformer; +use App\Services\MessageService; + +/** + * Messages resource representation. + * @Resource("Messages") + */ +class MessagesController extends Controller +{ + /** + * MessagesController constructor. + * @param MessageService $msgService + */ + public function __construct() + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth'); + $this->setMessageService(); + if (isPluginEnabled('VehicleDisputes')) { + $this->setVehicleDisputeService(); + } + } + + /** + * set MessageService + */ + public function setMessageService() + { + $this->msgService = new MessageService(); + } + + /** + * set VehicleDisputeService + */ + public function setVehicleDisputeService() + { + if (isPluginEnabled('VehicleDisputes')) { + $this->vehicleDisputeService = new \Plugins\VehicleDisputes\Services\VehicleDisputeService(); + } + } + + /** + * Show all Messages + * Get a JSON representation of all the Messages. + * + * @Get("/admin/messages?sort={sort}&sortby={sortby}&page={page}&q={q}") + * @Parameters({ + * @Parameter("sort", type="string", required=false, description="Sort the messages list by sort key.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort messages by Ascending / Descending Order.", default=null), + * @Parameter("q", type="string", required=false, description="Search messages.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1), + * @Parameter("filter", type="string", required=false, description="Filter messages.", default=null) + * }) + */ + public function inbox(Request $request) + { + $enabledIncludes = array('from_user', 'to_user', 'message_content', 'item_user_status', 'dispute_status'); + $user = $this->auth->user(); + $data = ['to_user_id' => $user->id, 'message_folder_id' => config('constants.ConstMessageFolder.Inbox')]; + $messages = Message::with($enabledIncludes)->where($data)->filterByRequest($request)->paginate(config('constants.ConstPageLimit')); + $enabledIncludes = array_merge($enabledIncludes, array('messageable')); + return $this->response->paginator($messages, (new MessageTransformer)->setDefaultIncludes($enabledIncludes)); + } + + /** + * Show all sent Messages + * Get a JSON representation of all the sent Messages. + * + * @Get("/admin/sentMessages?sort={sort}&sortby={sortby}&page={page}&q={q}") + * @Parameters({ + * @Parameter("sort", type="string", required=false, description="Sort the sent messages list by sort key.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort sent messages by Ascending / Descending Order.", default=null), + * @Parameter("q", type="string", required=false, description="Search sent messages.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1), + * @Parameter("filter", type="string", required=false, description="Filter sent messages.", default=null) + * }) + */ + public function sentMessage(Request $request) + { + $enabledIncludes = array('from_user', 'to_user', 'message_content', 'item_user_status', 'dispute_status'); + $user = $this->auth->user(); + $data = ['to_user_id' => $user->id, 'message_folder_id' => config('constants.ConstMessageFolder.SentMail')]; + $messages = Message::with($enabledIncludes)->where($data)->filterByRequest($request)->paginate(config('constants.ConstPageLimit')); + $enabledIncludes = array_merge($enabledIncludes, array('messageable')); + return $this->response->paginator($messages, (new MessageTransformer)->setDefaultIncludes($enabledIncludes)); + } + /** + * Show all starred Messages + * Get a JSON representation of all the starred Messages. + * + * @Get("/starMessages?sort={sort}&sortby={sortby}&page={page}&q={q}") + * @Parameters({ + * @Parameter("sort", type="string", required=false, description="Sort the star messages list by sort key.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort star messages by Ascending / Descending Order.", default=null), + * @Parameter("q", type="string", required=false, description="Search star messages.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1), + * @Parameter("filter", type="string", required=false, description="Filter star messages.", default=null) + * }) + */ + public function starMessage(Request $request) + { + $enabledIncludes = array('from_user', 'to_user', 'message_content', 'item_user_status', 'dispute_status'); + $user = $this->auth->user(); + $data = ['to_user_id' => $user->id, 'is_starred' => 1]; + $messages = Message::with($enabledIncludes)->where($data)->filterByRequest($request)->paginate(config('constants.ConstPageLimit')); + $enabledIncludes = array_merge($enabledIncludes, array('messageable')); + return $this->response->paginator($messages, (new MessageTransformer)->setDefaultIncludes($enabledIncludes)); + } + /** + * Get item activities + * + * @Get("/item_messages/{item_id}") + * @Transaction({ + * @Request({"item_id": 1}), + * @Response(200, body={"user_id":1,"item_id":1,"to_user_id":2,"message_content_id":1,"message_folder_id":1,"messageable_id":1,"messageable_type":"App\Model\User","is_sender":1,"is_starred":1,"is_read":1,"is_deleted":1,"is_archived":1,"is_review":1,"is_communication":0,"user":{},"item_user":{},"item":{},"message_content":{}}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function itemActivities($item_id) + { + $enabledIncludes = array('from_user', 'to_user', 'message_content', 'item_user_status', 'dispute_status'); + $item_messages = Message::with($enabledIncludes)->where('messageable_id', $item_id)->get(); + if (!$item_messages) { + return $this->response->errorNotFound('Invalid Request'); + } + $enabledIncludes = array_merge($enabledIncludes, array('messageable')); + return $this->response->Collection($item_messages, (new MessageTransformer)->setDefaultIncludes($enabledIncludes)); + } + + /** + * Get item user activities + * + * @Get("/item_user_messages/{item_user_id}") + * @Transaction({ + * @Request({"item_user_id": 1}), + * @Response(200, body={"user_id":1,"item_id":1,"to_user_id":2,"message_content_id":1,"message_folder_id":1,"messageable_id":1,"messageable_type":"App\Model\User","is_sender":1,"is_starred":1,"is_read":1,"is_deleted":1,"is_archived":1,"is_review":1,"is_communication":0,"user":{},"item_user":{},"item":{},"message_content":{}}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function bookerActivities($item_user_id) + { + $user = $this->auth->user(); + $enabledIncludes = array('user', 'message', 'item_user_status'); + (isPluginEnabled('VehicleFeedbacks')) ? $enabledIncludes[] = 'vehicle_feedback' : ''; + $vehicle_rental = \Plugins\VehicleRentals\Model\VehicleRental::with($enabledIncludes)->where('id', $item_user_id)->first(); + $messages = $this->msgService->getMessages($vehicle_rental, $user); + return response()->json(['messages' => $messages]); + } + + /** + * store messages + * + * @Get("/messages/{user_id}/user}") + * @Transaction({ + * @Request({"to_user_id": 1, "subject":"Welcome Mail", "message":"Welcome to lumen"}), + * @Response(200, body={"message":"Message Send Successfully"}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function store(Request $request) + { + $message_data = $request->only('to_user_id', 'message', 'subject'); + $validator = Validator::make($message_data, Message::GetValidationRule(), Message::GetValidationMessage()); + if ($validator->passes()) { + $user = $this->auth->user(); + //if to user and current user equal could not send message + if ($user->id == $request->to_user_id) { + return $this->response->errorNotFound("Message could not be sent"); + } + if (!$user) { + return $this->response->errorNotFound("User not found"); + } + $message_content = MessageContent::create($message_data); + if ($message_content) { + $message_array = array(); + $message_array['message_content_id'] = $message_content->id; + $message_array['user_id'] = $user->id; + $message_array['to_user_id'] = $request->to_user_id; + $message_array['message_folder_id'] = config('constants.ConstMessageFolder.Inbox'); + $this->msgService->saveMessage($message_array, $user->id, 'User'); + $message_array['user_id'] = $request->to_user_id; + $message_array['to_user_id'] = $user->id; + $message_array['message_folder_id'] = config('constants.ConstMessageFolder.SentMail'); + $this->msgService->saveMessage($message_array, $user->id, 'User'); + } + return response()->json(['Success' => 'Message has been sent'], 200); + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Message could not be added. Please, try again.', $validator->errors()); + } + } + + /** + * show the specified message. + * show the message with a `id`. + * @get("messages/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function show($id) + { + $user = $this->auth->user(); + $enabledIncludes = array('from_user', 'to_user', 'message_content', 'item_user_status', 'dispute_status'); + $message = Message::with($enabledIncludes)->find($id); + if (!$message || ($user->role_id != config('constans.ConstUserTypes.Admin') && ($user->id != $message->user_id && $user->id != $message->to_user_id))) { + return $this->response->errorNotFound("Invalid Request"); + } + $enabledIncludes = array_merge($enabledIncludes, array('messageable')); + return $this->response->item($message, (new MessageTransformer)->setDefaultIncludes($enabledIncludes)); + } + + /** + * reply messages + * + * @Get("/messages/{id}/reply}") + * @Transaction({ + * @Request({"to_user_id": 1,"message_id":"1", "subject":"Welcome Mail", "message":"Welcome to lumen"}), + * @Response(200, body={"message":"Message Send Successfully"}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function reply(Request $request) + { + $message = Message::find($request->message_id); + if (!$message) { + return $this->response->errorNotFound("Invalid request"); + } + $message_data = $request->only('message', 'subject'); + $validator = Validator::make($message_data, Message::GetValidationRule(), Message::GetValidationMessage()); + if ($validator->passes()) { + $user = $this->auth->user(); + //if to user and current user equal could not send message + if ($user->id == $request->to_user_id) { + return $this->response->errorNotFound("Message could not be sent"); + } + if (!$user) { + return $this->response->errorNotFound("User not found"); + } + $message_content = MessageContent::create($message_data); + if ($message_content) { + $message_array = array(); + $message_array['message_content_id'] = $message_content->id; + $message_array['user_id'] = $user->id; + $message_array['to_user_id'] = $request->to_user_id; + $message_array['message_folder_id'] = config('constants.ConstMessageFolder.SentMail'); + $message_array['message_id'] = $request->message_id; + $this->msgService->saveMessage($message_array); + $message_array['user_id'] = $request->to_user_id; + $message_array['to_user_id'] = $user->id; + $message_array['message_folder_id'] = config('constants.ConstMessageFolder.Inbox'); + $message_array['message_id'] = $request->message_id; + $this->msgService->saveMessage($message_array); + } + return response()->json(['Success' => 'Message has been added'], 200); + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Message could not be added. Please, try again.', $validator->errors()); + } + } + + /** + * Store private note. + * Store the private note with a `id`, `message`. + * @post("private_notes/{id}") + * @Transaction({ + * @Request({"id": 1, "message":"XXXX"}), + * @Response(200, body={"message": "Private Note has been added", "status_code": 200}), + * @Response(404, body={"message": "Private Note could not be added. Please, try again.", "status_code": 404}) + * }) + */ + public function privateNote(Request $request) + { + $user = $this->auth->user(); + $private_note_data = $request->only('message'); + $validator = Validator::make($private_note_data, Message::GetValidationRule($private_note_data), Message::GetValidationMessage($private_note_data)); + if ($validator->passes()) { + $private_note_data['subject'] = 'Private Note'; + $item_id = ''; + $vehicle_rental_id = ''; + if (isPluginEnabled('VehicleRentals') && $request->has('id')) { + $enabledIncludes = array('user'); + (isPluginEnabled('VehicleDisputes')) ? $enabledIncludes[] = 'item_user_dispute' : ''; + $vehicle_rental = \Plugins\VehicleRentals\Model\VehicleRental::with($enabledIncludes)->find($request->id); + $item_id = $vehicle_rental->item_userable_id; + $vehicle_rental_id = $vehicle_rental->id; + } + $item_user_status_id = config('constants.ConstItemUserStatus.PrivateConversation'); + if ($user->id == $vehicle_rental->user_id) { + $this->msgService->saveMessageContent($private_note_data, $item_id, $vehicle_rental_id, $vehicle_rental->user_id, $vehicle_rental->item_userable->user_id, $item_user_status_id, 'VehicleRental'); + } + if ($user->id == $vehicle_rental->item_userable->user_id) { + $this->msgService->saveMessageContent($private_note_data, $item_id, $vehicle_rental_id, $vehicle_rental->item_userable->user_id, $vehicle_rental->user_id, $item_user_status_id, 'VehicleRental'); + } + if (isPluginEnabled('VehicleDisputes')) { + if ($vehicle_rental->is_dispute) { + // update status in vehicle_rental disputes + $this->vehicleDisputeService->updateConversation($vehicle_rental, $request->message); + } + } + return response()->json(['Success' => 'Private Note has been added'], 200); + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Private Note could not be added. Please, try again.', $validator->errors()); + } + } + + /** + * update message as starred message. + * update the message with a `id`. + * @put("messages/{id}") + * @Transaction({ + * @Request({"id": 1,"stared":0}), + * @Response(200, body={"message":"Message Marked as Starred message", "status_code": 200}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function update($id, Request $request) + { + $message = Message::find($id); + if($request->has('stared')) { + $message['is_starred'] = ($request['stared'] == 0) ? 1 : 0; + } + if($message->save()) { + return response()->json(['Success' => 'Message updated successfully'], 200); + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Message could not be updated. Please, try again.'); + } + } +} diff --git a/app/Http/Controllers/PaymentGatewaysController.php b/app/Http/Controllers/PaymentGatewaysController.php new file mode 100644 index 0000000..4454c04 --- /dev/null +++ b/app/Http/Controllers/PaymentGatewaysController.php @@ -0,0 +1,135 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Http\Controllers; + +use Illuminate\Http\Request; + +class PaymentGatewaysController extends Controller +{ + /** + * @var \Plugins\Sudopays\Services\SudopayAPIService + */ + protected $sudopayService; + + /** + * PaymentGatewaysController constructor. + */ + public function __construct() + { + $this->setSudopayService(); + } + + public function setSudopayService() + { + if (isPluginEnabled('Sudopays')) { + $this->sudopayService = new \Plugins\Sudopays\Services\SudopayAPIService(); + } + } + + /** + * Show all enabled payment gateways. + * @Get("/get_gateways") + * @Transaction({ + * @Response(200, body={"paypal": {"error": {"code": 0}, "paypal_enabled": true}, "sudopay": [], "wallet": {"error": {"code": 0},"wallet_enabled": true}}) + * }) + */ + public function getGateways(Request $request) + { + $sudopay_gateway_response = $paypal_gateway_response = $wallet_response = $payment_gateways = array(); + $selected_payment_gateway_id = $selected_gateway_id = ''; + // wallet + $wallet = new \App\Services\WalletService(); + $wallet_response = $wallet->getWalletDetails(); + // paypal + if (isPluginEnabled('Paypal')) { + $paypal = new \Plugins\Paypal\Services\PayPalService(); + $paypal_gateway_response = $paypal->getPaypalDetails(); + } + if (isPluginEnabled('Sudopays')) { + $gateways = $this->sudopayService->callGateways(array('supported_actions' => 'auth,capture')); + $i = 0; + if (!empty($gateways['gateways'])) { + foreach ($gateways['gateways'] as $group_gateway) { + $gateway_groups[] = $group_gateway; + } + $unset_array = array(); + foreach ($gateways['gateways'] as $key => $group_gateway) { + if (count($group_gateway['gateways']) > 0) { + foreach ($group_gateway['gateways'] as $gateway) { + $gateway['group_id'] = $group_gateway['id']; + $gateway_array[] = $gateway; + } + } else { + $unset_array[] = $key; + } + } + if (count($unset_array) > 0) { + foreach ($unset_array as $unset_val) { + unset($gateway_groups[$unset_val]); + } + } + $payment_gateway_arrays = array(); + if (!empty($gateway_array)) { + foreach ($gateway_array as $gateway) { + $payment_gateway_arrays[$i]['id'] = $gateway['id']; + $payment_gateway_arrays[$i]['payment_id'] = 'sp_' . $gateway['id']; + $payment_gateway_arrays[$i]['group_id'] = $gateway['group_id']; + $payment_gateway_arrays[$i]['display_name'] = $gateway['display_name']; + $payment_gateway_arrays[$i]['thumb_url'] = $gateway['thumb_url']; + $payment_gateway_arrays[$i]['sp_' . $gateway['id']] = implode($gateway['_form_fields']['_extends_tpl'], ","); + $payment_gateway_arrays[$i]['form_fields'] = implode($gateway['_form_fields']['_extends_tpl'], ","); + $i++; + } + $payment_gateways = $payment_gateway_arrays; + } + //Load form fields + $form_fields_tpls = $gateways['_form_fields_tpls']; + //Get first payment + if (!empty($gateway_groups)) { + $default_group_id = ''; + $default_gateway_id = ''; + foreach ($gateway_groups As $key => $value) { + $default_group_id = $value['id']; + break; + } + foreach ($payment_gateways As $key => $value) { + $default_gateway_id = $value['payment_id']; + break; + } + $selected_payment_gateway_id = $default_gateway_id; + $selected_gateway_id = $default_group_id; + } + + $sudopay_gateway_response['gateway_groups'] = $gateway_groups; + $sudopay_gateway_response['payment_gateways'] = $payment_gateways; + $sudopay_gateway_response['form_fields_tpls'] = $form_fields_tpls; + $sudopay_gateway_response['selected_payment_gateway_id'] = $selected_payment_gateway_id; + $sudopay_gateway_response['selected_gateway_id'] = $selected_gateway_id; + + } + } + if ($request->has('page') && $request->page == 'wallet') { + $response['sudopay'] = $sudopay_gateway_response; + $response['paypal'] = $paypal_gateway_response; + } else { + $response['paypal'] = $paypal_gateway_response; + $response['sudopay'] = $sudopay_gateway_response; + $response['wallet'] = $wallet_response; + } + return $response; + } + +} diff --git a/app/Http/Controllers/SettingsController.php b/app/Http/Controllers/SettingsController.php new file mode 100644 index 0000000..0a9c960 --- /dev/null +++ b/app/Http/Controllers/SettingsController.php @@ -0,0 +1,67 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Http\Controllers; + +use Illuminate\Http\Request; +use App\Setting; + +use Validator; +use App\Transformers\SettingTransformer; +use App\Currency; + +/** + * Settings resource representation. + * @Resource("/Settings") + */ +class SettingsController extends Controller +{ + + /** + * Show all settings + * Get a JSON representation of all the settings. + * @Get("/settings?sort={sort}&sortby={sortby}&page={page}&setting_category_id={id}") + * @Parameters({ + * @Parameter("sort", type="string", required=false, description="Sort the settings list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort setting by Ascending / Descending Order.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1), + * @Parameter("setting_category_id", type="integer", required=false, description="Sort setting by category.", default=null) + * }) + */ + public function index(Request $request) + { + if ($request->input('type') == 'public_settings') { + $settings = Setting::filterByRequest($request)->get(); + if(isPluginEnabled('CurrencyConversions')) { + $currencyService = new \Plugins\CurrencyConversions\Services\CurrencyConversionService(); + $currency_response = $currencyService->getCurrencyconvertion(); + if(empty($currency_response['currency_conversion'])) { + $currency = Currency::where('code', config('site.currency_code'))->first(); + $response['currencies'] = array($currency); + }else { + $response['currencies'] = $currency_response['currency_conversion']; + } + } else { + $currency = Currency::where('code', config('site.currency_code'))->first(); + $response['currencies'] = array($currency); + } + $response['default_currency_code'] = config('site.currency_code'); + $response['settings'] = $this->response->Collection($settings, new SettingTransformer); + return $response; + } + } + + +} diff --git a/app/Http/Controllers/StatesController.php b/app/Http/Controllers/StatesController.php new file mode 100644 index 0000000..66b6241 --- /dev/null +++ b/app/Http/Controllers/StatesController.php @@ -0,0 +1,46 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Http\Controllers; + +use Illuminate\Http\Request; +use App\State; +use App\Transformers\StateTransformer; + +/** + * States resource representation. + * @Resource("States") + */ +class StatesController extends Controller +{ + /** + * Show all states. + * Get a JSON representation of all the states. + * + * @Get("/states?filter={filter}&sort={sort}&sortby={sortby}&q={q}") + * @Parameters({ + * @Parameter("filter", type="integer", required=false, description="Filter the states list by type.", default=null), + * @Parameter("sort", type="string", required=false, description="Sort the states list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort states by Ascending / Descending Order.", default=null), + * @Parameter("q", type="string", required=false, description="Search states.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1) + * }) + */ + public function index(Request $request) + { + $states = State::filterByRequest($request)->get(); + return $this->response->collection($states, new StateTransformer); + } +} diff --git a/app/Http/Controllers/TransactionTypesController.php b/app/Http/Controllers/TransactionTypesController.php new file mode 100644 index 0000000..f00f550 --- /dev/null +++ b/app/Http/Controllers/TransactionTypesController.php @@ -0,0 +1,55 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Http\Controllers; + +use Illuminate\Http\Request; +use JWTAuth; +use Validator; +use App\Transformers\TransactionTypeTransformer; +use App\TransactionType; + +/** + * TransactionTypes resource representation. + * @Resource("TransactionTypes") + */ +class TransactionTypesController extends Controller +{ + /** + * TransactionTypesController constructor. + */ + public function __construct() + { + // Check the logged user authentication. + $this->middleware('jwt.auth'); + } + + /** + * Show all transaction types. + * Get a JSON representation of all the transaction types. + * + * @Get("/transaction_types?sort={sort}&sortby={sortby}&page={page}") + * @Parameters({ + * @Parameter("sort", type="string", required=false, description="Sort the transaction types list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort transaction types by Ascending / Descending Order.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1) + * }) + */ + public function index(Request $request) + { + $transaction_types = TransactionType::filterByRequest($request)->paginate(config('constants.ConstPageLimit')); + return $this->response->paginator($transaction_types, (new TransactionTypeTransformer)); + } +} diff --git a/app/Http/Controllers/TransactionsController.php b/app/Http/Controllers/TransactionsController.php new file mode 100644 index 0000000..f383f86 --- /dev/null +++ b/app/Http/Controllers/TransactionsController.php @@ -0,0 +1,66 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Http\Controllers; + +use Illuminate\Http\Request; +use JWTAuth; +use Validator; +use App\Transformers\TransactionTransformer; +use App\Transaction; +use App\Services\TransactionService; + +/** + * Transactions resource representation. + * @Resource("Transactions") + */ +class TransactionsController extends Controller +{ + /** + * TransactionsController constructor. + */ + public function __construct() + { + // Check the logged user authentication. + $this->middleware('jwt.auth'); + $this->setTransactionService(); + } + public function setTransactionService() + { + $this->transactionService = new TransactionService(); + } + + /** + * Show all transaction types. + * Get a JSON representation of all the transaction types. + * + * @Get("/transactions?filter={filter}&sort={sort}&sortby={sortby}&page={q}&page={q}") + * @Parameters({ + * @Parameter("sort", type="string", required=false, description="Sort the transactions list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort transactions by Ascending / Descending Order.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1), + * @Parameter("filter", type="integer", required=false, description="Filter transactions list by status.", default=null), + * @Parameter("q", type="string", required=false, description="Search transactions.", default=null) + * }) + */ + public function index(Request $request) + { + $user = $this->auth->user(); + $transactions = Transaction::with('from_user','to_user', 'transaction_type')->where('user_id', $user->id)->orWhere('receiver_user_id', $user->id)->filterByRequest($request)->paginate(config('constants.ConstPageLimit')); + $converted_transactions = $this->transactionService->transactionDescription($transactions); + $transaction_details = $this->response->paginator($converted_transactions, (new TransactionTransformer)->setDefaultIncludes(['from_user','to_user', 'transaction_type'])); + return $transaction_details; + } +} diff --git a/app/Http/Controllers/UserProfilesController.php b/app/Http/Controllers/UserProfilesController.php new file mode 100644 index 0000000..8be3126 --- /dev/null +++ b/app/Http/Controllers/UserProfilesController.php @@ -0,0 +1,129 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Http\Controllers; + +use App\User; +use Illuminate\Http\Request; +use App\UserProfile; +use App\Attachment; +use JWTAuth; +use Validator; +use App\Transformers\UserProfileTransformer; +use Image; +use File; + +/** + * UserProfiles resource representation. + * @Resource("UserProfiles") + */ +class UserProfilesController extends Controller +{ + /** + * UserProfilesController constructor. + */ + public function __construct() + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth'); + } + + /** + * Get the specified user profile. + * @Get("/user_profiles") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"id": 1, "user_id": 1, "first_name": "admin", "last_name": "admin", "about_me": "I am the site admin", "website": null, "facebook_profile_link": null, "twitter_profile_link": null, "google_plus_profile_link": null, "linkedin_profile_link": null, "youtube_profile_link": null}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function edit() + { + $user = $this->auth->user(); + $user_profile = UserProfile::with('User.attachments')->where('user_id', '=', $user->id)->first(); + if (!$user_profile) { + UserProfile::create(['first_name' => $user->username, 'user_id' => $user->id]); + $user_profile = UserProfile::with('User.attachments')->where('user_id', '=', $user->id)->first(); + } + return $this->response->item($user_profile, (new UserProfileTransformer)->setDefaultIncludes(['User'])); + } + + /** + * Update user_profile + * Update user_profile with a `user_id`. + * @Put("/user_profiles") + * @Transaction({ + * @Request({"user_id": 1, "first_name": "admin", "last_name": "admin", "about_me": "I am the site admin", "website": null, "facebook_profile_link": null, "twitter_profile_link": null, "google_plus_profile_link": null, "linkedin_profile_link": null, "youtube_profile_link": null}), + * @Response(200, body={"success": "Record has been updated."}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {}, "status_code": 422}) + * }) + */ + public function update(Request $request) + { + $user_profile_data = $request->only('first_name', 'last_name', 'about_me', 'website', 'facebook_profile_link', 'twitter_profile_link', 'google_plus_profile_link', 'linkedin_profile_link', 'youtube_profile_link'); + $user_profile_data['website'] = ($user_profile_data['website'] == null || $user_profile_data['website'] == 'null') ? "" : $user_profile_data['website']; + $user_profile_data['facebook_profile_link'] = ($user_profile_data['facebook_profile_link'] == null || $user_profile_data['facebook_profile_link'] == 'null') ? "" : $user_profile_data['facebook_profile_link']; + $user_profile_data['twitter_profile_link'] = ($user_profile_data['twitter_profile_link'] == null || $user_profile_data['twitter_profile_link'] == 'null') ? "" : $user_profile_data['twitter_profile_link']; + $user_profile_data['google_plus_profile_link'] = ($user_profile_data['google_plus_profile_link'] == null || $user_profile_data['google_plus_profile_link'] == 'null') ? "" : $user_profile_data['google_plus_profile_link']; + $user_profile_data['linkedin_profile_link'] = ($user_profile_data['linkedin_profile_link'] == null || $user_profile_data['linkedin_profile_link'] == 'null') ? "" : $user_profile_data['linkedin_profile_link']; + $user_profile_data['youtube_profile_link'] = ($user_profile_data['youtube_profile_link'] == null || $user_profile_data['youtube_profile_link'] == 'null') ? "" : $user_profile_data['youtube_profile_link']; + $validator = Validator::make($user_profile_data, UserProfile::GetValidationRule(), UserProfile::GetValidationMessage()); + $user = $this->auth->user(); + if ($user) { + if ($validator->passes()) { + $user_profile = UserProfile::where('user_id', '=', $user->id)->first(); + try { + if (!empty($user_profile)) { + UserProfile::where('id', '=', $user_profile->id)->update($user_profile_data); + } else { + $user_profile_data['user_id'] = $user->id; + UserProfile::create($user_profile_data); + } + if ($request->hasFile('file')) { + if ($request->file('file')->isValid()) { + $path = storage_path('app/User/' . $user->id . '/'); + if (!File::isDirectory($path)) { + File::makeDirectory($path, 0775, true); + } + $img = Image::make($_FILES['file']['tmp_name']); + $path = storage_path('app/User/' . $user->id . '/' . $_FILES['file']['name']); + if ($img->save($path)) { + $curuser = User::with(['attachments'])->where('id', '=', $user->id)->first(); + $attachment = array(); + $attachment['filename'] = $_FILES['file']['name']; + $attachment['dir'] = 'app/User/' . $user->id . '/'; + $attachment['mimetype'] = $request->file('file')->getClientMimeType(); + $attachment['filesize'] = $request->file('file')->getClientSize(); + if ($curuser->attachments) { + $curuser->attachments()->update($attachment); + } else { + $att = Attachment::create($attachment); + $curuser = User::with(['attachments'])->where('id', '=', $user->id)->first(); + $curuser->attachments()->save($att); + } + } + } + } + return response()->json(['Success' => 'UserProfile has been updated'], 200); + } catch (\Exception $e) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('UserProfile could not be updated. Please, try again.'); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('UserProfile could not be updated. Please, try again.', $validator->errors()); + } + } + } + +} diff --git a/app/Http/Controllers/UsersController.php b/app/Http/Controllers/UsersController.php new file mode 100644 index 0000000..bab9f83 --- /dev/null +++ b/app/Http/Controllers/UsersController.php @@ -0,0 +1,358 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Http\Controllers; + +use Illuminate\Http\Request; + +use JWTAuth; +use Validator; +use Tymon\JWTAuth\Exceptions\JWTException; +use App\User; +use Illuminate\Support\Facades\Hash; + +use App\Transformers\UserTransformer; +use App\Transformers\UserAuthTransformer; +use App\Transformers\UploadAttachmentTransformer; + +use App\Services\UserService; +use App\Services\IpService; +use App\Services\UserLoginService; +use App\Attachment; + +/** + * Users resource representation. + * @Resource("Users") + */ +class UsersController extends Controller +{ + /** + * @var UserService + */ + protected $UserService; + /** + * @var IpService + */ + protected $IpService; + /** + * @var UserLoginService + */ + protected $UserLoginService; + + /** + * UsersController constructor. + */ + public function __construct(UserService $user_Service) + { + $this->middleware('jwt.auth', ['only' => ['change_password', 'getAuth', 'getStats']]); + $this->UserService = $user_Service; + $this->setIpService(); + $this->setUserLoginService(); + } + + public function setIpService() + { + $this->IpService = new IpService(); + } + + public function setUserLoginService() + { + $this->UserLoginService = new UserLoginService(); + } + + /** + * Show the specified user. + * Show the user with a `id`. + * @Get("/users/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"id": 1, "role_id": 1, "username": "admin", "email": "guest@gmail.com", "available_wallet_amount": 0, "is_active": 1, "is_email_confirmed": 1, "register_ip_id": 1, "last_login_ip_id": 3}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function show(Request $request) + { + $enabledIncludes = array('user_profile', 'attachments'); + (isPluginEnabled('SocialLogins')) ? $enabledIncludes[] = 'provider_user' : ''; + if ($request->has('username')) { + $user = User::with($enabledIncludes)->where("username", $request->username)->first(); + } else { + $auth_user = $this->auth->user(); + $user = User::with($enabledIncludes)->find($auth_user->id); + } + if (!$user) { + return $this->response->errorNotFound("Invalid Request"); + } + if ($request->has('username')) { + return $this->response->item($user, (new UserTransformer)->setDefaultIncludes(['user_profile', 'providerUser', 'attachmentable'])); + } else { + return $this->response->item($user, (new UserAuthTransformer)->setDefaultIncludes(['user_profile', 'providerUser', 'attachmentable'])); + } + } + + /** + * Store a new user. + * Store a new user with a `username`, `email`, `password`, `confirm_password` and `is_agree_terms_conditions`. + * @Post("/users/register") + * @Transaction({ + * @Request({"name": "XXXXXX", "email": "XXXXX@gmail.com", "password": "XXXXXX", "confirm_password": "XXXXXX", "is_agree_terms_conditions": 1}), + * @Response(200, body={"success": "Record has been added."}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {"name": {}}, "status_code": 422}) + * }) + */ + public function register(Request $request) + { + $user_data = $request->only('username', 'email', 'password', 'confirm_password', 'is_agree_terms_conditions'); + $validator = Validator::make($user_data, User::GetValidationRule(), User::GetValidationMessage()); + if ($validator->passes()) { + if ($request->has('password')) { + $user_data['password'] = Hash::make($request->password); + } + $user_data['is_active'] = 1; + $user_data['role_id'] = config('constants.ConstUserTypes.User'); + $user_data['register_ip_id'] = $this->IpService->getIpId($request->ip()); + $user_data['is_email_confirmed'] = 1; + $user_data['user_avatar_source_id'] = config('constants.ConstSocialLogin.User'); + if (config('user.is_email_verification_for_register')) { + $user_data['is_email_confirmed'] = 0; + $user_data['activate_hash'] = rand(1,100); + } + if (config('user.is_admin_activate_after_register')) { + $user_data['is_active'] = 0; + } + //Captcha verification + $captcha = $request['g-recaptcha-response']; + if ($this->UserService->captchaCheck($captcha) == false) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Captcha Verification failed.'); + } + $user = User::create($user_data); + if ($user) { + return $this->UserService->emailConditions($user, 'register'); + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Could not create new user.'); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Could not create new user.', $validator->errors()); + } + } + + /** + * User Authentication. + * @Post("/users/login") + * @Transaction({ + * @Request({"email": "guest@gmail.com", "password": "XXXXXX"}), + * @Response(200, body={"success": "Login successfully", "Token": "XXXXXX"}), + * @Response(401, body={"message": "Unauthorized", "status_code": 401}) + * }) + */ + public function authenticate(Request $request) + { + $credentials = $request->only('email', 'password'); + $credentials['is_active'] = true; + $credentials['is_email_confirmed'] = true; + $chk_user = User::where('email', $request->email)->first(); + if(empty($chk_user)) { + return response()->json(['error' => 'Account does not exist.'], 404); + } + try { + if (!$userToken = JWTAuth::attempt($credentials)) { + return $this->response->errorUnauthorized(); + } + } catch (JWTException $e) { + // something went wrong + throw new \Symfony\Component\HttpKernel\Exception\HttpException('Could not create token'); + } + // insert record in user logins after successful login + $ip_id = $this->IpService->getIpId($request->ip()); + $role = $this->UserLoginService->saveUserLogin($request, $ip_id); + // Admin End Token varaiable should be need. so we assign two variable + $token = $userToken; + $message = "Admin login successfully"; + $enabled_plugins_arr = enabled_plugins(); + $enabled_plugins = array(); + foreach($enabled_plugins_arr as $key=>$value) { + $enabled_plugins[] = $value; + } + // if no errors are encountered we can return a JWT + return response()->json(compact('userToken', 'token', 'message', 'role', 'enabled_plugins')); + } + + /** + * Activate user. + * @Put("/users/{id}/activate/{hash}") + * @Transaction({ + * @Request({"id": 1, "hash": "XXXXXXXXXXX"}), + * @Response(200, body={"success": "User Activated."}), + * @Response(404, body={"message": "Invalid Activation Request", "status_code": 404}) + * }) + */ + public function activate($hash, $id) + { + $user = User::find($id); + if (!$user) { + return $this->response->errorNotFound("Invalid Request"); + } + if ($user) { + $user_valid = $this->UserService->validateHash($user->id, $hash, $user->activate_hash); + if ($user_valid === false) { + return $this->response->errorNotFound("Invalid Activation Request"); + } + $user->is_email_confirmed = 1; + $user->activate_hash = rand(1,100); + if (!config('user.is_admin_activate_after_register')) { + $user->is_active = 1; + } + if ($user->save()) { + return $this->UserService->emailConditions($user, 'activate'); + } + } + } + + /** + * Change Password. + * @Put("/users/{id}/change_password") + * @Transaction({ + * @Request({"id": 1, "old_password": "XXXXXX", "password": "XXXXXX", "confirm_password": "XXXXXX"}), + * @Response(200, body={"success": "Password changed."}), + * @Response(422, body={"message": "Could not change password.","errors": {},"status_code": 422}), + * @Response(400, body={"error": "token_not_provided"}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}), + * }) + */ + public function changePassword(Request $request, $id) + { + $user = User::find($id); + if (!$user) { + return $this->response->errorNotFound("Invalid Request"); + } + if (!$password = Hash::check($request->old_password, $user->password)) { + $this->response->errorNotFound("Your old password is incorrect, please try again"); + } + if ($password == Hash::check($request->password, $user->password)) { + $this->response->errorNotFound("Your new password is same as old password"); + } + $user_data = $request->only('password', 'confirm_password'); + $validator = Validator::make($user_data, User::GetValidationRule(), User::GetValidationMessage()); + if ($validator->passes()) { + $user->password = Hash::make($request->password); + if ($user->save()) { + return response()->json(['Success' => 'Password Changed Successfully.'], 200); + } + } else { + throw new \Dingo\Api\Exception\UpdateResourceFailedException('Could not change password.', $validator->errors()); + } + } + + /** + * Forgot Password. + * @Put("/users/forgot_password") + * @Transaction({ + * @Request({"email": "guest@gmail.com"}), + * @Response(200, body={"success": "We have sent an email."}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}), + * @Response(422, body={"message": "Could not change password.","errors": {},"status_code": 422}) + * }) + */ + public function forgotPassword(Request $request) + { + $user_data = $request->only('email'); + $validator = Validator::make($user_data, User::GetForgotPasswordValidationRule()); + if ($validator->passes()) { + $user = User::where('email', $request->email)->first(); + if($user) { + if ($user->is_email_confirmed == 0 || $user->is_active == 0) { + return $this->response->errorNotFound("This email address is not verified."); + } + } + if (!$user) { + return $this->response->errorNotFound("This email address is not in our registered users."); + } + $user_data['id'] = $user->id; + $new_password = uniqid(); + $user_data['password'] = Hash::make($new_password); + + if ($user->update($user_data)) { + try { + $this->UserService->sendForgotPasswordMail($new_password, $user->email, $user->username); + return response()->json(['Success' => 'We have sent an email to ' . $user->email . ' with further instructions'], 200); + } catch (\Exception $e) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Password could not be updated. Please, try again.'); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Password could not be updated. Please, try again.'); + } + } else { + throw new \Dingo\Api\Exception\UpdateResourceFailedException('Password could not be updated.', $validator->errors()); + } + + } + + /* + * Get Authenticated user + * @Get("/users/auth") + * @Transaction({ + * @Response(200, body={"id": 1, "role_id": 1, "username": "test", "email": "guest@gmail.com", "available_wallet_amount": 10, "is_active": 1, "is_email_confirmed": 1, "register_ip_id": 192.168.1.22, "last_login_ip_id": 192.168.1.22,"user_profile :{}}), + * @Response(400, body={"message": "Token not provided", "status_code": 400}), + * }) + */ + public function getAuth() + { + $user = $this->auth->user(); + if ($user) { + return $this->response->item($user, (new UserAuthTransformer)->setDefaultIncludes(['user_profile', 'attachmentable', 'provider_user', 'vehicle_company'])); + } + } + + /* + * Get Authenticated user Upload OR default avatar thumb url + * @Get("/users/{id}/attachment") + * @Transaction({ + * @Response(200, body={"thumb": {}}), + * @Response(400, body={"message": "Token not provided", "status_code": 400}), + * }) + */ + public function getUserUploadAttachment() + { + $user = $this->auth->user(); + if ($user) { + if ($user->attachments) { + return $this->item($user->attachments, new UploadAttachmentTransformer()); + } else { + $user->attachments = Attachment::where('id', '=', config('constants.ConstAttachment.UserAvatar'))->first(); + $user->attachments->attachmentable_id = $user->id; + return $this->item($user->attachments, new UploadAttachmentTransformer()); + } + } + } + + /* + * Get Authenticated user Upload OR default avatar thumb url + * @Get("/users/{id}/attachment") + * @Transaction({ + * @Response(200, body={"thumb": {}}), + * @Response(400, body={"message": "Token not provided", "status_code": 400}), + * }) + */ + public function getStats() + { + $user = $this->auth->user(); + if (isPluginEnabled('VehicleRentals') && $user) { + $vehicle_rental_service = new \Plugins\VehicleRentals\Services\VehicleRentalService(); + $response = $vehicle_rental_service->getBookAndOrderCount($user->id); + return response()->json(compact('response'), 200); + } + } + +} \ No newline at end of file diff --git a/app/Http/Controllers/WalletsController.php b/app/Http/Controllers/WalletsController.php new file mode 100644 index 0000000..19d621c --- /dev/null +++ b/app/Http/Controllers/WalletsController.php @@ -0,0 +1,140 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Http\Controllers; + +use Illuminate\Http\Request; + +use App\Http\Controllers\Controller; +use App\Wallet; +use App\Services\WalletService; +use JWTAuth; +use Validator; + +/** + * Money Transfer Accounts resource representation. + * @Resource("Wallets") + */ +class WalletsController extends Controller +{ + /** + * @var + */ + protected $paymentService; + /** + * @var + */ + protected $logtService; + + /** + * WalletsController constructor. + */ + public function __construct() + { + // Check the logged user authentication. + $this->middleware('jwt.auth'); + $this->setWalletService(); + } + + public function setWalletService() + { + $this->walletService = new WalletService(); + } + + /** + * Update available wallet amount to user. + * Update available wallet amount with a `user_id`. + * @GET("/wallets") + * @Transaction({ + * @Request({"user_id": 1}), + * @Response(200, body={"available_wallet_amount": 100}), + * @Response(500, body={"message": "Creating default object from empty value.", "status_code": 500}) + * }) + */ + public function addToWallet(Request $request) + { + $user = $this->auth->user(); + $request_amount = $request->only('amount'); + $request->sudopay_gateway_id = ($request->has('payment_id')) ? (int)$request->payment_id : 0; + $validator = Validator::make($request_amount, Wallet::GetValidationRule(), Wallet::GetValidationMessage()); + if ($request->has('gateway_id') && ((isPluginEnabled('Paypal') && $request->gateway_id == config('constants.ConstPaymentGateways.PayPal')) || (isPluginEnabled('Sudopays') && $request->gateway_id == config('constants.ConstPaymentGateways.SudoPay')))) { + if ($request->gateway_id == config('constants.ConstPaymentGateways.SudoPay')) { + $sudopay_data = array('address', 'city', 'country', 'email', 'gateway_id', 'payment_id', 'phone', 'state', 'zip_code'); + if ($request->has('credit_card_code')) { + $sudopay_data = array_merge($sudopay_data, array('credit_card_code', 'credit_card_expire', 'credit_card_name_on_card', 'credit_card_number')); + } + if ($request->has('payment_note')) { + $sudopay_data = array_merge($sudopay_data, array('payment_note')); + } + $sudopay_data = $request->only($sudopay_data); + } + if ($validator->passes()) { + try { + $wallet_data = new Wallet; + $wallet_data->user_id = $user->id; + $wallet_data->amount = $request_amount['amount']; + $wallet_data->description = "Amount added to wallet"; + $wallet_data->payment_gateway_id = $request->gateway_id; + $wallet_data->sudopay_gateway_id = $request->sudopay_gateway_id; + $wallet = $wallet_data->save(); + $log_data['amount'] = $request_amount['amount']; + $log_data['gateway_id'] = $wallet_data->sudopay_gateway_id; + $log_data['fee_payer'] = 'User'; + if ($wallet) { + if ($request->gateway_id == config('constants.ConstPaymentGateways.SudoPay')) { + $this->logtService = new \Plugins\Sudopays\Services\SudopayTransactionLogService(); + $this->paymentService = new \Plugins\Sudopays\Services\SudopayService(); + $transaction_data = $this->logtService->log($log_data); + $cur_wallet = Wallet::with(['sudopay_transaction_logs'])->where('id', '=', $wallet_data->id)->first(); + $cur_transaction = $cur_wallet->sudopay_transaction_logs()->save($transaction_data); + $response = $this->paymentService->createPayment($cur_transaction->id, $sudopay_data); + if (!empty($response['gateway_callback_url'])) { + return response()->json(['url' => $response['gateway_callback_url']], 200); + } + if (!empty($response['pending'])) { + return response()->json(['Success' => 'Once payment is received, it will be processed'], 200); + } elseif (!empty($response['success'])) { + return response()->json(['Success' => 'Amount Added successfully'], 200); + } elseif (!empty($response['error'])) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Your payment could not be completed. Please, try again.', $response['error_message']); + } + } else if ($request->gateway_id == config('constants.ConstPaymentGateways.PayPal')) { + $this->logtService = new \Plugins\Paypal\Services\PaypalTransactionLogService(); + $this->paymentService = new \Plugins\Paypal\Services\PayPalService(); + $transaction_data = $this->logtService->log($log_data); + $cur_wallet = Wallet::with(['paypal_transaction_logs'])->where('id', '=', $wallet_data->id)->first(); + $cur_transaction = $cur_wallet->paypal_transaction_logs()->save($transaction_data); + $response = $this->paymentService->createPayment($cur_transaction->id, config('constants.ConstPaypalGatewaysProcess.sale')); + if (!empty($response['error'])) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Your payment could not be completed. Please, try again.', $response['error_message']); + } else if (empty($response['error'])) { + return response()->json(['url' => $response], 200); + } + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Wallet could not be updated. Please, try again.', $validator->errors()); + } + } catch (\Exception $e) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Wallet could not be updated. Please, try again.', array($e->getMessage())); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Wallet could not be updated. Please, try again.', $validator->errors()); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Payment gateway could not be set. Please, try again.'); + } + + } +} \ No newline at end of file diff --git a/app/Http/Middleware/Authenticate.php b/app/Http/Middleware/Authenticate.php new file mode 100644 index 0000000..3f30542 --- /dev/null +++ b/app/Http/Middleware/Authenticate.php @@ -0,0 +1,55 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Http\Middleware; + +use Closure; +use Illuminate\Contracts\Auth\Factory as Auth; + +class Authenticate +{ + /** + * The authentication guard factory instance. + * + * @var \Illuminate\Contracts\Auth\Factory + */ + protected $auth; + + /** + * Authenticate constructor. + * @param Auth $auth + */ + public function __construct(Auth $auth) + { + $this->auth = $auth; + } + + /** + * Handle an incoming request. + * + * @param \Illuminate\Http\Request $request + * @param \Closure $next + * @param string|null $guard + * @return mixed + */ + public function handle($request, Closure $next, $guard = null) + { + if ($this->auth->guard($guard)->guest()) { + return response('Unauthorized.', 401); + } + + return $next($request); + } +} diff --git a/app/Http/Middleware/AuthenticateRole.php b/app/Http/Middleware/AuthenticateRole.php new file mode 100644 index 0000000..d15321c --- /dev/null +++ b/app/Http/Middleware/AuthenticateRole.php @@ -0,0 +1,42 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Http\Middleware; +use Illuminate\Support\Facades\Auth; + +use Closure; + +/** + * Class AuthenticateRole + * @package App\Http\Middleware + */ + +class AuthenticateRole +{ + + /** + * @param $request + * @param Closure $next + * @return mixed + */ + public function handle($request, Closure $next) + { + $user = Auth::user()->toArray(); + if($user['role_id'] != config('constants.ConstUserTypes.Admin')){ + throw new \Symfony\Component\HttpKernel\Exception\BadRequestHttpException('Authentication failed'); + } + return $next($request); + } +} diff --git a/app/Http/Middleware/Tracking.php b/app/Http/Middleware/Tracking.php new file mode 100644 index 0000000..8f3e2b3 --- /dev/null +++ b/app/Http/Middleware/Tracking.php @@ -0,0 +1,79 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Http\Middleware; + +use Cache; +use Closure; +use Illuminate\Support\Facades\Auth; +use App\ApiRequest; +use App\Services\IpService; +use Log; + +class Tracking +{ + /** + * @var IpService + */ + protected $IpService; + /** + * The authentication guard factory instance. + * + * @var \Illuminate\Contracts\Auth\Factory + */ + protected $auth; + + /** + * Authenticate constructor. + * @param Auth $auth + */ + public function __construct() + { + $this->setIpService(); + } + + public function setIpService() + { + $this->IpService = new IpService(); + } + + /** + * Handle an incoming request. + * + * @param \Illuminate\Http\Request $request + * @param \Closure $next + * @param string|null $guard + * @return mixed + */ + public function handle($request, Closure $next, $guard = null) + { + //@todo: ip address need remove and update dynamic domain name + if (!Cache::has('site_url_for_shell')) { + Cache::forever('site_url_for_shell', $request->root()); + } + $response = $next($request); + $api_request = new ApiRequest(); + if (Auth::user()) { + $user = Auth::user()->toArray(); + $api_request->user_id = $user['id']; + } + $api_request->path = $request->fullUrl(); + $api_request->method = $request->method(); + $api_request->http_response_code = $response->status(); + $api_request->ip_id = $this->IpService->getIpId($request->ip()); + $api_request->save(); + return $response; + } +} \ No newline at end of file diff --git a/app/Http/Requests/CreateUserRequest.php b/app/Http/Requests/CreateUserRequest.php new file mode 100644 index 0000000..fb8602f --- /dev/null +++ b/app/Http/Requests/CreateUserRequest.php @@ -0,0 +1,70 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Http\Requests; + +use App\Http\Requests\Request; + +class CreateUserRequest extends Request +{ + /** + * Determine if the user is authorized to make this request. + * + * @return bool + */ + public function authorize() + { + return true; + } + + /** + * Get the validation rules that apply to the request. + * + * @return array + */ + public function rules() + { + + switch($this->method()) + { + case 'GET': + case 'DELETE': + { + return []; + } + case 'POST': + { + return [ + 'username' => 'required|min:3', + 'email' => 'required|email|unique:users', + 'password' => 'required|min:6', + 'confirm_password' => 'required|min:6|same:password', + 'is_agree_terms_conditions' => 'required' + ]; + } + case 'PUT': + { + return [ + 'password' => 'required|min:6', + 'confirm_password' => 'required|min:6|same:password' + ]; + } + case 'PATCH': + + default:break; + } + + } +} diff --git a/app/Http/Requests/Request.php b/app/Http/Requests/Request.php new file mode 100644 index 0000000..f90bbf5 --- /dev/null +++ b/app/Http/Requests/Request.php @@ -0,0 +1,23 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Http\Requests; + +use Illuminate\Foundation\Http\FormRequest; + +abstract class Request extends FormRequest +{ + // +} diff --git a/app/Http/routes.php b/app/Http/routes.php new file mode 100644 index 0000000..c7c2123 --- /dev/null +++ b/app/Http/routes.php @@ -0,0 +1,230 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +/* +|-------------------------------------------------------------------------- +| Application Routes +|-------------------------------------------------------------------------- +| +| Here is where you can register all of the routes for an application. +| It is a breeze. Simply tell Lumen the URIs it should respond to +| and give it the Closure to call when that URI is requested. +| +*/ + +$api = $app->make('Dingo\Api\Routing\Router'); + +$value = config('app.timezone'); +date_default_timezone_set($value); + +$app->get('/', function () use ($app) { + return $app->version(); +}); + +$app->get('robots.txt', function () use ($app) { + return config('site.robots'); +}); + +$app->get('clear_cache', function () use ($app) { + Cache::forget('settings_data'); + Cache::forget('site_url_for_shell'); + return response()->json(['Success' => 'setting cache cleared'], 200); +}); + +$api->version(['v1'], function ($api) use ($app) { + $api->group(['prefix' => 'admin', 'namespace' => 'App\Http\Controllers\Admin', 'middleware' => 'apitracking'], function () use ($api) { + + //Api Requests + $api->get('api_requests', 'AdminApiRequestsController@index'); + $api->get('api_requests/{id}', 'AdminApiRequestsController@show'); + $api->delete('api_requests/{id}', 'AdminApiRequestsController@destroy'); + + // cities admin side + $api->delete('cities/{id}', 'AdminCitiesController@destroy'); + $api->get('cities', 'AdminCitiesController@index'); + $api->get('cities/{id}/edit', 'AdminCitiesController@edit'); + $api->get('cities/{id}', 'AdminCitiesController@edit'); + $api->post('cities', 'AdminCitiesController@store'); + $api->put('cities/{id}', 'AdminCitiesController@update'); + $api->put('cities/{id}/deactive', 'AdminCitiesController@deactive'); + $api->put('cities/{id}/active', 'AdminCitiesController@active'); + + // countries admin side + $api->delete('countries/{id}', 'AdminCountriesController@destroy'); + $api->get('countries', 'AdminCountriesController@index'); + $api->get('countries/{id}/edit', 'AdminCountriesController@edit'); + $api->get('countries/{id}', 'AdminCountriesController@edit'); + $api->post('countries', 'AdminCountriesController@store'); + $api->put('countries/{id}', 'AdminCountriesController@update'); + $api->put('countries/{id}/deactive', 'AdminCountriesController@deactive'); + $api->put('countries/{id}/active', 'AdminCountriesController@active'); + + // currencies + $api->delete('currencies/{id}', 'AdminCurrenciesController@destroy'); + $api->get('currencies', 'AdminCurrenciesController@index'); + $api->get('currencies/{id}/edit', 'AdminCurrenciesController@edit'); + $api->get('currencies/{id}', 'AdminCurrenciesController@show'); + $api->post('currencies', 'AdminCurrenciesController@store'); + $api->put('currencies/{id}', 'AdminCurrenciesController@update'); + + $api->get('discount_types', 'AdminDiscountTypesController@index'); + $api->get('duration_types', 'AdminDurationTypesController@index'); + + // admin dashboards + $api->get('stats', 'AdminDashboardsController@stats'); + + // email templates admin side + $api->get('email_templates', 'AdminEmailTemplatesController@index'); + $api->get('email_templates/{id}/edit', 'AdminEmailTemplatesController@edit'); + $api->get('email_templates/{id}', 'AdminEmailTemplatesController@edit'); + $api->put('email_templates/{id}', 'AdminEmailTemplatesController@update'); + + // ips + $api->delete('ips/{id}', 'AdminIpsController@destroy'); + $api->get('ips', 'AdminIpsController@index'); + $api->get('ips/{id}', 'AdminIpsController@show'); + + // languages admin side + $api->get('languages', 'AdminLanguagesController@index'); + $api->get('languages/{id}/edit', 'AdminLanguagesController@edit'); + $api->get('languages/{id}', 'AdminLanguagesController@edit'); + $api->post('languages', 'AdminLanguagesController@store'); + $api->put('languages/{id}', 'AdminLanguagesController@update'); + $api->delete('languages/{id}', 'AdminLanguagesController@destroy'); + + //Messages admin side + $api->get('messages', 'AdminMessagesController@index'); + //$api->get('item_messages/{item_id}', 'AdminMessagesController@itemActivities'); + //$api->get('item_user_messages/{item_user_id}', 'AdminMessagesController@bookerActivities'); + //$api->get('user_messages/{user_id}', 'AdminMessagesController@userActivities'); + $api->get('messages/{id}', 'AdminMessagesController@show'); + $api->delete('messages/{id}', 'AdminMessagesController@destroy'); + + // roles + $api->get('roles', 'AdminRolesController@index'); + + // Settings + $api->get('settings', 'AdminSettingsController@index'); + $api->get('settings/{id}/edit', 'AdminSettingsController@edit'); + $api->get('settings/{id}', 'AdminSettingsController@edit'); + $api->get('settings/{name}/show', 'AdminSettingsController@show'); + $api->get('setting_categories/{id}/settings', 'AdminSettingsController@settings'); + $api->put('settings/{id}', 'AdminSettingsController@update'); + $api->get('plugins', 'AdminSettingsController@getPlugin'); + $api->put('plugins', 'AdminSettingsController@updatePlugin'); + + // Setting Categories + $api->get('setting_categories', 'AdminSettingCategoriesController@index'); + $api->get('setting_categories/{id}', 'AdminSettingCategoriesController@show'); + + // states + $api->delete('states/{id}', 'AdminStatesController@destroy'); + $api->get('states', 'AdminStatesController@index'); + $api->get('states/{id}/edit', 'AdminStatesController@edit'); + $api->get('states/{id}', 'AdminStatesController@edit'); + $api->post('states', 'AdminStatesController@store'); + $api->put('states/{id}', 'AdminStatesController@update'); + $api->put('states/{id}/deactive', 'AdminStatesController@deactive'); + $api->put('states/{id}/active', 'AdminStatesController@active'); + + //Transactions admin side + $api->get('transactions', 'AdminTransactionsController@index'); + + //Transactions types admin side + $api->get('transaction_types', 'AdminTransactionTypesController@index'); + $api->get('transaction_types/{id}', 'AdminTransactionTypesController@show'); + $api->get('transaction_types/{id}/edit', 'AdminTransactionTypesController@edit'); + $api->put('transaction_types/{id}', 'AdminTransactionTypesController@update'); + + // users + $api->delete('users/{id}', 'AdminUsersController@destroy'); + $api->get('users', 'AdminUsersController@index'); + $api->get('users/{id}', 'AdminUsersController@show'); + $api->get('users/{id}/edit', 'AdminUsersController@edit'); + $api->post('users', 'AdminUsersController@store'); + $api->put('users/{id}', 'AdminUsersController@update'); + $api->put('users/{id}/change_password', 'AdminUsersController@changePassword'); + $api->put('users/{id}/deactive', 'AdminUsersController@deactive'); + $api->put('users/{id}/active', 'AdminUsersController@active'); + // user_logins + $api->delete('user_logins/{id}', 'AdminUserLoginsController@destroy'); + $api->get('user_logins', 'AdminUserLoginsController@index'); + $api->get('user_logins/{id}', 'AdminUserLoginsController@show'); + // wallet transaction log + $api->get('wallet_transaction_logs', 'AdminWalletTransactionLogsController@index'); + $api->get('wallet_transaction_logs/{id}', 'AdminWalletTransactionLogsController@show'); + }); + // , 'middleware' => 'apitracking' + $api->group(['namespace' => 'App\Http\Controllers', 'middleware' => 'apitracking'], function () use ($api) { + //cities user side + $api->get('/cities', 'CitiesController@index'); + //Settings user side + $api->get('/settings', 'SettingsController@index'); + //countries user side + $api->get('/countries', 'CountriesController@index'); + //currencies user side + $api->get('/currencies', 'CurrenciesController@index'); + //discount types + $api->get('discount_types', 'DiscountTypesController@index'); + // duration types + $api->get('duration_types', 'DurationTypesController@index'); + + //languages user side + $api->get('/languages', 'LanguagesController@index'); + + //Messages user side + $api->get('messages', 'MessagesController@inbox'); + $api->get('sentMessages', 'MessagesController@sentMessage'); + $api->get('starMessages', 'MessagesController@starMessage'); + $api->get('item_messages/{item_id}', 'MessagesController@itemActivities'); + $api->get('item_user_messages/{item_user_id}', 'MessagesController@bookerActivities'); + $api->post('messages/{user_id}/user', 'MessagesController@store'); + $api->get('messages/{id}', 'MessagesController@show'); + $api->post('messages/{id}/reply', 'MessagesController@reply'); + $api->post('private_notes', 'MessagesController@privateNote'); + $api->put('messages/{id}', 'MessagesController@update'); + + //states user side + $api->get('/states', 'StatesController@index'); + + //Transactions user side + $api->get('/transactions', 'TransactionsController@index'); + // Transaction Types user side + $api->get('/transaction_types', 'TransactionTypesController@index'); + + // users + $api->post('/users/login', 'UsersController@authenticate'); + $api->get('/users/auth', 'UsersController@getAuth'); + $api->post('/users/register', 'UsersController@register'); + $api->put('/users/{user_id}/activate/{hash}', 'UsersController@activate'); + $api->get('/user', 'UsersController@show'); + $api->put('/users/{user_id}/change_password', 'UsersController@changePassword'); + $api->put('/users/forgot_password', 'UsersController@forgotPassword'); + $api->get('users/{id}/attachment', 'UsersController@getUserUploadAttachment'); + $api->get('users/stats', 'UsersController@getStats'); + // user profiles + $api->get('/user_profiles/', 'UserProfilesController@edit'); + $api->post('/user_profiles/', 'UserProfilesController@update'); + + $api->get('/img/{size}/{model}/{filename}', 'ImagesController@create'); + $api->get('/assets/js/plugins.js', 'AssetsController@createJsTplFiles'); + + //get_gateways + $api->get('/get_gateways', 'PaymentGatewaysController@getGateways'); + + //wallet + $api->post('/wallets', 'WalletsController@addToWallet'); + }); +}); diff --git a/app/Ip.php b/app/Ip.php new file mode 100644 index 0000000..1edd853 --- /dev/null +++ b/app/Ip.php @@ -0,0 +1,109 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App; + +use Illuminate\Http\Request; +use Illuminate\Database\Eloquent\Model; + +class Ip extends Model +{ + /** + * @var string + */ + protected $table = "ips"; + + protected $fillable = ['city_id', 'state_id', 'country_id', 'host', 'ip', 'latitude', 'longitude', 'user_agent', 'timezone', 'is_checked']; + + /** + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function city() + { + return $this->belongsTo(City::class); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function state() + { + return $this->belongsTo(State::class); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function country() + { + return $this->belongsTo(Country::class); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\HasOne + */ + public function userloginUserLoginIp() + { + return $this->hasOne(UserLogin::class, 'user_login_ip_id'); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\HasMany + */ + public function userLastLoginIp() + { + return $this->hasOne(User::class, 'last_login_ip_id'); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\HasMany + */ + public function userRegiserIp() + { + return $this->hasOne(User::class, 'register_ip_id'); + } + + /** + * @param $query + * @param Request $request + * @return mixed + */ + public function scopeFilterByRequest($query, Request $request) + { + if ($request->input('sort', 'id') == 'State.name') { + $query->orderBy('state_name', $request->input('sortby', 'desc')); + } elseif ($request->input('sort', 'id') == 'Country.name') { + $query->orderBy('country_name', $request->input('sortby', 'desc')); + } elseif ($request->input('sort', 'id') == 'City.name') { + $query->orderBy('city_name', $request->input('sortby', 'desc')); + } else { + $query->orderBy($request->input('sort', 'id'), $request->input('sortby', 'desc')); + } + + if ($request->has('q')) { + $query->whereHas('City', function ($q) use ($request) { + $q->where('name', 'like', '%' . $request->input('q') . '%'); + }); + $query->orwhereHas('State', function ($q) use ($request) { + $q->where('name', 'like', '%' . $request->input('q') . '%'); + }); + $query->orwhereHas('Country', function ($q) use ($request) { + $q->where('name', 'like', '%' . $request->input('q') . '%'); + }); + } + return $query; + } + +} diff --git a/app/ItemUserStatus.php b/app/ItemUserStatus.php new file mode 100644 index 0000000..75d4486 --- /dev/null +++ b/app/ItemUserStatus.php @@ -0,0 +1,28 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App; + +use Illuminate\Http\Request; +use Illuminate\Database\Eloquent\Model; + +class ItemUserStatus extends Model +{ + /** + * @var string + */ + protected $table = "item_user_statuses"; + +} diff --git a/app/Jobs/Job.php b/app/Jobs/Job.php new file mode 100644 index 0000000..ca8cca3 --- /dev/null +++ b/app/Jobs/Job.php @@ -0,0 +1,37 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Jobs; + +use Illuminate\Bus\Queueable; +use Illuminate\Queue\SerializesModels; +use Illuminate\Queue\InteractsWithQueue; +use Illuminate\Contracts\Queue\ShouldQueue; + +abstract class Job implements ShouldQueue +{ + /* + |-------------------------------------------------------------------------- + | Queueable Jobs + |-------------------------------------------------------------------------- + | + | This job base class provides a central location to place any logic that + | is shared across all of your jobs. The trait included with the class + | provides access to the "queueOn" and "delay" queue helper methods. + | + */ + + use InteractsWithQueue, Queueable, SerializesModels; +} diff --git a/app/Language.php b/app/Language.php new file mode 100644 index 0000000..faf04da --- /dev/null +++ b/app/Language.php @@ -0,0 +1,98 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App; + +use Illuminate\Http\Request; +use Illuminate\Database\Eloquent\Model; + +/** + * Class Language + * @package App + */ +class Language extends Model +{ + /** + * @var string + */ + protected $table = "languages"; + + /** + * The attributes that are mass assignable. + * + * @var array + */ + protected $fillable = [ + 'name', 'iso2', 'iso3', 'is_active' + ]; + + /** + * @return \Illuminate\Database\Eloquent\Relations\HasMany + */ + public function Page() + { + return $this->hasMany(Page::class); + } + + /** + * @param $query + * @param Request $request + * @return mixed + */ + public function scopeFilterByRequest($query, Request $request) + { + $query->orderBy($request->input('sort', 'id'), $request->input('sortby', 'desc')); + if ($request->has('filter')) { + $filter = false; + if ($request->input('filter') == 'active') { + $filter = true; + } + $query->where('is_active', '=', $filter); + } + if ($request->has('q')) { + $query->where('name', 'LIKE', '%' . $request->input('q') . '%') + ->orWhere('iso2', 'LIKE', '%' . $request->input('q') . '%'); + } + return $query; + + + } + + /** + * @return array + */ + public function scopeGetValidationRule() + { + return [ + 'name' => 'required|min:2', + 'iso2' => 'required|min:2|max:2', + 'iso3' => 'required|min:3|max:3' + ]; + } + + public function scopeGetValidationMessage() + { + return [ + 'name.required' => 'Required', + 'name.min' => 'name - minimum length is 2', + 'iso2.required' => 'Required', + 'iso2.min' => 'iso2 - minimum length is 2', + 'iso2.max' => 'iso2 - maximum length is 2', + 'iso3.required' => 'Required', + 'iso3.min' => 'iso3 - minimum length is 2', + 'iso3.max' => 'iso3 - maximum length is 2', + ]; + } +} diff --git a/app/Message.php b/app/Message.php new file mode 100644 index 0000000..baf0e16 --- /dev/null +++ b/app/Message.php @@ -0,0 +1,128 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App; + +use Illuminate\Http\Request; +use Illuminate\Database\Eloquent\Model; +use Symfony\Component\Translation\MessageCatalogue; + +class Message extends Model +{ + /** + * @var string + */ + protected $table = "messages"; + + protected $fillable = [ + 'message_id', 'item_id', 'user_id', 'to_user_id', 'message_content_id', 'message_folder_id', 'messageable_id', 'messageable_type', 'is_sender', 'is_starred', 'is_read', 'is_deleted', 'is_archived', 'is_review', 'is_communication', 'hash', 'size', 'item_user_status_id', 'dispute_status_id' + ]; + + /** + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function from_user() + { + return $this->belongsTo(User::class, 'user_id'); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function to_user() + { + return $this->belongsTo(User::class, 'to_user_id'); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function message_content() + { + return $this->belongsTo(MessageContent::class); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\MorphTo + */ + public function messageable() + { + return $this->morphTo(); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function item_user_status() + { + return $this->belongsTo(\Plugins\VehicleRentals\Model\VehicleRentalStatus::class); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function dispute_status() + { + return $this->belongsTo(\Plugins\VehicleDisputes\Model\VehicleDisputeStatus::class); + } + + + + /** + * @param $query + * @param Request $request + * @return mixed + */ + public function scopeFilterByRequest($query, Request $request) + { + $query->orderBy($request->input('sort', 'id'), $request->input('sortby', 'desc')); + if ($request->has('q')) { + $query->whereHas('from_user', function ($q) use ($request) { + $q->where('username', 'like', '%' . $request->input('q') . '%'); + }); + $query->orWhereHas('to_user', function ($q) use ($request) { + $q->Where('username', 'like', '%' . $request->input('q') . '%'); + }); + $query->orWhereHas('message_content', function ($q) use ($request) { + $q->Where('subject', 'like', '%' . $request->input('q') . '%'); + }); + } + if ($request->input('filter') === 'vehicle_rental_messages') { + $query->where('messageable_type', '=', 'MorphVehicleRental'); + } else if ($request->input('filter') === 'user_messages') { + $query->where('messageable_type', '=', 'MorphUser'); + } + return $query; + } + + /** + * @return array + */ + public function scopeGetValidationRule() + { + return [ + 'message' => 'required', + 'subject' => 'sometimes|required' + ]; + } + + public function scopeGetValidationMessage() + { + return [ + 'message.required' => 'Required', + 'subject.required' => 'Required', + ]; + } +} diff --git a/app/MessageContent.php b/app/MessageContent.php new file mode 100644 index 0000000..9117aab --- /dev/null +++ b/app/MessageContent.php @@ -0,0 +1,39 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App; + +use Illuminate\Http\Request; +use Illuminate\Database\Eloquent\Model; + +class MessageContent extends Model +{ + /** + * @var string + */ + protected $table = "message_contents"; + + protected $fillable = [ + 'subject', 'message', 'admin_suspend', 'is_system_flagged', 'detected_suspicious_words' + ]; + + /** + * @return \Illuminate\Database\Eloquent\Relations\HasMany + */ + public function message() + { + return $this->hasMany(Message::class); + } +} diff --git a/app/Plugins/Analytics/plugin.json b/app/Plugins/Analytics/plugin.json new file mode 100644 index 0000000..c4032b3 --- /dev/null +++ b/app/Plugins/Analytics/plugin.json @@ -0,0 +1,9 @@ +{ + "name": "Analytics", + "class": "fa fa-2x fa-user-md", + "description": "By enabling this plugin, we can easily understand about our audience and easily get statistic analysing about the site in google or facebook site. The Analytics plugin has two options: Google Analytics and Facebook Pixel.", + "dependencies": "", + "module_id": "789", + "module_hash": "bd90e913319ba5c39f83629e7ee430e7", + "display_order": "1" +} diff --git a/app/Plugins/Banner/plugin.json b/app/Plugins/Banner/plugin.json new file mode 100644 index 0000000..b7b8ac1 --- /dev/null +++ b/app/Plugins/Banner/plugin.json @@ -0,0 +1,9 @@ +{ + "name": "Banner", + "class": "fa fa-2x fa-image", + "description": "Banner for all page bottom, all page top, course page sidebar, profile page sidebar.", + "dependencies": "", + "module_id": "790", + "module_hash": "7e9349c79b206168a3cd1c5187dd8e96", + "display_order": "2" +} diff --git a/app/Plugins/Contacts/Controllers/Admin/AdminContactsController.php b/app/Plugins/Contacts/Controllers/Admin/AdminContactsController.php new file mode 100644 index 0000000..2316168 --- /dev/null +++ b/app/Plugins/Contacts/Controllers/Admin/AdminContactsController.php @@ -0,0 +1,100 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Contacts\Controllers\Admin; + +use Illuminate\Http\Request; + +use App\Http\Controllers\Controller; +use Plugins\Contacts\Model\Contact; +use JWTAuth; +use Validator; +use Plugins\Contacts\Transformers\ContactTransformer; + +/** + * Contacts resource representation. + * @Resource("Admin/AdminContacts") + */ +class AdminContactsController extends Controller +{ + /** + * AdminContactsController constructor. + */ + public function __construct() + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth'); + // Check the logged user role. + $this->middleware('role'); + } + + /** + * Show all contacts + * Get a JSON representation of all the contacts. + * + * @Get("/contacts?sort={sort}&sortby={sortby}&page={page}&q={q}") + * @Parameters({ + * @Parameter("sort", type="string", required=false, description="Sort the contacts list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort contacts by Ascending / Descending Order.", default=null), + * @Parameter("q", type="string", required=false, description="Search Contacts.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1) + * }) + */ + public function index(Request $request) + { + $contacts = Contact::with('user', 'ip')->filterByRequest($request)->paginate(config('constants.ConstPageLimit')); + return $this->response->paginator($contacts, (new ContactTransformer)->setDefaultIncludes(['user', 'ip'])); + } + + /** + * Edit the specified contact. + * Edit the contact with a `id`. + * @Get("/contacts/{id}/edit") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body= {"id": 1, "user_id": 1, "first_name": "XXXXXX", "last_name": "XXXXXX", "email": "guest@gmail.com", "subject": "XXXXXX", "message": "XXXXXX", "telephone": "XXXXXX", "user_type": "Guest", "User": {}, "Ip": {}}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function edit($id) + { + $contact = Contact::with('user', 'ip')->find($id); + if (!$contact) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($contact, (new ContactTransformer)->setDefaultIncludes(['user', 'ip'])); + } + + /** + * Delete the specified contact. + * Delete the contact with a `id`. + * @Delete("/contacs/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"success": "Record Deleted."}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function destroy($id) + { + $contact = Contact::find($id); + if (!$contact) { + return $this->response->errorNotFound("Invalid Request"); + } else { + $contact->delete(); + } + return response()->json(['Success' => 'Contact deleted'], 200); + } +} diff --git a/app/Plugins/Contacts/Controllers/ContactsController.php b/app/Plugins/Contacts/Controllers/ContactsController.php new file mode 100644 index 0000000..ebbbfcf --- /dev/null +++ b/app/Plugins/Contacts/Controllers/ContactsController.php @@ -0,0 +1,103 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Contacts\Controllers; + +use App\Services\IpService; +use App\Services\UserService; +use Plugins\Contacts\Services\ContactService; +use Illuminate\Http\Request; + +use App\Http\Controllers\Controller; +use Plugins\Contacts\Model\Contact; +use JWTAuth; +use Validator; + +/** + * Contacts resource representation. + * @Resource("Contacts") + */ +class ContactsController extends Controller +{ + /** + * @var IpService + */ + protected $IpService; + /** + * @var UserService + */ + protected $user_service; + /** + * @var ContactService + */ + protected $contact_service; + + /** + * ContactsController constructor. + */ + public function __construct(UserService $user_service) + { + $this->UserService = $user_service; + $this->setIpService(); + $this->setContactService(); + } + + public function setIpService() + { + $this->IpService = new IpService(); + } + + public function setContactService() + { + $this->ContactService = new ContactService(); + } + + /** + * Store a new contact. + * Store a new contact with a `user_id`, `ip_id`, 'first_name', 'last_name', 'subject', 'message', 'telephone', 'email'. + * @Post("/contacts") + * @Transaction({ + * @Request({"user_id": 1, "first_name": "Ahsan", "last_name": "L", "email": "guest@gmail.com", "subject": "Regarding VehicleRental", "message": "Need to Anke a vehicle_rental,. Where can i do that?", "telephone": "XXXXXX"}), + * @Response(200, body={"success": "Record has been added."}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {"name": {}}, "status_code": 422}) + * }) + */ + public function store(Request $request) + { + $contact_data = $request->only('first_name', 'last_name', 'subject', 'message', 'telephone', 'email', 'user_id', 'ip_id'); + $validator = Validator::make($contact_data, Contact::GetValidationRule(), Contact::GetValidationMessage()); + if ($validator->passes()) { + $contact_data['ip_id'] = $this->IpService->getIpId($request->ip()); + $user = $this->auth->user(); + if ($user) { + $contact_data['user_id'] = $user->id; + } + //Captcha verification + $captcha = $request['recaptcha_response']; + if ($this->UserService->captchaCheck($captcha) == false) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Captcha Verification failed.'); + } + $contact = Contact::create($contact_data); + if ($contact) { + $this->ContactService->sendContactMail($request); + return response()->json(['Success' => 'You have Successfully Contacted us. Will contact you soon'], 200); + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Contact message could not be sent. Please, try again.'); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Contact message could not be sent. Please, try again.', $validator->errors()); + } + } +} diff --git a/app/Plugins/Contacts/Model/Contact.php b/app/Plugins/Contacts/Model/Contact.php new file mode 100644 index 0000000..92d7f8b --- /dev/null +++ b/app/Plugins/Contacts/Model/Contact.php @@ -0,0 +1,114 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Contacts\Model; + +use Illuminate\Http\Request; +use Illuminate\Database\Eloquent\Model; +use App\User; +use App\Ip; + +class Contact extends Model +{ + /** + * @var string + */ + protected $table = "contacts"; + + protected $fillable = [ + 'first_name', 'last_name', 'subject', 'message', 'telephone', 'email', 'user_id', 'ip_id' + ]; + + + /** + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function user() + { + return $this->belongsTo(User::class); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function ip() + { + return $this->belongsTo(Ip::class); + } + + /** + * @param $query + * @param Request $request + * @return mixed + */ + public function scopeFilterByRequest($query, Request $request) + { + if($request->has('sort') && $request->sort == 'user_type'){ + $query->orderBy('user_id', $request->input('sortby', 'desc')); + } else if($request->has('sort') && $request->sort == 'ip.ip'){ + $query->orderBy('ip_id', $request->input('sortby', 'desc')); + } else { + $query->orderBy($request->input('sort', 'id'), $request->input('sortby', 'asc')); + } + + if ($request->has('q')) { + $query->where('first_name', 'LIKE', '%' . $request->input('q') . '%') + ->orWhere('last_name', 'LIKE', '%' . $request->input('q') . '%') + ->orWhere('email', 'LIKE', '%' . $request->input('q') . '%') + ->orWhere('subject', 'LIKE', '%' . $request->input('q') . '%') + ->orWhere('message', 'LIKE', '%' . $request->input('q') . '%'); + } + return $query; + } + + /** + * @return array + */ + public function scopeGetValidationRule() + { + return [ + 'first_name' => 'required|min:2', + 'last_name' => 'required|min:2', + 'user_id' => 'integer', + 'email' => 'required|email', + 'subject' => 'required|min:5', + 'message' => 'required|min:10', + 'telephone' => 'required|min:10' + ]; + } + + /** + * @return array + */ + public function scopeGetValidationMessage() + { + return [ + 'first_name.required' => 'Required', + 'first_name.min' => 'first_name - Minimum length is 2!', + 'last_name.required' => 'Required', + 'last_name.min' => 'last_name - Minimum length is 2!', + 'user_id.integer' => 'User id must be a number', + 'email.required' => 'Required', + 'email.email' => 'Enter valid e-mail address!', + 'subject.required' => 'Required', + 'subject.min' => 'subject - Minimum length is 5', + 'message.required' => 'Required', + 'message.min' => 'message -Minimum length is 10', + 'telephone.required' => 'Required', + 'telephone.min' => 'telephone - Minimum length is 10' + ]; + } + +} diff --git a/app/Plugins/Contacts/Providers/ContactServiceProvider.php b/app/Plugins/Contacts/Providers/ContactServiceProvider.php new file mode 100644 index 0000000..f414eae --- /dev/null +++ b/app/Plugins/Contacts/Providers/ContactServiceProvider.php @@ -0,0 +1,43 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Contacts\Providers; + +use Illuminate\Support\ServiceProvider; + +class ContactServiceProvider extends ServiceProvider +{ + /** + * Register any application services. + * + * @return void + */ + public function register() + { + include __DIR__ . '/../routes.php'; + $this->app->make('Plugins\Contacts\Controllers\ContactsController'); + $this->app->make('Plugins\Contacts\Controllers\Admin\AdminContactsController'); + } + + /** + * Bootstrap the application services. + * + * @return void + */ + public function boot() + { + + } +} diff --git a/app/Plugins/Contacts/Services/ContactService.php b/app/Plugins/Contacts/Services/ContactService.php new file mode 100644 index 0000000..0de0777 --- /dev/null +++ b/app/Plugins/Contacts/Services/ContactService.php @@ -0,0 +1,71 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Contacts\Services; + +use App\Services\MailService; + +class ContactService +{ + + /** + * @var MailService + */ + protected $mail_service; + + /** + * ContactService constructor. + */ + + public function __construct() + { + $this->setMailService(); + } + + public function setMailService() + { + $this->MailService = new MailService(); + } + + /** + * Send Contact Mail + * @param $request + */ + public function sendContactMail($request) + { + // send mail to admin + $template = $this->MailService->getTemplate('Contact Us'); + $emailFindReplace = array( + '##FIRST_NAME##' => $request->first_name, + '##LAST_NAME##' => $request->last_name, + '##FROM_URL##' => 'Contact Us', + '##IP##' => $request->ip(), + '##MESSAGE##' => $request->message, + '##SUBJECT##' => $request->subject, + '##TELEPHONE##' => $request->telephone, + ); + $this->MailService->sendMail($template, $emailFindReplace, config('site.reply_to_email'), 'Admin'); + + // send auto reply to user + $template = $this->MailService->getTemplate('Contact Us Auto Reply'); + $emailFindReplace = array( + '##USERNAME##' => $request->first_name . ' ' . $request->last_name, + '##SUBJECT##' => $request->subject, + '##MESSAGE##' => $request->message, + '##CONTACT_URL##' => 'Contact Us' + ); + $this->MailService->sendMail($template, $emailFindReplace, $request->email, $request->first_name); + } +} diff --git a/app/Plugins/Contacts/Transformers/ContactTransformer.php b/app/Plugins/Contacts/Transformers/ContactTransformer.php new file mode 100644 index 0000000..fa13f75 --- /dev/null +++ b/app/Plugins/Contacts/Transformers/ContactTransformer.php @@ -0,0 +1,76 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Contacts\Transformers; + +use League\Fractal; +use Plugins\Contacts\Model\Contact; +use App\Transformers\UserTransformer; +use App\Transformers\IpTransformer; + +/** + * Class ContactTransformer + * @package Contacts\Transformers + */ +class ContactTransformer extends Fractal\TransformerAbstract +{ + /** + * List of resources possible to include + * + * @var array + */ + protected $availableIncludes = [ + 'User', 'Ip' + ]; + + /** + * @param Contact $contact + * @return array + */ + public function transform(Contact $contact) + { + $output = array_only($contact->toArray(), ['id', 'user_id', 'first_name', 'last_name', 'subject', 'message', 'telephone', 'email']); + $output['user_type'] = empty($output['user_id']) ? "Guest" : $contact['user']['username']; + return $output; + } + + /** + * @param Contact $contact + * @return Fractal\Resource\Item + */ + public function includeUser(Contact $contact) + { + if ($contact->user) { + return $this->item($contact->user, new UserTransformer()); + } else { + return null; + } + + } + + /** + * @param Contact $contact + * @return Fractal\Resource\Item + */ + public function includeIp(Contact $contact) + { + if ($contact->ip) { + return $this->item($contact->ip, new IpTransformer()); + } else { + return null; + } + + } +} \ No newline at end of file diff --git a/app/Plugins/Contacts/plugin.json b/app/Plugins/Contacts/plugin.json new file mode 100644 index 0000000..47b14d2 --- /dev/null +++ b/app/Plugins/Contacts/plugin.json @@ -0,0 +1,9 @@ +{ + "name": "Contacts", + "class": "fa fa-2x fa-support", + "description": "By enabling this plugin, user can easily interact with admin", + "dependencies": "", + "module_id": "", + "module_hash": "", + "display_order": "3" +} diff --git a/app/Plugins/Contacts/routes.php b/app/Plugins/Contacts/routes.php new file mode 100644 index 0000000..ad640a6 --- /dev/null +++ b/app/Plugins/Contacts/routes.php @@ -0,0 +1,37 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ +/* +|-------------------------------------------------------------------------- +| Application Routes +|-------------------------------------------------------------------------- +| +| Here is where you can register all of the routes for an application. +| It is a breeze. Simply tell Lumen the URIs it should respond to +| and give it the Closure to call when that URI is requested. +| +*/ +$api = $this->app->make('Dingo\Api\Routing\Router'); +$api->version(['v1'], function ($api) { + $api->group(['prefix' => 'admin', 'namespace' => 'Plugins\Contacts\Controllers\Admin', 'middleware' => 'apitracking'], function () use ($api) { + // contacts admin side + $api->delete('contacts/{id}', 'AdminContactsController@destroy'); + $api->get('contacts', 'AdminContactsController@index'); + $api->get('contacts/{id}', 'AdminContactsController@edit'); + }); + $api->group(['namespace' => 'Plugins\Contacts\Controllers', 'middleware' => 'apitracking'], function () use ($api) { + //contacts user side + $api->post('/contacts', 'ContactsController@store'); + }); +}); diff --git a/app/Plugins/CurrencyConversions/Controllers/Admin/AdminCurrencyConversionHistoriesController.php b/app/Plugins/CurrencyConversions/Controllers/Admin/AdminCurrencyConversionHistoriesController.php new file mode 100644 index 0000000..a8c81f0 --- /dev/null +++ b/app/Plugins/CurrencyConversions/Controllers/Admin/AdminCurrencyConversionHistoriesController.php @@ -0,0 +1,67 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\CurrencyConversions\Controllers\Admin; + +use Illuminate\Http\Request; + + +use App\Http\Controllers\Controller; + +use Plugins\CurrencyConversions\Model\CurrencyConversionHistory; + +use JWTAuth; +use Validator; +use Tymon\JWTAuth\Exceptions\JWTException; +use Plugins\CurrencyConversions\Transformers\CurrencyConversionHistoryTransformer; +use DB; + +/** + * CurrencyConversionHistories resource representation. + * @Resource("Admin/AdminCurrencyConversionHistories") + */ +class AdminCurrencyConversionHistoriesController extends Controller +{ + public function __construct() + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth'); + // Check the logged user role. + $this->middleware('role'); + } + + /** + * Show all api requests. + * Get a JSON representation of all the api requests. + * + * @Get("/currency_conversion_histories?sort={sort}&sortby={sortby}") + * @Parameters({ + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1), + * @Parameter("sort", type="string", required=false, description="Sort the currency conversion histories list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort currency conversion histories by Ascending / Descending Order.", default=null), + * }) + */ + public function index(Request $request) + { + $currency_conversion_histories = CurrencyConversionHistory::with('currency_conversion') + ->select(DB::raw('currency_conversion_histories.*')) + ->leftJoin(DB::raw('(select id, currency_id, converted_currency_id from currency_conversions) as currency_conversion'), 'currency_conversion.id', '=', 'currency_conversion_histories.currency_conversion_id') + ->leftJoin(DB::raw('(select id,name from currencies) as currency'), 'currency.id', '=', 'currency_conversion.currency_id') + ->leftJoin(DB::raw('(select id,name from currencies) as converted_currency'), 'converted_currency.id', '=', 'currency_conversion.converted_currency_id') + ->filterByRequest($request)->paginate(config('constants.ConstPageLimit')); + + return $this->response->paginator($currency_conversion_histories, (new CurrencyConversionHistoryTransformer)->setDefaultIncludes(['currency_conversion'])); + } +} \ No newline at end of file diff --git a/app/Plugins/CurrencyConversions/Controllers/Admin/AdminCurrencyConversionsController.php b/app/Plugins/CurrencyConversions/Controllers/Admin/AdminCurrencyConversionsController.php new file mode 100644 index 0000000..bc7790e --- /dev/null +++ b/app/Plugins/CurrencyConversions/Controllers/Admin/AdminCurrencyConversionsController.php @@ -0,0 +1,64 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\CurrencyConversions\Controllers\Admin; + +use Illuminate\Http\Request; + + +use App\Http\Controllers\Controller; + +use Plugins\CurrencyConversions\Model\CurrencyConversion; + +use JWTAuth; +use Validator; +use Tymon\JWTAuth\Exceptions\JWTException; +use Plugins\CurrencyConversions\Transformers\CurrencyConversionTransformer; +use DB; +/** + * CurrencyConversions resource representation. + * @Resource("Admin/AdminCurrencyConversions") + */ +class AdminCurrencyConversionsController extends Controller +{ + public function __construct() + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth'); + // Check the logged user role. + $this->middleware('role'); + } + + /** + * Show all api requests. + * Get a JSON representation of all the api requests. + * + * @Get("/currency_conversions?sort={sort}&sortby={sortby}") + * @Parameters({ + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1), + * @Parameter("sort", type="string", required=false, description="Sort the currency conversions list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort currency conversions by Ascending / Descending Order.", default=null), + * }) + */ + public function index(Request $request) + { + $currency_conversions = CurrencyConversion::with('currency', 'converted_currency') + ->select(DB::raw('currency_conversions.*')) + ->leftJoin(DB::raw('(select id,name from currencies) as currency'), 'currency.id', '=', 'currency_conversions.currency_id') + ->leftJoin(DB::raw('(select id,name from currencies) as converted_currency'), 'converted_currency.id', '=', 'currency_conversions.converted_currency_id') + ->filterByRequest($request)->paginate(config('constants.ConstPageLimit')); + return $this->response->paginator($currency_conversions, (new CurrencyConversionTransformer)->setDefaultIncludes(['currency', 'converted_currency'])); + } +} \ No newline at end of file diff --git a/app/Plugins/CurrencyConversions/Model/CurrencyConversion.php b/app/Plugins/CurrencyConversions/Model/CurrencyConversion.php new file mode 100644 index 0000000..be1754f --- /dev/null +++ b/app/Plugins/CurrencyConversions/Model/CurrencyConversion.php @@ -0,0 +1,105 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\CurrencyConversions\Model; + +use Illuminate\Http\Request; +use Illuminate\Database\Eloquent\Model; +use App\Currency; + +class CurrencyConversion extends Model +{ + /** + * @var string + */ + protected $table = "currency_conversions"; + + /** + * The attributes that are mass assignable. + * + * @var array + */ + protected $fillable = [ + 'currency_id', 'converted_currency_id', 'rate' + ]; + + + /** + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function currency() + { + return $this->belongsTo(Currency::class, 'currency_id'); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function converted_currency() + { + return $this->belongsTo(Currency::class, 'converted_currency_id'); + } + + /** + * @param $query + * @param Request $request + * @return mixed + */ + public function scopeFilterByRequest($query, Request $request) + { + $query->orderBy($request->input('sort', 'id'), $request->input('sortby', 'desc')); + if ($request->has('q')) { + $query->orWhereHas('Currency', function ($q) use ($request) { + $q->where('name', 'like', '%' . $request->input('q') . '%'); + }); + $query->orWhereHas('ConvertedCurrency', function ($q) use ($request) { + $q->where('name', 'like', '%' . $request->input('q') . '%'); + }); + } + if ($request->has('from_currency')) { + $query->where('currency_id', '=', $request->input('from_currency')); + } + if ($request->has('to_currency')) { + $query->where('converted_currency_id', '=', $request->input('to_currency')); + } + return $query; + } + + /** + * @return array + */ + public function scopeGetValidationRule() + { + return [ + 'currency_id' => 'required|integer|exists:currencies,id', + 'converted_currency_id' => 'required|integer|exists:currencies,id', + 'rate' => 'required|numeric' + ]; + } + + public function scopeGetValidationMessage() + { + return [ + 'currency_id.required' => 'Required', + 'currency_id.integer' => 'Currency id must be a number!', + 'currency_id.exists' => 'Invalid currency id', + 'converted_currency_id.required' => 'Required', + 'converted_currency_id.integer' => 'Converted currency id must be a number!', + 'converted_currency_id.exists' => 'Invalid converted currency id', + 'rate.required' => 'Required', + 'rate.numeric' => 'Rate must be a number!' + ]; + } +} diff --git a/app/Plugins/CurrencyConversions/Model/CurrencyConversionHistory.php b/app/Plugins/CurrencyConversions/Model/CurrencyConversionHistory.php new file mode 100644 index 0000000..cbe4ce5 --- /dev/null +++ b/app/Plugins/CurrencyConversions/Model/CurrencyConversionHistory.php @@ -0,0 +1,106 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\CurrencyConversions\Model; + +use Illuminate\Http\Request; +use Illuminate\Database\Eloquent\Model; + +class CurrencyConversionHistory extends Model +{ + /** + * @var string + */ + protected $table = "currency_conversion_histories"; + + /** + * The attributes that are mass assignable. + * + * @var array + */ + protected $fillable = [ + 'currency_conversion_id', 'rate_before_change', 'rate' + ]; + + /** + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function currency_conversion() + { + return $this->belongsTo(CurrencyConversion::class); + } + + /** + * @param $query + * @param Request $request + * @return mixed + */ + public function scopeFilterByRequest($query, Request $request) + { + $query->orderBy($request->input('sort', 'id'), $request->input('sortby', 'desc')); + if ($request->has('q')) { + $query->orWhereHas('currency_conversion.Currency', function ($q) use ($request) { + $q->where('name', 'like', '%' . $request->input('q') . '%'); + }); + $query->orWhereHas('currency_conversion.ConvertedCurrency', function ($q) use ($request) { + $q->where('name', 'like', '%' . $request->input('q') . '%'); + }); + } + if ($request->has('start_date')) { + $start_date = date("Y-m-d H:i:s", strtotime($request->input('start_date'))); + $query->where('created_at', '>=', $start_date); + } + if ($request->has('end_date')) { + $end_date = date("Y-m-d H:i:s", strtotime($request->input('end_date'))); + $query->where('created_at', '<=', $end_date); + } + if ($request->has('from_currency')) { + $query->orWhereHas('currency_conversion', function ($q) use ($request) { + $q->where('currency_id', '=', $request->input('from_currency')); + }); + } + if ($request->has('to_currency')) { + $query->orWhereHas('currency_conversion', function ($q) use ($request) { + $q->where('converted_currency_id', '=', $request->input('to_currency')); + }); + } + return $query; + } + + /** + * @return array + */ + public function scopeGetValidationRule() + { + return [ + 'currency_conversion_id' => 'required|integer|exists:currency_conversions,id', + 'rate_before_change' => 'required|numeric', + 'rate' => 'required|numeric' + ]; + } + + public function scopeGetValidationMessage() + { + return [ + 'currency_conversion_id.required' => 'Required', + 'currency_conversion_id.integer' => 'Currency conversion id must be a number', + 'currency_conversion_id.exists' => 'Invalid currency conversion id', + 'rate_before_change.required' => 'Required', + 'rate_before_change.numeric' => 'rate_before_change must be a number', + 'rate.required' => 'Required', + 'rate.numeric' => 'Rate must be a number!', + ]; + } +} diff --git a/app/Plugins/CurrencyConversions/Providers/CurrencyConversionServiceProvider.php b/app/Plugins/CurrencyConversions/Providers/CurrencyConversionServiceProvider.php new file mode 100644 index 0000000..6b86bea --- /dev/null +++ b/app/Plugins/CurrencyConversions/Providers/CurrencyConversionServiceProvider.php @@ -0,0 +1,42 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\CurrencyConversions\Providers; + +use Illuminate\Support\ServiceProvider; +class CurrencyConversionServiceProvider extends ServiceProvider +{ + /** + * Register any application services. + * + * @return void + */ + public function register() + { + include __DIR__ . '/../routes.php'; + $this->app->make('Plugins\CurrencyConversions\Controllers\Admin\AdminCurrencyConversionsController'); + $this->app->make('Plugins\CurrencyConversions\Controllers\Admin\AdminCurrencyConversionHistoriesController'); + } + + /** + * Bootstrap the application services. + * + * @return void + */ + public function boot() + { + + } +} diff --git a/app/Plugins/CurrencyConversions/Services/CurrencyConversionService.php b/app/Plugins/CurrencyConversions/Services/CurrencyConversionService.php new file mode 100644 index 0000000..e78364c --- /dev/null +++ b/app/Plugins/CurrencyConversions/Services/CurrencyConversionService.php @@ -0,0 +1,84 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\CurrencyConversions\Services; + +use App\Currency; +use Plugins\CurrencyConversions\Model\CurrencyConversion; +use Plugins\CurrencyConversions\Model\CurrencyConversionHistory; +use Validator; + +class CurrencyConversionService +{ + /** + * updates daily currency rates in currency_conversion & currency_conversion_history table through cron + */ + public function currencyconversion() + { + $currency_conversion_data = []; + $currency_conversion_history_data = []; + $httpAdapter = new \Ivory\HttpAdapter\FileGetContentsHttpAdapter(); + $chainProvider = new \Swap\Provider\ChainProvider([ + new \Swap\Provider\YahooFinanceProvider($httpAdapter), + new \Swap\Provider\GoogleFinanceProvider($httpAdapter) + ]); + $swap = new \Swap\Swap($chainProvider); + $currency_list = Currency::select('id', 'code')->get(); + $active_currencies = Currency::select('id', 'code')->where('is_active', '=', 1)->get(); + foreach ($currency_list as $currency) { + foreach ($active_currencies as $active_currency) { + $currency_conversion_data['currency_id'] = $currency->id; + $currency_conversion_data['converted_currency_id'] = $active_currency->id; + $rate = $swap->quote($currency->code . '/' . $active_currency->code); + $currency_conversion_data['rate'] = (double)$rate->getValue(); + $currency_conversion_list = CurrencyConversion::where('currency_id', '=', $currency->id) + ->where('converted_currency_id', '=', $active_currency->id)->first(); + if ($currency_conversion_list) { + $currency_conversion_data['id'] = $currency_conversion_list->id; + $currency_conversion_history_data['rate_before_change'] = $currency_conversion_list->rate; + $currency_conversion_history_data['currency_conversion_id'] = $currency_conversion_list->id; + $validator = Validator::make($currency_conversion_data, CurrencyConversion::GetValidationRule()); + if ($validator->passes() && $currency_conversion_list) { + $currency_conversion_list->update($currency_conversion_data); + } + } else { + $currency_conversion_history_data['rate_before_change'] = 0.00; + $validator = Validator::make($currency_conversion_data, CurrencyConversion::GetValidationRule()); + if ($validator->passes()) { + $currency_conversion = CurrencyConversion::create($currency_conversion_data); + $currency_conversion_history_data['currency_conversion_id'] = $currency_conversion->id; + } + } + $currency_conversion_history_data['rate'] = (double)$rate->getValue(); + $validator = Validator::make($currency_conversion_history_data, CurrencyConversionHistory::GetValidationRule()); + if ($validator->passes()) { + CurrencyConversionHistory::create($currency_conversion_history_data); + } + } + } + } + + public function getCurrencyconvertion() { + $currency = Currency::where('code', config('site.currency_code'))->first(); + $currency_conversion = CurrencyConversion::with(['converted_currency', 'currency'])->where('currency_id', $currency->id)->get(); + $currency_response = array(); + foreach($currency_conversion as $currency) { + $currency_response[] = $currency->converted_currency; + $currency->converted_currency['rate'] = $currency->rate; + } + $response['currency_conversion'] = $currency_response; + return $response; + } +} diff --git a/app/Plugins/CurrencyConversions/Transformers/CurrencyConversionHistoryTransformer.php b/app/Plugins/CurrencyConversions/Transformers/CurrencyConversionHistoryTransformer.php new file mode 100644 index 0000000..52e2ec8 --- /dev/null +++ b/app/Plugins/CurrencyConversions/Transformers/CurrencyConversionHistoryTransformer.php @@ -0,0 +1,59 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\CurrencyConversions\Transformers; + +use League\Fractal; +use Plugins\CurrencyConversions\Model\CurrencyConversionHistory; + +/** + * Class CurrencyConversionHistoryTransformer + * @package App\Transformers + */ +class CurrencyConversionHistoryTransformer extends Fractal\TransformerAbstract +{ + /** + * List of resources possible to include + * + * @var array + */ + protected $availableIncludes = [ + 'CurrencyConversion' + ]; + + /** + * @param CurrencyConversionHistory $currency_conversion_histories + * @return array + */ + public function transform(CurrencyConversionHistory $currency_conversion_history) + { + $output = array_only($currency_conversion_history->toArray(), ['id', 'created_at', 'currency_conversion_id', 'rate_before_change', 'rate']); + return $output; + } + + /** + * @param CurrencyConversionHistory $currency_conversion_history + * @return Fractal\Resource\Item + */ + public function includeCurrencyConversion(CurrencyConversionHistory $currency_conversion_history) + { + if ($currency_conversion_history->currency_conversion) { + return $this->item($currency_conversion_history->currency_conversion, (new CurrencyConversionTransformer)->setDefaultIncludes(['currency', 'converted_currency'])); + } else { + return null; + } + + } +} \ No newline at end of file diff --git a/app/Plugins/CurrencyConversions/Transformers/CurrencyConversionTransformer.php b/app/Plugins/CurrencyConversions/Transformers/CurrencyConversionTransformer.php new file mode 100644 index 0000000..db0d6e2 --- /dev/null +++ b/app/Plugins/CurrencyConversions/Transformers/CurrencyConversionTransformer.php @@ -0,0 +1,74 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ +namespace Plugins\CurrencyConversions\Transformers; + +use League\Fractal; +use Plugins\CurrencyConversions\Model\CurrencyConversion; +use App\Transformers\CurrencyTransformer; + +/** + * Class CurrencyConversionTransformer + * @package App\Transformers + */ +class CurrencyConversionTransformer extends Fractal\TransformerAbstract +{ + /** + * List of resources possible to include + * + * @var array + */ + protected $availableIncludes = [ + 'Currency', 'ConvertedCurrency' + ]; + + /** + * @param CurrencyConversion $currency_conversion + * @return array + */ + public function transform(CurrencyConversion $currency_conversion_history) + { + $output = array_only($currency_conversion_history->toArray(), ['id', 'updated_at', 'currency_id', 'converted_currency_id', 'rate']); + return $output; + } + + /** + * @param CurrencyConversion $currency_conversion + * @return Fractal\Resource\Item + */ + public function includeCurrency(CurrencyConversion $currency_conversion) + { + if ($currency_conversion->currency) { + return $this->item($currency_conversion->currency, new CurrencyTransformer()); + } else { + return null; + } + + } + + /** + * @param CurrencyConversion $currency_conversion + * @return Fractal\Resource\Item + */ + public function includeConvertedCurrency(CurrencyConversion $currency_conversion) + { + if ($currency_conversion->converted_currency) { + return $this->item($currency_conversion->converted_currency, new CurrencyTransformer()); + } else { + return null; + } + + } + +} \ No newline at end of file diff --git a/app/Plugins/CurrencyConversions/plugin.json b/app/Plugins/CurrencyConversions/plugin.json new file mode 100644 index 0000000..58d23fb --- /dev/null +++ b/app/Plugins/CurrencyConversions/plugin.json @@ -0,0 +1,9 @@ +{ + "name": "CurrencyConversions", + "class": "fa fa-2x fa-money", + "description": "By enabling this plugin, Convert the currency code.", + "dependencies": "", + "module_id": "791", + "module_hash": "9f76c6399b9ccb8c6f9f9127bba0b6d3", + "display_order": "3" +} diff --git a/app/Plugins/CurrencyConversions/routes.php b/app/Plugins/CurrencyConversions/routes.php new file mode 100644 index 0000000..829a20e --- /dev/null +++ b/app/Plugins/CurrencyConversions/routes.php @@ -0,0 +1,34 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ +/* +|-------------------------------------------------------------------------- +| Application Routes +|-------------------------------------------------------------------------- +| +| Here is where you can register all of the routes for an application. +| It is a breeze. Simply tell Lumen the URIs it should respond to +| and give it the Closure to call when that URI is requested. +| +*/ +$api = $this->app->make('Dingo\Api\Routing\Router'); +$api->version(['v1'], function ($api) { + + $api->group(['prefix' => 'admin', 'namespace' => 'Plugins\CurrencyConversions\Controllers\Admin', 'middleware' => 'apitracking'], function () use ($api) { + // currency conversion history + $api->get('currency_conversion_histories', 'AdminCurrencyConversionHistoriesController@index'); + // currency conversions + $api->get('currency_conversions', 'AdminCurrencyConversionsController@index'); + }); +}); diff --git a/app/Plugins/Pages/Controllers/Admin/AdminPagesController.php b/app/Plugins/Pages/Controllers/Admin/AdminPagesController.php new file mode 100644 index 0000000..2b3241a --- /dev/null +++ b/app/Plugins/Pages/Controllers/Admin/AdminPagesController.php @@ -0,0 +1,186 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Pages\Controllers\Admin; + +use Illuminate\Http\Request; + + +use App\Http\Controllers\Controller; +use Plugins\Pages\Model\Page; + +use JWTAuth; +use Validator; +use Plugins\Pages\Transformers\PageTransformer; + + +/** + * Pages resource representation. + * @Resource("Admin/AdminPages") + */ +class AdminPagesController extends Controller +{ + /** + * AdminPagesController constructor. + */ + public function __construct() + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth'); + // Check the logged user role. + $this->middleware('role'); + } + + /** + * Show all pages + * Get a JSON representation of all the pages. + * + * @Get("/pages?sort={sort}&sortby={sortby}&page={page}") + * @Parameters({ + * @Parameter("sort", type="string", required=false, description="Sort the pages list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort pages by Ascending / Descending Order.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1) + * }) + */ + public function index(Request $request) + { + $pages = Page::with('language')->filterByRequest($request)->paginate(config('constants.ConstPageLimit')); + return $this->response->paginator($pages, (new PageTransformer)->setDefaultIncludes(['language'])); + } + + /** + * Store a new page. + * Store a new page with a `language_id`, `title`, `slug`, `page_content` and `is_active`. + * @Post("/pages") + * @Transaction({ + * @Request({"language_id": 1, "title": "FAQ", "slug": "faq", "page_content": "Coming Soon", "is_avtive": 1}), + * @Response(200, body={"success": "Record has been added."}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {"title": {}}, "status_code": 422}) + * }) + */ + public function store(Request $request) + { + $pages_arr = array(); + $pages_arr['pages'] = $request->all(); + $pages_arr['slug'] = $request->slug; + $validator = Validator::make($pages_arr, Page::GetBulkAddValidationRule(), Page::GetValidationMessage()); + $pages = $request->all(); + if ($validator->passes()) { + foreach ($pages as $key => $data) { + if ($key == 'slug') { + continue; + } + $pages = Page::create(is_array($data) ? $data : array($data)); + if (!$pages) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Page could not be updated. Please, try again.'); + } + } + return response()->json(['Success' => 'Page has been added'], 200); + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Page could not be updated. Please, try again.', $validator->errors()); + } + + } + + /** + * Edit the specified page. + * Edit the page with a `id`. + * @Get("/pages/{id}/edit") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"id": 1, "title": "FAQ", "slug": "faq", "page_content": "Coming Soon", "is_avtive": 1}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function edit($id) + { + $page = Page::with('language')->find($id); + if (!$page) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($page, (new PageTransformer)->setDefaultIncludes(['language'])); + } + + /** + * Show the specified page. + * Show the page with a `id`. * + * @Get("/pages/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"id": 1, "language_id": 42, "title": "Term and conditions", "slug": "term-and-conditions", "page_content": "XXX", "is_active": 0, "Language": {"id": 42, "name": "English", "iso2": "en", "iso3": "eng", "is_active": 1}}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function show($id) + { + $page = Page::with('language')->find($id); + if (!$page) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($page, (new PageTransformer)->setDefaultIncludes(['language'])); + } + + /** + * Update the specified page. + * Update the page with a `id`. + * @Put("/pages/{id}") + * @Transaction({ + * @Request({"id": 1, "title": "FAQ", "slug": "faq", "page_content": "Coming Soon", "is_avtive": 1}), + * @Response(200, body={"success": "Record has been updated."}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {"title": {}}, "status_code": 422}) + * }) + */ + public function update(Request $request, $id) + { + $page_data = $request->only('id', 'title', 'language_id', 'page_content', 'is_active'); + $validator = Validator::make($page_data, Page::GetValidationRule(), Page::GetValidationMessage()); + $page = false; + if ($request->has('id')) { + $page = Page::find($id); + $page = ($request->id != $id) ? false : $page; + } + if ($validator->passes() && $page) { + try { + $page->update($page_data); + return response()->json(['Success' => 'Page has been updated'], 200); + } catch (\Exception $e) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Page could not be updated. Please, try again.'); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Page could not be updated. Please, try again.', $validator->errors()); + } + } + + /** + * Delete the specified page. + * Delete the page with a `id`. + * @Delete("/pages/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"success": "Record Deleted."}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function destroy($id) + { + $page = Page::find($id); + if (!$page) { + return $this->response->errorNotFound("Invalid Request"); + } else { + $page->delete(); + } + return response()->json(['Success' => 'Page deleted'], 200); + } +} diff --git a/app/Plugins/Pages/Controllers/PagesController.php b/app/Plugins/Pages/Controllers/PagesController.php new file mode 100644 index 0000000..229591f --- /dev/null +++ b/app/Plugins/Pages/Controllers/PagesController.php @@ -0,0 +1,84 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Pages\Controllers; + +use Illuminate\Http\Request; + +use App\Http\Controllers\Controller; +use Plugins\Pages\Model\Page; +use App\Language; + +use JWTAuth; +use Validator; +use Plugins\Pages\Transformers\PageLanguageTransformer; +use Plugins\Pages\Transformers\PageTransformer; + + +/** + * Pages resource representation. + * @Resource("/Pages") + */ +class PagesController extends Controller +{ + /** + * Show all pages based on languages + * Get a JSON representation of all the pages. + * + * @Get("/languages/{en}/pages") + * @Transaction({ + * @Request({"iso2": "en"}), + * @Response(200, body={"id": 1, "title": "Static page", "slug": "static-page"}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function getPages($iso2) + { + if (empty($iso2)) { + $iso2 = config('site.dafault_language'); + } + $language = Language::where('iso2', '=', $iso2)->first(); + $page = Page::where('language_id', '=', $language['id'])->get(); + if ($page) { + return $this->response->collection($page, new PageLanguageTransformer); + } + } + + /** + * Show the specified page. + * Show the page with a `id`. + * @Get("/pages/{slug}/{iso2}") + * @Transaction({ + * @Request({"slug": "term-and-conditions", "iso2": "en"}), + * @Response(200, body={"id": 1, "is_active": 1, "language_id": "1", "slug": "term-and-conditions", "page_content": "XXX", "title":"term and condition"}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function show($slug, $iso2) + { + $language = Language::where('iso2', '=', $iso2)->first(); + if (!$language) { + return $this->response->errorNotFound("Invalid Request"); + } + $page = Page::where('slug', '=', $slug) + ->where('language_id', '=', $language->id) + ->first(); + if (!$page) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($page, new PageTransformer); + } + +} diff --git a/app/Plugins/Pages/Model/Page.php b/app/Plugins/Pages/Model/Page.php new file mode 100644 index 0000000..f1af006 --- /dev/null +++ b/app/Plugins/Pages/Model/Page.php @@ -0,0 +1,106 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Pages\Model; + +use Illuminate\Http\Request; +use Illuminate\Database\Eloquent\Model; +use App\Language; + +/** + * Class Page + * @package App + */ +class Page extends Model +{ + /** + * @var string + */ + protected $table = "pages"; + /** + * The attributes that are mass assignable. + * + * @var array + */ + protected $fillable = [ + 'title', 'language_id', 'slug', 'page_content' + ]; + + + /** + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function language() + { + return $this->belongsTo(Language::class); + } + + + /** + * @param $query + * @param Request $request + * @return mixed + */ + public function scopeFilterByRequest($query, Request $request) + { + $query->orderBy($request->input('sort', 'id'), $request->input('sortby', 'desc')); + if ($request->has('q')) { + $query->where('title', 'LIKE', '%' . $request->input('q') . '%'); + $query->orWhereHas('language', function ($q) use ($request) { + $q->where('name', 'LIKE', '%' . $request->input('q') . '%'); + }); + } + return $query; + } + + /** + * @return array + */ + public function scopeGetValidationRule() + { + return [ + 'title' => 'required|min:2', + 'language_id' => 'required|integer|exists:languages,id', + 'page_content' => 'required|min:10' + ]; + } + + /** + * @return array + */ + public function scopeGetBulkAddValidationRule() + { + return [ + 'pages.*.title' => 'sometimes|required|min:2', + 'pages.*.page_content' => 'sometimes|required|min:10', + 'slug' => 'sometimes|required' + ]; + } + + public function scopeGetValidationMessage() + { + return [ + 'slug.required' => 'Required', + 'title.required' => 'Required', + 'title.min' => 'Minimum length is 2', + 'language_id.required' => 'Required', + 'language_id.integer' => 'Language id must be a number', + 'language_id.exists' => 'Invalid language id', + 'page_content.required' => 'Required', + 'page_content.min' => 'Minimum length is 10', + ]; + } + +} diff --git a/app/Plugins/Pages/Providers/PageServiceProvider.php b/app/Plugins/Pages/Providers/PageServiceProvider.php new file mode 100644 index 0000000..8d27405 --- /dev/null +++ b/app/Plugins/Pages/Providers/PageServiceProvider.php @@ -0,0 +1,43 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Pages\Providers; + +use Illuminate\Support\ServiceProvider; + +class PageServiceProvider extends ServiceProvider +{ + /** + * Register any application services. + * + * @return void + */ + public function register() + { + include __DIR__ . '/../routes.php'; + $this->app->make('Plugins\Pages\Controllers\PagesController'); + $this->app->make('Plugins\Pages\Controllers\Admin\AdminPagesController'); + } + + /** + * Bootstrap the application services. + * + * @return void + */ + public function boot() + { + + } +} diff --git a/app/Plugins/Pages/Transformers/PageLanguageTransformer.php b/app/Plugins/Pages/Transformers/PageLanguageTransformer.php new file mode 100644 index 0000000..2016359 --- /dev/null +++ b/app/Plugins/Pages/Transformers/PageLanguageTransformer.php @@ -0,0 +1,37 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Pages\Transformers; + +use League\Fractal; +use Plugins\Pages\Model\Page; + +/** + * Class PageTransformer + * @package Pages\Transformers + */ +class PageLanguageTransformer extends Fractal\TransformerAbstract +{ + + /** + * @param Page $page + * @return array + */ + public function transform(Page $page) + { + $output = array_only($page->toArray(), ['id', 'title', 'slug']); + return $output; + } +} diff --git a/app/Plugins/Pages/Transformers/PageTransformer.php b/app/Plugins/Pages/Transformers/PageTransformer.php new file mode 100644 index 0000000..78e003a --- /dev/null +++ b/app/Plugins/Pages/Transformers/PageTransformer.php @@ -0,0 +1,60 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Pages\Transformers; + +use League\Fractal; +use Plugins\Pages\Model\Page; +use App\Transformers\LanguageTransformer; + +/** + * Class PageTransformer + * @package Pages\Transformers + */ +class PageTransformer extends Fractal\TransformerAbstract +{ + /** + * List of resources possible to include + * @var array + */ + protected $availableIncludes = [ + 'Language' + ]; + + /** + * @param Page $page + * @return array + */ + public function transform(Page $page) + { + $output = array_only($page->toArray(), ['id', 'title', 'language_id', 'slug', 'page_content', 'is_active']); + return $output; + } + + /** + * @param Page $page + * @return Fractal\Resource\Item + */ + public function includeLanguage(Page $page) + { + if ($page->language) { + return $this->item($page->language, new LanguageTransformer()); + } else { + return null; + } + + } + +} diff --git a/app/Plugins/Pages/plugin.json b/app/Plugins/Pages/plugin.json new file mode 100644 index 0000000..b1c97aa --- /dev/null +++ b/app/Plugins/Pages/plugin.json @@ -0,0 +1,9 @@ +{ + "name": "Pages", + "class": "fa fa-2x fa-file-text", + "description": "Static pages", + "dependencies": "", + "module_id": "", + "module_hash": "", + "display_order": "4" +} diff --git a/app/Plugins/Pages/routes.php b/app/Plugins/Pages/routes.php new file mode 100644 index 0000000..4f1d9c4 --- /dev/null +++ b/app/Plugins/Pages/routes.php @@ -0,0 +1,41 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ +/* +|-------------------------------------------------------------------------- +| Application Routes +|-------------------------------------------------------------------------- +| +| Here is where you can register all of the routes for an application. +| It is a breeze. Simply tell Lumen the URIs it should respond to +| and give it the Closure to call when that URI is requested. +| +*/ +$api = $this->app->make('Dingo\Api\Routing\Router'); +$api->version(['v1'], function ($api) { + $api->group(['prefix' => 'admin', 'namespace' => 'Plugins\Pages\Controllers\Admin', 'middleware' => 'apitracking'], function () use ($api) { + // pages admin side + $api->get('pages', 'AdminPagesController@index'); + $api->get('pages/{id}/edit', 'AdminPagesController@edit'); + $api->get('pages/{id}', 'AdminPagesController@show'); + $api->post('pages', 'AdminPagesController@store'); + $api->put('pages/{id}', 'AdminPagesController@update'); + $api->delete('pages/{id}', 'AdminPagesController@destroy'); + }); + //Pages user side + $api->group(['namespace' => 'Plugins\Pages\Controllers', 'middleware' => 'apitracking'], function () use ($api) { + $api->get('/languages/{iso2}/pages', 'PagesController@getPages'); + $api->get('/page/{slug}/{iso2}', 'PagesController@show'); + }); +}); diff --git a/app/Plugins/Paypal/Controllers/Admin/AdminPaypalTransactionLogsController.php b/app/Plugins/Paypal/Controllers/Admin/AdminPaypalTransactionLogsController.php new file mode 100644 index 0000000..5de6d91 --- /dev/null +++ b/app/Plugins/Paypal/Controllers/Admin/AdminPaypalTransactionLogsController.php @@ -0,0 +1,82 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Paypal\Controllers\Admin; + +use Illuminate\Http\Request; + + + +use App\Http\Controllers\Controller; +use Plugins\Paypal\Model\PaypalTransactionLog; +use JWTAuth; +use Validator; +use Plugins\Paypal\Transformers\PaypalTransactionLogTransformer; + +/** + * Money Transfer Accounts resource representation. + * @Resource("Sudopays") + */ +class AdminPaypalTransactionLogsController extends Controller +{ + /** + * PaypalController constructor. + */ + public function __construct() + { + // Check the logged user authentication. + $this->middleware('jwt.auth'); + // Check the logged user role. + $this->middleware('role'); + } + + /** + * Show all paypal transaction logs. + * Get a JSON representation of all the paypal transaction logs. + * + * @Get("/paypal_transaction_logs?sort={sort}&sortby={sortby}&page={page}") + * @Parameters({ + * @Parameter("sort", type="string", required=false, description="Sort the paypal transaction log list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort paypal transaction log by Ascending / Descending Order.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1), + * }) + */ + + public function index(Request $request) + { + $paypal_transaction_logs = PaypalTransactionLog::filterByRequest($request)->paginate(config('constants.ConstPageLimit')); + return $this->response->paginator($paypal_transaction_logs, (new PaypalTransactionLogTransformer)); + + } + + /** + * Show the paypal transaction log. + * Show the paypal transaction log with a `id`. + * @Get("/paypal_transaction_logs/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"id": 1, "amount": 100, "payment_id": 1, "paypal_transaction_logable_id": 1, "paypal_transaction_logable_type": "1", "paypal_pay_key": "1", "payer_id": 1, "authorization_id": 1, "capture_id": "sri", "void_id": "1", "refund_id": "1", "status": "approved", "payment_type": "1", "buyer_id": 1, "buyer_email": "1", "buyer_address": "1", "paypal_transaction_fee": "0.00", "fee_payer": ""}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function show($id) + { + $paypal_transaction_log = PaypalTransactionLog::find($id); + if (!$paypal_transaction_log) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($paypal_transaction_log, (new PaypalTransactionLogTransformer)); + } +} \ No newline at end of file diff --git a/app/Plugins/Paypal/Controllers/PaypalController.php b/app/Plugins/Paypal/Controllers/PaypalController.php new file mode 100644 index 0000000..6fdc3f9 --- /dev/null +++ b/app/Plugins/Paypal/Controllers/PaypalController.php @@ -0,0 +1,84 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Paypal\Controllers; + +use Illuminate\Http\Request; + +use App\Http\Controllers\Controller; + +use Paypal; +use Plugins\Paypal\Services\PaypalTransactionLogService; +use Plugins\Paypal\Services\PayPalService; + +/** + * Paypal resource representation. + * @Resource("Paypal") + */ +class PaypalController extends Controller +{ + /** + * @var + */ + private $_api_context; + + /** + * @var + */ + private $paypalService; + /** + * @var + */ + private $paypalLog; + + public function __construct() + { + $this->setPaypalTransactionLogService(); + $this->setPayPalService(); + } + + public function setPaypalTransactionLogService() + { + $this->paypalLog = new PaypalTransactionLogService(); + } + + public function setPayPalService() + { + $this->paypalService = new PayPalService(); + } + + /** + * @param Request $request + * @return \Illuminate\View\View + */ + public function processPayment(Request $request) + { + if($request->has('paymentId') && $request->has('PayerID') && $request->has('token')){ + $response = $this->paypalService->executePayment($request->get('paymentId'), $request->get('PayerID'), $request->get('token')); + return redirect($response['returnUrl']); + }else{ + return $this->response->errorNotFound("Invalid Request"); + } + } + + /** + * @return \Illuminate\View\View + */ + public function getCancel() + { + // Curse and humiliate the user for cancelling this most sacred payment (yours) + return view('checkout.cancel'); + } +} diff --git a/app/Plugins/Paypal/Model/PaypalTransactionLog.php b/app/Plugins/Paypal/Model/PaypalTransactionLog.php new file mode 100644 index 0000000..9ae51e1 --- /dev/null +++ b/app/Plugins/Paypal/Model/PaypalTransactionLog.php @@ -0,0 +1,60 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Paypal\Model; + +use Illuminate\Http\Request; +use Illuminate\Database\Eloquent\Model; + +/** + * Class PaypalTransactionLog + * @package App + */ +class PaypalTransactionLog extends Model +{ + /** + * @var string + */ + protected $table = "paypal_transaction_logs"; + /** + * The attributes that are mass assignable. + * + * @var array + */ + protected $fillable = [ + 'amount', 'payment_id', 'paypal_pay_key', 'status', 'payment_type', 'buyer_email', 'buyer_address', 'authorization_id', 'payer_id', 'capture_id', 'void_id', 'refund_id', 'fee_payer', 'paypal_transaction_fee' + ]; + + /** + * @return \Illuminate\Database\Eloquent\Relations\MorphTo + */ + public function paypal_transaction_logable() + { + return $this->morphTo(); + } + + + /** + * @param $query + * @param Request $request + * @return mixed + */ + public function scopeFilterByRequest($query, Request $request) + { + $query->orderBy($request->input('sort', 'id'), $request->input('sortby', 'desc')); + return $query; + } + +} diff --git a/app/Plugins/Paypal/Providers/PaypalServiceProvider.php b/app/Plugins/Paypal/Providers/PaypalServiceProvider.php new file mode 100644 index 0000000..50193dd --- /dev/null +++ b/app/Plugins/Paypal/Providers/PaypalServiceProvider.php @@ -0,0 +1,44 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Paypal\Providers; + +use Illuminate\Support\ServiceProvider; +use Illuminate\Database\Eloquent\Relations\Relation; + +class PaypalServiceProvider extends ServiceProvider +{ + /** + * Register any application services. + * @return void + */ + public function register() + { + include __DIR__ . '/../routes.php'; + $this->app->make('Plugins\Paypal\Controllers\PaypalController'); + $this->app->make('Plugins\Paypal\Controllers\Admin\AdminPaypalTransactionLogsController'); + } + + /** + * Bootstrap the application services. + * @return void + */ + public function boot() + { + $enabledIncludes = array(); + $enabledIncludes['MorphWallet'] = \App\Wallet::class; + Relation::morphMap($enabledIncludes); + } +} diff --git a/app/Plugins/Paypal/Services/PayPalService.php b/app/Plugins/Paypal/Services/PayPalService.php new file mode 100644 index 0000000..be1c40b --- /dev/null +++ b/app/Plugins/Paypal/Services/PayPalService.php @@ -0,0 +1,307 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Paypal\Services; + +use PayPal\Rest\ApiContext; +use PayPal\Auth\OAuthTokenCredential; +use Paypal; +use App\User; +use Plugins\Paypal\Model\PaypalTransactionLog; +use Log; + +class PayPalService +{ + /** + * @var + */ + private $_api_context; + + /** + * PayPalService constructor. + */ + public function __construct() + { + // setup PayPal api context + $paypal_conf = config('paypal'); + $this->_api_context = new ApiContext(new OAuthTokenCredential($paypal_conf['api_id'], $paypal_conf['secret'])); + $this->_api_context->setConfig($paypal_conf['settings']); + } + + public function createPayment($logable_id, $payment_type) + { + $transaction_log = PaypalTransactionLog::where('id', '=', $logable_id)->first(); + $related_details = $transaction_log->paypal_transaction_logable; + $desc = ''; + $cancel_url = '/'; + if ($transaction_log->paypal_transaction_logable_type == 'MorphWallet') { + $desc = $related_details->description; + $item1 = PayPal::Item(); + $item1->setName($desc) + ->setCurrency(config('site.currency_code')) + ->setQuantity(1) + ->setPrice((double)$transaction_log->amount); + $itemList = PayPal::ItemList(); + $itemList->setItems(array($item1)); + $cancel_url = '/#/wallets/fail'; + } + if ($transaction_log->paypal_transaction_logable_type == 'MorphVehicle') { + $desc = "Vehicle listing Fee"; + $item1 = PayPal::Item(); + $item1->setName($desc) + ->setCurrency(config('site.currency_code')) + ->setQuantity(1) + ->setPrice((double)$transaction_log->amount); + $itemList = PayPal::ItemList(); + $itemList->setItems(array($item1)); + $cancel_url = '/#/vehicle/fail'; + } + if ($transaction_log->paypal_transaction_logable_type == 'MorphVehicleRental') { + if (!is_null($transaction_log->paypal_transaction_logable) && !is_null($transaction_log->paypal_transaction_logable->item_userable)) { + $item1 = PayPal::Item(); + $item1->setName($transaction_log->paypal_transaction_logable->item_userable->name) + ->setCurrency(config('site.currency_code')) + ->setQuantity((int)$transaction_log->paypal_transaction_logable->quantity) + ->setPrice((double)$transaction_log->amount); + $itemList = PayPal::ItemList(); + $itemList->setItems(array($item1)); + $cancel_url = '/#/vehicle_rental/status/fail'; + } else { + return array('error' => 1, 'error_message' => "unable to get item detail"); + } + } + + $payer = PayPal::Payer(); + $payer->setPaymentMethod('paypal'); + + $amount = PayPal::Amount(); + $amount->setCurrency(config('site.currency_code')); + $amount->setTotal((double)$transaction_log->amount); + + $transaction = PayPal::Transaction(); + $transaction->setItemList($itemList); + $transaction->setAmount($amount); + $transaction->setDescription($desc); + + $redirectUrls = PayPal:: RedirectUrls(); + $redirectUrls->setReturnUrl(url('api/paypal/process_payment')); + $redirectUrls->setCancelUrl(url($cancel_url)); + + $payment = PayPal::Payment(); + $payment->setIntent($payment_type); + $payment->setPayer($payer); + $payment->setRedirectUrls($redirectUrls); + $payment->setTransactions(array($transaction)); + try { + $response = $payment->create($this->_api_context); + if ($payment->getState() == 'created') { + $data = array(); + $data['payment_id'] = $payment->getId(); + $data['status'] = $payment->getState(); + $data['payment_type'] = 'initiated'; + $transaction_log->update($data); + return $payment->getApprovalLink(); + } else { + return array('error' => 1, 'error_message' => "Payment could not be initialized, please try again"); + } + } catch (Exception $ex) { + return array('error' => 1, 'error_message' => $ex->getMessage()); + } + } + + public function executePayment($payID, $payerID, $token) + { + $process = false; + $error_message = ''; + $returnUrl = ''; + $transaction_log = PaypalTransactionLog::where('payment_id', '=', $payID)->first(); + if ($transaction_log) { + try { + $data = array(); + $payment = Paypal::getById($payID, $this->_api_context); + $paymentExecution = Paypal::PaymentExecution(); + $paymentExecution->setPayerId($payerID); + $payment->execute($paymentExecution, $this->_api_context); + $data['payer_id'] = $payerID; + $data['paypal_pay_key'] = $token; + if ($payment->getIntent() == 'sale' && $payment->getState() == 'approved') { + $transactions = $payment->getTransactions(); + $relatedResources = $transactions[0]->getRelatedResources(); + $sale = $relatedResources[0]->getSale(); + $transaction_fee = $sale->getTransactionFee(); + $data['status'] = $payment->getState(); + $data['capture_id'] = $sale->getId(); + $data['payment_type'] = $sale->getState(); + $process = true; + if ($transaction_log->paypal_transaction_logable_type == "MorphWallet") { + $transaction_log->paypal_transaction_fee = 0.00; + if ($transaction_log->fee_payer == 'User' && !is_null($transaction_fee)) { + $transaction_log->paypal_transaction_fee = $transaction_fee->getValue(); + $transaction_log->save(); + } + $walletService = new \App\Services\WalletService(); + $walletService->processAddToWallet($transaction_log->paypal_transaction_logable_id, config('constants.ConstPaymentGateways.PayPal'), $transaction_log->paypal_transaction_fee); + $returnUrl = '/#/wallets/success'; + } + if ($transaction_log->paypal_transaction_logable_type == "MorphVehicle") { + $transaction_log->paypal_transaction_fee = 0.00; + if (isPluginEnabled('Vehicles')) { + if ($transaction_log->fee_payer == 'User' && !is_null($transaction_fee)) { + $transaction_log->paypal_transaction_fee = $transaction_fee->getValue(); + $transaction_log->save(); + } + $vehicleService = new \Plugins\Vehicles\Services\VehicleService(); + $vehicleService->processVehicleLisitngFee($transaction_log->paypal_transaction_logable_id, config('constants.ConstPaymentGateways.PayPal'), $transaction_log->paypal_transaction_fee); + $returnUrl = '/#/vehicle/success'; + } + } + if ($transaction_log->paypal_transaction_logable_type == "MorphVehicleRental") { + if (isPluginEnabled('VehicleRentals')) { + $vehicleRentalService = new \Plugins\VehicleRentals\Services\VehicleRentalService(); + $vehicleRentalService->updateVehicleRental($transaction_log->paypal_transaction_logable_id, config('constants.ConstPaymentGateways.PayPal')); + $returnUrl = '/#/vehicle_rental/status/success'; + } + } + } else if ($payment->getIntent() == 'authorize' && $payment->getState() == 'approved') { + $transactions = $payment->getTransactions(); + $relatedResources = $transactions[0]->getRelatedResources(); + $authorization = $relatedResources[0]->getAuthorization(); + $data['status'] = $payment->getState(); + $data['authorization_id'] = $authorization->getId(); + $data['payment_type'] = $authorization->getState(); + $process = true; + if ($transaction_log->paypal_transaction_logable_type == "MorphWallet") { + $returnUrl = '/#/wallets/success'; + } elseif ($transaction_log->paypal_transaction_logable_type == "MorphVehicleRental") { + if (isPluginEnabled('VehicleRentals')) { + $vehicleRentalService = new \Plugins\VehicleRentals\Services\VehicleRentalService(); + $vehicleRentalService->updateVehicleRental($transaction_log->paypal_transaction_logable_id, config('constants.ConstPaymentGateways.PayPal')); + $returnUrl = '/#/vehicle_rental/status/success'; + } + } else { + $returnUrl = '/#/'; + } + } + if (!empty($data)) + $transaction_log->update($data); + } catch (\PayPal\Exception\PayPalConnectionException $ex) { + if ($transaction_log->paypal_transaction_logable_type == "MorphWallet") { + $returnUrl = '/#/wallets/fail'; + } elseif ($transaction_log->paypal_transaction_logable_type == "MorphVehicleRental") { + $returnUrl = '/#/vehicle_rental/status/fail'; + }elseif ($transaction_log->paypal_transaction_logable_type == "MorphVehicle") { + $returnUrl = '/#/vehicle/fail'; + } else { + $returnUrl = '/#/'; + } + $error_message = $ex->getMessage(); + } catch (Exception $ex) { + if ($transaction_log->paypal_transaction_logable_type == "MorphWallet") { + $returnUrl = '/#/wallets/fail'; + } elseif ($transaction_log->paypal_transaction_logable_type == "MorphVehicleRental") { + $returnUrl = '/#/vehicle_rental/status/fail'; + }elseif ($transaction_log->paypal_transaction_logable_type == "MorphVehicle") { + $returnUrl = '/#/vehicle/fail'; + } else { + $returnUrl = '/#/'; + } + $error_message = $ex->getMessage(); + } + } + return array( + 'status' => $process, + 'returnUrl' => $returnUrl, + 'message' => $error_message + ); + } + + public function getPaypalDetails() + { + try { + $paypal_gateway_response = array( + 'error' => array( + 'code' => 0 + ), + 'paypal_enabled' => true + ); + return $paypal_gateway_response; + } catch (Exception $e) { + return array('error' => 1, 'error_message' => $e->getMessage()); + } + } + + public function authorizePayment($id) + { + try { + $authorization = Paypal::Authorization(); + $result = $authorization->get($id, $this->_api_context); + return $result; + } catch (Exception $e) { + return array('error' => 1, 'error_message' => $e->getMessage()); + } + } + + public function capturePayment($authorization, $transaction_log) + { + try { + $amt = Paypal::Amount(); + $amt->setCurrency(config('site.currency_code')) + ->setTotal((double)$transaction_log->amount); + $capture = Paypal::Capture(); + $capture->setAmount($amt); + $capture->setIsFinalCapture(true); + $getCapture = $authorization->capture($capture, $this->_api_context); + return $getCapture; + } catch (Exception $e) { + return array('error' => 1, 'error_message' => $e->getMessage()); + } + } + + public function voidPayment($authorization_id) + { + try { + $authorization = Paypal::Authorization(); + $getAuth = $authorization->get($authorization_id, $this->_api_context); + $voidedAuth = $getAuth->void($this->_api_context); + return $voidedAuth; + } catch (Exception $e) { + return array('error' => 1, 'error_message' => $e->getMessage()); + } + } + + public function refundPayment($transaction_log) + { + $amt = Paypal::Amount(); + $amt->setCurrency(config('site.currency_code')) + ->setTotal((double)$transaction_log->amount); + $refund = Paypal::Refund(); + $refund->setAmount($amt); + try { + if (empty(config('vehicle_rental.is_auto_approve'))) { + $capture = Paypal::Capture(); + $capture_details = $capture->get($transaction_log->capture_id, $this->_api_context); + $captureRefund = $capture_details->refund($refund, $this->_api_context); + return $captureRefund; + } else { + $sale = Paypal::Sale(); + $sale->setId($transaction_log->capture_id); + $refundedSale = $sale->refund($refund, $this->_api_context); + return $refundedSale; + } + } catch (Exception $ex) { + return array('error' => 1, 'error_message' => $ex->getMessage()); + } + } +} diff --git a/app/Plugins/Paypal/Services/PaypalTransactionLogService.php b/app/Plugins/Paypal/Services/PaypalTransactionLogService.php new file mode 100644 index 0000000..3a57134 --- /dev/null +++ b/app/Plugins/Paypal/Services/PaypalTransactionLogService.php @@ -0,0 +1,52 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Paypal\Services; + +use Plugins\Paypal\Model\PaypalTransactionLog; + +class PaypalTransactionLogService +{ + /** + * PayPalService constructor. + */ + public function __construct() + { + } + + public function log($data) + { + return PaypalTransactionLog::create($data); + } + + public function updateLogByPayId($data, $payId = '') + { + if ($payId) { + $log = PaypalTransactionLog::where('payment_id', '=', $payId)->first(); + if ($log) + $log->update($data); + } + } + + public function updateLogById($data, $id = '') + { + if ($id) { + $log = PaypalTransactionLog::where('id', '=', $id)->first(); + if ($log) + $log->update($data); + } + } + +} diff --git a/app/Plugins/Paypal/Transformers/PaypalTransactionLogTransformer.php b/app/Plugins/Paypal/Transformers/PaypalTransactionLogTransformer.php new file mode 100644 index 0000000..d5bed8b --- /dev/null +++ b/app/Plugins/Paypal/Transformers/PaypalTransactionLogTransformer.php @@ -0,0 +1,37 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Paypal\Transformers; + +use League\Fractal; +use Plugins\Paypal\Model\PaypalTransactionLog; + +/** + * Class PaypalTransactionLogTransformer + * @package App\Transformers + */ +class PaypalTransactionLogTransformer extends Fractal\TransformerAbstract +{ + + /** + * @param PaypalTransactionLog $paypal_transaction_log + * @return array + */ + public function transform(PaypalTransactionLog $paypal_transaction_log) + { + $output = array_only($paypal_transaction_log->toArray(), ['id', 'created_at', 'amount', 'payment_id', 'paypal_transaction_logable_type', 'paypal_transaction_logable_id', 'paypal_pay_key', 'payer_id', 'authorization_id', 'capture_id', 'void_id', 'refund_id', 'status', 'payment_type', 'buyer_email', 'buyer_address', 'paypal_transaction_fee', 'fee_payer']); + return $output; + } +} diff --git a/app/Plugins/Paypal/plugin.json b/app/Plugins/Paypal/plugin.json new file mode 100644 index 0000000..bc503b1 --- /dev/null +++ b/app/Plugins/Paypal/plugin.json @@ -0,0 +1,9 @@ +{ + "name": "Paypal", + "class": "fa fa-2x fa-paypal", + "description": "By enabling this plugin, pay their transaction through this.", + "dependencies": "PaymentGateways", + "module_id": "", + "module_hash": "", + "display_order": "9" +} diff --git a/app/Plugins/Paypal/routes.php b/app/Plugins/Paypal/routes.php new file mode 100644 index 0000000..81d0443 --- /dev/null +++ b/app/Plugins/Paypal/routes.php @@ -0,0 +1,36 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ +/* +|-------------------------------------------------------------------------- +| Application Routes +|-------------------------------------------------------------------------- +| +| Here is where you can register all of the routes for an application. +| It is a breeze. Simply tell Lumen the URIs it should respond to +| and give it the Closure to call when that URI is requested. +| +*/ +$api = $this->app->make('Dingo\Api\Routing\Router'); +$api->version(['v1'], function ($api) { + + $api->group(['prefix' => 'admin', 'namespace' => 'Plugins\Paypal\Controllers\Admin', 'middleware' => 'apitracking'], function () use ($api) { + $api->get('paypal_transaction_logs', 'AdminPaypalTransactionLogsController@index'); + $api->get('paypal_transaction_logs/{id}', 'AdminPaypalTransactionLogsController@show'); + }); + + // Paypal + $api->get('paypal/process_payment', 'Plugins\Paypal\Controllers\PaypalController@processPayment'); + $api->get('paypal/cancel', 'Plugins\Paypal\Controllers\PaypalController@getCancel'); +}); diff --git a/app/Plugins/PluginServiceProvider.php b/app/Plugins/PluginServiceProvider.php new file mode 100644 index 0000000..f232cbb --- /dev/null +++ b/app/Plugins/PluginServiceProvider.php @@ -0,0 +1,49 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins; + +use Illuminate\Support\ServiceProvider; +use File; + +class PluginServiceProvider extends ServiceProvider +{ + /** + * Register any application services. + * + * @return void + */ + public function register() + { + $enabled_plugins = enabled_plugins(); + foreach ($enabled_plugins as $plugins) { + foreach (glob(base_path("app/Plugins/$plugins/Providers/*.php")) as $files) { + $filename = File::name($files); + $file_path = 'Plugins' . '\\' . $plugins . '\\Providers' . '\\' . $filename; + $this->app->register($file_path); + } + } + } + + /** + * Bootstrap the application services. + * + * @return void + */ + public function boot() + { + + } +} diff --git a/app/Plugins/SocialLogins/Controllers/Admin/AdminProvidersController.php b/app/Plugins/SocialLogins/Controllers/Admin/AdminProvidersController.php new file mode 100644 index 0000000..f473d30 --- /dev/null +++ b/app/Plugins/SocialLogins/Controllers/Admin/AdminProvidersController.php @@ -0,0 +1,135 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\SocialLogins\Controllers\Admin; + +use Illuminate\Http\Request; + + +use App\Http\Controllers\Controller; +use Plugins\SocialLogins\Model\Provider; + +use JWTAuth; +use Validator; +use Tymon\JWTAuth\Exceptions\JWTException; +use Plugins\SocialLogins\Transformers\ProviderTransformer; + +/** + * Providers resource representation. + * @Resource("Admin/AdminProviders") + */ +class AdminProvidersController extends Controller +{ + /** + * AdminProvidersController constructor. + */ + public function __construct() + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth'); + // Check the logged user role. + $this->middleware('role'); + } + + /** + * Show all providers + * Get a JSON representation of all the providers. + * + * @Get("/providers?filter={filter}&sort={sort}&sortby={sortby}&q={q}") + * @Parameters({ + * @Parameter("filter", type="integer", required=false, description="Filter the providers list by type.", default=null), + * @Parameter("sort", type="string", required=false, description="Sort the providers list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort providers by Ascending / Descending Order.", default=null), + * @Parameter("q", type="string", required=false, description="Search providers.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1) + * }) + */ + public function index(Request $request) + { + $providers = Provider::filterByRequest($request)->paginate(config('constants.ConstPageLimit')); + return $this->response->paginator($providers, new ProviderTransformer); + } + + /** + * Edit the specified provider. + * Edit the provider with a `id`. + * @Get("/providers/{id}/edit") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"id": 1, "name": "Facebook", "secret_key": "XXXXXX", "api_key": "XXXXXX", "icon_class": "fa-facebook", "button_class": "btn-facebook", "display_order": "2"}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function edit($id) + { + $provider = Provider::find($id); + if (!$provider) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($provider, new ProviderTransformer); + } + + /** + * Update the specified provider. + * Update the provider with a `id`. + * @Put("/providers/{id}") + * @Transaction({ + * @Request({"id": 1, "name": "Facebook", "secret_key": "XXXXXX", "api_key": "XXXXXX", "icon_class": "fa-facebook", "button_class": "btn-facebook", "display_order": "2"}), + * @Response(200, body={"success": "Record has been updated."}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {"name": {}}, "status_code": 422}) + * }) + */ + public function update(Request $request, $id) + { + $provider_data = $request->only('name', 'secret_key', 'api_key', 'display_order', 'is_active'); + $validator = Validator::make($provider_data, Provider::GetValidationRule(), Provider::GetValidationMessage()); + $provider = false; + if ($request->has('id')) { + $provider = Provider::find($id); + $provider = ($request->id != $id) ? false : $provider; + } + if ($validator->passes() && $provider) { + try { + $provider->update($provider_data); + return response()->json(['Success' => 'Provider has been updated'], 200); + } catch (\Exception $e) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Provider could not be updated. Please, try again.'); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Provider could not be updated. Please, try again.', $validator->errors()); + } + } + + /** + * Delete the specified provider. + * Delete the provider with a `id`. + * @Delete("/providers/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"success": "Record Deleted."}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function destroy($id) + { + $provider = Provider::find($id); + if (!$provider) { + return $this->response->errorNotFound("Invalid Request"); + } else { + $provider->delete(); + } + return response()->json(['Success' => 'Provider deleted'], 200); + } +} diff --git a/app/Plugins/SocialLogins/Controllers/ProvidersController.php b/app/Plugins/SocialLogins/Controllers/ProvidersController.php new file mode 100644 index 0000000..8b5cd22 --- /dev/null +++ b/app/Plugins/SocialLogins/Controllers/ProvidersController.php @@ -0,0 +1,53 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\SocialLogins\Controllers; + +use Illuminate\Http\Request; + + +use App\Http\Controllers\Controller; +use Plugins\SocialLogins\Model\Provider; + +use JWTAuth; +use Validator; +use Plugins\SocialLogins\Transformers\ProviderTransformer; + +/** + * Providers resource representation. + * @Resource("/Providers") + */ +class ProvidersController extends Controller +{ + /** + * Show all providers + * Get a JSON representation of all the providers. + * @Get("/providers?filter={filter}&sort={sort}&sortby={sortby}&q={q}") + * @Parameters({ + * @Parameter("filter", type="integer", required=false, description="Filter the providers list by type.", default=null), + * @Parameter("sort", type="string", required=false, description="Sort the providers list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort providers by Ascending / Descending Order.", default=null), + * @Parameter("q", type="string", required=false, description="Search providers.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1) + * }) + */ + public function index(Request $request) + { + $providers = Provider::filterByRequest($request)->get(); + return $this->response->Collection($providers, new ProviderTransformer); + } + + +} diff --git a/app/Plugins/SocialLogins/Controllers/SocialLoginsController.php b/app/Plugins/SocialLogins/Controllers/SocialLoginsController.php new file mode 100644 index 0000000..faded45 --- /dev/null +++ b/app/Plugins/SocialLogins/Controllers/SocialLoginsController.php @@ -0,0 +1,666 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\SocialLogins\Controllers; + +use Illuminate\Http\Request; + + +use App\Http\Controllers\Controller; +use JWTAuth; + +use Validator; +use App\User; + +use GuzzleHttp; +use GuzzleHttp\Subscriber\Oauth\Oauth1; + +use App\Services\UserService; +use Plugins\SocialLogins\Services\SocialLoginService; +use App\Services\IpService; +use App\Services\UserLoginService; +use Plugins\SocialLogins\Model\ProviderUser; +use Plugins\SocialLogins\Transformers\ProviderUserTransformer; +use Log; + +/** + * Users resource representation. + * @Resource("users") + */ +class SocialLoginsController extends Controller +{ + /** + * @var SocialLoginService + */ + protected $SocialLoginService; + /** + * @var UserService + */ + protected $UserService; + /** + * @var IpService + */ + protected $IpService; + /** + * @var UserLoginService + */ + protected $UserLoginService; + + /** + * SocialLoginsController constructor. + */ + public function __construct(SocialLoginService $service, UserService $userService) + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth', ['only' => ['unlink', 'getProviderUsers']]); + $this->setIpService(); + $this->setUserLoginService(); + $this->SocialLoginService = $service; + $this->UserService = $userService; + } + + public function setIpService() + { + $this->IpService = new IpService(); + } + + public function setUserLoginService() + { + $this->UserLoginService = new UserLoginService(); + } + + /** + * Check user connected with social + * @get("/provider_users") + * @Transaction({ + * @Response(200, body={"user_id": 1, "provider_id": 1, "is_connected": 1, "profile_picture_url": "/profile/1"}), + * @Response(200, body={}) + * }) + */ + public function getProviderUsers() + { + $user = $this->auth->user(); + $provider_user = ProviderUser::where('user_id', $user->id)->get(); + if (!$provider_user) { + return $this->response->array($provider_user->toArray()); + } + return $this->response->Collection($provider_user, (new ProviderUserTransformer)->setDefaultIncludes(['user'])); + } + + /** + * unlink provider user + * @post("/auth/unlink/{provider}") + * @Transaction({ + * @Request({"provider": "Facebook"}), + * @Response(200, body={"user_id": 1, "provider_id": 1, "is_connected": 1, "profile_picture_url": "/profile/1"}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function unlink(Request $request) + { + $provider_id = config(ucfirst($request->provider))['id']; + $user = $this->auth->user(); + $provider = ProviderUser::where(['user_id' => $user->id, 'provider_id' => $provider_id])->get(); + if (!$provider) { + return $this->response->errorNotFound("Invalid Request"); + } + ProviderUser::where(['user_id' => $user->id, 'provider_id' => $provider_id])->update(['is_connected' => false]); + $get_user = User::where('id', $user->id)->first(); + $get_user->update(['user_avatar_source_id' => config('constants.ConstSocialLogin.User')]); + $getProvider = ProviderUser::where(['user_id' => $user->id, 'provider_id' => $provider_id])->first(); + return $this->response->item($getProvider, new ProviderUserTransformer); + } + + /** + * update profile image + * @post("/update_profile") + * @Transaction({ + * @Request({"source_id": "1"}), + * @Response(200, body={"Success": "Profile image updated successfully."}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function update_profile(Request $request) + { + $user = $this->auth->user(); + $get_user = User::where('id', $user->id)->first(); + if (!$get_user) { + return $this->response->errorNotFound("Invalid Request"); + } + $update_user = $get_user->update(['user_avatar_source_id' => $request->source_id]); + if ($update_user) { + return response()->json(['Success' => 'Profile image updated successfully.'], 200); + } + } + + /** + * Login with Facebook. + * @post("/auth/facebook") + * @Transaction({ + * @Request({"client_id": "xxxxxxxxxx", "secret": "xxxxxxxxxx"}), + * @Response(200, body={"success": "Login successfully."}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + + public function facebook(Request $request) + { + $fb_detail = config('Facebook'); + $client = new GuzzleHttp\Client(); + $params = [ + 'code' => $request->input('code'), + 'client_id' => $request->input('clientId'), + 'redirect_uri' => $request->input('redirectUri'), + 'client_secret' => $fb_detail['secret_key'] + ]; + // Step 1. Exchange authorization code for access token. + $accessTokenResponse = $client->request('GET', 'https://graph.facebook.com/v2.5/oauth/access_token', [ + 'query' => $params + ]); + $accessToken = json_decode($accessTokenResponse->getBody(), true); + // Step 2. Retrieve profile information about the current user. + $fields = 'id,email,first_name,last_name,link,name'; + $profileResponse = $client->request('GET', 'https://graph.facebook.com/v2.5/me', [ + 'query' => [ + 'access_token' => $accessToken['access_token'], + 'fields' => $fields + ] + ]); + $profile = json_decode($profileResponse->getBody(), true); + + // Step 3a. If user is already signed in then link accounts. + if ($request->header('Authorization')) { + $provider_user = ProviderUser::where('foreign_id', '=', $profile['id'])->first(); + $auth_user = $this->auth->user(); + if ($provider_user) { + if ($auth_user->id != $provider_user->user_id) { + return response()->json(['message' => 'There is already a Facebook account registered by other user'], 409); + } + $provider_user->update(['is_connected' => true]); + return $this->response->item($provider_user, new ProviderUserTransformer); + } else { + $provider = new ProviderUser; + $provider->user_id = $auth_user->id; + $provider->provider_id = $fb_detail['id']; + $provider->foreign_id = $profile['id']; + $provider->access_token = $accessToken['access_token']; + $provider->profile_picture_url = 'http://graph.facebook.com/' . $profile['id'] . '/picture'; + $provider->is_connected = true; + $provider->save(); + return $this->response->item($provider, new ProviderUserTransformer); + } + + } // Step 3b. Create a new user account or return an existing one. + else { + $provider_user = ProviderUser::where('foreign_id', '=', $profile['id'])->first(); + if ($provider_user) { + $user = User::find($provider_user->user_id); + $request->email = $user->email; + $ip_id = $this->IpService->getIpId($request->ip()); + $role = $this->UserLoginService->saveUserLogin($request, $ip_id); + $token = $userToken = $this->SocialLoginService->createToken($user); + return response()->json(compact('userToken', 'token', 'role')); + } else { + $user = new User; + $user->email = $profile['email']; + $user->username = $this->SocialLoginService->generateUserName($profile['name']); + $user->role_id = config('constants.ConstUserTypes.User'); + $user->is_email_confirmed = 1; + $user->register_ip_id = $this->IpService->getIpId($request->ip()); + $user->last_login_ip_id = $this->IpService->getIpId($request->ip()); + $user->user_avatar_source_id = config('constants.ConstSocialLogin.Facebook'); + if (!config('user.is_admin_activate_after_register')) { + $user->is_active = 1; + } + if ($user->save()) { + //Save provider user + $provider = [ + 'user_id' => $user->id, + 'provider_id' => $fb_detail['id'], + 'foreign_id' => $profile['id'], + 'access_token' => $accessToken['access_token'], + 'profile_picture_url' => 'http://graph.facebook.com/' . $profile['id'] . '/picture', + 'is_connected' => true + ]; + ProviderUser::create($provider); + $request->email = $profile['email']; + + $ip_id = $this->IpService->getIpId($request->ip()); + $this->UserService->emailConditions($user, 'register'); + $role = $this->UserLoginService->saveUserLogin($request, $ip_id); + $token = $userToken = $this->SocialLoginService->createToken($user); + return response()->json(compact('userToken', 'token', 'role')); + } + } + } + } + + + /** + * Login with Google. + * @post("/auth/google") + * @Transaction({ + * @Request({"client_id": "xxxxxx", "secret": "xxxxxxxx"}), + * @Response(200, body={"success": "Login successfully."}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function google(Request $request) + { + $google_detail = config('Google'); + $client = new GuzzleHttp\Client(); + $params = [ + 'code' => $request->input('code'), + 'client_id' => $request->input('clientId'), + 'client_secret' => $google_detail['secret_key'], + 'redirect_uri' => $request->input('redirectUri'), + 'grant_type' => 'authorization_code', + ]; + // Step 1. Exchange authorization code for access token. + $accessTokenResponse = $client->request('POST', 'https://accounts.google.com/o/oauth2/token', [ + 'form_params' => $params + ]); + $accessToken = json_decode($accessTokenResponse->getBody(), true); + // Step 2. Retrieve profile information about the current user. + $profileResponse = $client->request('GET', 'https://www.googleapis.com/plus/v1/people/me/openIdConnect', [ + 'headers' => array('Authorization' => 'Bearer ' . $accessToken['access_token']) + ]); + $profile = json_decode($profileResponse->getBody(), true); + // Step 3a. If user is already signed in then link accounts. + if ($request->header('Authorization')) { + // check provider user already exists + $provider_user = ProviderUser::where('foreign_id', '=', $profile['sub'])->first(); + $auth_user = $this->auth->user(); + if ($provider_user) { + if ($auth_user->id != $provider_user->user_id) { + return response()->json(['message' => 'There is already a Google account registered by other user'], 409); + } + $provider_user->update(['is_connected' => true]); + return $this->response->item($provider_user, new ProviderUserTransformer); + } else { + $provider = new ProviderUser; + $provider->user_id = $auth_user->id; + $provider->provider_id = $google_detail['id']; + $provider->foreign_id = $profile['sub']; + $provider->access_token = $accessToken['access_token']; + $provider->profile_picture_url = $profile['picture']; + $provider->is_connected = true; + $provider->save(); + return $this->response->item($provider, new ProviderUserTransformer); + } + } // Step 3b. Create a new user account or return an existing one. + else { + $isAlreadyExistingUser = User::where('email', '=', $profile['email'])->first(); + if ($isAlreadyExistingUser) { + $request->email = $profile['email']; + $ip_id = $this->IpService->getIpId($request->ip()); + $role = $this->UserLoginService->saveUserLogin($request, $ip_id); + $token = $userToken = $this->SocialLoginService->createToken($isAlreadyExistingUser); + return response()->json(compact('userToken', 'token', 'role')); + } else { + $user = new User; + $user->email = $profile['email']; + $user->username = $this->SocialLoginService->generateUserName($profile['name']); + $user->role_id = config('constants.ConstUserTypes.User'); + $user->is_email_confirmed = 1; + $user->register_ip_id = $this->IpService->getIpId($request->ip()); + $user->last_login_ip_id = $this->IpService->getIpId($request->ip()); + $user->user_avatar_source_id = config('constants.ConstSocialLogin.Google'); + if (!config('user.is_admin_activate_after_register')) { + $user->is_active = 1; + } + if ($user->save()) { + //Save provider user + $provider = [ + 'user_id' => $user->id, + 'provider_id' => $google_detail['id'], + 'foreign_id' => $profile['sub'], + 'access_token' => $accessToken['access_token'], + 'profile_picture_url' => $profile['picture'], + 'is_connected' => true + ]; + ProviderUser::create($provider); + $request->email = $profile['email']; + $ip_id = $this->IpService->getIpId($request->ip()); + $this->UserService->emailConditions($user, 'register'); + $role = $this->UserLoginService->saveUserLogin($request, $ip_id); + $token = $userToken = $this->SocialLoginService->createToken($user); + return response()->json(compact('userToken', 'token', 'role')); + } + } + } + } + + /** + * Login with Twitter. + * @post("/auth/twitter") + * @Transaction({ + * @Request({"client_id": "xxxxxxxxxxxx", "secret": "xxxxxxxxxxxx"}), + * @Response(200, body={"success": "Login successfully."}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function twitter(Request $request) + { + $twtr_detail = config('Twitter'); + $provider_id = $twtr_detail->id; + $stack = GuzzleHttp\HandlerStack::create(); + // Part 1 of 2: Initial request from Satellizer. + if (!$request->input('oauth_token') || !$request->input('oauth_verifier')) { + $stack = GuzzleHttp\HandlerStack::create(); + $requestTokenOauth = new Oauth1([ + 'consumer_key' => $twtr_detail->api_key, + 'consumer_secret' => $twtr_detail->secret_key, + 'callback' => $request->input('redirectUri'), + 'token' => '', + 'token_secret' => '' + ]); + $stack->push($requestTokenOauth); + $client = new GuzzleHttp\Client([ + 'handler' => $stack + ]); + // Step 1. Obtain request token for the authorization popup. + $requestTokenResponse = $client->request('POST', 'https://api.twitter.com/oauth/request_token', [ + 'auth' => 'oauth' + ]); + $oauthToken = array(); + parse_str($requestTokenResponse->getBody(), $oauthToken); + // Step 2. Send OAuth token back to open the authorization screen. + return response()->json($oauthToken); + } // Part 2 of 2: Second request after Authorize app is clicked. + else { + $accessTokenOauth = new Oauth1([ + 'consumer_key' => $twtr_detail->api_key, + 'consumer_secret' => $twtr_detail->secret_key, + 'token' => $request->input('oauth_token'), + 'verifier' => $request->input('oauth_verifier'), + 'token_secret' => '' + ]); + $stack->push($accessTokenOauth); + $client = new GuzzleHttp\Client([ + 'handler' => $stack + ]); + // Step 3. Exchange oauth token and oauth verifier for access token. + $accessTokenResponse = $client->request('POST', 'https://api.twitter.com/oauth/access_token', [ + 'auth' => 'oauth' + ]); + $accessToken = array(); + parse_str($accessTokenResponse->getBody(), $accessToken); + $profileOauth = new Oauth1([ + 'consumer_key' => $twtr_detail->api_key, + 'consumer_secret' => $twtr_detail->secret_key, + 'oauth_token' => $accessToken['oauth_token'], + 'token_secret' => '' + ]); + $stack->push($profileOauth); + $client = new GuzzleHttp\Client([ + 'handler' => $stack + ]); + // Step 4. Retrieve profile information about the current user. + $profileResponse = $client->request('GET', 'https://api.twitter.com/1.1/users/show.json?screen_name=' . $accessToken['screen_name'], [ + 'auth' => 'oauth' + ]); + $profile = json_decode($profileResponse->getBody(), true); + // Step 5a. Link user accounts. + if ($request->header('Authorization')) { + // check provider user already exists + $provider_user = ProviderUser::where('foreign_id', '=', $profile['id'])->first(); + $auth_user = $this->auth->user(); + if ($provider_user) { + if ($auth_user->id != $provider_user->user_id) { + return response()->json(['message' => 'There is already a Twitter account registered by other user'], 409); + } + $provider_user->update(['is_connected' => true]); + return $this->response->item($provider_user, new ProviderUserTransformer); + } else { + $provider = new ProviderUser; + $provider->user_id = $auth_user->id; + $provider->provider_id = $twtr_detail['id']; + $provider->foreign_id = $profile['id']; + $provider->access_token = $accessToken['oauth_token']; + $provider->profile_picture_url = $profile['profile_image_url']; + $provider->is_connected = true; + $provider->save(); + return $this->response->item($provider, new ProviderUserTransformer); + } + } // Step 5b. Create a new user account or return an existing one. + else { + // check provider user already exists + $provider_user = ProviderUser::where('foreign_id', '=', $profile['id'])->first(); + if ($provider_user) { + // check user already exists for provider + $user = User::where('id', '=', $provider_user->user_id)->first(); + if ($user) { + $user = User::find($provider_user->user_id); + $request->email = $user->email; + $ip_id = $this->IpService->getIpId($request->ip()); + $role = $this->UserLoginService->saveUserLogin($request, $ip_id); + $token = $userToken = $this->SocialLoginService->createToken($user); + return response()->json(compact('userToken', 'token', 'role')); + } + } else { + if (empty($profile['email'])) { + $profile['provider_id'] = config('constants.ConstSocialLogin.Twitter'); + $profile['access_token'] = $accessToken['oauth_token']; + $profile['provider'] = 'twitter'; + $response['thrid_party_profile'] = $profile; + return response()->json($response); + } + } + } + } + } + + /** + * Login with Github. + * @post("/auth/github") + * @Transaction({ + * @Request({"client_id": 95821807561, "code": "F1xOUd6dOy0WJ9qH", "redirectUri": "../auth/github"}), + * @Response(200, body={"success": "Login successfully."}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function github(Request $request) + { + $github_detail = config('Github'); + $client = new GuzzleHttp\Client(); + + $params = [ + 'code' => $request->input('code'), + 'client_id' => $request->input('clientId'), + 'client_secret' => $github_detail['secret_key'], + 'redirect_uri' => $request->input('redirectUri') + ]; + + // Step 1. Exchange authorization code for access token. + $accessTokenResponse = $client->request('GET', 'https://github.com/login/oauth/access_token', [ + 'query' => $params + ]); + + $accessToken = array(); + parse_str($accessTokenResponse->getBody(), $accessToken); + + // Step 2. Retrieve profile information about the current user. + $profileResponse = $client->request('GET', 'https://api.github.com/user', [ + 'headers' => ['User-Agent' => 'Satellizer'], + 'query' => $accessToken + ]); + $profile = json_decode($profileResponse->getBody(), true); + // exit; + // Step 3a. If user is already signed in then link accounts. + if ($request->header('Authorization')) { + $provider_user = ProviderUser::where('foreign_id', '=', $profile['id'])->first(); + $auth_user = $this->auth->user(); + if ($provider_user) { + if ($auth_user->id != $provider_user->user_id) { + return response()->json(['message' => 'There is already a account registered by other user'], 409); + } + $provider_user->update(['is_connected' => true]); + return $this->response->item($provider_user, new ProviderUserTransformer); + } else { + $provider = new ProviderUser; + $provider->user_id = $auth_user->id; + $provider->provider_id = $github_detail['id']; + $provider->foreign_id = $profile['id']; + $provider->access_token = $accessToken['access_token']; + $provider->profile_picture_url = $profile['avatar_url']; + $provider->is_connected = true; + $provider->save(); + return $this->response->item($provider, new ProviderUserTransformer); + } + } // Step 3b. Create a new user account or return an existing one. + else { + $provider_user = ProviderUser::where('foreign_id', '=', $profile['id'])->first(); + if ($provider_user) { + $user = User::find($provider_user->user_id); + $request->email = $user->email; + $ip_id = $this->IpService->getIpId($request->ip()); + $role = $this->UserLoginService->saveUserLogin($request, $ip_id); + $token = $userToken = $this->SocialLoginService->createToken($user); + return response()->json(compact('userToken', 'token', 'role')); + } else { + if (empty($profile['email'])) { + $response['thrid_party_login_no_email'] = 1; + $profile['provider_id'] = config('constants.ConstSocialLogin.Github'); + $profile['access_token'] = $accessToken['access_token']; + $profile['provider'] = 'github'; + $response['thrid_party_profile'] = $profile; + return response()->json($response); + } else { + $user = new User; + $user->email = $profile['email']; + $user->username = $this->SocialLoginService->generateUserName($profile['login']); + $user->role_id = config('constants.ConstUserTypes.User'); + $user->is_email_confirmed = 1; + $user->user_avatar_source_id = config('constants.ConstSocialLogin.Github'); + $user->register_ip_id = $this->IpService->getIpId($request->ip()); + $user->last_login_ip_id = $this->IpService->getIpId($request->ip()); + $user->user_avatar_source_id = config('constants.ConstSocialLogin.Github'); + $user->is_active = (config('user.is_admin_activate_after_register')) ? 0 : 1; + if ($user->save()) { + //Save provider user + $provider = [ + 'user_id' => $user->id, + 'provider_id' => $github_detail['id'], + 'foreign_id' => $profile['id'], + 'access_token' => $accessToken['access_token'], + 'profile_picture_url' => $profile['avatar_url'], + 'is_connected' => true + ]; + ProviderUser::create($provider); + $request->email = $profile['email']; + $ip_id = $this->IpService->getIpId($request->ip()); + $this->UserService->emailConditions($user, 'register'); + $role = $this->UserLoginService->saveUserLogin($request, $ip_id); + $token = $userToken = $this->SocialLoginService->createToken($user); + return response()->json(compact('userToken', 'token', 'role')); + } + } + } + } + } + + /** + * Social register email must be needed. So we get it from user and register the user. + * @post("/social_login") + * @Transaction({ + * @Request({"email": 95821807561, "thrid_party_profile": ""}), + * @Response(200, body={"userToken": "F1xOUd6dOy0WJ9qH"}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}), + * @Response(409, body={"message": "There is already a provider account that belongs to you", "status_code": 404}) + * }) + */ + public function socialLoginWithEmail(Request $request) + { + $email = $request->input('email'); + $profile = $request->input('thrid_party_profile'); + $user = User::where('email', '=', $email)->first(); + if ($user) { + return response()->json(['message' => 'There is already a ' . $profile['provider'] . 'account that belongs to you'], 409); + } else { + switch ($profile['provider_id']) { + case 2: // Twitter + $user = new User; + $user->email = $email; + $user->username = $this->SocialLoginService->generateUserName($profile['name']); + $user->role_id = config('constants.ConstUserTypes.User'); + $user->is_email_confirmed = 1; + $user->register_ip_id = $this->IpService->getIpId($request->ip()); + $user->last_login_ip_id = $this->IpService->getIpId($request->ip()); + if (!config('user.is_admin_activate_after_register')) { + $user->is_active = 1; + } + if ($user->save()) { + //Save provider user + $provider = [ + 'user_id' => $user->id, + 'provider_id' => $profile['provider_id'], + 'foreign_id' => $profile['id'], + 'access_token' => $profile['access_token'], + 'profile_picture_url' => $profile['profile_image_url'], + 'is_connected' => true + ]; + ProviderUser::create($provider); + $request->email = $email; + $ip_id = $this->IpService->getIpId($request->ip()); + $this->UserService->emailConditions($user, 'register'); + $role = $this->UserLoginService->saveUserLogin($request, $ip_id); + $token = $userToken = $this->SocialLoginService->createToken($user); + return response()->json(compact('userToken', 'token', 'role')); + + } + case 4: // github + $user = new User; + $user->email = $email; + $user->username = $this->SocialLoginService->generateUserName($profile['login']); + $user->role_id = config('constants.ConstUserTypes.User'); + $user->is_email_confirmed = 1; + $user->register_ip_id = $this->IpService->getIpId($request->ip()); + $user->last_login_ip_id = $this->IpService->getIpId($request->ip()); + $user->user_avatar_source_id = config('constants.ConstSocialLogin.Github'); + if (!config('user.is_admin_activate_after_register')) { + $user->is_active = 1; + } + if ($user->save()) { + //Save provider user + $provider = [ + 'user_id' => $user->id, + 'provider_id' => $profile['provider_id'], + 'foreign_id' => $profile['id'], + 'access_token' => $profile['access_token'], + 'profile_picture_url' => $profile['avatar_url'], + 'is_connected' => true + ]; + ProviderUser::create($provider); + $request->email = $email; + $ip_id = $this->IpService->getIpId($request->ip()); + $this->UserService->emailConditions($user, 'register'); + + $role = $this->UserLoginService->saveUserLogin($request, $ip_id); + $token = $userToken = $this->SocialLoginService->createToken($user); + return response()->json(compact('userToken', 'token', 'role')); + } + break; + } + } + + + } + + public function getAuthProviders() { + return ""; + } + +} \ No newline at end of file diff --git a/app/Plugins/SocialLogins/Model/Provider.php b/app/Plugins/SocialLogins/Model/Provider.php new file mode 100644 index 0000000..ea3ca72 --- /dev/null +++ b/app/Plugins/SocialLogins/Model/Provider.php @@ -0,0 +1,81 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\SocialLogins\Model; + +use Illuminate\Http\Request; +use Illuminate\Database\Eloquent\Model; + +/** + * Class Provider + * @package App + */ +class Provider extends Model +{ + /** + * @var string + */ + protected $table = "providers"; + + /** + * The attributes that are mass assignable. + * + * @var array + */ + protected $fillable = [ + 'name', 'secret_key', 'api_key', 'icon_class', 'button_class', 'display_order', 'is_active' + ]; + + /** + * @param $query + * @param Request $request + * @return mixed + */ + public function scopeFilterByRequest($query, Request $request) + { + $query->orderBy($request->input('sort', 'id'), $request->input('sortby', 'desc')); + if ($request->has('filter')) { + $filter = false; + if ($request->input('filter') == 'active') { + $filter = true; + } + $query->where('is_active', '=', $filter); + } + if ($request->has('q')) { + $query->where('name', 'LIKE', '%' . $request->input('q') . '%'); + } + return $query; + + + } + + /** + * @return array + */ + public function scopeGetValidationRule() + { + return [ + 'name' => 'required|min:2', + ]; + } + + public function scopeGetValidationMessage() + { + return [ + 'name.required' => 'Required', + 'name.min' => 'name - Minimum length is 2', + ]; + } +} diff --git a/app/Plugins/SocialLogins/Model/ProviderUser.php b/app/Plugins/SocialLogins/Model/ProviderUser.php new file mode 100644 index 0000000..d1e0a96 --- /dev/null +++ b/app/Plugins/SocialLogins/Model/ProviderUser.php @@ -0,0 +1,39 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\SocialLogins\Model; + +use Illuminate\Auth\Authenticatable; +use Illuminate\Database\Eloquent\Model; +use App\User; + +class ProviderUser extends Model +{ + + /** + * The attributes that are mass assignable. + * + * @var array + */ + protected $fillable = [ + 'user_id', 'provider_id', 'access_token', 'profile_picture_url', 'is_connected', 'foreign_id' + ]; + + + public function user() + { + return $this->belongsTo(User::class); + } +} diff --git a/app/Plugins/SocialLogins/Providers/SocialLoginServiceProvider.php b/app/Plugins/SocialLogins/Providers/SocialLoginServiceProvider.php new file mode 100644 index 0000000..492090f --- /dev/null +++ b/app/Plugins/SocialLogins/Providers/SocialLoginServiceProvider.php @@ -0,0 +1,51 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\SocialLogins\Providers; + +use Illuminate\Support\ServiceProvider; +use Schema; +use Plugins\SocialLogins\Model\Provider; + +class SocialLoginServiceProvider extends ServiceProvider +{ + /** + * Register any application services. + * + * @return void + */ + public function register() + { + include __DIR__ . '/../routes.php'; + $this->app->make('Plugins\SocialLogins\Controllers\SocialLoginsController'); + $this->app->make('Plugins\SocialLogins\Controllers\ProvidersController'); + $this->app->make('Plugins\SocialLogins\Controllers\Admin\AdminProvidersController'); + } + + /** + * Bootstrap the application services. + * + * @return void + */ + public function boot() + { + if (Schema::hasTable('providers')) { + $providers = Provider::where('is_active', 1)->get(); + foreach ($providers as $value) { + config()->set($value->name, $value); + } + } + } +} diff --git a/app/Plugins/SocialLogins/Services/SocialLoginService.php b/app/Plugins/SocialLogins/Services/SocialLoginService.php new file mode 100644 index 0000000..afc0592 --- /dev/null +++ b/app/Plugins/SocialLogins/Services/SocialLoginService.php @@ -0,0 +1,80 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\SocialLogins\Services; + +use App\Services\UserService; +use Tymon\JWTAuth\Providers\JWT\JWTInterface; +use App\User; + +class SocialLoginService +{ + /** + * @var JWTInterface + */ + protected $jwt; + /** + * @var UserService + */ + protected $service; + + /** + * SocialLoginService constructor. + * @param JWTInterface $jwt + * @param UserService $service + */ + + public function __construct(JWTInterface $jwt, UserService $service) + { + $this->jwt = $jwt; + $this->service = $service; + } + + /** + * Generate JSON Web Token. + * @param $user + * @return token + */ + public function createToken($user) + { + $payload = [ + 'sub' => $user->id, + 'iat' => time(), + 'exp' => time() + (2 * 7 * 24 * 60 * 60) + ]; + return $this->jwt->encode($payload, config('constants.token_secret')); + } + + /** + * Generate facebook user name + * @param $fb_user_name + * @return username + */ + + public function generateUserName($fb_user_name) + { + $username = str_replace(' ', '', $fb_user_name); + $username = strtolower(str_replace('.', '_', $username)); + // A condtion to avoid unavilability of user username in our sites + $i = 1; + $created_username = $username; + while ($this->service->CheckUsernameAvailable($username) !== false) { + $username = $created_username . $i++; + } + return $username; + } + + +} diff --git a/app/Plugins/SocialLogins/Transformers/ProviderTransformer.php b/app/Plugins/SocialLogins/Transformers/ProviderTransformer.php new file mode 100644 index 0000000..f377b9b --- /dev/null +++ b/app/Plugins/SocialLogins/Transformers/ProviderTransformer.php @@ -0,0 +1,37 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\SocialLogins\Transformers; + +use League\Fractal; +use Plugins\SocialLogins\Model\Provider; + +/** + * Class ProviderTransformer + * @package app\Transformers + */ +class ProviderTransformer extends Fractal\TransformerAbstract +{ + /** + * @param Provider $provider + * @return array + */ + public function transform(Provider $provider) + { + $output = array_only($provider->toArray(), ['id', 'name', 'secret_key', 'api_key', 'icon_class', 'button_class', 'display_order', 'is_active']); + $output['is_active'] = ($output['is_active'] == 1) ? true : false; + return $output; + } +} \ No newline at end of file diff --git a/app/Plugins/SocialLogins/Transformers/ProviderUserTransformer.php b/app/Plugins/SocialLogins/Transformers/ProviderUserTransformer.php new file mode 100644 index 0000000..df4dc3c --- /dev/null +++ b/app/Plugins/SocialLogins/Transformers/ProviderUserTransformer.php @@ -0,0 +1,62 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\SocialLogins\Transformers; + +use League\Fractal; +use Plugins\SocialLogins\Model\ProviderUser; +use App\Transformers\UserTransformer; + +/** + * Class ProviderTransformer + * @package app\Transformers + */ +class ProviderUserTransformer extends Fractal\TransformerAbstract +{ + /** + * List of resources possible to include + * + * @var array + */ + protected $availableIncludes = [ + 'User' + ]; + + /** + * @param ProviderUser $provider_user + * @return array + */ + public function transform(ProviderUser $provider_user) + { + $output = array_only($provider_user->toArray(), ['user_id', 'provider_id', 'is_connected', 'profile_picture_url']); + $output['is_connected'] = (integer)$output['is_connected']; + return $output; + } + + /** + * @param ProviderUser $provider_user + * @return Fractal\Resource\Item + */ + public function includeUser(ProviderUser $provider_user) + { + if ($provider_user->user) { + return $this->item($provider_user->user, new UserTransformer()); + } else { + return null; + } + + } + +} \ No newline at end of file diff --git a/app/Plugins/SocialLogins/plugin.json b/app/Plugins/SocialLogins/plugin.json new file mode 100644 index 0000000..b8f8cff --- /dev/null +++ b/app/Plugins/SocialLogins/plugin.json @@ -0,0 +1,9 @@ +{ + "name": "SocialLogins", + "class": "fa fa-2x fa-user-plus", + "description": "By enabling this plugin, allow users to login with their social logins like facebook, twitter or google+.", + "dependencies": "", + "module_id": "", + "module_hash": "", + "display_order": "5" +} diff --git a/app/Plugins/SocialLogins/routes.php b/app/Plugins/SocialLogins/routes.php new file mode 100644 index 0000000..0caf17a --- /dev/null +++ b/app/Plugins/SocialLogins/routes.php @@ -0,0 +1,52 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +/* +|-------------------------------------------------------------------------- +| Application Routes +|-------------------------------------------------------------------------- +| +| Here is where you can register all of the routes for an application. +| It is a breeze. Simply tell Lumen the URIs it should respond to +| and give it the Closure to call when that URI is requested. +| +*/ +$api = $this->app->make('Dingo\Api\Routing\Router'); +$api->version(['v1'], function ($api) { + $api->group(['prefix' => 'admin', 'namespace' => 'Plugins\SocialLogins\Controllers\Admin', 'middleware' => 'apitracking'], function () use ($api) { + // providers admin side + $api->get('providers', 'AdminProvidersController@index'); + $api->get('providers/{id}/edit', 'AdminProvidersController@edit'); + $api->get('providers/{id}', 'AdminProvidersController@edit'); + $api->put('providers/{id}', 'AdminProvidersController@update'); + $api->delete('providers/{id}', 'AdminProvidersController@destroy'); + }); + $api->group(['namespace' => 'Plugins\SocialLogins\Controllers', 'middleware' => 'apitracking'], function () use ($api) { + //Providers user side + $api->get('/providers', 'ProvidersController@index'); + + $api->get('/auth/{provider}', 'SocialLoginsController@getAuthProviders'); + + $api->post('/auth/facebook', 'SocialLoginsController@facebook'); + $api->post('/auth/google', 'SocialLoginsController@google'); + $api->post('/auth/linkedin', 'SocialLoginsController@linkedin'); + $api->post('/auth/twitter', 'SocialLoginsController@twitter'); + $api->post('/auth/github', 'SocialLoginsController@github'); + $api->get('/provider_users', 'SocialLoginsController@getProviderUsers'); + $api->post('/auth/unlink', 'SocialLoginsController@unlink'); + $api->post('/update_profile', 'SocialLoginsController@update_profile'); + $api->post('/social_login', 'SocialLoginsController@socialLoginWithEmail'); + }); +}); diff --git a/app/Plugins/Sudopays/Controllers/Admin/AdminSudopayIpnLogsController.php b/app/Plugins/Sudopays/Controllers/Admin/AdminSudopayIpnLogsController.php new file mode 100644 index 0000000..d1ffabe --- /dev/null +++ b/app/Plugins/Sudopays/Controllers/Admin/AdminSudopayIpnLogsController.php @@ -0,0 +1,82 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Sudopays\Controllers\Admin; + +use Illuminate\Http\Request; + + + +use App\Http\Controllers\Controller; +use Plugins\Sudopays\Model\SudopayIpnLog; +use JWTAuth; +use Validator; +use Plugins\Sudopays\Transformers\SudopayIpnLogTransformer; + +/** + * Money Transfer Accounts resource representation. + * @Resource("Sudopays") + */ +class AdminSudopayIpnLogsController extends Controller +{ + /** + * SudopaysController constructor. + */ + public function __construct() + { + // Check the logged user authentication. + $this->middleware('jwt.auth'); + // Check the logged user role. + $this->middleware('role'); + } + + /** + * Show all sudopay transaction logs. + * Get a JSON representation of all the sudopay transaction logs. + * + * @Get("/sudopay_transaction_logs?sort={sort}&sortby={sortby}&page={page}") + * @Parameters({ + * @Parameter("sort", type="string", required=false, description="Sort the sudopay transaction log list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort sudopay transaction log by Ascending / Descending Order.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1), + * }) + */ + + public function index(Request $request) + { + $sudopay_ipn_logs = SudopayIpnLog::paginate(config('constants.ConstPageLimit')); + return $this->response->paginator($sudopay_ipn_logs, (new SudopayIpnLogTransformer)); + + } + + /** + * Show the sudopay transaction log. + * Show the sudopay transaction log with a `id`. + * @Get("/sudopay_transaction_logs/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"id": 1, "amount": 100, "payment_id": 1, "sudopay_transaction_logable_id": 1, "sudopay_transaction_logable_type": "1", "sudopay_pay_key": "1", "merchant_id": 1, "gateway_id": 1, "gateway_name": "sri", "status": "active", "payment_type": "1", "buyer_id": 1, "buyer_email": "1", "buyer_address": "1"}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function show($id) + { + $sudopay_ipn_log = SudopayIpnLog::find($id); + if (!$sudopay_ipn_log) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($sudopay_ipn_log, (new SudopayIpnLogTransformer)); + } +} \ No newline at end of file diff --git a/app/Plugins/Sudopays/Controllers/Admin/AdminSudopayTransactionLogsController.php b/app/Plugins/Sudopays/Controllers/Admin/AdminSudopayTransactionLogsController.php new file mode 100644 index 0000000..c7ec625 --- /dev/null +++ b/app/Plugins/Sudopays/Controllers/Admin/AdminSudopayTransactionLogsController.php @@ -0,0 +1,80 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Sudopays\Controllers\Admin; + +use Illuminate\Http\Request; + +use App\Http\Controllers\Controller; +use Plugins\Sudopays\Model\SudopayTransactionLog; +use JWTAuth; +use Validator; +use Plugins\Sudopays\Transformers\SudopayTransactionLogTransformer; + +/** + * Money Transfer Accounts resource representation. + * @Resource("Sudopays") + */ +class AdminSudopayTransactionLogsController extends Controller +{ + /** + * SudopaysController constructor. + */ + public function __construct() + { + // Check the logged user authentication. + $this->middleware('jwt.auth'); + // Check the logged user role. + $this->middleware('role'); + } + + /** + * Show all sudopay transaction logs. + * Get a JSON representation of all the sudopay transaction logs. + * + * @Get("/sudopay_transaction_logs?sort={sort}&sortby={sortby}&page={page}") + * @Parameters({ + * @Parameter("sort", type="string", required=false, description="Sort the sudopay transaction log list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort sudopay transaction log by Ascending / Descending Order.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1), + * }) + */ + + public function index(Request $request) + { + $sudopay_transaction_logs = SudopayTransactionLog::filterByRequest($request)->paginate(config('constants.ConstPageLimit')); + return $this->response->paginator($sudopay_transaction_logs, (new SudopayTransactionLogTransformer)); + + } + + /** + * Show the sudopay transaction log. + * Show the sudopay transaction log with a `id`. + * @Get("/sudopay_transaction_logs/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"id": 1, "amount": 100, "payment_id": 1, "sudopay_transaction_logable_id": 1, "sudopay_transaction_logable_type": "1", "sudopay_pay_key": "1", "merchant_id": 1, "gateway_id": 1, "gateway_name": "sri", "status": "active", "payment_type": "1", "buyer_id": 1, "buyer_email": "1", "buyer_address": "1"}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function show($id) + { + $sudopay_transaction_log = SudopayTransactionLog::find($id); + if (!$sudopay_transaction_log) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($sudopay_transaction_log, (new SudopayTransactionLogTransformer)); + } +} \ No newline at end of file diff --git a/app/Plugins/Sudopays/Controllers/Admin/AdminSudopaysController.php b/app/Plugins/Sudopays/Controllers/Admin/AdminSudopaysController.php new file mode 100644 index 0000000..587c49d --- /dev/null +++ b/app/Plugins/Sudopays/Controllers/Admin/AdminSudopaysController.php @@ -0,0 +1,110 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Sudopays\Controllers\Admin; + +use Illuminate\Http\Request; + + +use DB; +use App\Http\Controllers\Controller; +use Plugins\Sudopays\Model\Sudopay; +use JWTAuth; +use Validator; + +use Plugins\Sudopays\Services\SudopayAPIService; +use Plugins\Sudopays\Model\SudopayPaymentGateway; +use Plugins\Sudopays\Model\SudopayPaymentGroup; + +/** + * Money Transfer Accounts resource representation. + * @Resource("Sudopays") + */ +class AdminSudopaysController extends Controller +{ + + /** + * @var + */ + protected $sudopayApiService; + + /** + * SudopaysController constructor. + */ + public function __construct() + { + // Check the logged user authentication. + $this->middleware('jwt.auth'); + // Check the logged user role. + $this->middleware('role'); + $this->setSudopayAPIService(); + } + + public function setSudopayAPIService() + { + $this->SudopayAPIService = new SudopayAPIService(); + } + + /** + * @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response|void + */ + public function synchronize() + { + try { + $this->SudopayAPIService->_doDeleteCache(array('supported_actions' => 'auth,capture')); + $gateway_response = $this->SudopayAPIService->callGateways(array('supported_actions' => 'auth,capture')); + if (!$gateway_response) { + return $this->response->errorNotFound("Invalid Request"); + } else { + $enabled_gateways = array(); + DB::table('sudopay_payment_groups')->delete(); + DB::table('sudopay_payment_gateways')->delete(); + if (empty($gateway_response['error']['message'])) { + $i = 0; + foreach ($gateway_response['gateways'] as $key => $gateway_group) { + $group_data = array(); + $group_data['sudopay_group_id'] = $gateway_group['id']; + $group_data['name'] = $gateway_group['name']; + $group_data['thumb_url'] = $gateway_group['thumb_url']; + $sudopay_group = SudopayPaymentGroup::create($group_data); + $sudopay_group_id = $sudopay_group->id; + foreach ($gateway_group['gateways'] as $keyval => $gateway) { + $supported_actions = $gateway['supported_features'][0]['actions']; + $is_marketplace_supported = 0; + if (in_array('Marketplace-Auth', $supported_actions)) { + $is_marketplace_supported = 1; + } + $enabled_gateways[$i]['sudopay_gateway_name'] = $gateway['display_name']; + $enabled_gateways[$i]['is_marketplace_supported'] = $is_marketplace_supported; + $enabled_gateways[$i]['sudopay_gateway_id'] = $gateway['id']; + $enabled_gateways[$i]['sudopay_payment_group_id'] = $sudopay_group_id; + $enabled_gateways[$i]['sudopay_gateway_details'] = serialize($gateway); + $enabled_gateways[$i]['thumb_url'] = $gateway['thumb_url']; + $enabled_gateways[$i]['name'] = $gateway['name']; + SudopayPaymentGateway::create($enabled_gateways[$i]); + $enabled_gateways[$i]['supported_features']['actions'] = $gateway['supported_features'][0]['actions']; + $enabled_gateways[$i]['supported_features']['currencies'] = $gateway['supported_features'][0]['currencies']; + $i++; + } + } + } + return response()->json(['Success' => 'ZazPay synchronized successfully'], 200); + } + } catch (\Exception $e) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('ZazPay could not be synchronized. Please, try again.'); + } + } + +} \ No newline at end of file diff --git a/app/Plugins/Sudopays/Controllers/SudopaysController.php b/app/Plugins/Sudopays/Controllers/SudopaysController.php new file mode 100644 index 0000000..d28f168 --- /dev/null +++ b/app/Plugins/Sudopays/Controllers/SudopaysController.php @@ -0,0 +1,118 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Sudopays\Controllers; + +use Illuminate\Http\Request; + +use DB; +use App\Http\Controllers\Controller; +use Plugins\Sudopays\Model\Sudopay; +use JWTAuth; +use Validator; + +use Plugins\Sudopays\Services\SudopayAPIService; +use Plugins\Sudopays\Services\SudopayService; +use Plugins\Sudopays\Services\SudopayIpnService; + +/** + * Sudopays resource representation. + * @Resource("Sudopays") + */ +class SudopaysController extends Controller +{ + /** + * @var + */ + protected $sudopayIpnService; + /** + * @var + */ + protected $sudopayApiService; + /** + * @var + */ + protected $sudopayService; + + /** + * SudopaysController constructor. + */ + public function __construct() + { + $this->setSudopayAPIService(); + $this->setSudopayService(); + $this->setSudopayIpnService(); + } + + /** + * sudopayapi service object created + */ + public function setSudopayAPIService() + { + $this->sudopayApiService = new SudopayAPIService(); + } + + /** + * sudopay service object created + */ + public function setSudopayService() + { + $this->sudopayService = new SudopayService(); + } + + /** + * + */ + public function setSudopayIpnService() + { + $this->sudopayIpnService = new SudopayIpnService(); + } + + /** + * @param Request $request + * @param $logable_id + * @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response + */ + public function processPayment(Request $request, $logable_id) + { + $this->sudopayIpnService->log($request->all(), $request->ip()); + $response = $this->sudopayService->executePayment($logable_id, $request->all()); + if ($response) { + return response()->json(['success' => "ipn successfully updated"], 200); + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('IPN could not be updated.'); + } + + } + + /** + * @param $request + * @param $logable_id + */ + public function successPayment($logable_id) { + $response = $this->sudopayService->successPayment($logable_id); + return redirect($response['returnUrl']); + } + + /** + * @param $request + * @param $logable_id + */ + public function cancelPayment($logable_id) { + $response = $this->sudopayService->cancelPayment($logable_id); + return redirect($response['returnUrl']); + } + +} \ No newline at end of file diff --git a/app/Plugins/Sudopays/Model/SudopayIpnLog.php b/app/Plugins/Sudopays/Model/SudopayIpnLog.php new file mode 100644 index 0000000..59a3725 --- /dev/null +++ b/app/Plugins/Sudopays/Model/SudopayIpnLog.php @@ -0,0 +1,38 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Sudopays\Model; + +use Illuminate\Http\Request; +use Illuminate\Database\Eloquent\Model; + +class SudopayIpnLog extends Model +{ + protected $table = "sudopay_ipn_logs"; + + protected $fillable = ['ip', 'post_variable']; + /** + * @param $query + * @param Request $request + * @return mixed + */ + public function scopeFilterByRequest($query, Request $request) + { + $query->orderBy($request->input('sort', 'id'), $request->input('sortby', 'desc')); + + return $query; + } + +} diff --git a/app/Plugins/Sudopays/Model/SudopayPaymentGateway.php b/app/Plugins/Sudopays/Model/SudopayPaymentGateway.php new file mode 100644 index 0000000..41c48fa --- /dev/null +++ b/app/Plugins/Sudopays/Model/SudopayPaymentGateway.php @@ -0,0 +1,33 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Sudopays\Model; + +use Illuminate\Http\Request; +use Illuminate\Database\Eloquent\Model; + +class SudopayPaymentGateway extends Model +{ + /** + * @var string + */ + protected $table = "sudopay_payment_gateways"; + /** + * @var array + */ + protected $fillable = [ + 'sudopay_gateway_name', 'sudopay_gateway_details', 'is_marketplace_supported', 'sudopay_gateway_id', 'sudopay_payment_group_id', 'form_fields_credit_card', 'form_fields_manual', 'form_fields_buyer', 'thumb_url', 'supported_features_actions', 'supported_features_card_types', 'supported_features_countries', 'supported_features_credit_card_types', 'supported_features_currencies', 'supported_features_languages', 'supported_features_services', 'connect_instruction', 'name' + ]; +} diff --git a/app/Plugins/Sudopays/Model/SudopayPaymentGroup.php b/app/Plugins/Sudopays/Model/SudopayPaymentGroup.php new file mode 100644 index 0000000..cfb3f7e --- /dev/null +++ b/app/Plugins/Sudopays/Model/SudopayPaymentGroup.php @@ -0,0 +1,33 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Sudopays\Model; + +use Illuminate\Http\Request; +use Illuminate\Database\Eloquent\Model; + +class SudopayPaymentGroup extends Model +{ + /** + * @var string + */ + protected $table = "sudopay_payment_groups"; + /** + * @var array + */ + protected $fillable = [ + 'sudopay_group_id', 'name', 'thumb_url' + ]; +} diff --git a/app/Plugins/Sudopays/Model/SudopayTransactionLog.php b/app/Plugins/Sudopays/Model/SudopayTransactionLog.php new file mode 100644 index 0000000..b0bb5eb --- /dev/null +++ b/app/Plugins/Sudopays/Model/SudopayTransactionLog.php @@ -0,0 +1,65 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Sudopays\Model; + +use Illuminate\Http\Request; +use Illuminate\Database\Eloquent\Model; + +class SudopayTransactionLog extends Model +{ + /** + * @var string + */ + protected $table = "sudopay_transaction_logs"; + + /** + * @var array + */ + protected $fillable = [ + 'amount', 'payment_id', 'sudopay_pay_key', 'merchant_id', 'gateway_id', 'gateway_name', 'status', 'payment_type', 'buyer_id', 'buyer_email', 'buyer_address', 'sudopay_transaction_fee' + ]; + + /** + * @return mixed + */ + public function sudopay_transaction_logable() + { + return $this->morphTo(); + } + + + /** + * @param $query + * @param Request $request + * @return mixed + */ + public function scopeFilterByRequest($query, Request $request) + { + $query->orderBy($request->input('sort', 'id'), $request->input('sortby', 'desc')); + if ($request->has('q')) { + $query->where('payment_id', 'LIKE', '%' . $request->input('q') . '%') + ->orWhere('sudopay_transaction_logable_type', 'LIKE', '%' . $request->input('q') . '%') + ->orWhere('amount', 'LIKE', '%' . $request->input('q') . '%') + ->orWhere('sudopay_pay_key', 'LIKE', '%' . $request->input('q') . '%') + ->orWhere('merchant_id', 'LIKE', '%' . $request->input('q') . '%') + ->orWhere('gateway_name', 'LIKE', '%' . $request->input('q') . '%') + ->orWhere('status', 'LIKE', '%' . $request->input('q') . '%') + ->orWhere('payment_type', 'LIKE', '%' . $request->input('q') . '%'); + } + return $query; + } + +} diff --git a/app/Plugins/Sudopays/Providers/SudopayServiceProvider.php b/app/Plugins/Sudopays/Providers/SudopayServiceProvider.php new file mode 100644 index 0000000..54bf21c --- /dev/null +++ b/app/Plugins/Sudopays/Providers/SudopayServiceProvider.php @@ -0,0 +1,47 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Sudopays\Providers; + +use Illuminate\Support\ServiceProvider; +use Illuminate\Database\Eloquent\Relations\Relation; + +class SudopayServiceProvider extends ServiceProvider +{ + /** + * Register any application services. + * @return void + */ + public function register() + { + include __DIR__ . '/../routes.php'; + $this->app->make('Plugins\Sudopays\Controllers\Admin\AdminSudopayTransactionLogsController'); + $this->app->make('Plugins\Sudopays\Controllers\Admin\AdminSudopayIpnLogsController'); + $this->app->make('Plugins\Sudopays\Controllers\Admin\AdminSudopaysController'); + } + + /** + * Bootstrap the application services. + * @return void + */ + public function boot() + { + $enabledIncludes = array(); + $enabledIncludes['MorphWallet'] = \App\Wallet::class; + if (!empty($enabledIncludes)) { + Relation::morphMap($enabledIncludes); + } + } +} diff --git a/app/Plugins/Sudopays/Services/SudopayAPIService.php b/app/Plugins/Sudopays/Services/SudopayAPIService.php new file mode 100644 index 0000000..ea96752 --- /dev/null +++ b/app/Plugins/Sudopays/Services/SudopayAPIService.php @@ -0,0 +1,386 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Sudopays\Services; + +use Plugins\Sudopays\Model\Sudopay; +use File; + +class SudopayAPIService +{ + // API URL + private $live_api_url = 'https://zazpay.com/api/v1'; + private $sandbox_api_url = 'https://sandbox.zazpay.com/api/v1'; + public $api_url; + private $api_key = ''; + private $merchant_id = ''; + private $is_live = ''; + private $website_id = ''; + private $secret_string = ''; + private $format = 'json'; + private $debug = false; + private $cache_duration = '+48 hours'; + private $cache_path = ''; + private $url_replace_arr = array( + ' ', + '/', + ':', + '?', + '&', + '$', + ',', + '=' + ); + + public function __construct() + { + $this->cache_path = base_path('storage/logs/'); + $sudopay_conf = config('sudopay'); + $this->merchant_id = $sudopay_conf['sudopay_merchant_id']; + $this->website_id = $sudopay_conf['sudopay_website_id']; + $this->api_key = $sudopay_conf['sudopay_api_key']; + $this->secret_string = $sudopay_conf['sudopay_secret_string']; + $this->is_live = $sudopay_conf['is_live_mode']; + $this->api_url = ($this->is_live) ? $this->live_api_url : $this->sandbox_api_url; + } + + private function _safe_json_decode($json) + { + $return = json_decode($json, true); + if ($return === null) { + $error['error']['code'] = 1; + $error['error']['message'] = 'Syntax error, malformed JSON'; + return $error; + } + return $return; + } + + private function _safe_xml_decode($xml) + { + libxml_use_internal_errors(true); + $return = simplexml_load_string($xml); + if ($return === false) { + $error['error']['code'] = 1; + $error['error']['message'] = 'Syntax error, malformed XML'; + return $error; + } + $return = json_decode(json_encode((array)$return), true); + return $return; + } + + public function _doDeleteCache($supported_query = '') + { + $url = $this->api_url . '/merchants/' . $this->merchant_id . '/websites/' . $this->website_id . '/gateways' . '.' . $this->format; + if (!empty($supported_query)) { + $url .= '?' . http_build_query($supported_query); + } + $filename = $this->cache_path . str_replace($this->url_replace_arr, '_', urldecode($url)); + if (File::exists($filename)){ + File::delete($filename); + } + } + + private function _doGet($url) + { + $filename = $this->cache_path . str_replace($this->url_replace_arr, '_', urldecode($url)); + if (file_exists($filename)) { + $fh = fopen($filename, 'r'); + $content = unserialize(fread($fh, filesize($filename))); + fclose($fh); + if (strtotime('now') < $content['expires']) { + return $content['response']; + } + @unlink($filename); + } + $return = $this->_execute($url); + if (empty($return['error']['code'])) { + $fh = fopen($filename, 'w+'); + $content['expires'] = strtotime('now ' . $this->cache_duration); + $content['response'] = $return; + fwrite($fh, serialize($content)); + fclose($fh); + } + return $return; + } + + private function _doPost($url, $post = array()) + { + return $this->_execute($url, 'post', $post); + } + + private function _doPut($url, $post = array()) + { + return $this->_execute($url, 'put', $post); + } + + private function _doDelete($url) + { + return $this->_execute($url, 'delete'); + } + + private function _createSignature($post = array()) + { + $query_string = ''; + foreach ($post as $key => $val) { + $query_string .= $key . '=' . $val . '&'; + } + $query_string = substr($query_string, 0, -1); // remove final & + return md5($this->secret_string . $query_string); + } + + private function _execute($url, $method = 'get', $post = array()) + { + $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL, $url); + curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); + curl_setopt($ch, CURLOPT_USERPWD, $this->merchant_id . ':' . $this->api_key); + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); + curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); + curl_setopt($ch, CURLOPT_TIMEOUT, 60); // 60 seconds (1min) + curl_setopt($ch, CURLOPT_VERBOSE, ($this->debug) ? true : false); + if ($method == 'get') { + curl_setopt($ch, CURLOPT_POST, false); + } elseif ($method == 'post') { + //$post['signature'] = $this->_createSignature($post); + $post_string = http_build_query($post, '', '&'); + curl_setopt($ch, CURLOPT_POST, true); + curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string); + } elseif ($method == 'put') { + $post_string = http_build_query($post, '', '&'); + curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT'); + curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string); + } elseif ($method == 'delete') { + curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE"); + } + $response = curl_exec($ch); + $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); + if ($this->debug) { + $log_content = date('Y-m-d H:i:s') . __FILE__ . '#' . __LINE__ . "\n"; + $log_content .= 'URL: ' . $url . "\n"; + $log_content .= 'HTTP code: ' . $http_code . "\n"; + $log_content .= 'Response: ' . $response . "\n"; + error_log($log_content); + } + if (curl_errno($ch)) { + $error['error']['code'] = 1; + $error['error']['message'] = curl_error($ch); + curl_close($ch); + return $error; + } + switch ($http_code) { + case 200: + if ($this->format == 'json') { + $return = $this->_safe_json_decode($response); + } else if ($this->format == 'xml') { + $return = $this->_safe_xml_decode($response); + } + if (!empty($return['error']['code']) && is_array($return['error']['message'])) { + $return['error']['message'] = implode(', ', $return['error']['message']); + } + break; + + case 401: + $return['error']['code'] = 1; + $return['error']['message'] = 'Unauthorized'; + break; + + case 400: + case 500: + case 504: /* Here we're not sure if anything got already triggered/saved in SudoPay */ + $return['error']['code'] = 1; + $return['error']['message'] = 'Problem in gateway. Recheck later.'; + break; + + default: + $return['error']['code'] = 1; + $return['error']['message'] = 'Not Found'; + } + curl_close($ch); + return $return; + } + public function callPlan() + { + $url = $this->api_url . '/merchants/' . $this->merchant_id . '/websites/' . $this->website_id . '/plan' . '.' . $this->format; + return $this->_doGet($url); + } + public function callGateways($supported_query = '') + { + $url = $this->api_url . '/merchants/' . $this->merchant_id . '/websites/' . $this->website_id . '/gateways' . '.' . $this->format; + if (!empty($supported_query)) { + $url .= '?' . http_build_query($supported_query); + } + return $this->_doGet($url); + } + public function callCreateReceiverAccount($post) + { + $url = $this->api_url . '/merchants/' . $this->merchant_id . '/websites/' . $this->website_id . '/gateways/' . $post['gateway_id'] . '/receiver_accounts' . '.' . $this->format; + return $this->_doPost($url, $post); + } + public function callReceiverAccountListing($receiver_id = '', $gateway_id = '', $page = '') + { + if (!empty($gateway_id)) { + $url = $this->api_url . '/merchants/' . $this->merchant_id . '/websites/' . $this->website_id . '/gateways/' . $gateway_id . '/receiver_accounts/' . $receiver_id . '.' . $this->format; + } else { + $page = !empty($page) ? '?page=' . $page : ''; + $url = $this->api_url . '/merchants/' . $this->merchant_id . '/websites/' . $this->website_id . '/receiver_accounts/' . $receiver_id . $page . '.' . $this->format; + } + return $this->_doGet($url); + } + public function callCapture($post) + { + $url = $this->api_url . '/merchants/' . $this->merchant_id . '/gateways/' . $post['gateway_id'] . '/payments/capture' . '.' . $this->format; + $post['website_id'] = $this->website_id; + return $this->_doPost($url, $post); + } + public function callDisconnectGateway($gateway_id = '', $receiver_id = '') + { + $url = $this->api_url . '/merchants/' . $this->merchant_id . '/websites/' . $this->website_id . '/gateways/' . $gateway_id . '/receiver_accounts/' . $receiver_id . '.' . $this->format; + return $this->_doDelete($url); + } + public function callCaptureConfirm($post) + { + $url = $this->api_url . '/merchants/' . $this->merchant_id . '/gateways/' . $post['gateway_id'] . '/payments/capture/confirm' . '.' . $this->format; + $post['website_id'] = $this->website_id; + return $this->_doPost($url, $post); + } + + public function callAuth($post) + { + $url = $this->api_url . '/merchants/' . $this->merchant_id . '/gateways/' . $post['gateway_id'] . '/payments/auth' . '.' . $this->format; + $post['website_id'] = $this->website_id; + return $this->_doPost($url, $post); + } + + public function callAuthConfirm($post) + { + $url = $this->api_url . '/merchants/' . $this->merchant_id . '/gateways/' . $post['gateway_id'] . '/payments/auth/confirm' . '.' . $this->format; + $post['website_id'] = $this->website_id; + return $this->_doPost($url, $post); + } + + public function callAuthCapture($post) + { + $url = $this->api_url . '/merchants/' . $this->merchant_id . '/gateways/' . $post['gateway_id'] . '/payments/' . $post['payment_id'] . '/auth-capture' . '.' . $this->format; + return $this->_doPost($url, $post); + } + + public function callVoid($post) + { + $url = $this->api_url . '/merchants/' . $this->merchant_id . '/gateways/' . $post['gateway_id'] . '/payments/' . $post['payment_id'] . '/void' . '.' . $this->format; + return $this->_doPost($url, $post); + } + + public function callRefund($post) + { + $url = $this->api_url . '/merchants/' . $this->merchant_id . '/gateways/' . $post['gateway_id'] . '/payments/' . $post['payment_id'] . '/refund' . '.' . $this->format; + return $this->_doPost($url, $post); + } + public function callMarketplaceCapture($post) + { + $url = $this->api_url . '/merchants/' . $this->merchant_id . '/gateways/' . $post['gateway_id'] . '/payments/marketplace-capture' . '.' . $this->format; + $post['website_id'] = $this->website_id; + return $this->_doPost($url, $post); + } + public function callMarketplaceAuth($post) + { + $url = $this->api_url . '/merchants/' . $this->merchant_id . '/gateways/' . $post['gateway_id'] . '/payments/marketplace-auth' . '.' . $this->format; + $post['website_id'] = $this->website_id; + return $this->_doPost($url, $post); + } + public function callMarketplaceAuthCapture($post) + { + $url = $this->api_url . '/merchants/' . $this->merchant_id . '/gateways/' . $post['gateway_id'] . '/payments/' . $post['payment_id'] . '/marketplace-auth-capture' . '.' . $this->format; + return $this->_doPost($url, $post); + } + public function callMarketplaceVoid($post) + { + $url = $this->api_url . '/merchants/' . $this->merchant_id . '/gateways/' . $post['gateway_id'] . '/payments/' . $post['payment_id'] . '/marketplace-void' . '.' . $this->format; + return $this->_doPost($url, $post); + } + public function callMarketplaceRefund($post) + { + $url = $this->api_url . '/merchants/' . $this->merchant_id . '/gateways/' . $post['gateway_id'] . '/payments/' . $post['payment_id'] . '/marketplace-refund' . '.' . $this->format; + return $this->_doPost($url, $post); + } + public function callPayment($payment_id = '') + { + $url = $this->api_url . '/merchants/' . $this->merchant_id . '/payment/' . $payment_id . '.' . $this->format; + return $this->_doGet($url); + } + + public function callMerchantPayments($page = '') + { + $page = !empty($page) ? '?page=' . $page : ''; + $url = $this->api_url . '/merchants/' . $this->merchant_id . '/payments' . $page . '.' . $this->format; + return $this->_doGet($url); + } + + public function callWebsitePayments($page = '') + { + $page = !empty($page) ? '&page=' . $page : ''; + $url = $this->api_url . '/merchants/' . $this->merchant_id . '/payments?website_id=' . $this->website_id . $page . '.' . $this->format; + return $this->_doGet($url); + } + + public function isValidIPNPost($post) + { + $signature = $post['signature']; + unset($post['signature']); + if ($this->_createSignature($post) == $signature) { + return true; + } + return false; + } + public function callCreatePayPalSubscription($post) + { + $url = $this->api_url . '/merchants/' . $this->merchant_id . '/websites/' . $this->website_id . '/subscribe/create' . '.' . $this->format; + return $this->_doPost($url, $post); + } + public function callCancelPayPalSubscription($subscription_id = '') + { + $url = $this->api_url . '/merchants/' . $this->merchant_id . '/websites/' . $this->website_id . '/subscribe/' . $subscription_id . '/cancel.' . $this->format; + return $this->_doPut($url); + } + //get vault listing + public function callGetVaults($user_handle = '', $page = '') + { + if (!empty($user_handle)) { + $url = $this->api_url . '/merchants/' . $this->merchant_id . '/websites/' . $this->website_id . '/users/' . $user_handle . '/vaults/type/cc.' . $this->format; + } else { + $page = !empty($page) ? '?page=' . $page : ''; + $url = $this->api_url . '/merchants/' . $this->merchant_id . '/websites/' . $this->website_id . '/vaults/type/cc.' . $this->format . $page; + } + return $this->_doGet($url); + } + public function callAddVault($post) + { + $url = $this->api_url . '/merchants/' . $this->merchant_id . '/websites/' . $this->website_id . '/vaults/type/cc' . '.' . $this->format; + return $this->_doPost($url, $post); + } + public function callEditVault($vault_id = '') + { + $url = $this->api_url . '/merchants/' . $this->merchant_id . '/websites/' . $this->website_id . '/vaults/' . $vault_id . '.' . $this->format; + return $this->_doPut($url, $post); + } + public function callDeleteVault($vault_id = '') + { + $url = $this->api_url . '/merchants/' . $this->merchant_id . '/websites/' . $this->website_id . '/vaults/' . $vault_id . '.' . $this->format; + return $this->_doDelete($url); + } +} + +?> diff --git a/app/Plugins/Sudopays/Services/SudopayIpnService.php b/app/Plugins/Sudopays/Services/SudopayIpnService.php new file mode 100644 index 0000000..65b4453 --- /dev/null +++ b/app/Plugins/Sudopays/Services/SudopayIpnService.php @@ -0,0 +1,56 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Sudopays\Services; + +use Plugins\Sudopays\Model\SudopayIpnLog; +use App\Services\IpService; +class SudopayIpnService +{ + /** + * @var + */ + protected $ipService; + + /** + * SudopayIpnService constructor. + */ + public function __construct() + { + $this->setIpService(); + } + + /** + * Ipservice object created + */ + public function setIpService() { + $this->ipService = new IpService(); + } + + /** + * @param $request + * @param $ip + * @return static + */ + public function log($request, $ip) + { + $log = array(); + $log['ip'] = $this->ipService->getIpId($ip); + $log['post_variable'] = serialize($request); + return SudopayIpnLog::create($log); + } +} + +?> diff --git a/app/Plugins/Sudopays/Services/SudopayService.php b/app/Plugins/Sudopays/Services/SudopayService.php new file mode 100644 index 0000000..ca9d4c5 --- /dev/null +++ b/app/Plugins/Sudopays/Services/SudopayService.php @@ -0,0 +1,347 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Sudopays\Services; + +use Cache; +use Plugins\Sudopays\Services\SudopayAPIService; +use Plugins\Sudopays\Model\Sudopay; +use Plugins\Sudopays\Model\SudopayTransactionLog; +use Plugins\Sudopays\Model\SudopayPaymentGateway; +use Plugins\Sudopays\Services\SudopayTransactionLogService; +use App\User; + +class SudopayService +{ + + /** + * @var + */ + protected $sudopayAPIService; + + /** + * @var + */ + protected $sudopayTransactionLogService; + + /** + * SudopayService constructor. + */ + public function __construct() + { + $this->setSudopayAPIService(); + $this->setSudopayTransactionLogService(); + } + + public function setSudopayAPIService() + { + $this->sudopayAPIService = new SudopayAPIService(); + } + + public function setSudopayTransactionLogService() + { + $this->sudopayTransactionLogService = new SudopayTransactionLogService(); + } + + public function createPayment($logable_id, $data = array()) + { + $return['error'] = 0; + $sudopay_transaction_log = SudopayTransactionLog::where('id', '=', $logable_id)->first(); + $details = $sudopay_transaction_log->sudopay_transaction_logable; + $post_data = array(); + $return['fees_payer'] = 'buyer'; + if ($sudopay_transaction_log->sudopay_transaction_logable_type == 'MorphWallet') { + $post_data['item_name'] = 'Add to Wallet'; + $post_data['item_description'] = 'Add amount to wallet'; + $post_data['callAction'] = 'callCapture'; + $post_data['amount'] = $details['amount']; + } + if ($sudopay_transaction_log->sudopay_transaction_logable_type == 'MorphVehicle') { + $post_data['item_name'] = 'Vehicle Listing fee'; + $post_data['item_description'] = 'Vehicle Listing fee'; + $post_data['callAction'] = 'callCapture'; + $post_data['amount'] = config('vehicle.listing_fee'); + } + if ($sudopay_transaction_log->sudopay_transaction_logable_type == 'MorphVehicleRental') { + $post_data['item_name'] = 'RentItem'; + $post_data['item_description'] = 'VehicleRental an item'; + if (config('vehicle_rental.is_auto_approve')) { + $post_data['callAction'] = 'callCapture'; + } else { + $post_data['callAction'] = 'callAuth'; + } + $post_data['amount'] = $details['total_amount']; + } + $sudopay_payment_gateway = SudopayPaymentGateway::where('sudopay_gateway_id', '=', $sudopay_transaction_log->gateway_id)->first(); + $sudopayGatewayDetails = unserialize($sudopay_payment_gateway->sudopay_gateway_details); + $gateway_response = $this->sudopayAPIService->callGateways(array('supported_actions' => 'auth,capture')); + if (isset($sudopayGatewayDetails['_form_fields']['_extends_tpl'])) { + foreach ($sudopayGatewayDetails['_form_fields']['_extends_tpl'] as $k => $value) { + if (isset($gateway_response['_form_fields_tpls'][$value]['_fields'])) { + foreach ($gateway_response['_form_fields_tpls'][$value]['_fields'] as $key => $field) { + $form_field_arr[] = $key; + } + } + } + } + if ((isset($post_data['fees_payer']) && $post_data['fees_payer'] == 'buyer') && $details->sudopay_gateway_id != 1) { + $post_data['buyer_fees_payer_confirmation_token'] = $sudopayGatewayDetails['buyer_fees_payer_confirmation_token']; + } + $post_data['buyer_ip'] = $_SERVER['REMOTE_ADDR']; + $post_data['gateway_id'] = $sudopay_transaction_log->gateway_id; + $post_data['buyer_email'] = $data['email']; + $post_data['buyer_address'] = $data['address']; + $post_data['buyer_city'] = $data['city']; + $post_data['buyer_state'] = $data['state']; + $post_data['buyer_country'] = $data['country']; + $post_data['buyer_phone'] = $data['phone']; + $post_data['buyer_zip_code'] = $data['zip_code']; + $post_data['currency_code'] = Config('site.currency_code'); + if (!empty($data['credit_card_number'])) { + $post_data['credit_card_number'] = $data['credit_card_number']; + } + if (!empty($data['credit_card_expire'])) { + $post_data['credit_card_expire'] = $data['credit_card_expire']; + } + if (!empty($data['credit_card_name_on_card'])) { + $post_data['credit_card_name_on_card'] = $data['credit_card_name_on_card']; + } + if (!empty($data['credit_card_code'])) { + $post_data['credit_card_code'] = $data['credit_card_code']; + } + if (!empty($data['payment_note'])) { + $post_data['payment_note'] = $data['payment_note']; + } + $post_data['notify_url'] = Cache::get('site_url_for_shell') . '/api/sudopay/process_payment/' . $logable_id; + $post_data['cancel_url'] = Cache::get('site_url_for_shell') . '/api/sudopay/cancel_payment/' . $logable_id; + $post_data['success_url'] = Cache::get('site_url_for_shell') . '/api/sudopay/success_payment/' . $logable_id; + $sudo_data['status'] = 'init'; + $sudo_data['payment_type'] = $post_data['callAction']; + $sudo_data['buyer_email'] = $data['email']; + $sudo_data['buyer_address'] = $data['address'] . " " . $data['city'] . " " . $data['state'] . " " . $data['country'] . " " . $data['zip_code'] . " " . $data['phone']; + $this->sudopayTransactionLogService->updateLogById($sudo_data, $sudopay_transaction_log->id); + // sudopay process trigger + $response = $this->sudopayAPIService->{$post_data['callAction']}($post_data); + if ($response['error']['code'] <= 0) { + if (!empty($response['status']) && $response['status'] == 'Pending') { + $sudo_data['status'] = $response['status']; + $sudo_data['payment_id'] = $response['id']; + $this->sudopayTransactionLogService->updateLogById($sudo_data, $sudopay_transaction_log->id); + $return['pending'] = 1; + } elseif (!empty($response['status']) && ($response['status'] == 'Captured' || $response['status'] == 'Authorized')) { + /*if ($response['status'] == 'Authorized') { + $data['id'] = $details->id; + $data['item_user_status_id'] = config('constants.ConstItemUserStatus.WaitingForAcceptance'); + $details->update($data); + }*/ + $return['success'] = 1; + } elseif (!empty($response['confirmation'])) { + /* $data['id'] = $details->id; + $data['sudopay_revised_amount'] = $response['revised_amount']; + $data['sudopay_token'] = $response['confirmation']['token']; + $details->update($data);*/ + } elseif (!empty($response['gateway_callback_url'])) { + $return['gateway_callback_url'] = $response['gateway_callback_url']; + } + } else { + $return['error'] = 1; + $return['error_message'] = $response['error']['message']; + } + return $return; + } + + /** + * IPN reposnse update in transaction log and related table + * @param $logable_id + * @param array $post_data + * @return bool + */ + public function executePayment($logable_id, $post_data = array()) + { + $sudopay_transaction_log = SudopayTransactionLog::where('id', '=', $logable_id)->first(); + if ($sudopay_transaction_log && $post_data['error_code'] == '0') { + $sudo_data = array(); + if (isset($post_data['status'])) + $sudo_data['status'] = $post_data['status']; + if (isset($post_data['paykey'])) + $sudo_data['sudopay_pay_key'] = $post_data['paykey']; + if (isset($post_data['id'])) + $sudo_data['payment_id'] = $post_data['id']; + if (isset($post_data['action'])) + $sudo_data['payment_type'] = $post_data['action']; + if (isset($post_data['gateway_name'])) + $sudo_data['gateway_name'] = $post_data['gateway_name']; + if (isset($post_data['gateway_id'])) + $sudo_data['gateway_id'] = $post_data['gateway_id']; + if (isset($post_data['merchant_id'])) + $sudo_data['merchant_id'] = $post_data['merchant_id']; + if (isset($post_data['amount'])) + $sudo_data['sudopay_transaction_fee'] = $post_data['amount'] - $sudopay_transaction_log->amount; + if (!empty($sudo_data)) { + $this->sudopayTransactionLogService->updateLogById($sudo_data, $sudopay_transaction_log->id); + if ($sudopay_transaction_log->sudopay_transaction_logable_type == 'MorphWallet') { + $walletService = new \App\Services\WalletService(); + if ($post_data['status'] == 'Captured') { + $walletService->processAddToWallet($sudopay_transaction_log->sudopay_transaction_logable_id, config('constants.ConstPaymentGateways.SudoPay'), $sudo_data['sudopay_transaction_fee']); + } + if ($post_data['status'] == 'Refunded' && $sudopay_transaction_log->status != 'Refunded') { + $walletService->updateRefund($sudopay_transaction_log, config('constants.ConstPaymentGateways.SudoPay'), $post_data); + } + } + if ($sudopay_transaction_log->sudopay_transaction_logable_type == 'MorphVehicle') { + $vehicleService = new \Plugins\Vehicles\Services\VehicleService(); + if ($post_data['status'] == 'Captured') { + $vehicleService->processVehicleLisitngFee($sudopay_transaction_log->sudopay_transaction_logable_id, config('constants.ConstPaymentGateways.SudoPay'), $sudo_data['sudopay_transaction_fee']); + } + } + if ($sudopay_transaction_log->sudopay_transaction_logable_type == 'MorphVehicleRental') { + $vehicleRentalService = new \Plugins\VehicleRentals\Services\VehicleRentalService(); + if ($post_data['status'] == 'Canceled') { + $vehicleRentalService->updateVoid($sudopay_transaction_log->sudopay_transaction_logable_id, config('constants.ConstPaymentGateways.SudoPay')); + } else if ($post_data['status'] == 'Refunded') { + $vehicleRentalService->updateRefund($sudopay_transaction_log->sudopay_transaction_logable_id, config('constants.ConstPaymentGateways.SudoPay')); + } else if ($post_data['status'] == 'Captured' && $post_data['action'] != 'Auth-Capture') { + $vehicleRentalService->updateVehicleRental($sudopay_transaction_log->sudopay_transaction_logable_id, config('constants.ConstPaymentGateways.SudoPay')); + }else if ($post_data['status'] == 'Authorized' && $post_data['action'] == 'Auth') { + $vehicleRentalService->updateVehicleRental($sudopay_transaction_log->sudopay_transaction_logable_id, config('constants.ConstPaymentGateways.SudoPay')); + } + } + return true; + } else { + return false; + } + } else { + return false; + } + } + + /** + * @param $transaction_log + * @return mixed + */ + public function capturePayment($transaction_log) + { + try { + $post_data = array(); + $post_data['gateway_id'] = $transaction_log->gateway_id; + $post_data['payment_id'] = $transaction_log->payment_id; + $post_data['paykey'] = $transaction_log->sudopay_pay_key; + $post_data['callAction'] = 'callAuthCapture'; + $response = $this->sudopayAPIService->{$post_data['callAction']}($post_data); + return $response; + } catch (Exception $e) { + return array('error' => 1, 'error_message' => $e->getMessage()); + } + } + + /** + * @param $authorization_id + * @return array' + */ + public function voidPayment($transaction_log) + { + try { + $post_data = array(); + $post_data['gateway_id'] = $transaction_log->gateway_id; + $post_data['payment_id'] = $transaction_log->payment_id; + $post_data['paykey'] = $transaction_log->sudopay_pay_key; + $post_data['callAction'] = 'callVoid'; + $response = $this->sudopayAPIService->{$post_data['callAction']}($post_data); + return $response; + } catch (Exception $e) { + return array('error' => 1, 'error_message' => $e->getMessage()); + } + } + + public function refundPayment($transaction_log) + { + try { + $post_data = array(); + $post_data['gateway_id'] = $transaction_log->gateway_id; + $post_data['payment_id'] = $transaction_log->payment_id; + $post_data['paykey'] = $transaction_log->sudopay_pay_key; + $post_data['callAction'] = 'callRefund'; + $response = $this->sudopayAPIService->{$post_data['callAction']}($post_data); + return $response; + } catch (Exception $e) { + return array('error' => 1, 'error_message' => $e->getMessage()); + } + } + + public function successPayment($logable_id) { + $error_message = ''; + $transaction_log = SudopayTransactionLog::where('id', '=', $logable_id)->first(); + if($transaction_log) { + try { + if ($transaction_log->sudopay_transaction_logable_type == 'MorphWallet') { + $walletService = new \App\Services\WalletService(); + $walletService->processAddToWallet($transaction_log->sudopay_transaction_logable_id, config('constants.ConstPaymentGateways.SudoPay'), $transaction_log->sudopay_transaction_fee); + $returnUrl = '/#/wallets/success'; + } + if ($transaction_log->sudopay_transaction_logable_type == 'MorphVehicle') { + if (isPluginEnabled('Vehicles')) { + $vehicleService = new \Plugins\Vehicles\Services\VehicleService(); + $vehicleService->processVehicleLisitngFee($transaction_log->sudopay_transaction_logable_id, config('constants.ConstPaymentGateways.SudoPay'), $transaction_log->sudopay_transaction_fee); + $returnUrl = '/#/vehicle/success'; + } + } + if ($transaction_log->sudopay_transaction_logable_type == 'MorphVehicleRental') { + if (isPluginEnabled('VehicleRentals')) { + $vehicleRentalService = new \Plugins\VehicleRentals\Services\VehicleRentalService(); + $vehicleRentalService->updateVehicleRental($transaction_log->sudopay_transaction_logable_id, config('constants.ConstPaymentGateways.SudoPay')); + $returnUrl = '/#/vehicle_rental/status/success'; + } + } + } catch(Exception $e) { + if ($transaction_log->sudopay_transaction_logable_type == "MorphWallet") { + $returnUrl = '/#/wallets/fail'; + } elseif ($transaction_log->sudopay_transaction_logable_type == "MorphVehicleRental") { + $returnUrl = '/#/vehicle_rental/status/fail'; + }elseif ($transaction_log->sudopay_transaction_logable_type == "MorphVehicle") { + $returnUrl = '/#/vehicle/fail'; + } else { + $returnUrl = '/#/'; + } + $error_message = $e->getMessage(); + } + } + return array( + 'returnUrl' => $returnUrl, + 'message' => $error_message + ); + + } + + public function cancelPayment($logable_id) { + $error_message = ''; + $transaction_log = SudopayTransactionLog::where('id', '=', $logable_id)->first(); + if($transaction_log) { + if ($transaction_log->sudopay_transaction_logable_type == "MorphWallet") { + $returnUrl = '/#/wallets/fail'; + } elseif ($transaction_log->sudopay_transaction_logable_type == "MorphVehicleRental") { + $returnUrl = '/#/vehicle_rental/status/fail'; + }elseif ($transaction_log->sudopay_transaction_logable_type == "MorphVehicle") { + $returnUrl = '/#/vehicle/fail'; + } + } else { + $returnUrl = '/#/'; + } + return array( + 'returnUrl' => $returnUrl + ); + + } + +} diff --git a/app/Plugins/Sudopays/Services/SudopayTransactionLogService.php b/app/Plugins/Sudopays/Services/SudopayTransactionLogService.php new file mode 100644 index 0000000..c0cbc38 --- /dev/null +++ b/app/Plugins/Sudopays/Services/SudopayTransactionLogService.php @@ -0,0 +1,52 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Sudopays\Services; + +use Plugins\Sudopays\Model\SudopayTransactionLog; + +class SudopayTransactionLogService +{ + /** + * PayPalService constructor. + */ + public function __construct() + { + } + + public function log($data) + { + return SudopayTransactionLog::create($data); + } + + public function updateLogByPayId($data, $payId = '') + { + if ($payId) { + $log = SudopayTransactionLog::where('payment_id', '=', $payId)->first(); + if ($log) + $log->update($data); + } + } + + public function updateLogById($data, $id = '') + { + if ($id) { + $log = SudopayTransactionLog::where('id', '=', $id)->first(); + if ($log) + $log->update($data); + } + } + +} diff --git a/app/Plugins/Sudopays/Transformers/SudopayIpnLogTransformer.php b/app/Plugins/Sudopays/Transformers/SudopayIpnLogTransformer.php new file mode 100644 index 0000000..9be377f --- /dev/null +++ b/app/Plugins/Sudopays/Transformers/SudopayIpnLogTransformer.php @@ -0,0 +1,38 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Sudopays\Transformers; + +use League\Fractal; +use Plugins\Sudopays\Model\SudopayIpnLog; + +/** + * Class SudopayIpnLogTransformer + * @package Plugins\Sudopays\Transformers + * + */ +class SudopayIpnLogTransformer extends Fractal\TransformerAbstract +{ + + /** + * @param SudopayIpnLog $sudopay_ipn_log + * @return array + */ + public function transform(SudopayIpnLog $sudopay_ipn_log) + { + $output = array_only($sudopay_ipn_log->toArray(), ['id', 'created_at', 'ip', 'post_variable']); + return $output; + } +} diff --git a/app/Plugins/Sudopays/Transformers/SudopayTransactionLogTransformer.php b/app/Plugins/Sudopays/Transformers/SudopayTransactionLogTransformer.php new file mode 100644 index 0000000..278524f --- /dev/null +++ b/app/Plugins/Sudopays/Transformers/SudopayTransactionLogTransformer.php @@ -0,0 +1,36 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Sudopays\Transformers; + +use League\Fractal; +use Plugins\Sudopays\Model\SudopayTransactionLog; + +/** + * Class SudopayTransactionLogTransformer + * @package Plugins\Sudopays\Transformers + */ +class SudopayTransactionLogTransformer extends Fractal\TransformerAbstract +{ + /** + * @param SudopayTransactionLog $sudopay_transaction_log + * @return array + */ + public function transform(SudopayTransactionLog $sudopay_transaction_log) + { + $output = array_only($sudopay_transaction_log->toArray(), ['id', 'created_at', 'amount', 'payment_id', 'sudopay_transaction_logable_id', 'sudopay_transaction_logable_type', 'sudopay_pay_key', 'merchant_id', 'gateway_id', 'gateway_name', 'status', 'payment_type', 'buyer_id', 'buyer_email', 'buyer_address', 'sudopay_transaction_fee']); + return $output; + } +} diff --git a/app/Plugins/Sudopays/plugin.json b/app/Plugins/Sudopays/plugin.json new file mode 100644 index 0000000..831d3cc --- /dev/null +++ b/app/Plugins/Sudopays/plugin.json @@ -0,0 +1,9 @@ +{ + "name": "ZazPay", + "class": "fa fa-2x icon-sudopay-icon pull-left", + "description": "By enabling this plugin, user can synchronize with zazpay and can access more payment gateways.", + "dependencies": "PaymentGateways", + "module_id": "792", + "module_hash": "408ceefc3362ad8d8cdb52cc7f573b52", + "display_order": "10" +} diff --git a/app/Plugins/Sudopays/routes.php b/app/Plugins/Sudopays/routes.php new file mode 100644 index 0000000..72ef75d --- /dev/null +++ b/app/Plugins/Sudopays/routes.php @@ -0,0 +1,41 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +/* +|-------------------------------------------------------------------------- +| Application Routes +|-------------------------------------------------------------------------- +| +| Here is where you can register all of the routes for an application. +| It is a breeze. Simply tell Lumen the URIs it should respond to +| and give it the Closure to call when that URI is requested. +| +*/ +$api = $this->app->make('Dingo\Api\Routing\Router'); +$api->version(['v1'], function ($api) { + + $api->group(['prefix' => 'admin', 'namespace' => 'Plugins\Sudopays\Controllers\Admin', 'middleware' => 'apitracking'], function () use ($api) { + $api->get('sudopay_transaction_logs', 'AdminSudopayTransactionLogsController@index'); + $api->get('sudopay_transaction_logs/{id}', 'AdminSudopayTransactionLogsController@show'); + $api->get('sudopay_ipn_logs', 'AdminSudopayIpnLogsController@index'); + $api->get('sudopay_ipn_logs/{id}', 'AdminSudopayIpnLogsController@show'); + $api->get('sudopay/synchronize', 'AdminSudopaysController@synchronize'); + }); + $api->group(['namespace' => 'Plugins\Sudopays\Controllers', 'middleware' => 'apitracking'], function () use ($api) { + $api->post('sudopay/process_payment/{id}', 'SudopaysController@processPayment'); + $api->get('sudopay/cancel_payment/{id}', 'SudopaysController@cancelPayment'); + $api->get('sudopay/success_payment/{id}', 'SudopaysController@successPayment'); + }); +}); diff --git a/app/Plugins/Translations/plugin.json b/app/Plugins/Translations/plugin.json new file mode 100644 index 0000000..ef8c14f --- /dev/null +++ b/app/Plugins/Translations/plugin.json @@ -0,0 +1,9 @@ +{ + "name": "Translations", + "class": "fa fa-2x fa-language", + "description": "By enabling this, it helps the site to run the site in multiple languages.", + "dependencies": "", + "module_id": "", + "module_hash": "", + "display_order": "6" +} diff --git a/app/Plugins/VehicleCoupons/Controllers/Admin/AdminVehicleCouponsController.php b/app/Plugins/VehicleCoupons/Controllers/Admin/AdminVehicleCouponsController.php new file mode 100644 index 0000000..1a4396c --- /dev/null +++ b/app/Plugins/VehicleCoupons/Controllers/Admin/AdminVehicleCouponsController.php @@ -0,0 +1,226 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleCoupons\Controllers\Admin; + +use Illuminate\Http\Request; + +use App\Http\Controllers\Controller; +use JWTAuth; +use Validator; +use Plugins\VehicleCoupons\Model\VehicleCoupon; +use Plugins\VehicleCoupons\Transformers\VehicleCouponTransformer; +use DB; +use Carbon; + +/** + * VehicleCoupons resource representation. + * @Resource("Admin/AdminVehicleCouponss") + */ +class AdminVehicleCouponsController extends Controller +{ + /** + * AdminVehicleCouponsController constructor. + */ + public function __construct() + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth'); + // Check the logged user role. + $this->middleware('role'); + } + + /** + * Show all VehicleCoupons + * Get a JSON representation of all the VehicleCoupons. + * @Get("/vehicle_coupons?sort={sort}&sortby={sortby}&page={page}&q={q}") + * @Parameters({ + * @Parameter("sort", type="string", required=false, description="Sort the coupons list by sort key.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort coupons by Ascending / Descending Order.", default=null), + * @Parameter("q", type="string", required=false, description="Search coupons.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1), + * @Parameter("filter", type="string", required=false, description="Filter coupons.", default=null) + * }) + */ + public function index(Request $request) + { + // todo: Need to change the query + $vehicle_coupons = VehicleCoupon::select(DB::raw('coupons.*')) + ->leftJoin(DB::raw('(select id, name from vehicles) as couponable'), 'couponable.id', '=', 'coupons.couponable_id') + ->filterByRequest($request) + ->paginate(config('constants.ConstPageLimit')); + return $this->response->paginator($vehicle_coupons, (new VehicleCouponTransformer)->setDefaultIncludes(['couponable'])); + } + + /** + * Store a new coupon. + * Store a new coupon with a `name`, 'description', 'discount', 'discount_type', 'no_of_quantity', 'validity_start_date', 'validity_end_date', 'maximum_discount_amount'. + * @Post("/vehicle_coupons") + * @Transaction({ + * @Request({"vehicle_id":1, "name": "coupon1", "description": "coupon description", "discount": 10, "discount_type": "%", "no_of_quantity": 2, "validity_start_date": "12-05-2016", "validity_end_date": "13-05-2016", "maximum_discount_amount":100}), + * @Response(200, body={"success": "VehicleCoupon has been added."}), + * @Response(422, body={"message": "VehicleCoupon could not be updated. Please, try again.", "errors": {"name": {}}, "status_code": 422}) + * }) + */ + public function store(Request $request) + { + $vehicle_coupon_data = $request->only('name', 'description', 'discount', 'discount_type_id', 'no_of_quantity', 'validity_start_date', 'validity_end_date', 'maximum_discount_amount', 'is_active'); + if (!is_null($vehicle_coupon_data['validity_start_date'])) { + $vehicle_coupon_data['validity_start_date'] = date("Y-m-d", strtotime($vehicle_coupon_data['validity_start_date'])); + } + if (!is_null($vehicle_coupon_data['validity_end_date'])) { + $vehicle_coupon_data['validity_end_date'] = date("Y-m-d", strtotime($vehicle_coupon_data['validity_end_date'])); + } + $cur_date = Carbon::now()->toDateTimeString(); + if ($cur_date > $vehicle_coupon_data['validity_start_date'] || $vehicle_coupon_data['validity_start_date'] > $vehicle_coupon_data['validity_end_date']) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Start date should be less than end date and greater than current date.'); + } + $validator = Validator::make($vehicle_coupon_data, VehicleCoupon::GetValidationRule($request->method()), VehicleCoupon::GetValidationMessage()); + if ($validator->passes()) { + $vehicle_coupon_data['model_type'] = config('constants.ConstBookingTypes.Booking'); + if (isPluginEnabled('Vehicles') && $request->has('vehicle_id')) { + $vehicle = \Plugins\Vehicles\Model\Vehicle::find($request->vehicle_id); + if (!$vehicle) { + return $this->response->errorNotFound("Invalid Request"); + } + } + $vehicle_coupon = VehicleCoupon::create($vehicle_coupon_data); + if ($vehicle_coupon) { + if (isPluginEnabled('Vehicles') && $request->has('vehicle_id')) { + $vehicle = \Plugins\Vehicles\Model\Vehicle::with(['vehicle_coupons'])->where('id', '=', $request->vehicle_id)->first(); + $vehicle->vehicle_coupons()->save($vehicle_coupon); + } + return response()->json(['Success' => 'VehicleCoupon has been added'], 200); + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('VehicleCoupon could not be added. Please, try again.'); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('VehicleCoupon could not be added. Please, try again.', $validator->errors()); + } + } + + /** + * Edit the specified coupon. + * Edit the coupon with a `id`. + * @Get("vehicle_coupons/{id}/edit") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body= {"id": 1, "name": "coupon", "description": "coupon description", "discount": 10, "discount_type": "%", "no_of_quantity": 2, "validity_start_date": "12-05-2016", "validity_end_date": "13-05-2016", "maximum_discount_amount":100 }), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function edit($id) + { + $vehicle_coupon = VehicleCoupon::filterByVehicleRental()->find($id); + if (!$vehicle_coupon) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($vehicle_coupon, (new VehicleCouponTransformer)->setDefaultIncludes(['couponable'])); + } + + /** + * Update the specified coupon. + * Update the coupon with a `id`. + * @Put("vehicle_coupons/{id}") + * @Transaction({ + * @Request({"id": 1, "vehicle_id":1, "name": "coupon", "description": "coupon description", "discount": 10, "discount_type": "%", "no_of_quantity": 2, "validity_start_date": "12-05-2016", "validity_end_date": "13-05-2016", "maximum_discount_amount":100}), + * @Response(200, body={"success": "VehicleCoupon has been updated."}), + * @Response(422, body={"message": "VehicleCoupon could not be updated. Please, try again.", "errors": {"name": {}}, "status_code": 422}) + * }) + */ + public function update(Request $request, $id) + { + $vehicle_coupon_data = $request->only('name', 'description', 'discount', 'discount_type_id', 'no_of_quantity', 'validity_start_date', 'validity_end_date', 'maximum_discount_amount', 'is_active', 'vehicle_id'); + if (!is_null($vehicle_coupon_data['validity_start_date'])) { + $vehicle_coupon_data['validity_start_date'] = date("Y-m-d", strtotime($vehicle_coupon_data['validity_start_date'])); + } + if (!is_null($vehicle_coupon_data['validity_end_date'])) { + $vehicle_coupon_data['validity_end_date'] = date("Y-m-d", strtotime($vehicle_coupon_data['validity_end_date'])); + } + $cur_date = Carbon::now()->toDateTimeString(); + if ($cur_date > $vehicle_coupon_data['validity_start_date'] || $vehicle_coupon_data['validity_start_date'] > $vehicle_coupon_data['validity_end_date']) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Start date should be less than end date and greater than current date.'); + } + $vehicle_coupon = false; + if ($request->has('id')) { + $vehicle_coupon = VehicleCoupon::filterByVehicleRental()->find($id); + $vehicle_coupon = ($request->id != $id) ? false : $vehicle_coupon; + } + if ($vehicle_coupon && $vehicle_coupon->name == $vehicle_coupon_data['name']) { + unset($vehicle_coupon_data['name']); + } + $validator = Validator::make($vehicle_coupon_data, VehicleCoupon::GetValidationRule(), VehicleCoupon::GetValidationMessage()); + if ($validator->passes() && $vehicle_coupon) { + if (isPluginEnabled('Vehicles') && $request->has('vehicle_id')) { + $vehicle = \Plugins\Vehicles\Model\Vehicle::find($request->vehicle_id); + if (!$vehicle) { + return $this->response->errorNotFound("Vehicle not found"); + } + } + try { + $vehicle_coupon->update($vehicle_coupon_data); + if (isPluginEnabled('Vehicles') && $request->has('vehicle_id')) { + $vehicle = \Plugins\Vehicles\Model\Vehicle::with(['vehicle_coupons'])->where('id', '=', $request->vehicle_id)->first(); + $vehicle->vehicle_coupons()->save($vehicle_coupon); + } + return response()->json(['Success' => 'VehicleCoupon has been updated'], 200); + } catch (\Exception $e) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('VehicleCoupon could not be updated. Please, try again.'); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('VehicleCoupon could not be updated. Please, try again.', $validator->errors()); + } + } + + /** + * Delete the specified coupon. + * Delete the coupon with a `id`. + * @Delete("vehicle_coupons/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"success": "VehicleCoupon Deleted."}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function destroy($id) + { + $vehicle_coupon = VehicleCoupon::filterByVehicleRental()->find($id); + if (!$vehicle_coupon) { + return $this->response->errorNotFound("Invalid Request"); + } else { + $vehicle_coupon->delete(); + } + return response()->json(['Success' => 'VehicleCoupon deleted'], 200); + } + + /** + * Show the specified coupon. + * Show the coupon with a `id`. + * @Get("coupons/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"id": 1, "name": "coupon", "description": "coupon description", "discount": 10, "discount_type": "%", "no_of_quantity": 2, "validity_start_date": "12-05-2016", "validity_end_date": "13-05-2016", "maximum_discount_amount":100}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function show($id) + { + $vehicle_coupon = VehicleCoupon::filterByVehicleRental()->find($id); + if (!$vehicle_coupon) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($vehicle_coupon, (new VehicleCouponTransformer)->setDefaultIncludes(['couponable'])); + } +} diff --git a/app/Plugins/VehicleCoupons/Controllers/VehicleCouponsController.php b/app/Plugins/VehicleCoupons/Controllers/VehicleCouponsController.php new file mode 100644 index 0000000..284db02 --- /dev/null +++ b/app/Plugins/VehicleCoupons/Controllers/VehicleCouponsController.php @@ -0,0 +1,106 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleCoupons\Controllers; + +use Illuminate\Http\Request; + +use App\Http\Controllers\Controller; +use JWTAuth; +use Validator; +use Plugins\VehicleCoupons\Model\VehicleCoupon; + +/** + * VehicleCoupons resource representation. + * @Resource("coupons") + */ +class VehicleCouponsController extends Controller +{ + /** + * VehicleCouponsController constructor. + */ + public function __construct() + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth'); + } + + /** + * Apply coupon from item user. + * Apply coupon with a `item_id`, `item_user_id` and `name`. + * @Get("/coupons/{iem_id}/{iem_user_id}") + * @Transaction({ + * @Request({"item_user_id": 1, "name": "XXXX"}), + * @Response(200, body={"success": "Coupon Code Applied!."}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}), + * @Response(404, body={"message": "Invalid Coupon Code!", "status_code": 404}) + * }) + */ + + Public function applyCoupon(Request $request, $item_user_id) + { + $apply_coupon = array(); + $vehicle_coupon_name = $request->only('name'); + if (isPluginEnabled('VehicleRentals')) { + $vehicle_rental = \Plugins\VehicleRentals\Model\VehicleRental::find($item_user_id); + $vehicle = $vehicle_rental->item_userable; + if (!$vehicle || !$vehicle_rental || ($vehicle_rental->item_userable_type != 'MorphVehicle')) { + return $this->response->errorNotFound("Invalid Request"); + } + } + $vehicle_coupon = VehicleCoupon::where(['is_active' => true, 'name' => $vehicle_coupon_name])->first(); + if (!$vehicle_coupon) { + return $this->response->errorNotFound("Invalid Coupon Code!"); + } + if(is_null($vehicle_coupon->couponable) || $vehicle_coupon->couponable_id != $vehicle_rental->item_userable_id) { + return $this->response->errorNotFound("Invalid Coupon Code!"); + } + if($vehicle_rental->coupon_id || $vehicle_rental->coupon_id == $vehicle_coupon->id){ + return $this->response->errorNotFound("Coupon already used"); + } + if(($vehicle_coupon->validity_start_date != '0000-00-00 00:00:00') && ($vehicle_coupon->validity_end_date != '0000-00-00 00:00:00')) { + $current_date = date('Y-m-d H:i:s'); + $current_date=date('Y-m-d H:i:s', strtotime($current_date));; + $validity_start_date = date('Y-m-d H:i:s', strtotime($vehicle_coupon->validity_start_date)); + $validity_end_date = date('Y-m-d H:i:s', strtotime($vehicle_coupon->validity_end_date)); + if ($current_date < $validity_start_date) + { + return $this->response->errorNotFound("Invalid Coupon"); + } + if (($current_date > $validity_end_date) || ($vehicle_coupon->no_of_quantity_used == $vehicle_coupon->no_of_quantity)) + { + return $this->response->errorNotFound("Coupon Validity Expired"); + } + } + try { + $amount = $vehicle_coupon->maximum_discount_amount; + if($vehicle_coupon->discount_type_id == config('constants.ConstDiscountTypes.percentage')) { + $amount = ($vehicle_coupon->discount / 100) * $vehicle_rental->total_amount; + if($amount > $vehicle_coupon->maximum_discount_amount) { + $amount = $vehicle_coupon->maximum_discount_amount; + } + } + if(isPluginEnabled('VehicleRentals')) { + $apply_coupon['coupon_id'] = $vehicle_coupon->id; + $apply_coupon['coupon_discount_amount'] = $amount; + $apply_coupon['total_amount'] = $vehicle_rental->total_amount - $amount; + $vehicle_rental->update($apply_coupon); + return response()->json(['Success' => 'Coupon Code Applied!'], 200); + } + } catch (\Exception $e) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Coupon could not be applied. Please, try again.'); + } + } +} diff --git a/app/Plugins/VehicleCoupons/Model/VehicleCoupon.php b/app/Plugins/VehicleCoupons/Model/VehicleCoupon.php new file mode 100644 index 0000000..ef547f0 --- /dev/null +++ b/app/Plugins/VehicleCoupons/Model/VehicleCoupon.php @@ -0,0 +1,123 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleCoupons\Model; + +use Illuminate\Http\Request; +use Illuminate\Database\Eloquent\Model; + +class VehicleCoupon extends Model +{ + /** + * @var string + */ + protected $table = "coupons"; + + protected $fillable = [ + 'model_type', 'name', 'description', 'discount', 'discount_type_id', 'no_of_quantity', 'no_of_quantity_used', 'validity_start_date', 'validity_end_date', 'maximum_discount_amount', 'is_active' + ]; + + /** + * @return \Illuminate\Database\Eloquent\Relations\MorphTo + */ + public function couponable() + { + return $this->morphTo(); + } + + /** + * @param $query + * @param Request $request + * @return mixed + */ + public function scopeFilterByRequest($query, Request $request) + { + if ($request->input('sort', 'id') == 'item.name') { + $query->orderBy('name', $request->input('sortby', 'desc')); + } else { + $query->orderBy($request->input('sort', 'id'), $request->input('sortby', 'desc')); + } + if ($request->has('filter')) { + $filter = false; + if ($request->input('filter') == 'active') { + $filter = true; + } + $query->where('is_active', '=', $filter); + } + if ($request->has('q')) { + /*$query->whereHas('couponable', function ($query) use ($request) { + $query->Where('name', 'LIKE', '%' . $request->input('q') . '%'); + });*/ + $query->Where('couponable.name', 'LIKE', '%' . $request->input('q') . '%'); + $query->orWhere('coupons.name', 'LIKE', '%' . $request->input('q') . '%'); + } + if ($request->has('start_date')) { + $start_date = date("Y-m-d H:i:s", strtotime($request->input('start_date'))); + $query->where('validity_start_date', '>=', $start_date); + } + if ($request->has('end_date')) { + $end_date = date("Y-m-d H:i:s", strtotime($request->input('end_date'))); + $query->where('validity_end_date', '<=', $end_date); + } + return $query; + } + + public function scopeFilterByVehicleRental($query) + { + $query->where('model_type', config('constants.ConstBookingTypes.Booking')); + return $query; + } + + /** + * @return array + */ + public function scopeGetValidationRule() + { + return [ + 'name' => 'sometimes|required|unique:coupons|min:4', + 'description' => 'required', + 'discount' => 'required|numeric', + 'discount_type_id' => 'required', + 'no_of_quantity' => 'required|integer', + 'maximum_discount_amount' => 'required|numeric', + 'is_active' => 'required|boolean', + 'validity_start_date' => 'date|date_format:Y-m-d', + 'validity_end_date' => 'date|date_format:Y-m-d' + ]; + } + + public function scopeGetValidationMessage() + { + return [ + 'name.required' => 'Required', + 'name.unique' => 'Name already exists!', + 'name.min' => 'name - Minimum length is 4!', + 'description.required' => 'Required', + 'discount.required' => 'Required', + 'discount.numeric' => 'Discount must be a number', + 'discount_type_id.required' => 'Required', + 'no_of_quantity.required' => 'Required', + 'no_of_quantity.integer' => 'No of quantity must be a number', + 'maximum_discount_amount.required' => 'Required', + 'maximum_discount_amount.numeric' => 'Maximum discount amount must be a number', + 'is_active.required' => 'Required', + 'is_active.boolean' => 'is_active must be a boolean', + 'validity_start_date.date' => 'Start date should be a date!', + 'item_booking_start_date.date_format' => 'Date should be in yyyy-mm-dd format', + 'validity_end_date.date' => 'End date should be a date!', + 'validity_end_date.date_format' => 'Date should be in yyyy-mm-dd format', + ]; + } +} diff --git a/app/Plugins/VehicleCoupons/Providers/VehicleCouponServiceProvider.php b/app/Plugins/VehicleCoupons/Providers/VehicleCouponServiceProvider.php new file mode 100644 index 0000000..a757ce9 --- /dev/null +++ b/app/Plugins/VehicleCoupons/Providers/VehicleCouponServiceProvider.php @@ -0,0 +1,45 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleCoupons\Providers; + +use Illuminate\Support\ServiceProvider; +use Illuminate\Database\Eloquent\Relations\Relation; +class VehicleCouponServiceProvider extends ServiceProvider +{ + /** + * Register any application services. + * + * @return void + */ + public function register() + { + include __DIR__ . '/../routes.php'; + $this->app->make('Plugins\VehicleCoupons\Controllers\Admin\AdminVehicleCouponsController'); + $this->app->make('Plugins\VehicleCoupons\Controllers\VehicleCouponsController'); + } + + /** + * Bootstrap the application services. + * + * @return void + */ + public function boot() + { + Relation::morphMap([ + 'MorphVehicle' => \Plugins\Vehicles\Model\Vehicle::class + ]); + } +} diff --git a/app/Plugins/VehicleCoupons/Services/VehicleCouponService.php b/app/Plugins/VehicleCoupons/Services/VehicleCouponService.php new file mode 100644 index 0000000..17759a2 --- /dev/null +++ b/app/Plugins/VehicleCoupons/Services/VehicleCouponService.php @@ -0,0 +1,31 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleCoupons\Services; + +use Plugins\VehicleCoupons\Model\VehicleCoupon; +class VehicleCouponService +{ + + public function updateCouponquantity($coupon_id) + { + $vehicle_coupon = VehicleCoupon::find($coupon_id); + if ($vehicle_coupon) { + $data['no_of_quantity_used'] = \Plugins\VehicleRentals\Model\VehicleRental::where('coupon_id',$vehicle_coupon->id)->where('item_user_status_id' ,'!=', config('constants.ConstItemUserStatus.PaymentPending'))->count(); + $vehicle_coupon->update($data); + } + } + +} diff --git a/app/Plugins/VehicleCoupons/Transformers/VehicleCouponTransformer.php b/app/Plugins/VehicleCoupons/Transformers/VehicleCouponTransformer.php new file mode 100644 index 0000000..0e4593d --- /dev/null +++ b/app/Plugins/VehicleCoupons/Transformers/VehicleCouponTransformer.php @@ -0,0 +1,60 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleCoupons\Transformers; + +use League\Fractal; +use Plugins\VehicleCoupons\Model\VehicleCoupon; + +/** + * Class VehicleCouponTransformer + * @package VehicleCoupons\Transformers + */ +class VehicleCouponTransformer extends Fractal\TransformerAbstract +{ + /** + * @var array + */ + protected $availableIncludes = [ + 'Couponable' + ]; + + /** + * @param VehicleCoupon $vehicle_coupon + * @return array + */ + public function transform(VehicleCoupon $vehicle_coupon) + { + $output = array_only($vehicle_coupon->toArray(), ['id', 'morph_type', 'name', 'description', 'discount', 'discount_type_id', 'no_of_quantity', 'no_of_quantity_used', 'validity_start_date', 'validity_end_date', 'maximum_discount_amount', 'is_active', 'couponable_id']); + $output['no_of_quantity'] = (int)$output['no_of_quantity']; + $output['vehicle_id'] = $output['couponable_id']; + $output['is_active'] = ($output['is_active']) ? true : false; + return $output; + } + + /** + * @param VehicleCoupon $vehicle_coupon + * @return Fractal\Resource\Item|null + */ + public function includeCouponable(VehicleCoupon $vehicle_coupon) + { + if (!is_null($vehicle_coupon->couponable) && $vehicle_coupon->couponable_type == 'MorphVehicle') { + //Todo Need to change the vehicle transformer + return $this->item($vehicle_coupon->couponable, new \Plugins\Vehicles\Transformers\VehicleTransformer()); + } else { + return null; + } + } +} \ No newline at end of file diff --git a/app/Plugins/VehicleCoupons/plugin.json b/app/Plugins/VehicleCoupons/plugin.json new file mode 100644 index 0000000..a776c0e --- /dev/null +++ b/app/Plugins/VehicleCoupons/plugin.json @@ -0,0 +1,9 @@ +{ + "name": "VehicleCoupons", + "class": "fa fa-2x fa-gift", + "description": "By enabling this, item owner can add coupons. ", + "dependencies": "VehicleRentals", + "module_id": "793", + "module_hash": "13b14c3e061ad1ab578c6c9a16a66348", + "display_order": "11" +} diff --git a/app/Plugins/VehicleCoupons/routes.php b/app/Plugins/VehicleCoupons/routes.php new file mode 100644 index 0000000..796c463 --- /dev/null +++ b/app/Plugins/VehicleCoupons/routes.php @@ -0,0 +1,42 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +/* +|-------------------------------------------------------------------------- +| Application Routes +|-------------------------------------------------------------------------- +| +| Here is where you can register all of the routes for an application. +| It is a breeze. Simply tell Lumen the URIs it should respond to +| and give it the Closure to call when that URI is requested. +| +*/ +$api = $this->app->make('Dingo\Api\Routing\Router'); +$api->version(['v1'], function ($api) { + $api->group(['prefix' => 'admin', 'namespace' => 'Plugins\VehicleCoupons\Controllers\Admin', 'middleware' => 'apitracking'], function () use ($api) { + // coupons admin side + $api->get('vehicle_coupons', 'AdminVehicleCouponsController@index'); + $api->post('vehicle_coupons', 'AdminVehicleCouponsController@store'); + $api->put('vehicle_coupons/{id}', 'AdminVehicleCouponsController@update'); + $api->get('vehicle_coupons/{id}/edit', 'AdminVehicleCouponsController@edit'); + $api->get('vehicle_coupons/{id}', 'AdminVehicleCouponsController@show'); + $api->delete('vehicle_coupons/{id}', 'AdminVehicleCouponsController@destroy'); + + }); + $api->group(['namespace' => 'Plugins\VehicleCoupons\Controllers', 'middleware' => 'apitracking'], function () use ($api) { + //coupons user side + $api->post('vehicle_coupons/{item_user_id}', 'VehicleCouponsController@applyCoupon'); + }); +}); diff --git a/app/Plugins/VehicleDisputes/Controllers/Admin/AdminVehicleDisputeClosedTypesController.php b/app/Plugins/VehicleDisputes/Controllers/Admin/AdminVehicleDisputeClosedTypesController.php new file mode 100644 index 0000000..499a9cf --- /dev/null +++ b/app/Plugins/VehicleDisputes/Controllers/Admin/AdminVehicleDisputeClosedTypesController.php @@ -0,0 +1,111 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleDisputes\Controllers\Admin; + +use Illuminate\Http\Request; +use App\Http\Controllers\Controller; +use JWTAuth; +use Validator; +use Plugins\VehicleDisputes\Model\VehicleDisputeClosedType; +use Plugins\VehicleDisputes\Transformers\VehicleDisputeClosedTypeTransformer; +use DB; + +/** + * Class AdminVehicleDisputeClosedTypesController + * @package Plugins\VehicleDisputes\Controllers + */ +class AdminVehicleDisputeClosedTypesController extends Controller +{ + /** + * AdminVehicleDisputeClosedTypesController constructor. + */ + public function __construct() + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth'); + // Check the logged user role. + $this->middleware('role'); + } + + /** + * Show all VehicleDisputeClosedTypes + * Get a JSON representation of all the VehicleDisputeClosedTypes. + * + * @Get("/vehicle_dispute_closed_types?sort={sort}&sortby={sortby}&page={page}") + * @Parameters({ + * @Parameter("sort", type="string", required=false, description="Sort the disputes list by sort key.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort disputes by Ascending / Descending Order.", default=null) + * }) + */ + public function index(Request $request) + { + $vehicle_dispute_closed_types = VehicleDisputeClosedType::with(['dispute_type']) + ->select(DB::raw('dispute_closed_types.*')) + ->leftJoin(DB::raw('(select id,name from dispute_types) as dispute_type'), 'dispute_type.id', '=', 'dispute_closed_types.dispute_type_id') + ->filterByRequest($request)->paginate(config('constants.ConstPageLimit')); + return $this->response->paginator($vehicle_dispute_closed_types, (new VehicleDisputeClosedTypeTransformer)->setDefaultIncludes(['dispute_type'])); + } + + /** + * Edit the specified dispute_closed_type. + * Edit the dispute_closed_type with a `id`. + * @Get("/vehicle_dispute_closed_types/{id}/edit") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"id": 1, "name": "Favor Booker", "dispute_type_id": 1, "is_booker": 1, "resolved_type": "refunded", "reason": "Property doesn't match with the one mentioned in property specification", "DisputeType": {}}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function edit($id) + { + $dispute_closed_type = VehicleDisputeClosedType::with(['dispute_type'])->find($id); + if (!$dispute_closed_type) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($dispute_closed_type, (new VehicleDisputeClosedTypeTransformer)->setDefaultIncludes(['dispute_type'])); + } + + /** + * Update the specified dispute closed type. + * Update the dispute_closed_type with a `id`. + * @Put("/vehicle_dispute_closed_types/{id}") + * @Transaction({ + * @Request({"id": 1, "name": "Favor Booker", "dispute_type_id": 1, "is_booker": 1, "resolved_type": "refunded", "reason": "Property doesn't match with the one mentioned in property specification"}), + * @Response(200, body={"success": "Record has been updated."}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {"name": {}}, "status_code": 422}) + * }) + */ + public function update(Request $request, $id) + { + $dispute_closed_type_data = $request->only('name', 'dispute_type_id', 'is_booker', 'resolved_type', 'reason'); + $validator = Validator::make($dispute_closed_type_data, VehicleDisputeClosedType::GetValidationRule(), VehicleDisputeClosedType::GetValidationMessage()); + $dispute_closed_type = false; + if ($request->has('id')) { + $dispute_closed_type = VehicleDisputeClosedType::find($id); + $dispute_closed_type = ($request->id != $id) ? false : $dispute_closed_type; + } + if ($validator->passes() && $dispute_closed_type) { + try { + $dispute_closed_type->update($dispute_closed_type_data); + return response()->json(['Success' => 'VehicleDisputeClosedType has been updated'], 200); + } catch (\Exception $e) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('VehicleDisputeClosedType could not be updated. Please, try again.'); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('VehicleDisputeClosedType could not be updated. Please, try again.', $validator->errors()); + } + } +} diff --git a/app/Plugins/VehicleDisputes/Controllers/Admin/AdminVehicleDisputeTypesController.php b/app/Plugins/VehicleDisputes/Controllers/Admin/AdminVehicleDisputeTypesController.php new file mode 100644 index 0000000..3f4df8d --- /dev/null +++ b/app/Plugins/VehicleDisputes/Controllers/Admin/AdminVehicleDisputeTypesController.php @@ -0,0 +1,107 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleDisputes\Controllers\Admin; + +use Illuminate\Http\Request; +use App\Http\Controllers\Controller; +use JWTAuth; +use Validator; +use Plugins\VehicleDisputes\Model\VehicleDisputeType; +use Plugins\VehicleDisputes\Transformers\VehicleDisputeTypeTransformer; + +/** + * Class AdminVehicleDisputeTypesController + * @package Plugins\VehicleDisputes\Controllers + */ +class AdminVehicleDisputeTypesController extends Controller +{ + /** + * AdminVehicleDisputeTypesController constructor. + */ + public function __construct() + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth'); + // Check the logged user role. + $this->middleware('role'); + } + + /** + * Show all VehicleDisputeTypes + * Get a JSON representation of all the VehicleDisputeTypes. + * + * @Get("/vehicle_disputes?sort={sort}&sortby={sortby}&page={page}&q={q}") + * @Parameters({ + * @Parameter("sort", type="string", required=false, description="Sort the disputes list by sort key.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort disputes by Ascending / Descending Order.", default=null) + * }) + */ + public function index(Request $request) + { + $vehicle_dispute_types = VehicleDisputeType::filterByRequest($request)->paginate(config('constants.ConstPageLimit')); + return $this->response->paginator($vehicle_dispute_types, (new VehicleDisputeTypeTransformer)); + } + + /** + * Edit the specified dispute type. + * Edit the dispute type with a `id`. + * @Get("/vehicle_dispute_types/{id}/edit") + * @Transaction({ + * @Request({"id": 2}), + * @Response(200, body={"id": 2, "name": "Booker given poor feedback", "is_booker": 0, "is_active": 1}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function edit($id) + { + $dispute_type = VehicleDisputeType::find($id); + if (!$dispute_type) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($dispute_type, (new VehicleDisputeTypeTransformer)); + } + + /** + * Update the specified dispute type. + * Update the dispute type with a `id`. + * @Put("/dispute_types/{id}") + * @Transaction({ + * @Request({"id": 1, "name": "chennai", "state_id": 1, "country_id": 1, "latitude": 10.10, "longitude": 12.12, "is_active": 1}), + * @Response(200, body={"success": "Record has been updated."}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {"name": {}}, "status_code": 422}) + * }) + */ + public function update(Request $request, $id) + { + $dispute_type_data = $request->only('name', 'is_booker', 'is_active'); + $validator = Validator::make($dispute_type_data, VehicleDisputeType::GetValidationRule(), VehicleDisputeType::GetValidationMessage()); + $dispute_type = false; + if ($request->has('id')) { + $dispute_type = VehicleDisputeType::find($id); + $dispute_type = ($request->id != $id) ? false : $dispute_type; + } + if ($validator->passes() && $dispute_type) { + try { + $dispute_type->update($dispute_type_data); + return response()->json(['Success' => 'VehicleDisputeType has been updated'], 200); + } catch (\Exception $e) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('VehicleDisputeType could not be updated. Please, try again.'); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('VehicleDisputeType could not be updated. Please, try again.', $validator->errors()); + } + } +} diff --git a/app/Plugins/VehicleDisputes/Controllers/Admin/AdminVehicleDisputesController.php b/app/Plugins/VehicleDisputes/Controllers/Admin/AdminVehicleDisputesController.php new file mode 100644 index 0000000..67bcdcc --- /dev/null +++ b/app/Plugins/VehicleDisputes/Controllers/Admin/AdminVehicleDisputesController.php @@ -0,0 +1,165 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleDisputes\Controllers\Admin; + +use Illuminate\Http\Request; +use App\Http\Controllers\Controller; +use JWTAuth; +use Validator; +use Plugins\VehicleDisputes\Model\VehicleDispute; +use Plugins\VehicleRentals\Model\VehicleRental; +use Plugins\VehicleDisputes\Transformers\VehicleDisputeTransformer; +use Plugins\VehicleDisputes\Services\VehicleDisputeService; +use Plugins\VehicleDisputes\Services\VehicleDisputeClosedTypeService; +use DB; +/** + * VehicleDisputes resource representation. + * @Resource("Admin/AdminVehicleDisputess") + */ +class AdminVehicleDisputesController extends Controller +{ + /** + * @var vehicleDisputeService + */ + protected $vehicleDisputeService; + /** + * @var + */ + protected $disputeClosedTypeService; + + /** + * AdminVehicleDisputesController constructor. + */ + public function __construct() + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth'); + // Check the logged user role. + $this->middleware('role'); + $this->setVehicleDisputeService(); + $this->setVehicleDisputeClosedTypeService(); + } + + /** + * Set VehicleDisputeClosedTypeService + */ + public function setVehicleDisputeClosedTypeService() + { + $this->disputeClosedTypeService = new VehicleDisputeClosedTypeService(); + } + + /** + * Set VehicleDisputeService + */ + public function setVehicleDisputeService() + { + $this->vehicleDisputeService = new VehicleDisputeService(); + } + + /** + * Show all VehicleDisputes + * Get a JSON representation of all the VehicleDisputes. + * + * @Get("/vehicle_disputes?sort={sort}&sortby={sortby}&page={page}&q={q}") + * @Parameters({ + * @Parameter("sort", type="string", required=false, description="Sort the disputes list by sort key.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort disputes by Ascending / Descending Order.", default=null), + * @Parameter("q", type="string", required=false, description="Search disputes.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1), + * @Parameter("filter", type="string", required=false, description="Filter disputes.", default=null) + * }) + */ + public function index(Request $request) + { + $enabledIncludes = array('user', 'dispute_type', 'dispute_closed_type', 'dispute_status'); + $vehicle_disputes = VehicleDispute::with($enabledIncludes) + ->select(DB::raw('item_user_disputes.*')) + ->leftJoin(DB::raw('(select id,username from users) as user'), 'user.id', '=', 'item_user_disputes.user_id') + ->leftJoin(DB::raw('(select id,name from dispute_types) as dispute_type'), 'dispute_type.id', '=', 'item_user_disputes.dispute_type_id') + ->leftJoin(DB::raw('(select id,name from dispute_statuses) as dispute_status'), 'dispute_status.id', '=', 'item_user_disputes.dispute_status_id') + ->leftJoin(DB::raw('(select id from item_users) as item_user_disputable'), 'item_user_disputable.id', '=', 'item_user_disputes.item_user_disputable_id') + ->leftJoin(DB::raw('(select id, name from vehicles) as item_userable'), 'item_userable.id', '=', 'item_user_disputable.id') + ->leftJoin(DB::raw('(select id, name from item_user_statuses) as item_user_status'), 'item_user_status.id', '=', 'item_userable.id') + ->filterByVehicleRental()->filterByRequest($request)->paginate(config('constants.ConstPageLimit')); + $enabledIncludes = array_merge($enabledIncludes, array('item_user_disputable')); + return $this->response->paginator($vehicle_disputes, (new VehicleDisputeTransformer)->setDefaultIncludes($enabledIncludes)); + } + + /** + * Store a new dispute. + * Store a new dispute with a `item_user_id`, 'dispute_closed_type_id', 'discount', 'discount_type', 'no_of_quantity', 'validity_start_date', 'validity_end_date', 'maximum_discount_amount'. + * @Post("/vehicle_disputes") + * @Transaction({ + * @Request({"item_id":1, "dispute_closed_type_id": 1}), + * @Response(200, body={"success": "VehicleDispute has been resolved."}), + * @Response(422, body={"message": "VehicleDispute could not be resolved. Please, try again.", "errors": {"name": {}}, "status_code": 422}) + * }) + */ + public function resolve(Request $request) + { + $user = $this->auth->user(); + $vehicle_dispute_data = $request->only('item_user_id', 'dispute_closed_type_id'); + // checking conditions + $enabledIncludes = array('user'); + // check if plugin enabled and include + (isPluginEnabled('VehicleFeedbacks')) ? $enabledIncludes[] = 'vehicle_feedback' : ''; + $vehicle_rental = VehicleRental::with($enabledIncludes)->where('id', '=', $request->item_user_id) + ->where('is_dispute', '=', 1)->first(); + if (!$vehicle_rental) { + return $this->response->errorNotFound("Invalid Request"); + } + $booker_id = $vehicle_rental->user_id; + if ($vehicle_rental->item_user_dispute->dispute_status_id === config('constants.ConstDisputeStatuses.Closed')) { + return $this->response->errorNotFound("Invalid Request"); + } + ($user->id === $booker_id) ? $vehicle_dispute_data['is_booker'] = 1 : $vehicle_dispute_data['is_booker'] = 0; + $dispute_closed_types = $this->disputeClosedTypeService->getClosedTypeByDisputeType($vehicle_rental->item_user_dispute->dispute_type_id); + $dispute_closed_type_id = (int)$request->dispute_closed_type_id; + if (!in_array($dispute_closed_type_id, $dispute_closed_types)) { + return $this->response->errorNotFound("Invalid Request"); + } + $validator = Validator::make($vehicle_dispute_data, VehicleDispute::GetValidationRule(), VehicleDispute::GetValidationMessage()); + if ($validator->passes() && $vehicle_rental) { + if ($dispute_closed_type_id === config('constants.ConstDisputeClosedTypes.SpecificationFavourBookerRefund') || $request->dispute_closed_type_id === config('constants.ConstDisputeClosedTypes.SpecificationResponseFavourBooker')) { + $is_favour_booker = 1; + $this->vehicleDisputeService->resolveByRefund($vehicle_rental); + } elseif ($dispute_closed_type_id === config('constants.ConstDisputeClosedTypes.FeedbackFavourHost') || $request->dispute_closed_type_id === config('constants.ConstDisputeClosedTypes.FeedbackResponseFavourHost')) { + $is_favour_booker = 0; + if (isPluginEnabled('VehicleFeedbacks') && !empty($vehicle_rental->vehicle_feedback)) { + $vehicleFeedbackService = new \Plugins\VehicleFeedbacks\Services\VehicleFeedbackService(); + $vehicleFeedbackService->feedBackUpdate($request, $vehicle_rental->vehicle_feedback[0]->id, $vehicle_rental); + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('VehicleDispute could not be resolved. Please, try again.'); + } + } elseif ($dispute_closed_type_id === config('constants.ConstDisputeClosedTypes.FeedbackFavourBooker')) { + $is_favour_booker = 1; + } elseif ($dispute_closed_type_id === config('constants.ConstDisputeClosedTypes.SpecificationFavourHost')) { + $is_favour_booker = 0; + } elseif ($dispute_closed_type_id === config('constants.ConstDisputeClosedTypes.SecurityFavourBooker')) { + $is_favour_booker = 1; + $this->vehicleDisputeService->resolveByDepositAmountRefund($vehicle_rental, $dispute_closed_type_id); + } elseif ($dispute_closed_type_id === config('constants.ConstDisputeClosedTypes.SecurityFavourHost') || $dispute_closed_type_id === config('constants.ConstDisputeClosedTypes.SecurityResponseFavourHost')) { + $is_favour_booker = 0; + $this->vehicleDisputeService->resolveByDepositAmountRefund($vehicle_rental, $dispute_closed_type_id); + } + // Closing Dispute // + $this->vehicleDisputeService->closeDispute($request, $vehicle_rental, $is_favour_booker); + return response()->json(['Success' => 'VehicleDispute has been Closed'], 200); + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('VehicleDispute could not be resolved. Please, try again.', $validator->errors()); + } + } +} diff --git a/app/Plugins/VehicleDisputes/Controllers/VehicleDisputeClosedTypesController.php b/app/Plugins/VehicleDisputes/Controllers/VehicleDisputeClosedTypesController.php new file mode 100644 index 0000000..30d1434 --- /dev/null +++ b/app/Plugins/VehicleDisputes/Controllers/VehicleDisputeClosedTypesController.php @@ -0,0 +1,55 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleDisputes\Controllers; + +use Illuminate\Http\Request; +use App\Http\Controllers\Controller; +use JWTAuth; +use Plugins\VehicleDisputes\Model\VehicleDisputeClosedType; +use Plugins\VehicleDisputes\Transformers\VehicleDisputeClosedTypeTransformer; + +/** + * Class VehicleDisputeClosedTypesController + * @package Plugins\VehicleDisputes\Controllers\Admin + */ +class VehicleDisputeClosedTypesController extends Controller +{ + /** + * VehicleDisputeClosedTypesController constructor. + */ + public function __construct() + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth'); + } + + /** + * Show all VehicleDisputeClosedTypes + * Get a JSON representation of all the VehicleDisputeClosedTypes. + * + * @Get("/vehicle_dispute_closed_types?sort={sort}&sortby={sortby}&page={page}") + * @Parameters({ + * @Parameter("sort", type="string", required=false, description="Sort the disputes list by sort key.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort disputes by Ascending / Descending Order.", default=null) + * }) + */ + public function index(Request $request) + { + $vehicle_dispute_closed_types = VehicleDisputeClosedType::with('dispute_type')->filterByRequest($request)->paginate(config('constants.ConstPageLimit')); + return $this->response->paginator($vehicle_dispute_closed_types, (new VehicleDisputeClosedTypeTransformer)->setDefaultIncludes('dispute_type')); + } + +} diff --git a/app/Plugins/VehicleDisputes/Controllers/VehicleDisputeTypesController.php b/app/Plugins/VehicleDisputes/Controllers/VehicleDisputeTypesController.php new file mode 100644 index 0000000..908b5be --- /dev/null +++ b/app/Plugins/VehicleDisputes/Controllers/VehicleDisputeTypesController.php @@ -0,0 +1,56 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleDisputes\Controllers; + +use Illuminate\Http\Request; + +use App\Http\Controllers\Controller; +use JWTAuth; +use Validator; +use Plugins\VehicleDisputes\Model\VehicleDisputeType; +use Plugins\VehicleDisputes\Transformers\VehicleDisputeTypeTransformer; + +/** + * Class VehicleDisputeTypesController + * @package Plugins\VehicleDisputes\Controllers + */ +class VehicleDisputeTypesController extends Controller +{ + /** + * VehicleDisputeTypesController constructor. + */ + public function __construct() + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth'); + } + + /** + * Show all VehicleDisputeTypes + * Get a JSON representation of all the VehicleDisputeTypes. + * + * @Get("/vehicle_dispute_types?sort={sort}&sortby={sortby}&page={page}&q={q}") + * @Parameters({ + * @Parameter("sort", type="string", required=false, description="Sort the disputes list by sort key.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort disputes by Ascending / Descending Order.", default=null) + * }) + */ + public function index(Request $request) + { + $vehicle_dispute_types = VehicleDisputeType::filterByRequest($request)->paginate(config('constants.ConstPageLimit')); + return $this->response->paginator($vehicle_dispute_types, (new VehicleDisputeTypeTransformer)); + } +} diff --git a/app/Plugins/VehicleDisputes/Controllers/VehicleDisputesController.php b/app/Plugins/VehicleDisputes/Controllers/VehicleDisputesController.php new file mode 100644 index 0000000..8e98b60 --- /dev/null +++ b/app/Plugins/VehicleDisputes/Controllers/VehicleDisputesController.php @@ -0,0 +1,227 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleDisputes\Controllers; + +use Illuminate\Http\Request; + +use App\Http\Controllers\Controller; +use JWTAuth; +use Validator; +use Plugins\VehicleDisputes\Model\VehicleDispute; +use Plugins\VehicleRentals\Model\VehicleRental; +use Plugins\VehicleDisputes\Model\VehicleDisputeType; +use Plugins\VehicleDisputes\Model\VehicleDisputeClosedType; +use Plugins\VehicleDisputes\Transformers\VehicleDisputeTransformer; +use Plugins\VehicleDisputes\Services\VehicleDisputeService; +use Plugins\VehicleRentals\Services\VehicleRentalService; + +/** + * VehicleDisputes resource representation. + * @Resource("disputes") + */ +class VehicleDisputesController extends Controller +{ + /** + * @var vehicleDisputeService + */ + protected $vehicleDisputeService; + /** + * @var VehicleRentalService + */ + protected $vehicleRentalService; + + /** + * VehicleDisputesController constructor. + */ + public function __construct() + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth'); + $this->setVehicleDisputeService(); + $this->setVehicleRentalService(); + } + + /** + * Set VehicleRentalService + */ + public function setVehicleRentalService() + { + $this->vehicleRentalService = new VehicleRentalService(); + } + + /** + * Set VehicleDisputeService + */ + public function setVehicleDisputeService() + { + $this->vehicleDisputeService = new VehicleDisputeService(); + } + + /** + * Show all VehicleDisputes + * Get a JSON representation of all the VehicleDisputes. + * + * @Get("/vehicle_disputes?sort={sort}&sortby={sortby}&page={page}&q={q}") + * @Parameters({ + * @Parameter("sort", type="string", required=false, description="Sort the disputes list by sort key.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort disputes by Ascending / Descending Order.", default=null), + * @Parameter("q", type="string", required=false, description="Search disputes.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1), + * @Parameter("filter", type="string", required=false, description="Filter disputes.", default=null) + * }) + */ + public function index(Request $request) + { + $enabledIncludes = array('user', 'dispute_type', 'dispute_closed_type', 'dispute_status'); + $vehicle_disputes = VehicleDispute::with($enabledIncludes)->filterByVehicleRental()->filterByRequest($request)->paginate(config('constants.ConstPageLimit')); + $enabledIncludes = array_merge($enabledIncludes, array('item_user_disputable')); + return $this->response->paginator($vehicle_disputes, (new VehicleDisputeTransformer)->setDefaultIncludes($enabledIncludes)); + } + + /** + * Store a new dispute. + * Store a new dispute with a `item_user_id`, 'dispute_type_id', 'reason'. + * @Post("/vehicle_disputes") + * @Transaction({ + * @Request({"item_user_id":1, "dispute_type_id":1, "reason": "Not matching the specification"}), + * @Response(200, body={"success": "VehicleDispute has been added."}), + * @Response(422, body={"message": "VehicleDispute could not be updated. Please, try again.", "errors": {"name": {}}, "status_code": 422}) + * }) + */ + public function store(Request $request) + { + $user = $this->auth->user(); + $vehicle_dispute_data = $request->only('item_user_id', 'dispute_type_id', 'reason'); + // checking conditions + $vehicle_rental = VehicleRental::with('user')->where('id', '=', $request->item_user_id) + ->where('is_dispute', '=', 0) + ->whereIn('item_user_status_id', [config('constants.ConstItemUserStatus.WaitingForReview'), config('constants.ConstItemUserStatus.BookerReviewed')])->first(); + if (!$vehicle_rental || is_null($vehicle_rental->item_userable)) { + return $this->response->errorNotFound("Invalid Request"); + } + $booker_id = (int)$vehicle_rental->user_id; + $host_id = (int)$vehicle_rental->item_userable->user_id; + if ($user->role_id != config('constants.ConstUserTypes.Admin') && $booker_id != $user->id && $host_id != $user->id) { + return $this->response->errorNotFound("Invalid Request"); + } + if($booker_id == $user->id && ($vehicle_rental->item_user_status_id != config('constants.ConstItemUserStatus.WaitingForReview') || $request->dispute_type_id == config('constants.ConstDisputeTypes.Feedback') || $request->dispute_type_id == config('constants.ConstDisputeTypes.Security'))) { + return $this->response->errorNotFound("Invalid Request"); + } + if($host_id == $user->id && ($request->dispute_type_id == config('constants.ConstDisputeTypes.Specification') || ($request->dispute_type_id == config('constants.ConstDisputeTypes.Feedback') && $vehicle_rental->item_user_status_id == config('constants.ConstItemUserStatus.WaitingForReview')))) { + return $this->response->errorNotFound("Invalid Request"); + } + ($user->id === $booker_id) ? $vehicle_dispute_data['is_booker'] = 1 : $vehicle_dispute_data['is_booker'] = 0; + $validator = Validator::make($vehicle_dispute_data, VehicleDispute::GetValidationRule(), VehicleDispute::GetValidationMessage()); + if ($validator->passes() && $vehicle_rental) { + $vehicle_dispute_data['model_type'] = config('constants.ConstBookingTypes.Booking'); + $vehicle_dispute_data['dispute_status_id'] = config('constants.ConstDisputeStatuses.Open'); + $vehicle_dispute_data['dispute_conversation_count'] = 1; + $vehicle_dispute_data['last_replied_user_id'] = $user->id; + $vehicle_dispute_data['last_replied_date'] = date('Y-m-d h:i:s'); + $vehicle_dispute_data['user_id'] = $user->id; + $vehicle_dispute = VehicleDispute::create($vehicle_dispute_data); + if ($vehicle_dispute) { + $item_user = VehicleRental::with(['item_user_dispute'])->where('id', '=', $request->item_user_id)->first(); + $item_user->item_user_dispute()->save($vehicle_dispute); + // update dispute in item_users + $this->vehicleRentalService->updateDispute($request->item_user_id); + // send mail + $this->vehicleDisputeService->sendDisputeOpenMail($vehicle_dispute, $vehicle_rental); + return response()->json(['Success' => 'Vehicle Dispute has been added'], 200); + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Vehicle Dispute could not be sent. Please, try again.'); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Vehicle Dispute could not be sent. Please, try again.', $validator->errors()); + } + } + + /** + * @param $vehicle_rental_id + * @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response|void + */ + public function getPossibleDisputeTypes($vehicle_rental_id) + { + $user = $this->auth->user(); + if (isPluginEnabled('VehicleRentals')) { + $enabledIncludes = array('user', 'item_user_status', 'message'); + // check if plugin enabled and include + (isPluginEnabled('VehicleFeedbacks')) ? $enabledIncludes[] = 'vehicle_feedback' : ''; + $vehicle_rental = \Plugins\VehicleRentals\Model\VehicleRental::with($enabledIncludes) + ->where('id', '=', $vehicle_rental_id) + ->whereIn('item_user_status_id', array(config('constants.ConstItemUserStatus.WaitingForReview'), config('constants.ConstItemUserStatus.BookerReviewed')))->first(); + if (!($vehicle_rental)) { + return $this->response->errorNotFound("Invalid Request"); + } + $booker_id = (int)$vehicle_rental->user_id; + $host_id = (int)$vehicle_rental->item_userable->user_id; + if ($user->role_id == config('constants.ConstUserTypes.Admin') && $booker_id != $user->id && $host_id != $user->id && $vehicle_rental->is_dispute) { + $dispute = VehicleDispute::with('dispute_type', 'dispute_status', 'user', 'item_user_disputable') + ->where('item_user_disputable_id', '=', $vehicle_rental_id) + ->where('dispute_type_id', '!=', config('constants.ConstDisputeStatuses.Closed'))->first(); + $dispute_closed_types = VehicleDisputeClosedType::with('dispute_type') + ->where('dispute_type_id', '=', $dispute->dispute_type_id)->get(); + $dispute_array['dispute'] = $dispute; + $dispute_array['dispute_close_types'] = $dispute_closed_types; + $dispute_array['feedback'] = $vehicle_rental->vehicle_feedback; + $now = time(); // or your date as well + $dispute_date = strtotime($dispute->created_at); + $datediff = $now - $dispute_date; + $dispute_array['diff_days'] = floor($datediff / (60 * 60 * 24)); + return response()->json(['dispute_array' => $dispute_array], 200); + } else { + if ($vehicle_rental->is_dispute) { + return response()->json(['is_under_dispute' => true], 200); + } + + ($user->id === $booker_id) ? $is_booker = 1 : $is_booker = 0; + // all disputes for this user type + $all_vehicle_dispute_types = VehicleDisputeType::where('is_booker', '=', $is_booker)->where('is_active', '=', 1)->get(); + $disputeTypes = false; + foreach ($all_vehicle_dispute_types as $key => $dispute_type_det) { + if ((int)$vehicle_rental->item_user_status_id === config('constants.ConstItemUserStatus.WaitingForReview')) { + // property doesn't match host requirements (booker) + if ($booker_id === $user->id && $dispute_type_det && $dispute_type_det->id === config('constants.ConstDisputeTypes.Specification')) { + $disputeTypes[] = $dispute_type_det; + } + // Claim the security damage (host) + if ($host_id === $user->id && $dispute_type_det && $dispute_type_det->id === config('constants.ConstDisputeTypes.Security')) { + $disputeTypes[] = $dispute_type_det; + } + } else if ((int)$vehicle_rental->item_user_status_id === config('constants.ConstItemUserStatus.BookerReviewed') && $host_id === $user->id && $vehicle_rental->vehicle_feedback && $vehicle_rental->vehicle_feedback[0]->rating < config('dispute.rating_limit_to_raise_dispute')) { + // Poor Feedback dispute (host) + if ($dispute_type_det && $dispute_type_det->id === config('constants.ConstDisputeTypes.Feedback')) { + $disputeTypes[] = $dispute_type_det; + } + // Claim the security damage (host) + if ($dispute_type_det && $dispute_type_det->id === config('constants.ConstDisputeTypes.Security')) { + $disputeTypes[] = $dispute_type_det; + } + } + } + if ($disputeTypes) { + return response()->json(['dispute_types' => $disputeTypes], 200); + } else if ($all_vehicle_dispute_types) { + return response()->json(['all_dispute_types' => $all_vehicle_dispute_types], 200); + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('VehicleDispute could not be raised.'); + } + } + } else { + return $this->response->errorNotFound("Invalid Request"); + } + } +} diff --git a/app/Plugins/VehicleDisputes/Model/VehicleDispute.php b/app/Plugins/VehicleDisputes/Model/VehicleDispute.php new file mode 100644 index 0000000..bbe683d --- /dev/null +++ b/app/Plugins/VehicleDisputes/Model/VehicleDispute.php @@ -0,0 +1,161 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleDisputes\Model; + +use Illuminate\Http\Request; +use Illuminate\Database\Eloquent\Model; + +use JWTAuth; +use Illuminate\Support\Facades\Auth; + +/** + * Class VehicleDispute + * @package App + */ +class VehicleDispute extends Model +{ + /** + * @var string + */ + protected $table = "item_user_disputes"; + /** + * The attributes that are mass assignable. + * @var array + */ + protected $fillable = [ + 'user_id', 'item_user_disputable_id', 'item_user_disputable_type', 'dispute_type_id', 'dispute_status_id', 'last_replied_user_id', 'dispute_closed_type_id', 'is_favor_booker', 'is_booker', 'last_replied_date', 'resolved_date', 'dispute_conversation_count', 'reason', 'model_type' + ]; + + /** + * Get all of the owning likeable models. + */ + public function item_user_disputable() + { + return $this->morphTo(); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function user() + { + return $this->belongsTo(\App\User::class); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function dispute_type() + { + return $this->belongsTo(\Plugins\VehicleDisputes\Model\VehicleDisputeType::class); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function dispute_status() + { + return $this->belongsTo(\Plugins\VehicleDisputes\Model\VehicleDisputeStatus::class); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function dispute_closed_type() + { + return $this->belongsTo(\Plugins\VehicleDisputes\Model\VehicleDisputeClosedType::class); + } + + /** + * @param $query + * @param Request $request + * @return mixed + */ + public function scopeFilterByRequest($query, Request $request) + { + $query->orderBy($request->input('sort', 'id'), $request->input('sortby', 'desc')); + if ($request->has('q')) { + $query->where('reason', 'like', '%' . $request->input('q') . '%'); + $query->orWhereHas('user', function ($q) use ($request) { + $q->where('username', 'like', '%' . $request->input('q') . '%'); + }); + $query->orWhereHas('dispute_type', function ($q) use ($request) { + $q->where('name', 'like', '%' . $request->input('q') . '%'); + }); + $query->orWhereHas('dispute_status', function ($q) use ($request) { + $q->where('name', 'like', '%' . $request->input('q') . '%'); + }); + } + if ($request->input('filter') === 'Open') { + $query->where('dispute_status_id', '=', config('constants.ConstDisputeStatuses.Open')); + } else if ($request->input('filter') === 'Under Discussion') { + $query->where('dispute_status_id', '=', config('constants.ConstDisputeStatuses.UnderDiscussion')); + } else if ($request->input('filter') === 'Waiting Administrator Decision') { + $query->where('dispute_status_id', '=', config('constants.ConstDisputeStatuses.WaitingAdministratorDecision')); + } else if ($request->input('filter') === 'Closed') { + $query->where('dispute_status_id', '=', config('constants.ConstDisputeStatuses.Closed')); + } + + // if not admin user can view their own disputes only + $user = Auth::user(); + if ($user->role_id != config('constants.ConstUserTypes.Admin')) { + $query->where('user_id', $user->id); + } + + //$query->where('item_user_disputable_type', 'MorphVehicleRental'); + + return $query; + } + + /** + * @param $query + * @return mixed + */ + + public function scopeFilterByVehicleRental($query) + { + $query->where('model_type', config('constants.ConstBookingTypes.Booking')); + return $query; + } + + /** + * @return array + */ + public function scopeGetValidationRule() + { + return [ + 'item_user_id' => 'required|integer', + 'dispute_type_id' => 'sometimes|required|integer', + 'dispute_closed_type_id' => 'sometimes|required|integer' + ]; + } + + /** + * @return array + */ + public function scopeGetValidationMessage() + { + return [ + 'item_user_id.required' => 'Required', + 'item_user_id.integer' => 'Item id must be a number!', + 'dispute_type_id.required' => 'Required', + 'dispute_type_id.integer' => 'Dispute Type Id must be a number!', + 'dispute_closed_type_id.required' => 'Required', + 'dispute_closed_type_id.integer' => 'Dispute Type Id must be a number!' + ]; + } + +} diff --git a/app/Plugins/VehicleDisputes/Model/VehicleDisputeClosedType.php b/app/Plugins/VehicleDisputes/Model/VehicleDisputeClosedType.php new file mode 100644 index 0000000..795d247 --- /dev/null +++ b/app/Plugins/VehicleDisputes/Model/VehicleDisputeClosedType.php @@ -0,0 +1,104 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleDisputes\Model; + +use Illuminate\Http\Request; +use Illuminate\Database\Eloquent\Model; + +class VehicleDisputeClosedType extends Model +{ + /** + * @var string + */ + protected $table = "dispute_closed_types"; + /** + * The attributes that are mass assignable. + * @var array + */ + protected $fillable = [ + 'name', 'dispute_type_id', 'is_booker', 'resolved_type', 'reason' + ]; + + /** + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function dispute_type() + { + return $this->belongsTo(\Plugins\VehicleDisputes\Model\VehicleDisputeType::class); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\HasMany + */ + public function dispute() + { + return $this->hasMany(\Plugins\VehicleDisputes\Model\VehicleDispute::class); + } + + /** + * @param $query + * @param Request $request + * @return mixed + */ + public function scopeFilterByRequest($query, Request $request) + { + $query->orderBy($request->input('sort', 'id'), $request->input('sortby', 'desc')); + if($request->has('q')){ + $query->where('dispute_closed_types.name', 'like', '%'.$request->q.'%'); + $query->orWhere('dispute_closed_types.resolved_type', 'like', '%'.$request->q.'%'); + $query->orWhere('dispute_closed_types.reason', 'like', '%'.$request->q.'%'); + } + if ($request->input('filter') === 'booker') { + $query->where('is_booker', '=', 1); + } else if ($request->input('filter') === 'host') { + $query->where('is_booker', '=', 0); + } + return $query; + } + + /** + * @return array + */ + public function scopeGetValidationRule() + { + return [ + 'name' => 'required|min:5', + 'dispute_type_id' => 'required|integer', + 'is_booker' => 'required|boolean', + 'resolved_type' => 'required|min:5', + 'reason' => 'required|min:5' + ]; + } + + /** + * @return array + */ + public function scopeGetValidationMessage() + { + return [ + 'name.required' => 'Required', + 'name.min' => 'Name must be min 5 characters!', + 'dispute_type_id.required' => 'Required', + 'dispute_type_id.integer' => 'Enter only number values for dispute type id !', + 'is_booker.required' => 'Required', + 'is_booker.boolean' => 'Accepted input for Is Booker are 1, 0 !', + 'resolved_type.required' => 'Required', + 'resolved_type.min' => 'Name must be min 5 characters!', + 'reason.required' => 'Required', + 'reason.min' => 'Name must be min 5 characters!' + ]; + } +} diff --git a/app/Plugins/VehicleDisputes/Model/VehicleDisputeStatus.php b/app/Plugins/VehicleDisputes/Model/VehicleDisputeStatus.php new file mode 100644 index 0000000..ef19bed --- /dev/null +++ b/app/Plugins/VehicleDisputes/Model/VehicleDisputeStatus.php @@ -0,0 +1,44 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleDisputes\Model; + +use Illuminate\Http\Request; +use Illuminate\Database\Eloquent\Model; + +class VehicleDisputeStatus extends Model +{ + /** + * @var string + */ + protected $table = "dispute_statuses"; + + /** + * @return \Illuminate\Database\Eloquent\Relations\HasMany + */ + public function item_user_dispute() + { + return $this->hasMany(VehicleDispute::class); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\HasMany + */ + public function message() + { + return $this->hasMany(\App\Message::class); + } + +} diff --git a/app/Plugins/VehicleDisputes/Model/VehicleDisputeType.php b/app/Plugins/VehicleDisputes/Model/VehicleDisputeType.php new file mode 100644 index 0000000..2a6612b --- /dev/null +++ b/app/Plugins/VehicleDisputes/Model/VehicleDisputeType.php @@ -0,0 +1,97 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleDisputes\Model; + +use Illuminate\Http\Request; +use Illuminate\Database\Eloquent\Model; + +class VehicleDisputeType extends Model +{ + /** + * @var string + */ + protected $table = "dispute_types"; + + /** + * The attributes that are mass assignable. + * @var array + */ + protected $fillable = [ + 'name', 'is_booker', 'is_active' + ]; + /** + * @return \Illuminate\Database\Eloquent\Relations\HasMany + */ + public function vehicle_dispute() + { + return $this->hasMany(\Plugins\VehicleDisputes\Model\VehicleDispute::class); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\HasMany + */ + public function vehicle_dispute_closed_type() + { + return $this->hasMany(\Plugins\VehicleDisputes\Model\VehicleDisputeClosedType::class); + } + + /** + * @param $query + * @param Request $request + * @return mixed + */ + public function scopeFilterByRequest($query, Request $request) + { + $query->orderBy($request->input('sort', 'id'), $request->input('sortby', 'desc')); + if ($request->input('filter') === 'active') { + $query->where('is_active', '=', 1); + } else if ($request->input('filter') === 'inactive') { + $query->where('is_active', '=', 0); + } + if($request->has('q')){ + $query->where('name', 'like', '%'.$request->q.'%'); + } + return $query; + } + + /** + * @return array + */ + public function scopeGetValidationRule() + { + return [ + 'name' => 'required|min:5', + 'is_booker' => 'required|boolean', + 'is_active' => 'required|boolean' + ]; + } + + /** + * @return array + */ + public function scopeGetValidationMessage() + { + return [ + 'name.required' => 'Required', + 'name.min' => 'Name must be min 5 characters!', + 'is_booker.required' => 'Required', + 'is_booker.boolean' => 'Accepted input for Is Booker are 1, 0 !', + 'is_active.required' => 'Required', + 'is_active.boolean' => 'Accepted input for Is Activer are 1, 0 !', + ]; + } + +} diff --git a/app/Plugins/VehicleDisputes/Providers/VehicleDisputeServiceProvider.php b/app/Plugins/VehicleDisputes/Providers/VehicleDisputeServiceProvider.php new file mode 100644 index 0000000..4e3a100 --- /dev/null +++ b/app/Plugins/VehicleDisputes/Providers/VehicleDisputeServiceProvider.php @@ -0,0 +1,50 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleDisputes\Providers; + +use Illuminate\Support\ServiceProvider; +use Illuminate\Database\Eloquent\Relations\Relation; + +class VehicleDisputeServiceProvider extends ServiceProvider +{ + /** + * Register any application services. + * + * @return void + */ + public function register() + { + include __DIR__ . '/../routes.php'; + $this->app->make('Plugins\VehicleDisputes\Controllers\Admin\AdminVehicleDisputesController'); + $this->app->make('Plugins\VehicleDisputes\Controllers\Admin\AdminVehicleDisputeTypesController'); + $this->app->make('Plugins\VehicleDisputes\Controllers\Admin\AdminVehicleDisputeClosedTypesController'); + $this->app->make('Plugins\VehicleDisputes\Controllers\VehicleDisputesController'); + $this->app->make('Plugins\VehicleDisputes\Controllers\VehicleDisputeTypesController'); + $this->app->make('Plugins\VehicleDisputes\Controllers\VehicleDisputeClosedTypesController'); + } + + /** + * Bootstrap the application services. + * + * @return void + */ + public function boot() + { + Relation::morphMap([ + 'MorphVehicleRental' => \Plugins\VehicleRentals\Model\VehicleRental::class + ]); + } +} diff --git a/app/Plugins/VehicleDisputes/Services/VehicleDisputeClosedTypeService.php b/app/Plugins/VehicleDisputes/Services/VehicleDisputeClosedTypeService.php new file mode 100644 index 0000000..97c5f71 --- /dev/null +++ b/app/Plugins/VehicleDisputes/Services/VehicleDisputeClosedTypeService.php @@ -0,0 +1,59 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleDisputes\Services; + +use Plugins\VehicleDisputes\Model\VehicleDisputeClosedType; + +class VehicleDisputeClosedTypeService +{ + + + /** + * VehicleDisputeService constructor. + */ + public function __construct() + { + + } + + /** + * @param $close_type_id + * @return string + */ + public function getDisputeClosedType($close_type_id) + { + $dispute_close_type = VehicleDisputeClosedType::where('id', '=', $close_type_id)->first(); + if (!empty($dispute_close_type)) { + return $dispute_close_type; + } else { + return ''; + } + } + + /** + * @param $dispute_type_id + * @return string + */ + public function getClosedTypeByDisputeType($dispute_type_id) + { + $dispute_close_type = VehicleDisputeClosedType::where('dispute_type_id', '=', $dispute_type_id)->pluck('id')->all(); + if (!empty($dispute_close_type)) { + return $dispute_close_type; + } else { + return ''; + } + } +} diff --git a/app/Plugins/VehicleDisputes/Services/VehicleDisputeService.php b/app/Plugins/VehicleDisputes/Services/VehicleDisputeService.php new file mode 100644 index 0000000..7891928 --- /dev/null +++ b/app/Plugins/VehicleDisputes/Services/VehicleDisputeService.php @@ -0,0 +1,496 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleDisputes\Services; + +use App\Services\MailService; +use Carbon; +use App\Services\TransactionService; +use App\Services\MessageService; +use Plugins\VehicleDisputes\Model\VehicleDispute; +use Plugins\VehicleRentals\Services\VehicleRentalService; +use Illuminate\Support\Facades\Auth; + +class VehicleDisputeService +{ + /** + * @var + */ + protected $mailService; + /** + * @var + */ + protected $messageService; + /** + * @var + */ + protected $walletService; + /** + * @var + */ + protected $transactionService; + /** + * @var + */ + protected $vehicleRentalService; + /** + * @var + */ + protected $disputeClosedTypeService; + /** + * @var + */ + protected $reply_link; + + /** + * VehicleDisputeService constructor. + */ + public function __construct() + { + $this->setMailService(); + $this->setMessageService(); + $this->setTransactionService(); + $this->setWalletService(); + $this->setVehicleRentalService(); + $this->setVehicleDisputeClosedTypeService(); + } + + /** + * Set MailService + */ + public function setMailService() + { + $this->mailService = new MailService(); + } + + /** + * Set setTransactionService + */ + public function setTransactionService() + { + $this->transactionService = new TransactionService(); + } + + /** + * Set MessageService + */ + public function setMessageService() + { + $this->messageService = new MessageService(); + } + + /** + * Set WalletService + */ + public function setWalletService() + { + $this->walletService = new \App\Services\WalletService(); + } + + /** + * Set VehicleRentalService + */ + public function setVehicleRentalService() + { + $this->vehicleRentalService = new VehicleRentalService(); + } + + /** + * Set VehicleDisputeClosedTypeService + */ + public function setVehicleDisputeClosedTypeService() + { + $this->disputeClosedTypeService = new VehicleDisputeClosedTypeService(); + } + + + /** + * @param $vehicle_dispute + * @param $vehicle_rental + */ + public function sendDisputeOpenMail($vehicle_dispute, $vehicle_rental) + { + $template = $this->mailService->getTemplate('Dispute Open Notification'); + $item_link = '' . $vehicle_rental->item_userable->name . ''; + $order_link = '' . $vehicle_rental->id . ''; + $site_link = '' . url('/') . ''; + $booker_link = '' . $vehicle_rental->user->username . ''; + $host_link = '' . $vehicle_rental->item_userable->user->username . ''; + $to_user_booker_id = $vehicle_rental->user_id; + $to_user_host_id = $vehicle_rental->item_userable->user_id; + $common_emailFindReplace = array( + '##ITEM_NAME##' => $item_link, + '##ORDERNO##' => $order_link, + '##MESSAGE##' => $vehicle_dispute->reason, + '##REPLY_DAYS##' => config('dispute.days_left_for_disputed_user_to_reply') . ' days' + ); + $reply_link = 'REPLY'; + if ($vehicle_dispute->is_booker === 0) { + $emailFindReplace = array( + '##OTHER_USER##' => $host_link, + '##USER_TYPE##' => 'Host (' . $vehicle_rental->item_userable->user->username . ')', + '##USER_TYPE_URL##' => 'Host (' . $host_link . ')', + '##REPLY_LINK##' => $reply_link, + ); + $to_username = $vehicle_rental->user->id; + $to_email = $vehicle_rental->user->email; + $from_user_id = $vehicle_rental->item_userable->user->id; + } elseif ($vehicle_dispute->is_booker === 1) { + $emailFindReplace = array( + '##OTHER_USER##' => $booker_link, + '##USER_TYPE##' => 'Booker (' . $vehicle_rental->user->username . ')', + '##USER_TYPE_URL##' => 'Booker (' . $booker_link . ')', + '##REPLY_LINK##' => $reply_link, + ); + $to_username = $vehicle_rental->item_userable->user->username; + $to_email = $vehicle_rental->item_userable->user->email; + $from_user_id = $vehicle_rental->user->id; + } + $emailFindReplace = array_merge($common_emailFindReplace, $emailFindReplace); + $this->mailService->sendMail($template, $emailFindReplace, $to_email, $to_username); + + //Save internal message + $default_content = array( + '##SITE_NAME##' => config('site.name'), + '##SITE_URL##' => $site_link, + '##FROM_EMAIL##' => config('site.from_email'), + '##CONTACT_MAIL##' => config('site.contact_email') + ); + $message_content_arr_booker = array(); + $message_content_arr_host = array(); + $vehicle_rental_mail_template_booker = array_merge($emailFindReplace, $default_content); + $username_replace = array( + '##USERNAME##' => $vehicle_rental->user->username + ); + $message_content_arr_booker = array_merge($vehicle_rental_mail_template_booker, $username_replace); + $message_content_arr_booker['message'] = strtr($template['body_content'], $message_content_arr_booker); + $message_content_arr_booker['subject'] = strtr($template['subject'], $message_content_arr_booker); + $this->messageService->saveMessageContent($message_content_arr_booker, $vehicle_rental->item_userable->id, $vehicle_rental->id, config('constants.ConstUserIds.Admin'), $to_user_booker_id, $vehicle_rental->item_user_status_id, 'VehicleRental', config('constants.ConstDisputeStatuses.Open')); + $vehicle_rental_mail_template_host = array_merge($emailFindReplace, $default_content); + $username_replace = array( + '##USERNAME##' => $vehicle_rental->item_userable->user->username + ); + $message_content_arr_host = array_merge($vehicle_rental_mail_template_host, $username_replace); + $message_content_arr_host['message'] = strtr($template['body_content'], $message_content_arr_host); + $message_content_arr_host['subject'] = strtr($template['subject'], $message_content_arr_host); + $this->messageService->saveMessageContent($message_content_arr_host, $vehicle_rental->item_userable->id, $vehicle_rental->id, config('constants.ConstUserIds.Admin'), $to_user_host_id, $vehicle_rental->item_user_status_id, 'VehicleRental', config('constants.ConstDisputeStatuses.Open')); + } + + /** + * @param $vehicle_rental + * @param $message + * @param $is_booker + * @param $user_name + */ + public function disputeConversationMail($vehicle_rental, $message, $is_booker, $user_name) + { + $template = $this->mailService->getTemplate('Dispute Conversation Notification'); + $site_link = '' . url('/') . ''; + $emailFindReplace = array( + '##OTHER_USER##' => $user_name, + '##MESSAGE##' => $message + ); + $to_email = ($is_booker) ? $vehicle_rental->user->email : $vehicle_rental->item_userable->user->email; + $to_username = ($is_booker) ? $vehicle_rental->user->username : $vehicle_rental->item_userable->user->username; + $this->mailService->sendMail($template, $emailFindReplace, $to_email, $to_username); + + $to_user_id = ($is_booker) ? $vehicle_rental->user->id : $vehicle_rental->item_userable->user->id; + $from_user_id = ($is_booker) ? $vehicle_rental->item_userable->user->id : $vehicle_rental->user->id; + + //Save internal message + $default_content = array( + '##SITE_NAME##' => config('site.name'), + '##SITE_URL##' => $site_link, + '##FROM_EMAIL##' => config('site.from_email'), + '##CONTACT_MAIL##' => config('site.contact_email') + ); + $vehicle_rental_mail_template = array_merge($emailFindReplace, $default_content); + $message_content_arr = array(); + $message_content_arr['message'] = strtr($template['body_content'], $vehicle_rental_mail_template); + $message_content_arr['subject'] = strtr($template['subject'], $vehicle_rental_mail_template); + $this->messageService->saveMessageContent($message_content_arr, $vehicle_rental->item_userable->id, $vehicle_rental->id, $from_user_id, $to_user_id, $vehicle_rental->item_user_status_id, 'VehicleRental', config('constants.ConstDisputeStatuses.UnderDiscussion')); + } + + /** + * @param $vehicle_rental + * @param $close_type + * @param $is_favor_booker + */ + public function disputeClosedMail($vehicle_rental, $close_type, $is_favor_booker) + { + $template = $this->mailService->getTemplate('Dispute Resolved Notification'); + $item_link = '' . $vehicle_rental->item_userable->name . ''; + $order_link = '' . $vehicle_rental->id . ''; + $site_link = '' . url('/') . ''; + $booker_link = '' . $vehicle_rental->user->username . ''; + $host_link = '' . $vehicle_rental->item_userable->user->username . ''; + $disputer_link = '' . $vehicle_rental->item_user_dispute->user->username . ''; + $common_emailFindReplace = array( + '##ORDER_ID##' => $order_link, + '##DISPUTE_ID##' => $vehicle_rental->item_user_dispute->id, + '##DISPUTER##' => $disputer_link, + '##DISPUTER_USER_TYPE##' => ($vehicle_rental->item_user_dispute->is_booker) ? 'Booker' : 'Host', + '##REASON##' => $vehicle_rental->item_user_dispute->reason, + '##ITEM_NAME##' => $item_link, + ); + $emailFindReplace = array(); + $to_email = ''; + $to_username = ''; + $close_type = (int)$close_type; + if ($close_type === config('constants.ConstDisputeClosedTypes.SpecificationFavourBookerRefund')) { + $emailFindReplace['##FAVOUR_USER##'] = 'Booker (' . $vehicle_rental->user->username . ')'; + $emailFindReplace['##FAVOUR_USER_LINK##'] = 'Booker (' . $booker_link . ')'; + $reason_for_closing = $this->disputeClosedTypeService->getDisputeClosedType(config('constants.ConstDisputeClosedTypes.SpecificationFavourBookerRefund')); + $emailFindReplace['##REASON_FOR_CLOSING##'] = $reason_for_closing->reason; + $emailFindReplace['##RESOLVED_BY##'] = $reason_for_closing->resolved_type; + $to_username = $vehicle_rental->user->username; + $to_email = $vehicle_rental->user->email; + } elseif ($close_type === config('constants.ConstDisputeClosedTypes.SpecificationFavourHost')) { + $emailFindReplace['##FAVOUR_USER##'] = 'Host (' . $vehicle_rental->item_userable->user->username . ')'; + $emailFindReplace['##FAVOUR_USER_LINK##'] = 'Host (' . $host_link . ')'; + $reason_for_closing = $this->disputeClosedTypeService->getDisputeClosedType(config('constants.ConstDisputeClosedTypes.SpecificationFavourHost')); + $emailFindReplace['##REASON_FOR_CLOSING##'] = $reason_for_closing->reason; + $emailFindReplace['##RESOLVED_BY##'] = $reason_for_closing->resolved_type; + $to_username = $vehicle_rental->item_userable->user->username; + $to_email = $vehicle_rental->item_userable->user->email; + } elseif ($close_type === config('constants.ConstDisputeClosedTypes.SpecificationResponseFavourBooker')) { + $emailFindReplace['##FAVOUR_USER##'] = 'Booker (' . $vehicle_rental->user->username . ')'; + $emailFindReplace['##FAVOUR_USER_LINK##'] = 'Booker (' . $booker_link . ')'; + $reason_for_closing = $this->disputeClosedTypeService->getDisputeClosedType(config('constants.ConstDisputeClosedTypes.SpecificationResponseFavourBooker')); + $emailFindReplace['##REASON_FOR_CLOSING##'] = $reason_for_closing->reason; + $emailFindReplace['##RESOLVED_BY##'] = $reason_for_closing->resolved_type; + $to_username = $vehicle_rental->user->username; + $to_email = $vehicle_rental->user->email; + } elseif ($close_type === config('constants.ConstDisputeClosedTypes.FeedbackFavourBooker')) { + $emailFindReplace['##FAVOUR_USER##'] = 'Booker (' . $vehicle_rental->user->username . ')'; + $emailFindReplace['##FAVOUR_USER_LINK##'] = 'Booker (' . $booker_link . ')'; + $reason_for_closing = $this->disputeClosedTypeService->getDisputeClosedType(config('constants.ConstDisputeClosedTypes.FeedbackFavourBooker')); + $emailFindReplace['##REASON_FOR_CLOSING##'] = $reason_for_closing->reason; + $emailFindReplace['##RESOLVED_BY##'] = $reason_for_closing->resolved_type; + $to_username = $vehicle_rental->user->username; + $to_email = $vehicle_rental->user->email; + } elseif ($close_type === config('constants.ConstDisputeClosedTypes.FeedbackFavourHost')) { + $emailFindReplace['##FAVOUR_USER##'] = 'Host (' . $vehicle_rental->item_userable->user->username . ')'; + $emailFindReplace['##FAVOUR_USER_LINK##'] = 'Host (' . $host_link . ')'; + $reason_for_closing = $this->disputeClosedTypeService->getDisputeClosedType(config('constants.ConstDisputeClosedTypes.FeedbackFavourHost')); + $emailFindReplace['##REASON_FOR_CLOSING##'] = $reason_for_closing->reason; + $emailFindReplace['##RESOLVED_BY##'] = $reason_for_closing->resolved_type; + $to_username = $vehicle_rental->item_userable->user->username; + $to_email = $vehicle_rental->item_userable->user->email; + } elseif ($close_type === config('constants.ConstDisputeClosedTypes.FeedbackResponseFavourHost')) { + $emailFindReplace['##FAVOUR_USER##'] = 'Host (' . $vehicle_rental->item_userable->user->username . ')'; + $emailFindReplace['##FAVOUR_USER_LINK##'] = 'Host (' . $host_link . ')'; + $reason_for_closing = $this->disputeClosedTypeService->getDisputeClosedType(config('constants.ConstDisputeClosedTypes.FeedbackResponseFavourHost')); + $emailFindReplace['##REASON_FOR_CLOSING##'] = $reason_for_closing->reason; + $emailFindReplace['##RESOLVED_BY##'] = $reason_for_closing->resolved_type; + $to_username = $vehicle_rental->item_userable->user->username; + $to_email = $vehicle_rental->item_userable->user->email; + } elseif ($close_type === config('constants.ConstDisputeClosedTypes.SecurityFavourBooker')) { + $emailFindReplace['##FAVOUR_USER##'] = 'Booker (' . $vehicle_rental->user->username . ')'; + $emailFindReplace['##FAVOUR_USER_LINK##'] = 'Booker (' . $booker_link . ')'; + $reason_for_closing = $this->disputeClosedTypeService->getDisputeClosedType(config('constants.ConstDisputeClosedTypes.SecurityFavourBooker')); + $emailFindReplace['##REASON_FOR_CLOSING##'] = $reason_for_closing->reason; + $emailFindReplace['##RESOLVED_BY##'] = $reason_for_closing->resolved_type; + $to_username = $vehicle_rental->user->username; + $to_email = $vehicle_rental->user->email; + } elseif ($close_type === config('constants.ConstDisputeClosedTypes.SecurityFavourHost')) { + $emailFindReplace['##FAVOUR_USER##'] = 'Host (' . $vehicle_rental->item_userable->user->username . ')'; + $emailFindReplace['##FAVOUR_USER_LINK##'] = 'Host (' . $host_link . ')'; + $reason_for_closing = $this->disputeClosedTypeService->getDisputeClosedType(config('constants.ConstDisputeClosedTypes.SecurityFavourHost')); + $emailFindReplace['##REASON_FOR_CLOSING##'] = $reason_for_closing->reason; + $emailFindReplace['##RESOLVED_BY##'] = $reason_for_closing->resolved_type; + $to_username = $vehicle_rental->item_userable->user->username; + $to_email = $vehicle_rental->item_userable->user->email; + } elseif ($close_type === config('constants.ConstDisputeClosedTypes.SecurityResponseFavourHost')) { + $emailFindReplace['##FAVOUR_USER##'] = 'Host (' . $vehicle_rental->item_userable->user->username . ')'; + $emailFindReplace['##FAVOUR_USER_LINK##'] = 'Host (' . $host_link . ')'; + $reason_for_closing = $this->disputeClosedTypeService->getDisputeClosedType(config('constants.ConstDisputeClosedTypes.SecurityResponseFavourHost')); + $emailFindReplace['##REASON_FOR_CLOSING##'] = $reason_for_closing->reason; + $emailFindReplace['##RESOLVED_BY##'] = $reason_for_closing->resolved_type; + $to_username = $vehicle_rental->item_userable->user->username; + $to_email = $vehicle_rental->item_userable->user->email; + } + $emailFindReplace = array_merge($common_emailFindReplace, $emailFindReplace); + $this->mailService->sendMail($template, $emailFindReplace, $to_email, $to_username); + + //Save internal message + $default_content = array( + '##SITE_NAME##' => config('site.name'), + '##SITE_URL##' => $site_link, + '##FROM_EMAIL##' => config('site.from_email'), + '##CONTACT_MAIL##' => config('site.contact_email') + ); + $message_content_arr_booker = array(); + $message_content_arr_host = array(); + /// message save to host + $vehicle_rental_mail_template_host = array_merge($emailFindReplace, $default_content); + $username_replace = array( + '##USERNAME##' => $vehicle_rental->item_userable->user->username + ); + $message_content_arr_host = array_merge($vehicle_rental_mail_template_host, $username_replace); + $message_content_arr_host['message'] = strtr($template['body_content'], $message_content_arr_host); + $message_content_arr_host['subject'] = strtr($template['subject'], $message_content_arr_host); + $this->messageService->saveMessageContent($message_content_arr_host, $vehicle_rental->item_userable->id, $vehicle_rental->id, config('constants.ConstUserIds.Admin'), $vehicle_rental->item_userable->user_id, $vehicle_rental->item_user_status_id, 'VehicleRental', config('constants.ConstDisputeStatuses.Closed')); + //message save to booker + $vehicle_rental_mail_template_booker = array_merge($emailFindReplace, $default_content); + $username_replace = array( + '##USERNAME##' => $vehicle_rental->user->username + ); + $message_content_arr_booker = array_merge($vehicle_rental_mail_template_booker, $username_replace); + $message_content_arr_booker['message'] = strtr($template['body_content'], $message_content_arr_booker); + $message_content_arr_booker['subject'] = strtr($template['subject'], $message_content_arr_booker); + $this->messageService->saveMessageContent($message_content_arr_booker, $vehicle_rental->item_userable->id, $vehicle_rental->id, config('constants.ConstUserIds.Admin'), $vehicle_rental->user_id, $vehicle_rental->item_user_status_id, 'VehicleRental', config('constants.ConstDisputeStatuses.Closed')); + + } + + /** + * @param $vehicle_rental + */ + public function resolveByRefund($vehicle_rental) + { + $refund_percentage = config('dispute.refund_amount_during_dispute_cancellation') / 100; + $refund_commission = $vehicle_rental->paid_manual_amount + ($vehicle_rental->total_amount * $refund_percentage); + $booker_transaction_amount = $vehicle_rental->total_amount - $refund_commission; + // for specification dispute closed in favour of booker host should not get any amount, so it is set to 0. + $vehicle_rental_data['host_service_amount'] = 0; + $vehicle_rental_data['admin_commission_amount'] = $refund_commission; + $vehicle_rental->update($vehicle_rental_data); + //update user wallet amount + $this->walletService->updateWalletForUser($vehicle_rental->user_id, $booker_transaction_amount, $vehicle_rental->id, 'VehicleRentals'); + // update transaction logs + $this->transactionService->log(config('constants.ConstUserIds.Admin'), $vehicle_rental->user_id, config('constants.ConstTransactionTypes.RefundForSpecificationDispute'), $booker_transaction_amount, $vehicle_rental->id, 'VehicleRentals'); + } + + /** + * @param $vehicle_rental + */ + public function resolveByDepositAmountRefund($vehicle_rental, $dispute_closed_type_id) + { + //update user wallet amount + if ($dispute_closed_type_id == config('constants.ConstDisputeClosedTypes.SecurityFavourBooker')) { + $item_user_data['paid_deposit_amount'] = 0; + $vehicle_rental->update($item_user_data); + $this->walletService->updateWalletForUser($vehicle_rental->user_id, $vehicle_rental->deposit_amount, $vehicle_rental->id, 'VehicleRentals'); + // update transaction logs + $this->transactionService->log(config('constants.ConstUserIds.Admin'), $vehicle_rental->user_id, config('constants.ConstTransactionTypes.SecuirtyDepositAmountRefundedToBooker'), $vehicle_rental->deposit_amount, $vehicle_rental->id, 'VehicleRentals'); + } else if ($dispute_closed_type_id == config('constants.ConstDisputeClosedTypes.SecurityFavourHost') || $dispute_closed_type_id === config('constants.ConstDisputeClosedTypes.SecurityResponseFavourHost')) { + $payable_manual_claim = $vehicle_rental->paid_manual_amount; + if ($payable_manual_claim > 0) { + // manually paid claim + $this->transactionService->log($vehicle_rental->user_id, config('constants.ConstUserIds.Admin'), config('constants.ConstTransactionTypes.ManualTransferForClaimRequestAmount'), $payable_manual_claim, $vehicle_rental->item_userable->id, 'Vehicles'); + } + } + + } + + /** + * @param $request + * @param $vehicle_rental + * @param null $is_favour_booker + */ + public function closeDispute($request, $vehicle_rental, $is_favour_booker) + { + $dispute_data = array(); + if (is_array($request)) { + $dispute_data['dispute_closed_type_id'] = $request['dispute_closed_type_id']; + } else { + $dispute_data['dispute_closed_type_id'] = $request->dispute_closed_type_id; + } + $dispute_data['dispute_status_id'] = config('constants.ConstDisputeStatuses.Closed'); + $dispute_data['resolved_date'] = Carbon::now()->toDateTimeString(); + $dispute_data['is_favor_booker'] = $is_favour_booker; + $vehicle_dispute = VehicleDispute::where('id', '=', $vehicle_rental->item_user_dispute->id)->update($dispute_data); + if ($vehicle_dispute) { + $this->disputeClosedMail($vehicle_rental, $dispute_data['dispute_closed_type_id'], $is_favour_booker); + $item_user_data['is_dispute'] = 0; + $item_user_data['item_user_status_id'] = config('constants.ConstItemUserStatus.Completed'); + if ($vehicle_rental->update($item_user_data)) { + $this->vehicleRentalService->completeTransactionAmounts($vehicle_rental, 1); + $this->vehicleRentalService->changeStatusMail($vehicle_rental, $vehicle_rental->item_userable, $vehicle_rental->item_user_status_id, config('constants.ConstItemUserStatus.Completed')); + } + } + } + + /** + * update dispute conversation + * @param $vehicle_rental + */ + public function updateConversation($vehicle_rental, $message) + { + $user = Auth::user(); + $dispute_data = array(); + $conversation_count = ($vehicle_rental->item_user_dispute->dispute_conversation_count) + 1; + $dispute_data['dispute_status_id'] = config('constants.ConstDisputeStatuses.UnderDiscussion'); + $dispute_data['dispute_conversation_count'] = $conversation_count; + ($user->id === $vehicle_rental->user_id) ? $is_booker = 1 : $is_booker = 0; + if ($user->id === $vehicle_rental->item_userable->user_id || $user->id == $vehicle_rental->user_id) { + // user update + $dispute_data['last_replied_user_id'] = $user->id; + $dispute_data['last_replied_date'] = Carbon::now()->toDateTimeString(); + } + VehicleDispute::where('id', $vehicle_rental->item_user_dispute->id)->update($dispute_data); + if ($conversation_count < config('dispute.discussion_threshold_for_admin_decision')) { + $this->disputeConversationMail($vehicle_rental, $message, $is_booker, $user->username); + } else { + $dispute_data['dispute_status_id'] = config('constants.ConstDisputeStatuses.WaitingAdministratorDecision'); + VehicleDispute::where('id', $vehicle_rental->item_user_dispute->id)->update($dispute_data); + $this->disputeAdminDecisionMail($vehicle_rental); + } + } + + public function disputeAdminDecisionMail($vehicle_rental) + { + $template = $this->mailService->getTemplate('Discussion Threshold for Admin Decision'); + // send booker mail + $emailFindReplace = array( + '##USERNAME##' => $vehicle_rental->user->username, + '##OTHER_USER##' => 'Admin' + ); + $to_username = $vehicle_rental->user->id; + $to_email = $vehicle_rental->user->email; + + $this->mailService->sendMail($template, $emailFindReplace, $to_email, $to_username); + + // send host mail + $emailFindReplace = array( + '##USERNAME##' => $vehicle_rental->item_userable->user->username, + '##OTHER_USER##' => 'Admin' + ); + $to_username = $vehicle_rental->item_userable->user->id; + $to_email = $vehicle_rental->item_userable->user->email; + $this->mailService->sendMail($template, $emailFindReplace, $to_email, $to_username); + + //Save internal message + $default_content = array( + '##SITE_NAME##' => config('site.name'), + '##SITE_URL##' => '' . url('/') . '', + '##FROM_EMAIL##' => config('site.from_email'), + '##CONTACT_MAIL##' => config('site.contact_email') + ); + $vehicle_rental_mail_template = array_merge($emailFindReplace, $default_content); + + // save message booker + $message_content_arr = array(); + $message_content_arr['message'] = strtr($template['body_content'], $vehicle_rental_mail_template); + $message_content_arr['subject'] = strtr($template['subject'], $vehicle_rental_mail_template); + $this->messageService->saveMessageContent($message_content_arr, $vehicle_rental->item_userable->id, $vehicle_rental->id, config('constants.ConstUserIds.Admin'), $vehicle_rental->user_id, $vehicle_rental->item_user_status_id, 'VehicleRental', config('constants.ConstDisputeStatuses.WaitingAdministratorDecision')); + + //save message to host + $message_content_arr = array(); + $message_content_arr['message'] = strtr($template['body_content'], $vehicle_rental_mail_template); + $message_content_arr['subject'] = strtr($template['subject'], $vehicle_rental_mail_template); + $this->messageService->saveMessageContent($message_content_arr, $vehicle_rental->item_userable->id, $vehicle_rental->id, config('constants.ConstUserIds.Admin'), $vehicle_rental->item_userable->user_id, $vehicle_rental->item_user_status_id, 'VehicleRental', config('constants.ConstDisputeStatuses.WaitingAdministratorDecision')); + } +} diff --git a/app/Plugins/VehicleDisputes/Transformers/VehicleDisputeClosedTypeTransformer.php b/app/Plugins/VehicleDisputes/Transformers/VehicleDisputeClosedTypeTransformer.php new file mode 100644 index 0000000..1d1f12c --- /dev/null +++ b/app/Plugins/VehicleDisputes/Transformers/VehicleDisputeClosedTypeTransformer.php @@ -0,0 +1,53 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleDisputes\Transformers; + +use League\Fractal; +use Plugins\VehicleDisputes\Model\VehicleDisputeClosedType; +use Plugins\VehicleDisputes\Transformers\VehicleDisputeTypeTransformer; + +class VehicleDisputeClosedTypeTransformer extends Fractal\TransformerAbstract +{ + /** + * List of resources possible to include + * + * @var array + */ + protected $availableIncludes = [ + 'dispute_type' + ]; + + public function transform(VehicleDisputeClosedType $vehicle_dispute_closed_type) + { + $output = array_only($vehicle_dispute_closed_type->toArray(), ['id', 'name', 'dispute_type_id', 'is_booker', 'resolved_type', 'reason']); + $output['is_booker'] = (int)$output['is_booker']; + return $output; + } + + /** + * @param VehicleDisputeClosedType $vehicle_dispute_closed_type + * @return Fractal\Resource\Item + */ + public function includeDisputeType(VehicleDisputeClosedType $vehicle_dispute_closed_type) + { + if ($vehicle_dispute_closed_type->dispute_type) { + return $this->item($vehicle_dispute_closed_type->dispute_type, new \Plugins\VehicleDisputes\Transformers\VehicleDisputeTypeTransformer()); + } else { + return null; + } + + } +} diff --git a/app/Plugins/VehicleDisputes/Transformers/VehicleDisputeStatusTransformer.php b/app/Plugins/VehicleDisputes/Transformers/VehicleDisputeStatusTransformer.php new file mode 100644 index 0000000..54b89a9 --- /dev/null +++ b/app/Plugins/VehicleDisputes/Transformers/VehicleDisputeStatusTransformer.php @@ -0,0 +1,29 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleDisputes\Transformers; + +use League\Fractal; +use Plugins\VehicleDisputes\Model\VehicleDisputeStatus; + +class VehicleDisputeStatusTransformer extends Fractal\TransformerAbstract +{ + + public function transform(VehicleDisputeStatus $vehicle_dispute_status) + { + $output = array_only($vehicle_dispute_status->toArray(), ['id', 'name']); + return $output; + } +} diff --git a/app/Plugins/VehicleDisputes/Transformers/VehicleDisputeTransformer.php b/app/Plugins/VehicleDisputes/Transformers/VehicleDisputeTransformer.php new file mode 100644 index 0000000..85cbb13 --- /dev/null +++ b/app/Plugins/VehicleDisputes/Transformers/VehicleDisputeTransformer.php @@ -0,0 +1,146 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleDisputes\Transformers; + +use League\Fractal; +use Plugins\VehicleDisputes\Model\VehicleDispute; +use App\Transformers\UserTransformer; + +class VehicleDisputeTransformer extends Fractal\TransformerAbstract +{ + /** + * List of resources possible to include + * + * @var array + */ + protected $availableIncludes = [ + 'user', 'dispute_status', 'dispute_type', 'dispute_closed_type', 'LastRepliedUser', 'item_user_disputable', 'message' + ]; + + /** + * @param VehicleDispute $vehicle_dispute + * @return array + */ + public function transform(VehicleDispute $vehicle_dispute) + { + $output = array_only($vehicle_dispute->toArray(), ['id', 'created_at', 'user_id', 'item_user_disputable_id', 'item_user_disputable_type', 'dispute_type_id', 'dispute_status_id', 'last_replied_user_id', 'dispute_closed_type_id', 'is_favor_booker', 'is_booker', 'last_replied_date', 'resolved_date', 'dispute_conversation_count', 'reason']); + ($output['is_booker']) ? $output['is_booker'] = 'Booker' : $output['is_booker'] = 'Host'; + if ($output['is_favor_booker'] == 0 && $output['dispute_status_id'] == config('constants.ConstDisputeStatuses.Closed')) { + $output['is_favor_booker'] = 'Host'; + } elseif ($output['is_favor_booker'] == 1 && $output['dispute_status_id'] == config('constants.ConstDisputeStatuses.Closed')) { + $output['is_favor_booker'] = 'Booker'; + } else { + $output['is_favor_booker'] = ''; + } + return $output; + } + + /** + * @param VehicleDispute $vehicle_dispute + * @return Fractal\Resource\Item|null + */ + public function includeUser(VehicleDispute $vehicle_dispute) + { + if ($vehicle_dispute->user) { + return $this->item($vehicle_dispute->user, new UserTransformer()); + } else { + return null; + } + } + + /** + * @param VehicleDispute $vehicle_dispute + * @return Fractal\Resource\Item|null + */ + public function LastRepliedUser(VehicleDispute $vehicle_dispute) + { + if ($vehicle_dispute->LastRepliedUser) { + return $this->item($vehicle_dispute->LastRepliedUser, new UserTransformer()); + } else { + return null; + } + } + + /** + * @param VehicleDispute $vehicle_dispute + * @return Fractal\Resource\Item|null + */ + public function includeDisputeStatus(VehicleDispute $vehicle_dispute) + { + if ($vehicle_dispute->dispute_status) { + return $this->item($vehicle_dispute->dispute_status, new \Plugins\VehicleDisputes\Transformers\VehicleDisputeStatusTransformer()); + } else { + return null; + } + } + + /** + * @param VehicleDispute $vehicle_dispute + * @return Fractal\Resource\Item|null + */ + public function includeDisputeType(VehicleDispute $vehicle_dispute) + { + if ($vehicle_dispute->dispute_type) { + return $this->item($vehicle_dispute->dispute_type, new \Plugins\VehicleDisputes\Transformers\VehicleDisputeTypeTransformer()); + } else { + return null; + } + } + + /** + * @param VehicleDispute $vehicle_dispute + * @return Fractal\Resource\Item|null + */ + public function includeItemUserDisputable(VehicleDispute $vehicle_dispute) + { + if ($vehicle_dispute->item_user_disputable) { + if ($vehicle_dispute->item_user_disputable_type == 'MorphVehicleRental') { + $enabledIncludes = array('item_user_status', 'user', 'item_userable'); + return $this->item($vehicle_dispute->item_user_disputable, (new \Plugins\VehicleRentals\Transformers\VehicleRentalTransformer)->setDefaultIncludes($enabledIncludes)); + } + } else { + return null; + } + } + + /** + * @param VehicleDispute $vehicle_dispute + * @return Fractal\Resource\Item|null + */ + public function includeDisputeClosedType(VehicleDispute $vehicle_dispute) + { + if ($vehicle_dispute->dispute_Closed_type) { + return $this->item($vehicle_dispute->dispute_Closed_type, new \Plugins\VehicleDisputes\Transformers\VehicleDisputeClosedTypeTransformer()); + } else { + return null; + } + } + + /** + * @param VehicleDispute $vehicle_dispute + * @return Fractal\Resource\Item|null + */ + public function includeMessage(VehicleDispute $vehicle_dispute) + { + if ($vehicle_dispute->messageable) { + if ($vehicle_dispute->messageable_type == 'MorphVehicleRentalDispute') { + return $this->item($vehicle_dispute->messageable, (new \App\Transformers\MessageTransformer)->setDefaultIncludes('message_content')); + } + } else { + return null; + } + } +} diff --git a/app/Plugins/VehicleDisputes/Transformers/VehicleDisputeTypeTransformer.php b/app/Plugins/VehicleDisputes/Transformers/VehicleDisputeTypeTransformer.php new file mode 100644 index 0000000..85638a6 --- /dev/null +++ b/app/Plugins/VehicleDisputes/Transformers/VehicleDisputeTypeTransformer.php @@ -0,0 +1,31 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleDisputes\Transformers; + +use League\Fractal; +use Plugins\VehicleDisputes\Model\VehicleDisputeType; + +class VehicleDisputeTypeTransformer extends Fractal\TransformerAbstract +{ + + public function transform(VehicleDisputeType $vehicle_dispute_type) + { + $output = array_only($vehicle_dispute_type->toArray(), ['id', 'name', 'is_booker', 'is_active']); + $output['is_active'] = ($output['is_active'] == 1) ? true : false; + $output['is_booker'] = ($output['is_booker'] == 1) ? true : false; + return $output; + } +} diff --git a/app/Plugins/VehicleDisputes/plugin.json b/app/Plugins/VehicleDisputes/plugin.json new file mode 100644 index 0000000..276e867 --- /dev/null +++ b/app/Plugins/VehicleDisputes/plugin.json @@ -0,0 +1,9 @@ +{ + "name": "VehicleDisputes", + "class": "fa fa-2x fa-retweet", + "description": "By enabling this, item owner / booker can raise dispute against their inconveniences.", + "dependencies": "VehicleRentals", + "module_id": "794", + "module_hash": "e92a3686920c2a8696450d198f31eea1", + "display_order": "12" +} diff --git a/app/Plugins/VehicleDisputes/routes.php b/app/Plugins/VehicleDisputes/routes.php new file mode 100644 index 0000000..8b3b548 --- /dev/null +++ b/app/Plugins/VehicleDisputes/routes.php @@ -0,0 +1,53 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +/* +|-------------------------------------------------------------------------- +| Application Routes +|-------------------------------------------------------------------------- +| +| Here is where you can register all of the routes for an application. +| It is a breeze. Simply tell Lumen the URIs it should respond to +| and give it the Closure to call when that URI is requested. +| +*/ +$api = $this->app->make('Dingo\Api\Routing\Router'); +$api->version(['v1'], function ($api) { + $api->group(['prefix' => 'admin', 'namespace' => 'Plugins\VehicleDisputes\Controllers\Admin', 'middleware' => 'apitracking'], function () use ($api) { + // disputes admin side + $api->get('vehicle_disputes', 'AdminVehicleDisputesController@index'); + $api->post('vehicle_disputes/resolve', 'AdminVehicleDisputesController@resolve'); + // vehicle dispute types + $api->get('vehicle_dispute_types', 'AdminVehicleDisputeTypesController@index'); + $api->get('vehicle_dispute_types/{id}/edit', 'AdminVehicleDisputeTypesController@edit'); + $api->get('vehicle_dispute_types/{id}', 'AdminVehicleDisputeTypesController@edit'); + $api->put('vehicle_dispute_types/{id}', 'AdminVehicleDisputeTypesController@update'); + // vehicle dispute closed types + $api->get('vehicle_dispute_closed_types', 'AdminVehicleDisputeClosedTypesController@index'); + $api->get('vehicle_dispute_closed_types/{id}/edit', 'AdminVehicleDisputeClosedTypesController@edit'); + $api->get('vehicle_dispute_closed_types/{id}', 'AdminVehicleDisputeClosedTypesController@edit'); + $api->put('vehicle_dispute_closed_types/{id}', 'AdminVehicleDisputeClosedTypesController@update'); + }); + $api->group(['namespace' => 'Plugins\VehicleDisputes\Controllers', 'middleware' => 'apitracking'], function () use ($api) { + //disputes user side + $api->get('vehicle_disputes', 'VehicleDisputesController@index'); + $api->post('vehicle_disputes/add', 'VehicleDisputesController@store'); + $api->get('vehicle_disputes/{id}', 'VehicleDisputesController@getPossibleDisputeTypes'); + + $api->get('vehicle_dispute_types', 'VehicleDisputeTypesController@index'); + + $api->get('vehicle_dispute_closed_types', 'VehicleDisputeClosedTypesController@index'); + }); +}); diff --git a/app/Plugins/VehicleExtraAccessories/Controllers/Admin/AdminVehicleExtraAccessoriesController.php b/app/Plugins/VehicleExtraAccessories/Controllers/Admin/AdminVehicleExtraAccessoriesController.php new file mode 100644 index 0000000..dc5e88a --- /dev/null +++ b/app/Plugins/VehicleExtraAccessories/Controllers/Admin/AdminVehicleExtraAccessoriesController.php @@ -0,0 +1,190 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleExtraAccessories\Controllers\Admin; + +use Illuminate\Http\Request; +use App\Http\Controllers\Controller; +use Plugins\VehicleExtraAccessories\Model\VehicleExtraAccessory; +use JWTAuth; +use Plugins\VehicleExtraAccessories\Transformers\VehicleExtraAccessoryTransformer; +use Validator; +use Tymon\JWTAuth\Exceptions\JWTException; +use Plugins\VehicleExtraAccessories\Transformers\AdminVehicleExtraAccessoryTransformer; +use EasySlug\EasySlug\EasySlugFacade as EasySlug; + +/** + * VehicleExtraAccessories resource representation. + * @Resource("Admin/AdminVehicleExtraAccessories") + */ +class AdminVehicleExtraAccessoriesController extends Controller +{ + /** + * AdminVehicleExtraAccessoriesController constructor. + */ + public function __construct() + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth'); + // Check the logged user role. + $this->middleware('role'); + } + + /** + * Show all vehicle_extra_accessories + * Get a JSON representation of all the vehicle_extra_accessories. + * + * @Get("/admin/vehicle_extra_accessories?sort={sort}&sortby={sortby}&page={page}&q={q}") + * @Parameters({ + * @Parameter("sort", type="string", required=false, description="Sort the vehicle_extra_accessories list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort vehicle_extra_accessories by Ascending / Descending Order.", default=null), + * @Parameter("q", type="string", required=false, description="Search VehicleExtraAccessories.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1) + * }) + */ + public function index(Request $request) + { + if($request->has('limit') && $request->limit == 'all') { + $vehicle_extra_accessory_count = VehicleExtraAccessory::count(); + $vehicle_extra_accessories = VehicleExtraAccessory::filterByActiveRecord($request)->filterByRequest($request)->select('id', 'name')->paginate($vehicle_extra_accessory_count); + return $this->response->paginator($vehicle_extra_accessories, new VehicleExtraAccessoryTransformer); + } else { + $vehicle_extra_accessories = VehicleExtraAccessory::filterByRequest($request)->paginate(config('constants.ConstPageLimit')); + return $this->response->paginator($vehicle_extra_accessories, new AdminVehicleExtraAccessoryTransformer); + } + } + + /** + * Edit the specified vehicle_extra_accessory. + * Edit the vehicle_extra_accessory with a `id`. + * @Get("/admin/vehicle_extra_accessories/{id}/edit") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body= {"id": 1, "name": "Service ExtraAccessory", "short_description": "The costs of service needed to support our business operations have escalated considerably.", "description": "The costs of service needed to support our business operations have escalated considerably. To offset the increasing costs of utilities, bus fuel, oil and grease, etc.,"}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function edit($id) + { + $vehicle_extra_accessory = VehicleExtraAccessory::find($id); + if (!$vehicle_extra_accessory) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($vehicle_extra_accessory, (new AdminVehicleExtraAccessoryTransformer)); + } + + /** + * Show the specified vehicle_extra_accessory. + * Show the vehicle_extra_accessory with a `id`. + * @Get("/admin/vehicle_extra_accessories/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body= {"id": 1, "name": "Service ExtraAccessory", "short_description": "The costs of service needed to support our business operations have escalated considerably.", "description": "The costs of service needed to support our business operations have escalated considerably. To offset the increasing costs of utilities, bus fuel, oil and grease, etc.,"}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function show($id) + { + $vehicle_extra_accessory = VehicleExtraAccessory::find($id); + if (!$vehicle_extra_accessory) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($vehicle_extra_accessory, (new AdminVehicleExtraAccessoryTransformer)); + } + + /** + * Store a new vehicle_extra_accessory. + * Store a new vehicle_extra_accessory with a `name`, `short_description`, and `description`. + * @Post("/admin/vehicle_extra_accessories") + * @Transaction({ + * @Request({"name": "Service ExtraAccessory", "short_description": "The costs of service needed to support our business operations have escalated considerably.", "description": "The costs of service needed to support our business operations have escalated considerably. To offset the increasing costs of utilities, bus fuel, oil and grease, etc.,"}), + * @Response(200, body={"success": "Record has been added."}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {"name": {}}, "status_code": 422}) + * }) + */ + public function store(Request $request) + { + $vehicle_extra_accessory_data = $request->only('name', 'short_description', 'description'); + $validator = Validator::make($vehicle_extra_accessory_data, VehicleExtraAccessory::GetValidationRule(), VehicleExtraAccessory::GetValidationMessage()); + $vehicle_extra_accessory_data['slug'] = EasySlug::generateUniqueSlug($request->name, 'extra_accessories'); + if ($validator->passes()) { + $vehicle_extra_accessory_data['is_active'] = true; + $vehicle_extra_accessory = VehicleExtraAccessory::create($vehicle_extra_accessory_data); + if ($vehicle_extra_accessory) { + return response()->json(['Success' => 'VehicleExtraAccessory has been added'], 200); + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('VehicleExtraAccessory could not be updated. Please, try again.'); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('VehicleExtraAccessory could not be updated. Please, try again.', $validator->errors()); + } + } + + + /** + * Update the specified vehicle_extra_accessory + * Update the vehicle_extra_accessory with a `id`. + * @Put("/admin/vehicle_extra_accessories/{id}") + * @Transaction({ + * @Request({"id": 1, "name": "Energy ExtraAccessory", "short_description": "The costs of energy needed to support our business operations have escalated considerably.", "description": "The costs of energy needed to support our business operations have escalated considerably. To offset the increasing costs of utilities, bus fuel, oil and grease, etc.,", "is_active": 1}), + * @Response(200, body={"success": "Record has been updated."}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {"name": {}}, "status_code": 422}) + * }) + */ + public function update(Request $request, $id) + { + $vehicle_extra_accessory_data = $request->only('name', 'short_description', 'description', 'is_active'); + $validator = Validator::make($vehicle_extra_accessory_data, VehicleExtraAccessory::GetValidationRule(), VehicleExtraAccessory::GetValidationMessage()); + $vehicle_extra_accessory = false; + if ($request->has('id')) { + $vehicle_extra_accessory = VehicleExtraAccessory::find($id); + $vehicle_extra_accessory = ($request->id != $id) ? false : $vehicle_extra_accessory; + if ($vehicle_extra_accessory->name !== $request->name) { + $vehicle_extra_accessory_data['slug'] = EasySlug::generateUniqueSlug($request->name, 'extra_accessories'); + } + } + if ($validator->passes() && $vehicle_extra_accessory) { + try { + $vehicle_extra_accessory->update($vehicle_extra_accessory_data); + return response()->json(['Success' => 'VehicleExtraAccessory has been updated'], 200); + } catch (\Exception $e) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('VehicleExtraAccessory could not be updated. Please, try again.'); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('VehicleExtraAccessory could not be updated. Please, try again.', $validator->errors()); + } + } + + /** + * Delete the specified vehicle_extra_accessory. + * Delete the vehicle_extra_accessory with a `id`. + * @Delete("/admin/vehicle_extra_accessories/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"success": "Record Deleted."}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function destroy($id) + { + $vehicle_extra_accessory = VehicleExtraAccessory::find($id); + if (!$vehicle_extra_accessory) { + return $this->response->errorNotFound("Invalid Request"); + } else { + $vehicle_extra_accessory->delete(); + } + return response()->json(['Success' => 'VehicleExtraAccessory deleted'], 200); + } +} diff --git a/app/Plugins/VehicleExtraAccessories/Controllers/Admin/AdminVehicleTypeExtraAccessoriesController.php b/app/Plugins/VehicleExtraAccessories/Controllers/Admin/AdminVehicleTypeExtraAccessoriesController.php new file mode 100644 index 0000000..f35f516 --- /dev/null +++ b/app/Plugins/VehicleExtraAccessories/Controllers/Admin/AdminVehicleTypeExtraAccessoriesController.php @@ -0,0 +1,188 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleExtraAccessories\Controllers\Admin; + +use Illuminate\Http\Request; +use App\Http\Requests; +use App\Http\Controllers\Controller; +use Plugins\VehicleExtraAccessories\Model\VehicleTypeExtraAccessory; +use JWTAuth; +use Validator; +use Plugins\VehicleExtraAccessories\Transformers\VehicleTypeExtraAccessoryTransformer; +use DB; + +/** + * VehicleTypeExtraAccessories resource representation. + * @Resource("Admin/AdminVehicleTypeExtraAccessories") + */ +class AdminVehicleTypeExtraAccessoriesController extends Controller +{ + /** + * AdminVehicleTypeExtraAccessoriesController constructor. + */ + public function __construct() + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth'); + // Check the logged user role. + $this->middleware('role'); + } + + /** + * Show all vehicle_type_extra_accessories + * Get a JSON representation of all the vehicle_type_extra_accessories. + * + * @Get("/admin/vehicle_type_extra_accessories?sort={sort}&sortby={sortby}&page={page}&q={q}") + * @Parameters({ + * @Parameter("sort", type="string", required=false, description="Sort the vehicle_type_extra_accessories list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort vehicle_type_extra_accessories by Ascending / Descending Order.", default=null), + * @Parameter("q", type="string", required=false, description="Search VehicleTypeExtraAccessories.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1) + * }) + */ + public function index(Request $request) + { + $enabled_includes = array('vehicle_extra_accessory', 'discount_type', 'duration_type', 'vehicle_type'); + $vehicle_type_extra_accessories = VehicleTypeExtraAccessory::with($enabled_includes) + ->select(DB::raw('vehicle_type_extra_accessories.*')) + ->leftJoin(DB::raw('(select id,name from vehicle_types) as vehicle_type'), 'vehicle_type.id', '=', 'vehicle_type_extra_accessories.vehicle_type_id') + ->leftJoin(DB::raw('(select id,name from extra_accessories) as vehicle_extra_accessory'), 'vehicle_extra_accessory.id', '=', 'vehicle_type_extra_accessories.extra_accessory_id') + ->leftJoin(DB::raw('(select id,type from discount_types) as discount_type'), 'discount_type.id', '=', 'vehicle_type_extra_accessories.discount_type_id') + ->leftJoin(DB::raw('(select id,name from duration_types) as duration_type'), 'duration_type.id', '=', 'vehicle_type_extra_accessories.duration_type_id') + ->filterByRequest($request)->paginate(config('constants.ConstPageLimit')); + return $this->response->paginator($vehicle_type_extra_accessories, (new VehicleTypeExtraAccessoryTransformer)->setDefaultIncludes($enabled_includes)); + } + + /** + * Edit the specified vehicle_type_extra_accessory. + * Edit the vehicle_type_extra_accessory with a `id`. + * @Get("/admin/vehicle_type_extra_accessories/{id}/edit") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body= {"id": 1, "vehicle_type_id": 1, "extra_accessory_id": 1, "discount_type_id": 1, "duration_type_id": 1, "rate": 200, "max_allowed_amount": 1000, "vehicle_type": {}, "vehicle_extra_accessory": {}, "duration_type": {}, "discount_type": {}}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function edit($id) + { + $enabled_includes = array('vehicle_extra_accessory', 'discount_type', 'duration_type', 'vehicle_type'); + $vehicle_type_extra_accessory = VehicleTypeExtraAccessory::with($enabled_includes)->find($id); + if (!$vehicle_type_extra_accessory) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($vehicle_type_extra_accessory, (new VehicleTypeExtraAccessoryTransformer)->setDefaultIncludes($enabled_includes)); + } + + /** + * Show the specified vehicle_type_extra_accessory. + * Show the vehicle_type_extra_accessory with a `id`. + * @Get("/admin/vehicle_type_extra_accessories/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body= {"id": 1, "vehicle_type_id": 1, "extra_accessory_id": 1, "discount_type_id": 1, "duration_type_id": 1, "rate": 200, "max_allowed_amount": 1000, "vehicle_type": {}, "vehicle_extra_accessory": {}, "duration_type": {}, "discount_type": {}}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function show($id) + { + $enabled_includes = array('vehicle_extra_accessory', 'discount_type', 'duration_type', 'vehicle_type'); + $vehicle_type_extra_accessory = VehicleTypeExtraAccessory::with($enabled_includes)->find($id); + if (!$vehicle_type_extra_accessory) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($vehicle_type_extra_accessory, (new VehicleTypeExtraAccessoryTransformer)->setDefaultIncludes($enabled_includes)); + } + + /** + * Store a new vehicle_type_extra_accessory. + * Store a new vehicle_type_extra_accessory with a `name`, `short_description`, and `description`. + * @Post("/admin/vehicle_type_extra_accessories") + * @Transaction({ + * @Request({"vehicle_type_id": 1, "extra_accessory_id": 1, "discount_type_id": 1, "duration_type_id": 1, "rate": 200, "max_allowed_amount": 1000}), + * @Response(200, body={"success": "Record has been added."}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {"name": {}}, "status_code": 422}) + * }) + */ + public function store(Request $request) + { + $vehicle_type_extra_accessory_data = $request->only('vehicle_type_id', 'extra_accessory_id', 'rate', 'discount_type_id', 'duration_type_id', 'max_allowed_amount', 'deposit_amount', 'is_active'); + $validator = Validator::make($vehicle_type_extra_accessory_data, VehicleTypeExtraAccessory::GetValidationRule(), VehicleTypeExtraAccessory::GetValidationMessage()); + if ($validator->passes()) { + $vehicle_type_extra_accessory_data['is_active'] = true; + $vehicle_type_extra_accessory = VehicleTypeExtraAccessory::create($vehicle_type_extra_accessory_data); + if ($vehicle_type_extra_accessory) { + return response()->json(['Success' => 'VehicleTypeExtraAccessory has been added'], 200); + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('VehicleTypeExtraAccessory could not be added. Please, try again.'); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('VehicleTypeExtraAccessory could not be added. Please, try again.', $validator->errors()); + } + } + + + /** + * Update the specified vehicle_type_extra_accessory + * Update the vehicle_type_extra_accessory with a `id`. + * @Put("/admin/vehicle_type_extra_accessories/{id}") + * @Transaction({ + * @Request({"id": 1, "vehicle_type_id": 1, "extra_accessory_id": 1, "discount_type_id": 1, "duration_type_id": 1, "rate": 200, "max_allowed_amount": 1000}), + * @Response(200, body={"success": "Record has been updated."}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {"name": {}}, "status_code": 422}) + * }) + */ + public function update(Request $request, $id) + { + $vehicle_type_extra_accessory_data = $request->only('vehicle_type_id', 'extra_accessory_id', 'rate', 'discount_type_id', 'duration_type_id', 'max_allowed_amount', 'deposit_amount', 'is_active'); + $validator = Validator::make($vehicle_type_extra_accessory_data, VehicleTypeExtraAccessory::GetValidationRule(), VehicleTypeExtraAccessory::GetValidationMessage()); + $vehicle_type_extra_accessory = false; + if ($request->has('id')) { + $vehicle_type_extra_accessory = VehicleTypeExtraAccessory::find($id); + $vehicle_type_extra_accessory = ($request->id != $id) ? false : $vehicle_type_extra_accessory; + } + if ($validator->passes() && $vehicle_type_extra_accessory) { + try { + $vehicle_type_extra_accessory->update($vehicle_type_extra_accessory_data); + return response()->json(['Success' => 'VehicleTypeExtraAccessory has been updated'], 200); + } catch (\Exception $e) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('VehicleTypeExtraAccessory could not be updated. Please, try again.'); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('VehicleTypeExtraAccessory could not be updated. Please, try again.', $validator->errors()); + } + } + + /** + * Delete the specified vehicle_type_extra_accessory. + * Delete the vehicle_type_extra_accessory with a `id`. + * @Delete("/admin/vehicle_type_extra_accessories/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"success": "Record Deleted."}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function destroy($id) + { + $vehicle_type_extra_accessory = VehicleTypeExtraAccessory::find($id); + if (!$vehicle_type_extra_accessory) { + return $this->response->errorNotFound("Invalid Request"); + } else { + $vehicle_type_extra_accessory->delete(); + } + return response()->json(['Success' => 'VehicleTypeExtraAccessory deleted'], 200); + } +} diff --git a/app/Plugins/VehicleExtraAccessories/Controllers/VehicleExtraAccessoriesController.php b/app/Plugins/VehicleExtraAccessories/Controllers/VehicleExtraAccessoriesController.php new file mode 100644 index 0000000..d9b68dc --- /dev/null +++ b/app/Plugins/VehicleExtraAccessories/Controllers/VehicleExtraAccessoriesController.php @@ -0,0 +1,58 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleExtraAccessories\Controllers; + +use Illuminate\Http\Request; +use App\Http\Controllers\Controller; +use Plugins\VehicleExtraAccessories\Model\VehicleExtraAccessory; +use JWTAuth; +use Validator; +use Tymon\JWTAuth\Exceptions\JWTException; +use Plugins\VehicleExtraAccessories\Transformers\VehicleExtraAccessoryTransformer; + +/** + * VehicleExtraAccessories resource representation. + * @Resource("VehicleExtraAccessories") + */ +class VehicleExtraAccessoriesController extends Controller +{ + /** + * VehicleExtraAccessoriesController constructor. + */ + public function __construct() + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth'); + } + + /** + * Show all extra_accessories + * Get a JSON representation of all the extra_accessories. + * + * @Get("/extra_accessories?sort={sort}&sortby={sortby}&page={page}&q={q}") + * @Parameters({ + * @Parameter("sort", type="string", required=false, description="Sort the extra_accessories list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort extra_accessories by Ascending / Descending Order.", default=null), + * @Parameter("q", type="string", required=false, description="Search VehicleExtraAccessories.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1) + * }) + */ + public function index(Request $request) + { + $extra_accessories = VehicleExtraAccessory::filterByRequest($request)->paginate(config('constants.ConstPageLimit')); + return $this->response->paginator($extra_accessories, (new VehicleExtraAccessoryTransformer)); + } +} diff --git a/app/Plugins/VehicleExtraAccessories/Controllers/VehicleTypeExtraAccessoriesController.php b/app/Plugins/VehicleExtraAccessories/Controllers/VehicleTypeExtraAccessoriesController.php new file mode 100644 index 0000000..f35e763 --- /dev/null +++ b/app/Plugins/VehicleExtraAccessories/Controllers/VehicleTypeExtraAccessoriesController.php @@ -0,0 +1,59 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleExtraAccessories\Controllers; + +use Illuminate\Http\Request; +use App\Http\Controllers\Controller; +use Plugins\VehicleExtraAccessories\Model\VehicleTypeExtraAccessory; +use JWTAuth; +use Validator; +use Tymon\JWTAuth\Exceptions\JWTException; +use Plugins\VehicleExtraAccessories\Transformers\VehicleTypeExtraAccessoryTransformer; + +/** + * VehicleExtraAccessories resource representation. + * @Resource("VehicleExtraAccessories") + */ +class VehicleTypeExtraAccessoriesController extends Controller +{ + /** + * VehicleExtraAccessoriesController constructor. + */ + public function __construct() + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth'); + } + + /** + * Show all extra_accessories + * Get a JSON representation of all the extra_accessories. + * + * @Get("/extra_accessories?sort={sort}&sortby={sortby}&page={page}&q={q}") + * @Parameters({ + * @Parameter("sort", type="string", required=false, description="Sort the extra_accessories list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort extra_accessories by Ascending / Descending Order.", default=null), + * @Parameter("q", type="string", required=false, description="Search VehicleExtraAccessories.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1) + * }) + */ + public function index(Request $request) + { + $enabled_includes = array('vehicle_extra_accessory', 'discount_type', 'duration_type', 'vehicle_type'); + $vehicle_type_extra_accessories = VehicleTypeExtraAccessory::with($enabled_includes)->filterByRequest($request)->paginate(config('constants.ConstPageLimit')); + return $this->response->paginator($vehicle_type_extra_accessories, (new VehicleTypeExtraAccessoryTransformer)->setDefaultIncludes($enabled_includes)); + } +} diff --git a/app/Plugins/VehicleExtraAccessories/Model/VehicleExtraAccessory.php b/app/Plugins/VehicleExtraAccessories/Model/VehicleExtraAccessory.php new file mode 100644 index 0000000..a0c7c10 --- /dev/null +++ b/app/Plugins/VehicleExtraAccessories/Model/VehicleExtraAccessory.php @@ -0,0 +1,101 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleExtraAccessories\Model; + +use Illuminate\Http\Request; +use Illuminate\Database\Eloquent\Model; + +class VehicleExtraAccessory extends Model +{ + /** + * @var string + */ + protected $table = "extra_accessories"; + + protected $fillable = [ + 'name', 'short_description', 'description', 'is_active', 'slug' + ]; + + + /** + * @return \Illuminate\Database\Eloquent\Relations\HasMany + */ + public function vehicle_type_extra_accessory() + { + return $this->hasMany(VehicleTypeExtraAccessory::class); + } + /** + * @param $query + * @param Request $request + */ + public function scopeFilterByActiveRecord($query, Request $request) + { + $query->where('is_active', '=', 1); + } + /** + * @param $query + * @param Request $request + * @return mixed + */ + public function scopeFilterByRequest($query, Request $request) + { + $query->orderBy($request->input('sort', 'id'), $request->input('sortby', 'asc')); + if ($request->has('q')) { + $query->where('name', 'LIKE', '%' . $request->input('q') . '%') + ->orWhere('short_description', 'LIKE', '%' . $request->input('q') . '%') + ->orWhere('description', 'LIKE', '%' . $request->input('q') . '%'); + } + if ($request->has('filter')) { + $filter = false; + if ($request->input('filter') == 'active') { + $filter = true; + } + $query->where('is_active', '=', $filter); + } + return $query; + } + + /** + * @return array + */ + public function scopeGetValidationRule() + { + return [ + 'name' => 'required|min:5', + 'short_description' => 'required|min:10', + 'description' => 'required|min:15', + 'is_active' => 'sometimes|required|boolean' + ]; + } + + /** + * @return array + */ + public function scopeGetValidationMessage() + { + return [ + 'name.required' => 'Required', + 'name.min' => 'name - Minimum length is 5', + 'short_description.required' => 'Required', + 'short_description.min' => 'Short Description - Minimum length is 10', + 'description.required' => 'Required', + 'description.min' => 'Description - Minimum length is 15', + 'is_active.required' => 'Required', + 'is_active.boolean' => 'Possible values to be entered is 0 or 1' + ]; + } + +} diff --git a/app/Plugins/VehicleExtraAccessories/Model/VehicleTypeExtraAccessory.php b/app/Plugins/VehicleExtraAccessories/Model/VehicleTypeExtraAccessory.php new file mode 100644 index 0000000..6bd45da --- /dev/null +++ b/app/Plugins/VehicleExtraAccessories/Model/VehicleTypeExtraAccessory.php @@ -0,0 +1,151 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleExtraAccessories\Model; + +use Illuminate\Http\Request; +use Illuminate\Database\Eloquent\Model; +use Illuminate\Support\Facades\App; +use App\DiscountType; +use App\DurationType; + +class VehicleTypeExtraAccessory extends Model +{ + /** + * @var string + */ + protected $table = "vehicle_type_extra_accessories"; + + protected $fillable = [ + 'vehicle_type_id', 'extra_accessory_id', 'rate', 'discount_type_id', 'duration_type_id', 'max_allowed_amount', 'deposit_amount', 'is_active' + ]; + + + /** + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function vehicle_extra_accessory() + { + return $this->belongsTo(VehicleExtraAccessory::class, 'extra_accessory_id'); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function vehicle_type() + { + return $this->belongsTo(\Plugins\Vehicles\Model\VehicleType::class); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function discount_type() + { + return $this->belongsTo(DiscountType::class); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function duration_type() + { + return $this->belongsTo(DurationType::class); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\MorphMany + */ + public function vehicle_rental_additional_charges() + { + return $this->morphMany(\Plugins\VehicleRentals\Model\VehicleRentalAdditionalCharge::class, 'item_user_additional_chargable'); + } + + /** + * @param $query + * @param Request $request + * @return mixed + */ + public function scopeFilterByRequest($query, Request $request) + { + $query->orderBy($request->input('sort', 'id'), $request->input('sortby', 'asc')); + if ($request->has('q')) { + $query->WhereHas('vehicle_extra_accessory', function ($q) use ($request) { + $q->where('name', 'like', '%' . $request->input('q') . '%'); + }); + $query->orWhereHas('vehicle_type', function ($q) use ($request) { + $q->where('name', 'like', '%' . $request->input('q') . '%'); + }); + $query->orWhereHas('discount_type', function ($q) use ($request) { + $q->where('type', 'like', '%' . $request->input('q') . '%'); + }); + $query->orWhereHas('duration_type', function ($q) use ($request) { + $q->where('name', 'like', '%' . $request->input('q') . '%'); + }); + } + if ($request->has('filter')) { + $filter = false; + if ($request->filter == 'active') { + $filter = true; + } + $query->where('is_active', '=', $filter); + } + if ($request->has('extra_accessory_id')) { + $query->where('extra_accessory_id', '=', $request->extra_accessory_id); + } + return $query; + } + + /** + * @return array + */ + public function scopeGetValidationRule() + { + return [ + 'vehicle_type_id' => 'required|integer|exists:vehicle_types,id', + 'extra_accessory_id' => 'required|integer|exists:extra_accessories,id', + 'rate' => 'required|numeric', + 'discount_type_id' => 'required|integer|exists:discount_types,id', + 'duration_type_id' => 'required|integer|exists:duration_types,id', + 'max_allowed_amount' => 'required|numeric' + ]; + } + + /** + * @return array + */ + public function scopeGetValidationMessage() + { + return [ + 'vehicle_type_id.required' => 'Required', + 'vehicle_type_id.integer' => 'Vehicle Type Id must be integer', + 'vehicle_type_id.exists' => 'Invalid vehicle type id', + 'extra_accessory_id.required' => 'Required', + 'extra_accessory_id.integer' => 'Extra Accessories Id must be integer', + 'extra_accessory_id.exists' => 'Invalid extra accessory id', + 'rate.required' => 'Required', + 'rate.numeric' => 'Rate must be numeric', + 'discount_type_id.required' => 'Required', + 'discount_type_id.integer' => 'Discount Type Id must be integer', + 'discount_type_id.exists' => 'Invalid discount type id', + 'duration_type_id.required' => 'Required', + 'duration_type_id.integer' => 'Duration Type Id must be integer', + 'discount_type_id.exists' => 'Invalid duration type id', + 'max_allowed_amount.required' => 'Required', + 'max_allowed_amount.numeric' => 'Max allowed amount must be numeric' + ]; + } + +} diff --git a/app/Plugins/VehicleExtraAccessories/Providers/VehicleExtraAccessoryServiceProvider.php b/app/Plugins/VehicleExtraAccessories/Providers/VehicleExtraAccessoryServiceProvider.php new file mode 100644 index 0000000..90ec75e --- /dev/null +++ b/app/Plugins/VehicleExtraAccessories/Providers/VehicleExtraAccessoryServiceProvider.php @@ -0,0 +1,44 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleExtraAccessories\Providers; + +use Illuminate\Support\ServiceProvider; + +class VehicleExtraAccessoryServiceProvider extends ServiceProvider +{ + /** + * Register any application services. + * + * @return void + */ + public function register() + { + include __DIR__ . '/../routes.php'; + $this->app->make('Plugins\VehicleExtraAccessories\Controllers\VehicleExtraAccessoriesController'); + $this->app->make('Plugins\VehicleExtraAccessories\Controllers\Admin\AdminVehicleExtraAccessoriesController'); + $this->app->make('Plugins\VehicleExtraAccessories\Controllers\VehicleTypeExtraAccessoriesController'); + $this->app->make('Plugins\VehicleExtraAccessories\Controllers\Admin\AdminVehicleTypeExtraAccessoriesController'); + } + + /** + * Bootstrap the application services. + * + * @return void + */ + public function boot() + { + } +} diff --git a/app/Plugins/VehicleExtraAccessories/Services/VehicleExtraAccessoryService.php b/app/Plugins/VehicleExtraAccessories/Services/VehicleExtraAccessoryService.php new file mode 100644 index 0000000..7cc4c59 --- /dev/null +++ b/app/Plugins/VehicleExtraAccessories/Services/VehicleExtraAccessoryService.php @@ -0,0 +1,67 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleExtraAccessories\Services; + +use Plugins\VehicleExtraAccessories\Model\VehicleTypeExtraAccessory; +use Plugins\VehicleRentals\Model\VehicleRentalAdditionalCharge; + +class VehicleExtraAccessoryService +{ + /** + * VehicleExtraAccessoryService constructor. + */ + public function __construct() + { + } + + /** + * @param $item_user_id + * @param $amount + * @param $extra_accessories + * @param $no_of_days + * @return int + */ + public function processExtraAccessoryAmount($item_user_id, $amount, $extra_accessories, $no_of_days) + { + $res_amount = 0; + $vehicle_type_extra_accessories = VehicleTypeExtraAccessory::whereIn('id', $extra_accessories)->get(); + foreach ($vehicle_type_extra_accessories as $vehicle_type_extra_accessory) { + if (!empty($vehicle_type_extra_accessory->rate)) { + if (!empty($vehicle_type_extra_accessory->discount_type_id) && $vehicle_type_extra_accessory->discount_type_id == 1) { + $extra_accessory_amount = $amount * $vehicle_type_extra_accessory->rate / 100; + } else if (!empty($vehicle_type_extra_accessory->discount_type_id) && $vehicle_type_extra_accessory->discount_type_id == 2) { + $extra_accessory_amount = $vehicle_type_extra_accessory->rate; + } + if (!empty($vehicle_type_extra_accessory->duration_type_id) && $vehicle_type_extra_accessory->duration_type_id == 1) { + $extra_accessory_amount = $extra_accessory_amount * $no_of_days; + } + if (!empty($vehicle_type_extra_accessory->max_allowed_amount)) { + if ($extra_accessory_amount > $vehicle_type_extra_accessory->max_allowed_amount) { + $extra_accessory_amount = $vehicle_type_extra_accessory->max_allowed_amount; + } + } + } + $vehicle_rental_additional_data['item_user_id'] = $item_user_id; + $vehicle_rental_additional_data['amount'] = $extra_accessory_amount; + $vehicle_rental_additional_charge = VehicleRentalAdditionalCharge::create($vehicle_rental_additional_data); + $vehicle_extra_accessory = VehicleTypeExtraAccessory::with(['vehicle_rental_additional_charges'])->where('id', '=', $vehicle_type_extra_accessory->id)->first(); + $vehicle_extra_accessory->vehicle_rental_additional_charges()->save($vehicle_rental_additional_charge); + $res_amount = $res_amount + $extra_accessory_amount; + } + return $res_amount; + } + +} diff --git a/app/Plugins/VehicleExtraAccessories/Transformers/AdminVehicleExtraAccessoryTransformer.php b/app/Plugins/VehicleExtraAccessories/Transformers/AdminVehicleExtraAccessoryTransformer.php new file mode 100644 index 0000000..6ebee66 --- /dev/null +++ b/app/Plugins/VehicleExtraAccessories/Transformers/AdminVehicleExtraAccessoryTransformer.php @@ -0,0 +1,40 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleExtraAccessories\Transformers; + +use League\Fractal; +use Plugins\VehicleExtraAccessories\Model\VehicleExtraAccessory; + +/** + * Class VehicleExtraAccessoryTransformer + * @package VehicleExtraAccessories\Transformers + */ +class AdminVehicleExtraAccessoryTransformer extends Fractal\TransformerAbstract +{ + + /** + * @param VehicleExtraAccessory $vehicle_extra_accessory + * @return array + */ + public function transform(VehicleExtraAccessory $vehicle_extra_accessory) + { + $output = array_only($vehicle_extra_accessory->toArray(), ['id', 'created_at', 'name', 'short_description', 'description', 'is_active']); + $output['is_active'] = ($output['is_active']) ? true : false; + return $output; + } + + +} \ No newline at end of file diff --git a/app/Plugins/VehicleExtraAccessories/Transformers/VehicleExtraAccessoryTransformer.php b/app/Plugins/VehicleExtraAccessories/Transformers/VehicleExtraAccessoryTransformer.php new file mode 100644 index 0000000..7e79ffc --- /dev/null +++ b/app/Plugins/VehicleExtraAccessories/Transformers/VehicleExtraAccessoryTransformer.php @@ -0,0 +1,37 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleExtraAccessories\Transformers; + +use League\Fractal; +use Plugins\VehicleExtraAccessories\Model\VehicleExtraAccessory; +use Plugins\VehicleExtraAccessories\Model\VehicleTypeExtraAccessory; + +/** + * Class VehicleExtraAccessoryTransformer + * @package VehicleExtraAccessories\Transformers + */ +class VehicleExtraAccessoryTransformer extends Fractal\TransformerAbstract +{ + /** + * @param VehicleExtraAccessory $vehicle_extra_accessory + * @return array + */ + public function transform(VehicleExtraAccessory $vehicle_extra_accessory) + { + $output = array_only($vehicle_extra_accessory->toArray(), ['id', 'name', 'description']); + return $output; + } +} \ No newline at end of file diff --git a/app/Plugins/VehicleExtraAccessories/Transformers/VehicleTypeExtraAccessoryTransformer.php b/app/Plugins/VehicleExtraAccessories/Transformers/VehicleTypeExtraAccessoryTransformer.php new file mode 100644 index 0000000..2bd79bf --- /dev/null +++ b/app/Plugins/VehicleExtraAccessories/Transformers/VehicleTypeExtraAccessoryTransformer.php @@ -0,0 +1,104 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleExtraAccessories\Transformers; + +use App\Transformers\DiscountTypeTransformer; +use App\Transformers\DurationTypeTransformer; +use League\Fractal; +use Plugins\VehicleExtraAccessories\Model\VehicleTypeExtraAccessory; + +/** + * Class VehicleExtraAccessoryTransformer + * @package VehicleExtraAccessories\Transformers + */ +class VehicleTypeExtraAccessoryTransformer extends Fractal\TransformerAbstract +{ + /** + * List of resources possible to include + * + * @var array + */ + protected $availableIncludes = [ + 'VehicleExtraAccessory', 'VehicleType', 'DurationType', 'DiscountType' + ]; + + /** + * @param VehicleTypeExtraAccessory $vehicle_type_extra_accessory + * @return array + */ + public function transform(VehicleTypeExtraAccessory $vehicle_type_extra_accessory) + { + $output = array_only($vehicle_type_extra_accessory->toArray(), ['id', 'created_at', 'vehicle_type_id', 'extra_accessory_id', 'rate', 'discount_type_id', 'duration_type_id', 'max_allowed_amount', 'deposit_amount', 'is_active']); + $output['is_active'] = ($output['is_active']) ? true : false; + return $output; + } + + /** + * @param VehicleTypeExtraAccessory $vehicle_type_extra_accessory + * @return Fractal\Resource\Item|null + */ + public function includeVehicleExtraAccessory(VehicleTypeExtraAccessory $vehicle_type_extra_accessory) + { + if ($vehicle_type_extra_accessory->vehicle_extra_accessory) { + return $this->item($vehicle_type_extra_accessory->vehicle_extra_accessory, new VehicleExtraAccessoryTransformer()); + } else { + return null; + } + + } + + /** + * @param VehicleTypeExtraAccessory $vehicle_type_extra_accessory + * @return Fractal\Resource\Item|null + */ + public function includeVehicleType(VehicleTypeExtraAccessory $vehicle_type_extra_accessory) + { + if ($vehicle_type_extra_accessory->vehicle_type) { + return $this->item($vehicle_type_extra_accessory->vehicle_type, new \Plugins\Vehicles\Transformers\VehicleTypeTransformer()); + } else { + return null; + } + + } + + /** + * @param VehicleTypeExtraAccessory $vehicle_type_extra_accessory + * @return Fractal\Resource\Item|null + */ + public function includeDiscountType(VehicleTypeExtraAccessory $vehicle_type_extra_accessory) + { + if ($vehicle_type_extra_accessory->discount_type) { + return $this->item($vehicle_type_extra_accessory->discount_type, new DiscountTypeTransformer()); + } else { + return null; + } + + } + + /** + * @param VehicleTypeExtraAccessory $vehicle_type_extra_accessory + * @return Fractal\Resource\Item|null + */ + public function includeDurationType(VehicleTypeExtraAccessory $vehicle_type_extra_accessory) + { + if ($vehicle_type_extra_accessory->duration_type) { + return $this->item($vehicle_type_extra_accessory->duration_type, new DurationTypeTransformer()); + } else { + return null; + } + + } +} \ No newline at end of file diff --git a/app/Plugins/VehicleExtraAccessories/plugin.json b/app/Plugins/VehicleExtraAccessories/plugin.json new file mode 100644 index 0000000..71b4d30 --- /dev/null +++ b/app/Plugins/VehicleExtraAccessories/plugin.json @@ -0,0 +1,9 @@ +{ + "name": "VehicleExtraAccessories", + "class": "fa fa-2x fa-external-link-square", + "description": "By enabling this, item owner can manage extra_accessories based on vehicle types.", + "dependencies": "VehicleRentals", + "module_id": "", + "module_hash": "", + "display_order": "17" +} diff --git a/app/Plugins/VehicleExtraAccessories/routes.php b/app/Plugins/VehicleExtraAccessories/routes.php new file mode 100644 index 0000000..efa2e04 --- /dev/null +++ b/app/Plugins/VehicleExtraAccessories/routes.php @@ -0,0 +1,51 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +/* +|-------------------------------------------------------------------------- +| Application Routes +|-------------------------------------------------------------------------- +| +| Here is where you can register all of the routes for an application. +| It is a breeze. Simply tell Lumen the URIs it should respond to +| and give it the Closure to call when that URI is requested. +| +*/ +$api = $this->app->make('Dingo\Api\Routing\Router'); +$api->version(['v1'], function ($api) { + $api->group(['prefix' => 'admin', 'namespace' => 'Plugins\VehicleExtraAccessories\Controllers\Admin', 'middleware' => 'apitracking'], function () use ($api) { + // ExtraAccessories admin side + $api->get('vehicle_extra_accessories', 'AdminVehicleExtraAccessoriesController@index'); + $api->post('vehicle_extra_accessories', 'AdminVehicleExtraAccessoriesController@store'); + $api->put('vehicle_extra_accessories/{id}', 'AdminVehicleExtraAccessoriesController@update'); + $api->get('vehicle_extra_accessories/{id}/edit', 'AdminVehicleExtraAccessoriesController@edit'); + $api->get('vehicle_extra_accessories/{id}', 'AdminVehicleExtraAccessoriesController@show'); + $api->delete('vehicle_extra_accessories/{id}', 'AdminVehicleExtraAccessoriesController@destroy'); + + // Vehicle Type ExtraAccessories admin side + $api->get('vehicle_type_extra_accessories', 'AdminVehicleTypeExtraAccessoriesController@index'); + $api->post('vehicle_type_extra_accessories', 'AdminVehicleTypeExtraAccessoriesController@store'); + $api->put('vehicle_type_extra_accessories/{id}', 'AdminVehicleTypeExtraAccessoriesController@update'); + $api->get('vehicle_type_extra_accessories/{id}/edit', 'AdminVehicleTypeExtraAccessoriesController@edit'); + $api->get('vehicle_type_extra_accessories/{id}', 'AdminVehicleTypeExtraAccessoriesController@show'); + $api->delete('vehicle_type_extra_accessories/{id}', 'AdminVehicleTypeExtraAccessoriesController@destroy'); + + }); + $api->group(['namespace' => 'Plugins\VehicleExtraAccessories\Controllers', 'middleware' => 'apitracking'], function () use ($api) { + //extra_accessories user side + $api->get('vehicle_extra_accessories', 'VehicleExtraAccessoriesController@index'); + $api->get('vehicle_type_extra_accessories', 'VehicleTypeExtraAccessoriesController@index'); + }); +}); diff --git a/app/Plugins/VehicleFeedbacks/Controllers/Admin/AdminVehicleFeedbacksController.php b/app/Plugins/VehicleFeedbacks/Controllers/Admin/AdminVehicleFeedbacksController.php new file mode 100644 index 0000000..8953d76 --- /dev/null +++ b/app/Plugins/VehicleFeedbacks/Controllers/Admin/AdminVehicleFeedbacksController.php @@ -0,0 +1,170 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + + +namespace Plugins\VehicleFeedbacks\Controllers\Admin; + +use Illuminate\Http\Request; + +use App\Http\Controllers\Controller; +use JWTAuth; +use Validator; +use Plugins\VehicleFeedbacks\Model\VehicleFeedback; +use Plugins\VehicleFeedbacks\Transformers\VehicleFeedbackTransformer; +use Plugins\VehicleFeedbacks\Services\VehicleFeedbackService; +use DB; + +/** + * AdminVehicleFeedbacksController resource representation. + * @Resource("Admin/AdminVehicleFeedbacksController") + */ +class AdminVehicleFeedbacksController extends Controller +{ + /** + * @var vehicleService + */ + protected $vehicleFeedbackService; + + /** + * AdminVehicleFeedbacksController constructor. + */ + + public function __construct() + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth'); + // Check the logged user role. + $this->middleware('role'); + $this->setVehicleFeedbackService(); + } + + public function setVehicleFeedbackService() + { + $this->vehicleFeedbackService = new VehicleFeedbackService(); + } + + /** + * Show all vehicle feedbacks + * Get a JSON representation of all the vehicle feedbacks. + * + * @Get("/vehicle_feedbacks?sort={sort}&sortby={sortby}&page={page}&q={q}") + * @Parameters({ + * @Parameter("sort", type="string", required=false, description="Sort the vehicle feedbacks list by sort key.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort vehicle feedbacks by Ascending / Descending Order.", default=null), + * @Parameter("q", type="string", required=false, description="Search vehicle feedbacks.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1) + * }) + */ + public function index(Request $request) + { + $enabledIncludes = array('user', 'ip', 'to_user', 'vehicle_rental'); + $vehicle_feedbacks = VehicleFeedback::with($enabledIncludes) + ->select(DB::raw('feedbacks.*')) + ->leftJoin(DB::raw('(select id,username from users) as user'), 'user.id', '=', 'feedbacks.user_id') + ->leftJoin(DB::raw('(select id,username from users) as to_user'), 'to_user.id', '=', 'feedbacks.to_user_id') + ->leftJoin(DB::raw('(select id,name from vehicles) as feedbackable'), 'feedbackable.id', '=', 'feedbacks.feedbackable_id') + ->leftJoin(DB::raw('(select id,ip from ips) as ip'), 'ip.id', '=', 'feedbacks.ip_id') + ->filterByRequest($request)->paginate(config('constants.ConstPageLimit')); + $enabledIncludes = array_merge($enabledIncludes, array('feedbackable')); + return $this->response->paginator($vehicle_feedbacks, (new VehicleFeedbackTransformer)->setDefaultIncludes($enabledIncludes)); + } + + /** + * Edit the specified vehicle feedbacks. + * Edit the vehicle feedbacks with a `id`. + * @Get("vehicle_feedbacks/{id}/edit") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body= {"id": 1, "user_id": 1, "to_user_id":1, "feedbackable_id": 1, "feedbackable_type"=>"MorphVehicleRental", "item_id": 1, "feedback": "item feedback", "ip_id": 2, "rating": "1", "User": {}, "Item": {}, "item_user": {}}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function edit($id) + { + $enabledIncludes = array('user', 'to_user'); + $vehicle_feedback = VehicleFeedback::with($enabledIncludes)->find($id); + if (!$vehicle_feedback) { + return $this->response->errorNotFound("Invalid Request"); + } + $enabledIncludes = array_merge($enabledIncludes, array('feedbackable')); + return $this->response->item($vehicle_feedback, (new VehicleFeedbackTransformer)->setDefaultIncludes($enabledIncludes)); + } + + /** + * Update the specified vehicle feedbacks. + * Update the vehicle feedbacks with a `id`. + * @Put("vehicle_feedbacks/{id}") + * @Transaction({ + * @Request({"feedback": "item feedback","rating": "1"}), + * @Response(200, body={"success": "Feedback has been updated."}), + * @Response(422, body={"message": "Feedback could not be updated. Please, try again.", "errors": {"name": {}}, "status_code": 422}) + * }) + */ + public function update(Request $request, $id) + { + if ($request->has('id') && $request->id == $id) { + $vehicle_rental = null; + if ($request->has('dispute_closed_type_id') && $request->has('item_user_id')) { + $vehicle_rental = \Plugins\VehicleRentals\Model\VehicleRental::find($request->item_user_id); + } + $this->vehicleFeedbackService->feedBackUpdate($request, $id, $vehicle_rental); + return response()->json(['Success' => 'Feedback has been updated'], 200); + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Feedback could not be updated. Please, try again.'); + } + } + + /** + * Delete the specified vehicle feedbacks. + * Delete the vehicle feedbacks with a `id`. + * @Delete("vehicle_feedbacks/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"success": "Feedback Deleted."}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function destroy($id) + { + $vehicle_feedback = VehicleFeedback::find($id); + if (!$vehicle_feedback) { + return $this->response->errorNotFound("Invalid Request"); + } else { + $vehicle_feedback->delete(); + } + return response()->json(['Success' => 'Feedback deleted'], 200); + } + + /** + * Show the specified vehicle Feedback. + * Show the vehicle Feedback with a `id`. + * @Get("vehicle_feedbacks/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"id": 1, "user_id": 1, "to_user_id":1, "feedbackable_id": 1, "feedbackable_type"=>"MorphVehicleRental", "item_id": 1, "feedback": "item feedback", "ip_id": 2, "rating": "1", "User": {}, "Item": {}, "item_user": {}}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function show($id) + { + $enabledIncludes = array('user', 'to_user'); + $vehicle_feedback = VehicleFeedback::with($enabledIncludes)->find($id); + if (!$vehicle_feedback) { + return $this->response->errorNotFound("Invalid Request"); + } + $enabledIncludes = array_merge($enabledIncludes, array('feedbackable')); + return $this->response->item($vehicle_feedback, (new VehicleFeedbackTransformer)->setDefaultIncludes($enabledIncludes)); + } +} diff --git a/app/Plugins/VehicleFeedbacks/Controllers/VehicleFeedbacksController.php b/app/Plugins/VehicleFeedbacks/Controllers/VehicleFeedbacksController.php new file mode 100644 index 0000000..2606a1d --- /dev/null +++ b/app/Plugins/VehicleFeedbacks/Controllers/VehicleFeedbacksController.php @@ -0,0 +1,301 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleFeedbacks\Controllers; + +use Illuminate\Http\Request; + +use App\Http\Controllers\Controller; +use JWTAuth; +use Plugins\VehicleRentals\Services\VehicleRentalService; +use Validator; +use App\Services\IpService; +use Plugins\VehicleFeedbacks\Model\VehicleFeedback; +use Plugins\VehicleFeedbacks\Transformers\VehicleFeedbackTransformer; +use App\User; +use App\Services\MessageService; +use App\Services\UserService; +use Plugins\VehicleFeedbacks\Services\VehicleFeedbackService; +use Plugins\Vehicles\Services\VehicleService; + +/** + * VehicleFeedbacks resource representation. + * @Resource("VehicleFeedbacksController") + */ +class VehicleFeedbacksController extends Controller +{ + /** + * @var + */ + protected $vehicleFeedbackService; + /** + * @var + */ + protected $ip_service; + /** + * @var + */ + protected $messageService; + + /** + * @var + */ + protected $vehicleService; + + /** + * @var + */ + protected $userService; + + /** + * @var + */ + protected $vehicleRentalService; + + /** + * VehicleFeedbacksController constructor. + */ + public function __construct(UserService $userService) + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth', ['except' => ['index']]); + $this->setIpService(); + $this->setMessageService(); + $this->setVehicleFeedbackService(); + $this->setVehicleService(); + $this->setVehicleRentalService(); + $this->userService = $userService; + } + + /** Object created for ipservice */ + public function setIpService() + { + $this->IpService = new IpService(); + } + + /** Object created for messageservice*/ + public function setMessageService() + { + $this->messageService = new MessageService(); + } + + /** Object created for VehicleFeedback service */ + public function setVehicleFeedbackService() + { + $this->vehicleFeedbackService = new VehicleFeedbackService(); + } + + /** + * setVehicleService + */ + public function setVehicleService() + { + $this->vehicleService = new VehicleService(); + } + + /** + * setVehicleRentalService + */ + public function setVehicleRentalService() + { + $this->vehicleRentalService = new VehicleRentalService(); + } + + /** + * Show all vehicle feedbacks + * Get a JSON representation of all the vehicle feedbacks. + * + * @Get("/vehicle_feedbacks?sort={sort}&sortby={sortby}&page={page}&q={q}") + * @Parameters({ + * @Parameter("sort", type="string", required=false, description="Sort the vehicle feedbacks list by sort key.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort vehicle feedbacks by Ascending / Descending Order.", default=null), + * @Parameter("q", type="string", required=false, description="Search vehicle feedbacks.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1) + * }) + */ + public function index(Request $request) + { + $enabledIncludes = array('user', 'to_user'); + $feedbacks = VehicleFeedback::with($enabledIncludes)->filterByRequest($request)->paginate(config('constants.ConstPageLimit')); + $enabledIncludes = array_merge($enabledIncludes, array('feedbackable')); + return $this->response->paginator($feedbacks, (new VehicleFeedbackTransformer)->setDefaultIncludes($enabledIncludes)); + } + + /** + * Show the specified vehicle Feedback. + * Show the vehicle Feedback with a `id`. + * @Get("vehicle_feedbacks/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"id": 1, "user_id": 1, "to_user_id":1, "feedbackable_id": 1, "feedbackable_type"=>"MorphVehicleRental", "item_id": 1, "feedback": "item feedback", "ip_id": 2, "rating": "1", "User": {}, "Item": {}, "item_user": {}}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function show($id) + { + $enabledIncludes = array('user', 'to_user'); + $feedback = VehicleFeedback::with($enabledIncludes)->find($id); + if (!$feedback) { + return $this->response->errorNotFound("Invalid Request"); + } + $enabledIncludes = array_merge($enabledIncludes, array('feedbackable')); + return $this->response->item($feedback, (new VehicleFeedbackTransformer)->setDefaultIncludes($enabledIncludes)); + } + + /** + * Booker review + * @Get('booker/review') + * @Transaction({ + * @Request({"item_user_id": 1, "item_id":1, "feedback":"testing', "rating":"2"}), + * @Response(200, body={"success": "Feedback has been added."}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}), + * @Response(422, body={"message": "Feedback could not be added. Please, try again", "status_code": 422}), + * @Response(404, body={"message": "Unauthorized", "status_code": 404}) + * }) + */ + public function BookerReview(Request $request) + { + $feedback_data = $request->only('item_user_id', 'feedback', 'rating'); + $validator = Validator::make($feedback_data, VehicleFeedback::GetValidationRule(), VehicleFeedback::GetValidationMessage()); + $user = $this->auth->user(); + if ($validator->passes()) { + $vehicle_rental = \Plugins\VehicleRentals\Model\VehicleRental::find($request->item_user_id); + $item = $vehicle_rental->item_userable; + if (is_null($item)) { + return $this->response->errorNotFound("Invalid Request"); + } + //Check vehicle_rental status must be waiting for review + if ($vehicle_rental->item_user_status_id != config('constants.ConstItemUserStatus.WaitingForReview') && $vehicle_rental->item_user_status_id != config('constants.ConstItemUserStatus.HostReviewed')) { + return $this->response->errorNotFound("Invalid Request"); + } + //Check if item_id or item_user_id found or not + if (!$vehicle_rental || ($vehicle_rental->item_userable_id != $item->id) || ($user->id != $vehicle_rental->user_id) || ($vehicle_rental->item_userable_type != 'MorphVehicle')) { + return $this->response->errorNotFound("Invalid Request"); + } + $feedback_data['user_id'] = $user->id; + $feedback_data['to_user_id'] = $item->user_id; + $feedback_data['ip_id'] = $this->IpService->getIpId($request->ip()); + $feedback = VehicleFeedback::create($feedback_data); + $vehicle_feedback = \Plugins\Vehicles\Model\Vehicle::with(['vehicle_feedback'])->where('id', '=', $vehicle_rental->item_userable->id)->first(); + $feedback = $vehicle_feedback->vehicle_feedback()->save($feedback); + $payment_status = false; + if ($feedback) { + if ($vehicle_rental->item_user_status_id == config('constants.ConstItemUserStatus.WaitingForReview')) { + $vehicle_rental->item_user_status_id = config('constants.ConstItemUserStatus.BookerReviewed'); + $from_status = config('constants.ConstItemUserStatus.WaitingForReview'); + $to_status = config('constants.ConstItemUserStatus.BookerReviewed'); + } + if ($vehicle_rental->item_user_status_id == config('constants.ConstItemUserStatus.HostReviewed')) { + $vehicle_rental->item_user_status_id = config('constants.ConstItemUserStatus.WaitingForPaymentCleared'); + $from_status = config('constants.ConstItemUserStatus.HostReviewed'); + $to_status = config('constants.ConstItemUserStatus.BookerReviewed'); + $payment_status = true; + } + $vehicle_rental->save(); + $average_rating = VehicleFeedback::where(['feedbackable_id' => $vehicle_rental->item_userable->id, 'feedbackable_type' => 'MorphVehicle', 'is_host' => 0])->avg('rating'); + $this->vehicleService->updateFeedbackDetails($vehicle_feedback, $average_rating); + $message_content_arr = array(); + $message_content_arr['subject'] = 'Feedback'; + $message_content_arr['message'] = $user->username . ' has left a feedback on your item - ' . $feedback->feedback; + $this->vehicleFeedbackService->sendFeedbackMail($user->username, $item->user->username, $item->user->email, 'booker', $feedback->feedback); + $this->messageService->saveMessageContent($message_content_arr, $item->id, $vehicle_rental->id, $user->id, $item->user_id, config('constants.ConstItemUserStatus.BookerReviewed'), 'VehicleRental'); + $this->vehicleRentalService->changeStatusMail($vehicle_rental, $vehicle_rental->item_userable, $from_status, $to_status); + if ($payment_status) { + $this->vehicleRentalService->changeStatusMail($vehicle_rental, $vehicle_rental->item_userable, config('constants.ConstItemUserStatus.BookerReviewed'), config('constants.ConstItemUserStatus.WaitingForPaymentCleared')); + } + return response()->json(['Success' => 'Feedback has been added'], 200); + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Feedback could not be added. Please, try again.'); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Feedback could not be added. Please, try again.', $validator->errors()); + } + } + + /** + * Host review + * @Get('host/review') + * @Transaction({ + * @Request({"item_user_id": 1, "item_id":1, "feedback":"testing', "rating":"2"}), + * @Response(200, body={"success": "Feedback has been added."}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}), + * @Response(422, body={"message": "Feedback could not be added. Please, try again", "status_code": 422}), + * @Response(404, body={"message": "Unauthorized", "status_code": 404}) + * }) + */ + public function HostReview(Request $request) + { + $feedback_data = $request->only('item_user_id', 'feedback', 'rating'); + $validator = Validator::make($feedback_data, VehicleFeedback::GetValidationRule(), VehicleFeedback::GetValidationMessage()); + $user = $this->auth->user(); + //Check if user is authenticated + if (!$user) { + return $this->response->errorNotFound("Unauthorized"); + } + if ($validator->passes()) { + $vehicle_rental = \Plugins\VehicleRentals\Model\VehicleRental::find($request->item_user_id); + $item = $vehicle_rental->item_userable; + if (is_null($item)) { + return $this->response->errorNotFound("Invalid Request"); + } + //Check vehicle_rental status must be waiting for review + if ($vehicle_rental->item_user_status_id != config('constants.ConstItemUserStatus.WaitingForReview') && $vehicle_rental->item_user_status_id != config('constants.ConstItemUserStatus.BookerReviewed')) { + return $this->response->errorNotFound("Invalid Request"); + } + //Check if item_id or item_user_id found or not + if ((!$vehicle_rental) || ($vehicle_rental->item_userable_id != $item->id) || ($user->id != $item->user_id) || ($vehicle_rental->item_userable_type != 'MorphVehicle')) { + return $this->response->errorNotFound("Invalid Request"); + } + $feedback_data['is_host'] = true; + $feedback_data['user_id'] = $user->id; + $feedback_data['to_user_id'] = $vehicle_rental->user_id; + $feedback_data['ip_id'] = $this->IpService->getIpId($request->ip()); + $feedback = VehicleFeedback::create($feedback_data); + $user_feedback = User::with(['vehicle_feedback'])->where('id', '=', $vehicle_rental->user_id)->first(); + $feedback = $user_feedback->vehicle_feedback()->save($feedback); + $payment_status = false; + if ($feedback) { + if ($vehicle_rental->item_user_status_id == config('constants.ConstItemUserStatus.WaitingForReview')) { + $vehicle_rental->item_user_status_id = config('constants.ConstItemUserStatus.HostReviewed'); + $from_status = config('constants.ConstItemUserStatus.WaitingForReview'); + $to_status = config('constants.ConstItemUserStatus.HostReviewed'); + } + if ($vehicle_rental->item_user_status_id == config('constants.ConstItemUserStatus.BookerReviewed')) { + $vehicle_rental->item_user_status_id = config('constants.ConstItemUserStatus.WaitingForPaymentCleared'); + $from_status = config('constants.ConstItemUserStatus.BookerReviewed'); + $to_status = config('constants.ConstItemUserStatus.HostReviewed'); + $payment_status = true; + } + $vehicle_rental->save(); + $average_rating = VehicleFeedback::where(['feedbackable_id' => $vehicle_rental->user_id, 'feedbackable_type' => 'MorphUser', 'is_host' => 1])->avg('rating'); + $this->userService->updateFeedbackDetails($user_feedback, $average_rating); + $message_content_arr = array(); + $message_content_arr['subject'] = 'Feedback'; + $message_content_arr['message'] = $user->username . ' has left a feedback about you - ' . $feedback->feedback; + $this->vehicleFeedbackService->sendFeedbackMail($user->username, $vehicle_rental->user->username, $vehicle_rental->user->email, 'host', $feedback->feedback); + $this->messageService->saveMessageContent($message_content_arr, $item->id, $vehicle_rental->id, $user->id, $vehicle_rental->user_id, config('constants.ConstItemUserStatus.HostReviewed'), 'VehicleRental'); + $this->vehicleRentalService->changeStatusMail($vehicle_rental, $vehicle_rental->item_userable, $from_status, $to_status); + if ($payment_status) { + $this->vehicleRentalService->changeStatusMail($vehicle_rental, $vehicle_rental->item_userable, config('constants.ConstItemUserStatus.HostReviewed'), config('constants.ConstItemUserStatus.WaitingForPaymentCleared')); + } + return response()->json(['Success' => 'Feedback has been added'], 200); + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Feedback could not be added. Please, try again.'); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Feedback could not be added. Please, try again.', $validator->errors()); + } + } +} diff --git a/app/Plugins/VehicleFeedbacks/Model/VehicleFeedback.php b/app/Plugins/VehicleFeedbacks/Model/VehicleFeedback.php new file mode 100644 index 0000000..f1f42a8 --- /dev/null +++ b/app/Plugins/VehicleFeedbacks/Model/VehicleFeedback.php @@ -0,0 +1,117 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleFeedbacks\Model; + +use Illuminate\Http\Request; +use Illuminate\Database\Eloquent\Model; + +use App\User; +use App\Ip; + +class VehicleFeedback extends Model +{ + /** + * @var string + */ + protected $table = "feedbacks"; + + protected $fillable = [ + 'user_id', 'to_user_id', 'is_host', 'feedback', 'ip_id', 'rating', 'item_user_id' + ]; + + + /** + * @return \Illuminate\Database\Eloquent\Relations\HasMany + */ + public function ip() + { + return $this->belongsTo(Ip::class); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\MorphTo + */ + public function feedbackable() + { + return $this->morphTo(); + } + + public function user(){ + return $this->belongsTo(User::class, 'user_id'); + } + + public function vehicle_rental(){ + return $this->belongsTo(\Plugins\VehicleRentals\Model\VehicleRental::class, 'item_user_id'); + } + + public function to_user(){ + return $this->belongsTo(User::class, 'to_user_id'); + } + + /** + * @param $query + * @param Request $request + * @return mixed + */ + public function scopeFilterByRequest($query, Request $request) + { + $query->orderBy($request->input('sort', 'id'), $request->input('sortby', 'desc')); + if ($request->has('q')) { + $query->where('feedback', 'like', '%' . $request->input('q') . '%'); + $query->orWhere('user.username', 'like', '%' . $request->input('q') . '%'); + $query->orWhere('to_user.username', 'like', '%' . $request->input('q') . '%'); + $query->orWhere('feedbackable.name', 'like', '%' . $request->input('q') . '%'); + } + if ($request->input('filter') === 'feedback_to_host') { + $query->where('is_host', '=', false); + } else if ($request->input('filter') === 'feedback_to_booker') { + $query->where('is_host', '=', true); + } + if($request->has('user_id')){ + $query->where('feedbackable_type', 'MorphUser'); + $query->where('feedbackable_id', $request->user_id); + } + if($request->has('to_user_id')){ + $query->where('to_user_id', $request->to_user_id); + } + if($request->has('vehicle_id')){ + $query->where('feedbackable_type', 'MorphVehicle'); + $query->where('feedbackable_id', $request->vehicle_id); + } + if($request->has('type') && $request->type == 'vehicle') { + $query->where('feedbackable_type', 'MorphVehicle'); + } + return $query; + } + + /** + * @return array + */ + public function scopeGetValidationRule() + { + return [ + 'feedback' => 'sometimes|required|string' + ]; + } + + public function scopeGetValidationMessage() + { + return [ + 'feedback.required' => 'Required', + 'feedback.string' => 'Feedback must be a string', + ]; + } +} diff --git a/app/Plugins/VehicleFeedbacks/Providers/VehicleFeedbackServiceProvider.php b/app/Plugins/VehicleFeedbacks/Providers/VehicleFeedbackServiceProvider.php new file mode 100644 index 0000000..d90fddd --- /dev/null +++ b/app/Plugins/VehicleFeedbacks/Providers/VehicleFeedbackServiceProvider.php @@ -0,0 +1,51 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleFeedbacks\Providers; + +use Illuminate\Support\ServiceProvider; +use Illuminate\Database\Eloquent\Relations\Relation; +use App\User; +class VehicleFeedbackServiceProvider extends ServiceProvider +{ + /** + * Register any application services. + * + * @return void + */ + public function register() + { + include __DIR__ . '/../routes.php'; + $this->app->make('Plugins\VehicleFeedbacks\Controllers\Admin\AdminVehicleFeedbacksController'); + $this->app->make('Plugins\VehicleFeedbacks\Controllers\VehicleFeedbacksController'); + } + + /** + * Bootstrap the application services. + * + * @return void + */ + public function boot() + { + $morphRelations = array(); + $morphRelations['MorphUser'] = User::class; + if (isPluginEnabled('Vehicles')) { + $morphRelations['MorphVehicle'] = \Plugins\Vehicles\Model\Vehicle::class; + } + if (!empty($morphRelations)) { + Relation::morphMap($morphRelations); + } + } +} diff --git a/app/Plugins/VehicleFeedbacks/Services/VehicleFeedbackService.php b/app/Plugins/VehicleFeedbacks/Services/VehicleFeedbackService.php new file mode 100644 index 0000000..21c8ae6 --- /dev/null +++ b/app/Plugins/VehicleFeedbacks/Services/VehicleFeedbackService.php @@ -0,0 +1,142 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleFeedbacks\Services; + + +use App\Services\MailService; +use Plugins\VehicleFeedbacks\Model\VehicleFeedback; +use Carbon; +use Validator; + +class VehicleFeedbackService +{ + /** + * VehicleFeedbackService constructor. + */ + public function __construct() + { + $this->setMailService(); + } + + public function setMailService() + { + $this->mailService = new MailService(); + } + + /** + * get last Feedback record for admin dashboard + * @return mixed + */ + public function getLastFeedback() + { + $feedback_details = VehicleFeedback::select('created_at')->where('feedbackable_type', '=', 'MorphVehicle')->orderBy('created_at', 'desc')->first(); + return ($feedback_details) ? $feedback_details->created_at->diffForHumans() : '-'; + } + + /** + * @param $request + * @param string $type + * @return mixed + */ + public function getFeedbackCount($request, $type = 'filter') + { + if ($type == 'filter') { + $check_date = $this->getDateFilter($request); + $check_date = Carbon::parse($check_date)->format('Y-m-d'); + $booking_count = VehicleFeedback::where('created_at', '>=', $check_date)->count(); + } else { + $booking_count = VehicleFeedback::count(); + } + return $booking_count; + } + + /** + * get the date filter + * @return $check_date + */ + public function getDateFilter($request) + { + $check_date = Carbon::now()->subDays(7); + if ($request->has('filter')) { + if ($request->filter == 'lastDays') { + $check_date = Carbon::now()->subDays(7); + } else if ($request->filter == 'lastWeeks') { + $check_date = Carbon::now()->subWeeks(4); + } else if ($request->filter == 'lastMonths') { + $check_date = Carbon::now()->subMonths(3); + } else if ($request->filter == 'lastYears') { + $check_date = Carbon::now()->subYears(3); + } + } + return $check_date; + } + + public function sendFeedbackMail($from_user, $username, $email, $reviewer, $feedback) + { + $from = config('constants.ConstUserIds.Admin'); + if ($reviewer == 'host') { + $template = $this->mailService->getTemplate('Feedback to Booker'); + } + if ($reviewer == 'booker') { + $template = $this->mailService->getTemplate('Feedback to Host'); + } + $user_link = '' . $from_user . ''; + $emailFindReplace = array( + '##USERNAME##' => $username, + '##BOOKER##' => $from_user, + '##BOOKER_URL##' => $user_link, + '##HOST##' => $from_user, + '##HOST_URL##' => $user_link, + '##MESSAGE##' => $feedback + ); + $this->mailService->sendMail($template, $emailFindReplace, $email, $username); + } + + public function feedBackUpdate($request, $id, $vehicle_rental = null) + { + $vehicle_feedback_data = $request->only('feedback', 'rating'); + $validator = Validator::make($vehicle_feedback_data, VehicleFeedback::GetValidationRule(), VehicleFeedback::GetValidationMessage()); + $vehicle_feedback = false; + if ($request->has('id')) { + $vehicle_feedback = VehicleFeedback::find($id); + $vehicle_feedback = ($request->id != $id) ? false : $vehicle_feedback; + } else { + $vehicle_feedback = $vehicle_rental->vehicle_feedback[0]; + } + if ($validator->passes() && $vehicle_feedback) { + try { + $vehicle_feedback->update($vehicle_feedback_data); + if ($request->has('dispute_closed_type_id')) { + if (isPluginEnabled('VehicleRentals')) { + if (!$vehicle_rental) { + return $this->response->errorNotFound("Invalid Request"); + } + } + if (isPluginEnabled('VehicleDisputes')) { + $vehicle_dispute_data = $request->only('item_user_id', 'dispute_closed_type_id'); + $VehicleDisputeService = new \Plugins\VehicleDisputes\Services\VehicleDisputeService(); + $VehicleDisputeService->closeDispute($vehicle_dispute_data, $vehicle_rental, 0); + } + } + return response()->json(['Success' => 'Feedback has been updated'], 200); + } catch (\Exception $e) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Feedback could not be updated. Please, try again.'); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Feedback could not be updated. Please, try again.', $validator->errors()); + } + } +} diff --git a/app/Plugins/VehicleFeedbacks/Transformers/VehicleFeedbackTransformer.php b/app/Plugins/VehicleFeedbacks/Transformers/VehicleFeedbackTransformer.php new file mode 100644 index 0000000..fb71455 --- /dev/null +++ b/app/Plugins/VehicleFeedbacks/Transformers/VehicleFeedbackTransformer.php @@ -0,0 +1,113 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleFeedbacks\Transformers; + +use League\Fractal; +use Plugins\VehicleFeedbacks\Model\VehicleFeedback; +use App\Transformers\IpTransformer; + +/** + * Class VehicleFeedbackTransformer + * @package Plugins\VehicleFeedbacks\Transformers + */ +class VehicleFeedbackTransformer extends Fractal\TransformerAbstract +{ + /** + * @var array + */ + protected $availableIncludes = [ + 'User', 'Feedbackable', 'Ip', 'ToUser', 'VehicleRental' + ]; + + /** + * @param VehicleFeedback $vehicle_feedback + * @return array + */ + public function transform(VehicleFeedback $vehicle_feedback) + { + $output = array_only($vehicle_feedback->toArray(), ['id', 'created_at', 'item_id', 'user_id', 'to_user_id', 'feedbackable_id', 'feedbackable_type', 'feedback', 'ip_id', 'rating']); + return $output; + } + + /** + * @param VehicleFeedback $vehicle_feedback + * @return Fractal\Resource\Item|null + */ + public function includeUser(VehicleFeedback $vehicle_feedback) + { + if ($vehicle_feedback->user) { + return $this->item($vehicle_feedback->user, (new \App\Transformers\UserSimpleTransformer())->setDefaultIncludes(['attachmentable'])); + } else { + return null; + } + } + + /** + * @param VehicleFeedback $vehicle_feedback + * @return Fractal\Resource\Item|null + */ + public function includeToUser(VehicleFeedback $vehicle_feedback) + { + if ($vehicle_feedback->to_user) { + return $this->item($vehicle_feedback->to_user, (new \App\Transformers\UserSimpleTransformer())->setDefaultIncludes(['attachmentable'])); + } else { + return null; + } + } + + /** + * @param VehicleFeedback $vehicle_feedback + * @return Fractal\Resource\Item|null + */ + public function includeIp(VehicleFeedback $vehicle_feedback) + { + if ($vehicle_feedback->ip) { + return $this->item($vehicle_feedback->ip, new IpTransformer()); + } else { + return null; + } + } + + /** + * @param VehicleFeedback $vehicle_feedback + * @return Fractal\Resource\Item|null + */ + public function includeFeedbackable(VehicleFeedback $vehicle_feedback) + { + if ($vehicle_feedback->feedbackable) { + if ($vehicle_feedback->feedbackable_type == 'MorphVehicle') { + return $this->item($vehicle_feedback->feedbackable, (new \Plugins\Vehicles\Transformers\VehicleTransformer)->setDefaultIncludes(['user', 'vehicle_company', 'vehicle_make', 'vehicle_model'])); + } elseif ($vehicle_feedback->feedbackable_type == 'MorphUser') { + return $this->item($vehicle_feedback->feedbackable, (new \App\Transformers\UserSimpleFeedbackTransformer)); + } + } else { + return null; + } + } + + /** + * @param VehicleFeedback $vehicle_feedback + * @return Fractal\Resource\Item|null + */ + public function includeVehicleRental(VehicleFeedback $vehicle_feedback) + { + if ($vehicle_feedback->vehicle_rental) { + return $this->item($vehicle_feedback->vehicle_rental, (new \Plugins\VehicleRentals\Transformers\VehicleRentalTransformer())->setDefaultIncludes(['item_userable'])); + } else { + return null; + } + } +} \ No newline at end of file diff --git a/app/Plugins/VehicleFeedbacks/plugin.json b/app/Plugins/VehicleFeedbacks/plugin.json new file mode 100644 index 0000000..6085804 --- /dev/null +++ b/app/Plugins/VehicleFeedbacks/plugin.json @@ -0,0 +1,9 @@ +{ + "name": "VehicleFeedbacks", + "class": "fa fa-2x fa-thumbs-up", + "description": "By enabling this plugin, vehicle feedback to be added for items", + "dependencies": "VehicleRentals", + "module_id": "", + "module_hash": "", + "display_order": "13" +} diff --git a/app/Plugins/VehicleFeedbacks/routes.php b/app/Plugins/VehicleFeedbacks/routes.php new file mode 100644 index 0000000..979fd35 --- /dev/null +++ b/app/Plugins/VehicleFeedbacks/routes.php @@ -0,0 +1,44 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +/* +|-------------------------------------------------------------------------- +| Application Routes +|-------------------------------------------------------------------------- +| +| Here is where you can register all of the routes for an application. +| It is a breeze. Simply tell Lumen the URIs it should respond to +| and give it the Closure to call when that URI is requested. +| +*/ +$api = $this->app->make('Dingo\Api\Routing\Router'); +$api->version(['v1'], function ($api) { + $api->group(['prefix' => 'admin', 'namespace' => 'Plugins\VehicleFeedbacks\Controllers\Admin', 'middleware' => 'apitracking'], function () use ($api) { + // Vehicle feedbacks admin side + $api->get('vehicle_feedbacks', 'AdminVehicleFeedbacksController@index'); + $api->put('vehicle_feedbacks/{id}', 'AdminVehicleFeedbacksController@update'); + $api->get('vehicle_feedbacks/{id}/edit', 'AdminVehicleFeedbacksController@edit'); + $api->get('vehicle_feedbacks/{id}', 'AdminVehicleFeedbacksController@show'); + $api->delete('vehicle_feedbacks/{id}', 'AdminVehicleFeedbacksController@destroy'); + + }); + $api->group(['namespace' => 'Plugins\VehicleFeedbacks\Controllers', 'middleware' => 'apitracking'], function () use ($api) { + //Vehicle feedbacks user side + $api->get('vehicle_feedbacks', 'VehicleFeedbacksController@index'); + $api->get('vehicle_feedbacks/{id}', 'VehicleFeedbacksController@show'); + $api->post('booker/review', 'VehicleFeedbacksController@BookerReview'); + $api->post('host/review', 'VehicleFeedbacksController@HostReview'); + }); +}); diff --git a/app/Plugins/VehicleFuelOptions/Controllers/Admin/AdminVehicleFuelOptionsController.php b/app/Plugins/VehicleFuelOptions/Controllers/Admin/AdminVehicleFuelOptionsController.php new file mode 100644 index 0000000..209f352 --- /dev/null +++ b/app/Plugins/VehicleFuelOptions/Controllers/Admin/AdminVehicleFuelOptionsController.php @@ -0,0 +1,190 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleFuelOptions\Controllers\Admin; + +use Illuminate\Http\Request; +use App\Http\Controllers\Controller; +use Plugins\VehicleFuelOptions\Model\VehicleFuelOption; +use JWTAuth; +use Validator; +use Tymon\JWTAuth\Exceptions\JWTException; +use Plugins\VehicleFuelOptions\Transformers\AdminVehicleFuelOptionTransformer; +use Plugins\VehicleFuelOptions\Transformers\VehicleFuelOptionTransformer; +use EasySlug\EasySlug\EasySlugFacade as EasySlug; + +/** + * VehicleFuelOptions resource representation. + * @Resource("Admin/AdminVehicleFuelOptions") + */ +class AdminVehicleFuelOptionsController extends Controller +{ + /** + * AdminVehicleFuelOptionsController constructor. + */ + public function __construct() + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth'); + // Check the logged user role. + $this->middleware('role'); + } + + /** + * Show all vehicle_fuel_options + * Get a JSON representation of all the vehicle_fuel_options. + * + * @Get("/admin/vehicle_fuel_options?sort={sort}&sortby={sortby}&page={page}&q={q}") + * @Parameters({ + * @Parameter("sort", type="string", required=false, description="Sort the vehicle_fuel_options list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort vehicle_fuel_options by Ascending / Descending Order.", default=null), + * @Parameter("q", type="string", required=false, description="Search VehicleFuelOptions.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1) + * }) + */ + public function index(Request $request) + { + if($request->has('limit') && $request->limit == 'all') { + $vehicle_fuel_option_count = VehicleFuelOption::count(); + $vehicle_fuel_options = VehicleFuelOption::filterByActiveRecord($request)->filterByRequest($request)->select('id', 'name')->paginate($vehicle_fuel_option_count); + return $this->response->paginator($vehicle_fuel_options, new VehicleFuelOptionTransformer); + } else { + $vehicle_fuel_options = VehicleFuelOption::filterByRequest($request)->paginate(config('constants.ConstPageLimit')); + return $this->response->paginator($vehicle_fuel_options, new AdminVehicleFuelOptionTransformer); + } + } + + /** + * Edit the specified vehicle_fuel_option. + * Edit the vehicle_fuel_option with a `id`. + * @Get("/admin/vehicle_fuel_options/{id}/edit") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body= {"id": 1, "name": "Service FuelOption", "short_description": "The costs of service needed to support our business operations have escalated considerably.", "description": "The costs of service needed to support our business operations have escalated considerably. To offset the increasing costs of utilities, bus fuel, oil and grease, etc.,"}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function edit($id) + { + $vehicle_fuel_option = VehicleFuelOption::find($id); + if (!$vehicle_fuel_option) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($vehicle_fuel_option, (new AdminVehicleFuelOptionTransformer)); + } + + /** + * Show the specified vehicle_fuel_option. + * Show the vehicle_fuel_option with a `id`. + * @Get("/admin/vehicle_fuel_options/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body= {"id": 1, "name": "Service FuelOption", "short_description": "The costs of service needed to support our business operations have escalated considerably.", "description": "The costs of service needed to support our business operations have escalated considerably. To offset the increasing costs of utilities, bus fuel, oil and grease, etc.,"}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function show($id) + { + $vehicle_fuel_option = VehicleFuelOption::find($id); + if (!$vehicle_fuel_option) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($vehicle_fuel_option, (new AdminVehicleFuelOptionTransformer)); + } + + /** + * Store a new vehicle_fuel_option. + * Store a new vehicle_fuel_option with a `name`, `short_description`, and `description`. + * @Post("/admin/vehicle_fuel_options") + * @Transaction({ + * @Request({"name": "Service FuelOption", "short_description": "The costs of service needed to support our business operations have escalated considerably.", "description": "The costs of service needed to support our business operations have escalated considerably. To offset the increasing costs of utilities, bus fuel, oil and grease, etc.,"}), + * @Response(200, body={"success": "Record has been added."}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {"name": {}}, "status_code": 422}) + * }) + */ + public function store(Request $request) + { + $vehicle_fuel_option_data = $request->only('name', 'short_description', 'description'); + $validator = Validator::make($vehicle_fuel_option_data, VehicleFuelOption::GetValidationRule(), VehicleFuelOption::GetValidationMessage()); + $vehicle_fuel_option_data['slug'] = EasySlug::generateUniqueSlug($request->name, 'fuel_options'); + if ($validator->passes()) { + $vehicle_fuel_option_data['is_active'] = true; + $vehicle_fuel_option = VehicleFuelOption::create($vehicle_fuel_option_data); + if ($vehicle_fuel_option) { + return response()->json(['Success' => 'VehicleFuelOption has been added'], 200); + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('VehicleFuelOption could not be updated. Please, try again.'); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('VehicleFuelOption could not be updated. Please, try again.', $validator->errors()); + } + } + + + /** + * Update the specified vehicle_fuel_option + * Update the vehicle_fuel_option with a `id`. + * @Put("/admin/vehicle_fuel_options/{id}") + * @Transaction({ + * @Request({"id": 1, "name": "Energy FuelOption", "short_description": "The costs of energy needed to support our business operations have escalated considerably.", "description": "The costs of energy needed to support our business operations have escalated considerably. To offset the increasing costs of utilities, bus fuel, oil and grease, etc.,", "is_active": 1}), + * @Response(200, body={"success": "Record has been updated."}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {"name": {}}, "status_code": 422}) + * }) + */ + public function update(Request $request, $id) + { + $vehicle_fuel_option_data = $request->only('name', 'short_description', 'description', 'is_active'); + $validator = Validator::make($vehicle_fuel_option_data, VehicleFuelOption::GetValidationRule(), VehicleFuelOption::GetValidationMessage()); + $vehicle_fuel_option = false; + if ($request->has('id')) { + $vehicle_fuel_option = VehicleFuelOption::find($id); + $vehicle_fuel_option = ($request->id != $id) ? false : $vehicle_fuel_option; + if ($vehicle_fuel_option->name !== $request->name) { + $vehicle_fuel_option_data['slug'] = EasySlug::generateUniqueSlug($request->name, 'fuel_options'); + } + } + if ($validator->passes() && $vehicle_fuel_option) { + try { + $vehicle_fuel_option->update($vehicle_fuel_option_data); + return response()->json(['Success' => 'VehicleFuelOption has been updated'], 200); + } catch (\Exception $e) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('VehicleFuelOption could not be updated. Please, try again.'); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('VehicleFuelOption could not be updated. Please, try again.', $validator->errors()); + } + } + + /** + * Delete the specified vehicle_fuel_option. + * Delete the vehicle_fuel_option with a `id`. + * @Delete("/admin/vehicle_fuel_options/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"success": "Record Deleted."}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function destroy($id) + { + $vehicle_fuel_option = VehicleFuelOption::find($id); + if (!$vehicle_fuel_option) { + return $this->response->errorNotFound("Invalid Request"); + } else { + $vehicle_fuel_option->delete(); + } + return response()->json(['Success' => 'VehicleFuelOption deleted'], 200); + } +} diff --git a/app/Plugins/VehicleFuelOptions/Controllers/Admin/AdminVehicleTypeFuelOptionsController.php b/app/Plugins/VehicleFuelOptions/Controllers/Admin/AdminVehicleTypeFuelOptionsController.php new file mode 100644 index 0000000..00a1a49 --- /dev/null +++ b/app/Plugins/VehicleFuelOptions/Controllers/Admin/AdminVehicleTypeFuelOptionsController.php @@ -0,0 +1,187 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleFuelOptions\Controllers\Admin; + +use Illuminate\Http\Request; +use App\Http\Requests; +use App\Http\Controllers\Controller; +use Plugins\VehicleFuelOptions\Model\VehicleTypeFuelOption; +use JWTAuth; +use Validator; +use Plugins\VehicleFuelOptions\Transformers\VehicleTypeFuelOptionTransformer; +use DB; +/** + * VehicleTypeFuelOptions resource representation. + * @Resource("Admin/AdminVehicleTypeFuelOptions") + */ +class AdminVehicleTypeFuelOptionsController extends Controller +{ + /** + * AdminVehicleTypeFuelOptionsController constructor. + */ + public function __construct() + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth'); + // Check the logged user role. + $this->middleware('role'); + } + + /** + * Show all vehicle_type_fuel_options + * Get a JSON representation of all the vehicle_type_fuel_options. + * + * @Get("/admin/vehicle_type_fuel_options?sort={sort}&sortby={sortby}&page={page}&q={q}") + * @Parameters({ + * @Parameter("sort", type="string", required=false, description="Sort the vehicle_type_fuel_options list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort vehicle_type_fuel_options by Ascending / Descending Order.", default=null), + * @Parameter("q", type="string", required=false, description="Search VehicleTypeFuelOptions.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1) + * }) + */ + public function index(Request $request) + { + $enabled_includes = array('vehicle_fuel_option', 'discount_type', 'duration_type', 'vehicle_type'); + $vehicle_type_fuel_options = VehicleTypeFuelOption::with($enabled_includes) + ->select(DB::raw('vehicle_type_fuel_options.*')) + ->leftJoin(DB::raw('(select id,name from vehicle_types) as vehicle_type'), 'vehicle_type.id', '=', 'vehicle_type_fuel_options.vehicle_type_id') + ->leftJoin(DB::raw('(select id,name from fuel_options) as vehicle_fuel_option'), 'vehicle_fuel_option.id', '=', 'vehicle_type_fuel_options.fuel_option_id') + ->leftJoin(DB::raw('(select id,type from discount_types) as discount_type'), 'discount_type.id', '=', 'vehicle_type_fuel_options.discount_type_id') + ->leftJoin(DB::raw('(select id,name from duration_types) as duration_type'), 'duration_type.id', '=', 'vehicle_type_fuel_options.duration_type_id') + ->filterByRequest($request)->paginate(config('constants.ConstPageLimit')); + return $this->response->paginator($vehicle_type_fuel_options, (new VehicleTypeFuelOptionTransformer)->setDefaultIncludes($enabled_includes)); + } + + /** + * Edit the specified vehicle_type_fuel_option. + * Edit the vehicle_type_fuel_option with a `id`. + * @Get("/admin/vehicle_type_fuel_options/{id}/edit") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body= {"id": 1, "vehicle_type_id": 1, "fuel_option_id": 1, "discount_type_id": 1, "duration_type_id": 1, "rate": 200, "max_allowed_amount": 1000, "vehicle_type": {}, "vehicle_fuel_option": {}, "duration_type": {}, "discount_type": {}}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function edit($id) + { + $enabled_includes = array('vehicle_fuel_option', 'discount_type', 'duration_type', 'vehicle_type'); + $vehicle_type_fuel_option = VehicleTypeFuelOption::with($enabled_includes)->find($id); + if (!$vehicle_type_fuel_option) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($vehicle_type_fuel_option, (new VehicleTypeFuelOptionTransformer)->setDefaultIncludes($enabled_includes)); + } + + /** + * Show the specified vehicle_type_fuel_option. + * Show the vehicle_type_fuel_option with a `id`. + * @Get("/admin/vehicle_type_fuel_options/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body= {"id": 1, "vehicle_type_id": 1, "fuel_option_id": 1, "discount_type_id": 1, "duration_type_id": 1, "rate": 200, "max_allowed_amount": 1000, "vehicle_type": {}, "vehicle_fuel_option": {}, "duration_type": {}, "discount_type": {}}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function show($id) + { + $enabled_includes = array('vehicle_fuel_option', 'discount_type', 'duration_type', 'vehicle_type'); + $vehicle_type_fuel_option = VehicleTypeFuelOption::with($enabled_includes)->find($id); + if (!$vehicle_type_fuel_option) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($vehicle_type_fuel_option, (new VehicleTypeFuelOptionTransformer)->setDefaultIncludes($enabled_includes)); + } + + /** + * Store a new vehicle_type_fuel_option. + * Store a new vehicle_type_fuel_option with a `name`, `short_description`, and `description`. + * @Post("/admin/vehicle_type_fuel_options") + * @Transaction({ + * @Request({"vehicle_type_id": 1, "fuel_option_id": 1, "discount_type_id": 1, "duration_type_id": 1, "rate": 200, "max_allowed_amount": 1000}), + * @Response(200, body={"success": "Record has been added."}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {"name": {}}, "status_code": 422}) + * }) + */ + public function store(Request $request) + { + $vehicle_type_fuel_option_data = $request->only('vehicle_type_id', 'fuel_option_id', 'rate', 'discount_type_id', 'duration_type_id', 'max_allowed_amount'); + $validator = Validator::make($vehicle_type_fuel_option_data, VehicleTypeFuelOption::GetValidationRule(), VehicleTypeFuelOption::GetValidationMessage()); + if ($validator->passes()) { + $vehicle_type_fuel_option_data['is_active'] = true; + $vehicle_type_fuel_option = VehicleTypeFuelOption::create($vehicle_type_fuel_option_data); + if ($vehicle_type_fuel_option) { + return response()->json(['Success' => 'VehicleTypeFuelOption has been added'], 200); + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('VehicleTypeFuelOption could not be added. Please, try again.'); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('VehicleTypeFuelOption could not be added. Please, try again.', $validator->errors()); + } + } + + + /** + * Update the specified vehicle_type_fuel_option + * Update the vehicle_type_fuel_option with a `id`. + * @Put("/admin/vehicle_type_fuel_options/{id}") + * @Transaction({ + * @Request({"id": 1, "vehicle_type_id": 1, "fuel_option_id": 1, "discount_type_id": 1, "duration_type_id": 1, "rate": 200, "max_allowed_amount": 1000}), + * @Response(200, body={"success": "Record has been updated."}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {"name": {}}, "status_code": 422}) + * }) + */ + public function update(Request $request, $id) + { + $vehicle_type_fuel_option_data = $request->only('vehicle_type_id', 'fuel_option_id', 'rate', 'discount_type_id', 'duration_type_id', 'max_allowed_amount', 'is_active'); + $validator = Validator::make($vehicle_type_fuel_option_data, VehicleTypeFuelOption::GetValidationRule(), VehicleTypeFuelOption::GetValidationMessage()); + $vehicle_type_fuel_option = false; + if ($request->has('id')) { + $vehicle_type_fuel_option = VehicleTypeFuelOption::find($id); + $vehicle_type_fuel_option = ($request->id != $id) ? false : $vehicle_type_fuel_option; + } + if ($validator->passes() && $vehicle_type_fuel_option) { + try { + $vehicle_type_fuel_option->update($vehicle_type_fuel_option_data); + return response()->json(['Success' => 'VehicleTypeFuelOption has been updated'], 200); + } catch (\Exception $e) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('VehicleTypeFuelOption could not be updated. Please, try again.'); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('VehicleTypeFuelOption could not be updated. Please, try again.', $validator->errors()); + } + } + + /** + * Delete the specified vehicle_type_fuel_option. + * Delete the vehicle_type_fuel_option with a `id`. + * @Delete("/admin/vehicle_type_fuel_options/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"success": "Record Deleted."}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function destroy($id) + { + $vehicle_type_fuel_option = VehicleTypeFuelOption::find($id); + if (!$vehicle_type_fuel_option) { + return $this->response->errorNotFound("Invalid Request"); + } else { + $vehicle_type_fuel_option->delete(); + } + return response()->json(['Success' => 'VehicleTypeFuelOption deleted'], 200); + } +} diff --git a/app/Plugins/VehicleFuelOptions/Controllers/VehicleFuelOptionsController.php b/app/Plugins/VehicleFuelOptions/Controllers/VehicleFuelOptionsController.php new file mode 100644 index 0000000..0e63849 --- /dev/null +++ b/app/Plugins/VehicleFuelOptions/Controllers/VehicleFuelOptionsController.php @@ -0,0 +1,58 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleFuelOptions\Controllers; + +use Illuminate\Http\Request; +use App\Http\Controllers\Controller; +use Plugins\VehicleFuelOptions\Model\VehicleFuelOption; +use JWTAuth; +use Validator; +use Tymon\JWTAuth\Exceptions\JWTException; +use Plugins\VehicleFuelOptions\Transformers\VehicleFuelOptionTransformer; + +/** + * VehicleFuelOptions resource representation. + * @Resource("VehicleFuelOptions") + */ +class VehicleFuelOptionsController extends Controller +{ + /** + * VehicleFuelOptionsController constructor. + */ + public function __construct() + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth'); + } + + /** + * Show all fuel_options + * Get a JSON representation of all the fuel_options. + * + * @Get("/vehicle_fuel_options?sort={sort}&sortby={sortby}&page={page}&q={q}") + * @Parameters({ + * @Parameter("sort", type="string", required=false, description="Sort the fuel_options list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort fuel_options by Ascending / Descending Order.", default=null), + * @Parameter("q", type="string", required=false, description="Search VehicleFuelOptions.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1) + * }) + */ + public function index(Request $request) + { + $fuel_options = VehicleFuelOption::filterByRequest($request)->paginate(config('constants.ConstPageLimit')); + return $this->response->paginator($fuel_options, (new VehicleFuelOptionTransformer)); + } +} diff --git a/app/Plugins/VehicleFuelOptions/Controllers/VehicleTypeFuelOptionsController.php b/app/Plugins/VehicleFuelOptions/Controllers/VehicleTypeFuelOptionsController.php new file mode 100644 index 0000000..feeb914 --- /dev/null +++ b/app/Plugins/VehicleFuelOptions/Controllers/VehicleTypeFuelOptionsController.php @@ -0,0 +1,59 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleFuelOptions\Controllers; + +use Illuminate\Http\Request; +use App\Http\Controllers\Controller; +use Plugins\VehicleFuelOptions\Model\VehicleTypeFuelOption; +use JWTAuth; +use Validator; +use Tymon\JWTAuth\Exceptions\JWTException; +use Plugins\VehicleFuelOptions\Transformers\VehicleTypeFuelOptionTransformer; + +/** + * VehicleFuelOptions resource representation. + * @Resource("VehicleFuelOptions") + */ +class VehicleTypeFuelOptionsController extends Controller +{ + /** + * VehicleFuelOptionsController constructor. + */ + public function __construct() + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth'); + } + + /** + * Show all fuel_options + * Get a JSON representation of all the fuel_options. + * + * @Get("/vehicle_fuel_options?sort={sort}&sortby={sortby}&page={page}&q={q}") + * @Parameters({ + * @Parameter("sort", type="string", required=false, description="Sort the fuel_options list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort fuel_options by Ascending / Descending Order.", default=null), + * @Parameter("q", type="string", required=false, description="Search VehicleFuelOptions.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1) + * }) + */ + public function index(Request $request) + { + $enabled_includes = array('vehicle_fuel_option', 'discount_type', 'duration_type', 'vehicle_type'); + $vehicle_type_fuel_options = VehicleTypeFuelOption::with($enabled_includes)->filterByRequest($request)->paginate(config('constants.ConstPageLimit')); + return $this->response->paginator($vehicle_type_fuel_options, (new VehicleTypeFuelOptionTransformer)->setDefaultIncludes($enabled_includes)); + } +} diff --git a/app/Plugins/VehicleFuelOptions/Model/VehicleFuelOption.php b/app/Plugins/VehicleFuelOptions/Model/VehicleFuelOption.php new file mode 100644 index 0000000..2c625a8 --- /dev/null +++ b/app/Plugins/VehicleFuelOptions/Model/VehicleFuelOption.php @@ -0,0 +1,101 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleFuelOptions\Model; + +use Illuminate\Http\Request; +use Illuminate\Database\Eloquent\Model; + +class VehicleFuelOption extends Model +{ + /** + * @var string + */ + protected $table = "fuel_options"; + + protected $fillable = [ + 'name', 'short_description', 'description', 'is_active', 'slug' + ]; + + + /** + * @return \Illuminate\Database\Eloquent\Relations\HasMany + */ + public function vehicle_type_fuel_option() + { + return $this->hasMany(VehicleTypeFuelOption::class); + } + /** + * @param $query + * @param Request $request + */ + public function scopeFilterByActiveRecord($query, Request $request) + { + $query->where('is_active', '=', 1); + } + /** + * @param $query + * @param Request $request + * @return mixed + */ + public function scopeFilterByRequest($query, Request $request) + { + $query->orderBy($request->input('sort', 'id'), $request->input('sortby', 'asc')); + if ($request->has('q')) { + $query->where('name', 'LIKE', '%' . $request->input('q') . '%') + ->orWhere('short_description', 'LIKE', '%' . $request->input('q') . '%') + ->orWhere('description', 'LIKE', '%' . $request->input('q') . '%'); + } + if ($request->has('filter')) { + $filter = false; + if ($request->input('filter') == 'active') { + $filter = true; + } + $query->where('is_active', '=', $filter); + } + return $query; + } + + /** + * @return array + */ + public function scopeGetValidationRule() + { + return [ + 'name' => 'required|min:5', + 'short_description' => 'required|min:10', + 'description' => 'required|min:15', + 'is_active' => 'sometimes|required|boolean' + ]; + } + + /** + * @return array + */ + public function scopeGetValidationMessage() + { + return [ + 'name.required' => 'Required', + 'name.min' => 'name - Minimum length is 5', + 'short_description.required' => 'Required', + 'short_description.min' => 'Short Description - Minimum length is 10', + 'description.required' => 'Required', + 'description.min' => 'Description - Minimum length is 15', + 'is_active.required' => 'Required', + 'is_active.boolean' => 'Possible values to be entered is 0 or 1' + ]; + } + +} diff --git a/app/Plugins/VehicleFuelOptions/Model/VehicleTypeFuelOption.php b/app/Plugins/VehicleFuelOptions/Model/VehicleTypeFuelOption.php new file mode 100644 index 0000000..bd1bdc2 --- /dev/null +++ b/app/Plugins/VehicleFuelOptions/Model/VehicleTypeFuelOption.php @@ -0,0 +1,152 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleFuelOptions\Model; + +use Illuminate\Http\Request; +use Illuminate\Database\Eloquent\Model; +use Illuminate\Support\Facades\App; +use App\DiscountType; +use App\DurationType; + +class VehicleTypeFuelOption extends Model +{ + /** + * @var string + */ + protected $table = "vehicle_type_fuel_options"; + + protected $fillable = [ + 'vehicle_type_id', 'fuel_option_id', 'rate', 'discount_type_id', 'duration_type_id', 'max_allowed_amount', 'is_active' + ]; + + + /** + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function vehicle_fuel_option() + { + return $this->belongsTo(VehicleFuelOption::class, 'fuel_option_id'); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function vehicle_type() + { + return $this->belongsTo(\Plugins\Vehicles\Model\VehicleType::class); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function discount_type() + { + return $this->belongsTo(DiscountType::class); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function duration_type() + { + return $this->belongsTo(DurationType::class); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\MorphMany + */ + public function vehicle_rental_additional_charges() + { + return $this->morphMany(\Plugins\VehicleRentals\Model\VehicleRentalAdditionalCharge::class, 'item_user_additional_chargable'); + } + + /** + * @param $query + * @param Request $request + * @return mixed + */ + public function scopeFilterByRequest($query, Request $request) + { + $query->orderBy($request->input('sort', 'id'), $request->input('sortby', 'asc')); + if ($request->has('q')) { + $query->WhereHas('vehicle_fuel_option', function ($q) use ($request) { + $q->where('name', 'like', '%' . $request->input('q') . '%'); + }); + $query->orWhereHas('vehicle_type', function ($q) use ($request) { + $q->where('name', 'like', '%' . $request->input('q') . '%'); + }); + $query->orWhereHas('discount_type', function ($q) use ($request) { + $q->where('type', 'like', '%' . $request->input('q') . '%'); + }); + $query->orWhereHas('duration_type', function ($q) use ($request) { + $q->where('name', 'like', '%' . $request->input('q') . '%'); + }); + } + if ($request->has('fuel_option_id')) { + $query->where('fuel_option_id', '=', $request->fuel_option_id); + } + if ($request->has('filter')) { + $filter = false; + if ($request->filter == 'active') { + $filter = true; + } + $query->where('is_active', '=', $filter); + } + + return $query; + } + + /** + * @return array + */ + public function scopeGetValidationRule() + { + return [ + 'vehicle_type_id' => 'required|integer|exists:vehicle_types,id', + 'fuel_option_id' => 'required|integer|exists:fuel_options,id', + 'rate' => 'required|numeric', + 'discount_type_id' => 'required|integer|exists:discount_types,id', + 'duration_type_id' => 'required|integer|exists:duration_types,id', + 'max_allowed_amount' => 'required|numeric' + ]; + } + + /** + * @return array + */ + public function scopeGetValidationMessage() + { + return [ + 'vehicle_type_id.required' => 'Required', + 'vehicle_type_id.integer' => 'Vehicle Type Id must be integer', + 'vehicle_type_id.exists' => 'Invalid vehicle type id', + 'fuel_option_id.required' => 'Required', + 'fuel_option_id.integer' => 'Fuel option Id must be integer', + 'fuel_option_id.exists' => 'Invalid fuel option id', + 'rate.required' => 'Required', + 'rate.numeric' => 'Rate must be numeric', + 'discount_type_id.required' => 'Required', + 'discount_type_id.integer' => 'Discount Type Id must be integer', + 'discount_type_id.exists' => 'Invalid discount type id', + 'duration_type_id.required' => 'Required', + 'duration_type_id.integer' => 'Duration Type Id must be integer', + 'discount_type_id.exists' => 'Invalid duration type id', + 'max_allowed_amount.required' => 'Required', + 'max_allowed_amount.numeric' => 'Max allowed amount must be numeric' + ]; + } + +} diff --git a/app/Plugins/VehicleFuelOptions/Providers/VehicleFuelOptionServiceProvider.php b/app/Plugins/VehicleFuelOptions/Providers/VehicleFuelOptionServiceProvider.php new file mode 100644 index 0000000..918c564 --- /dev/null +++ b/app/Plugins/VehicleFuelOptions/Providers/VehicleFuelOptionServiceProvider.php @@ -0,0 +1,44 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleFuelOptions\Providers; + +use Illuminate\Support\ServiceProvider; + +class VehicleFuelOptionServiceProvider extends ServiceProvider +{ + /** + * Register any application services. + * + * @return void + */ + public function register() + { + include __DIR__ . '/../routes.php'; + $this->app->make('Plugins\VehicleFuelOptions\Controllers\VehicleFuelOptionsController'); + $this->app->make('Plugins\VehicleFuelOptions\Controllers\Admin\AdminVehicleFuelOptionsController'); + $this->app->make('Plugins\VehicleFuelOptions\Controllers\VehicleTypeFuelOptionsController'); + $this->app->make('Plugins\VehicleFuelOptions\Controllers\Admin\AdminVehicleTypeFuelOptionsController'); + } + + /** + * Bootstrap the application services. + * + * @return void + */ + public function boot() + { + } +} diff --git a/app/Plugins/VehicleFuelOptions/Services/VehicleFuelOptionService.php b/app/Plugins/VehicleFuelOptions/Services/VehicleFuelOptionService.php new file mode 100644 index 0000000..fc79a3e --- /dev/null +++ b/app/Plugins/VehicleFuelOptions/Services/VehicleFuelOptionService.php @@ -0,0 +1,72 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleFuelOptions\Services; + +use Plugins\VehicleFuelOptions\Model\VehicleTypeFuelOption; +use Plugins\VehicleRentals\Model\VehicleRentalAdditionalCharge; + +class VehicleFuelOptionService +{ + /** + * VehicleFuelOptionService constructor. + */ + public function __construct() + { + } + + /** + * @param $item_user_id + * @param $amount + * @param $fuel_options + * @param $no_of_days + * @return int + */ + public function processFuelOptionAmount($item_user_id, $amount, $fuel_options, $no_of_days) + { + $res_amount = 0; + $vehicle_type_fuel_options = VehicleTypeFuelOption::whereIn('id', $fuel_options)->get(); + if (!empty($vehicle_type_fuel_options)) { + foreach ($vehicle_type_fuel_options as $vehicle_type_fuel_option) { + $fuel_option_amount = 0; + if (!empty($vehicle_type_fuel_option->rate)) { + if (!empty($vehicle_type_fuel_option->discount_type_id) && $vehicle_type_fuel_option->discount_type_id == 1) { + $fuel_option_amount = $amount * $vehicle_type_fuel_option->rate / 100; + } else if (!empty($vehicle_type_fuel_option->discount_type_id) && $vehicle_type_fuel_option->discount_type_id == 2) { + $fuel_option_amount = $vehicle_type_fuel_option->rate; + } + if (!empty($vehicle_type_fuel_option->duration_type_id) && $vehicle_type_fuel_option->duration_type_id == 1) { + $fuel_option_amount = $fuel_option_amount * $no_of_days; + } + if (!empty($vehicle_type_fuel_option->max_allowed_amount)) { + if ($fuel_option_amount > $vehicle_type_fuel_option->max_allowed_amount) { + $fuel_option_amount = $vehicle_type_fuel_option->max_allowed_amount; + } + } + } + $vehicle_rental_additional_data['item_user_id'] = $item_user_id; + $vehicle_rental_additional_data['amount'] = $fuel_option_amount; + $vehicle_rental_additional_charge = VehicleRentalAdditionalCharge::create($vehicle_rental_additional_data); + $vehicle_fuel_option = VehicleTypeFuelOption::with(['vehicle_rental_additional_charges'])->where('id', '=', $vehicle_type_fuel_option->id)->first(); + $vehicle_fuel_option->vehicle_rental_additional_charges()->save($vehicle_rental_additional_charge); + $res_amount = $res_amount + $fuel_option_amount; + } + return $res_amount; + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Given Fuel options not available. Please, try again.'); + } + } + +} diff --git a/app/Plugins/VehicleFuelOptions/Transformers/AdminVehicleFuelOptionTransformer.php b/app/Plugins/VehicleFuelOptions/Transformers/AdminVehicleFuelOptionTransformer.php new file mode 100644 index 0000000..959b292 --- /dev/null +++ b/app/Plugins/VehicleFuelOptions/Transformers/AdminVehicleFuelOptionTransformer.php @@ -0,0 +1,39 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleFuelOptions\Transformers; + +use League\Fractal; +use Plugins\VehicleFuelOptions\Model\VehicleFuelOption; + +/** + * Class VehicleFuelOptionTransformer + * @package VehicleFuelOptions\Transformers + */ +class AdminVehicleFuelOptionTransformer extends Fractal\TransformerAbstract +{ + /** + * @param VehicleFuelOption $vehicle_fuel_option + * @return array + */ + public function transform(VehicleFuelOption $vehicle_fuel_option) + { + $output = array_only($vehicle_fuel_option->toArray(), ['id', 'created_at', 'name', 'short_description', 'description', 'is_active']); + $output['is_active'] = ($output['is_active']) ? true : false; + return $output; + } + + +} \ No newline at end of file diff --git a/app/Plugins/VehicleFuelOptions/Transformers/VehicleFuelOptionTransformer.php b/app/Plugins/VehicleFuelOptions/Transformers/VehicleFuelOptionTransformer.php new file mode 100644 index 0000000..c50ac30 --- /dev/null +++ b/app/Plugins/VehicleFuelOptions/Transformers/VehicleFuelOptionTransformer.php @@ -0,0 +1,37 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleFuelOptions\Transformers; + +use League\Fractal; +use Plugins\VehicleFuelOptions\Model\VehicleFuelOption; +use Plugins\VehicleFuelOptions\Model\VehicleTypeFuelOption; + +/** + * Class VehicleFuelOptionTransformer + * @package VehicleFuelOptions\Transformers + */ +class VehicleFuelOptionTransformer extends Fractal\TransformerAbstract +{ + /** + * @param VehicleFuelOption $vehicle_fuel_option + * @return array + */ + public function transform(VehicleFuelOption $vehicle_fuel_option) + { + $output = array_only($vehicle_fuel_option->toArray(), ['id', 'name', 'description']); + return $output; + } +} \ No newline at end of file diff --git a/app/Plugins/VehicleFuelOptions/Transformers/VehicleTypeFuelOptionTransformer.php b/app/Plugins/VehicleFuelOptions/Transformers/VehicleTypeFuelOptionTransformer.php new file mode 100644 index 0000000..f382e7c --- /dev/null +++ b/app/Plugins/VehicleFuelOptions/Transformers/VehicleTypeFuelOptionTransformer.php @@ -0,0 +1,104 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleFuelOptions\Transformers; + +use App\Transformers\DiscountTypeTransformer; +use App\Transformers\DurationTypeTransformer; +use League\Fractal; +use Plugins\VehicleFuelOptions\Model\VehicleTypeFuelOption; + +/** + * Class VehicleFuelOptionTransformer + * @package VehicleFuelOptions\Transformers + */ +class VehicleTypeFuelOptionTransformer extends Fractal\TransformerAbstract +{ + /** + * List of resources possible to include + * + * @var array + */ + protected $availableIncludes = [ + 'VehicleFuelOption', 'VehicleType', 'DurationType', 'DiscountType' + ]; + + /** + * @param VehicleTypeFuelOption $vehicle_type_fuel_option + * @return array + */ + public function transform(VehicleTypeFuelOption $vehicle_type_fuel_option) + { + $output = array_only($vehicle_type_fuel_option->toArray(), ['id', 'created_at', 'vehicle_type_id', 'fuel_option_id', 'rate', 'discount_type_id', 'duration_type_id', 'max_allowed_amount', 'is_active']); + $output['is_active'] = ($output['is_active']) ? true : false; + return $output; + } + + /** + * @param VehicleTypeFuelOption $vehicle_type_fuel_option + * @return Fractal\Resource\Item|null + */ + public function includeVehicleFuelOption(VehicleTypeFuelOption $vehicle_type_fuel_option) + { + if ($vehicle_type_fuel_option->vehicle_fuel_option) { + return $this->item($vehicle_type_fuel_option->vehicle_fuel_option, new VehicleFuelOptionTransformer()); + } else { + return null; + } + + } + + /** + * @param VehicleTypeFuelOption $vehicle_type_fuel_option + * @return Fractal\Resource\Item|null + */ + public function includeVehicleType(VehicleTypeFuelOption $vehicle_type_fuel_option) + { + if ($vehicle_type_fuel_option->vehicle_type) { + return $this->item($vehicle_type_fuel_option->vehicle_type, new \Plugins\Vehicles\Transformers\VehicleTypeTransformer()); + } else { + return null; + } + + } + + /** + * @param VehicleTypeFuelOption $vehicle_type_fuel_option + * @return Fractal\Resource\Item|null + */ + public function includeDiscountType(VehicleTypeFuelOption $vehicle_type_fuel_option) + { + if ($vehicle_type_fuel_option->discount_type) { + return $this->item($vehicle_type_fuel_option->discount_type, new DiscountTypeTransformer()); + } else { + return null; + } + + } + + /** + * @param VehicleTypeFuelOption $vehicle_type_fuel_option + * @return Fractal\Resource\Item|null + */ + public function includeDurationType(VehicleTypeFuelOption $vehicle_type_fuel_option) + { + if ($vehicle_type_fuel_option->duration_type) { + return $this->item($vehicle_type_fuel_option->duration_type, new DurationTypeTransformer()); + } else { + return null; + } + + } +} \ No newline at end of file diff --git a/app/Plugins/VehicleFuelOptions/plugin.json b/app/Plugins/VehicleFuelOptions/plugin.json new file mode 100644 index 0000000..0a48936 --- /dev/null +++ b/app/Plugins/VehicleFuelOptions/plugin.json @@ -0,0 +1,9 @@ +{ + "name": "VehicleFuelOptions", + "class": "fa fa-2x fa-tint", + "description": "By enabling this, item owner can manage fuel_options based on vehicle types.", + "dependencies": "VehicleRentals", + "module_id": "", + "module_hash": "", + "display_order": "18" +} diff --git a/app/Plugins/VehicleFuelOptions/routes.php b/app/Plugins/VehicleFuelOptions/routes.php new file mode 100644 index 0000000..fdd8220 --- /dev/null +++ b/app/Plugins/VehicleFuelOptions/routes.php @@ -0,0 +1,51 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +/* +|-------------------------------------------------------------------------- +| Application Routes +|-------------------------------------------------------------------------- +| +| Here is where you can register all of the routes for an application. +| It is a breeze. Simply tell Lumen the URIs it should respond to +| and give it the Closure to call when that URI is requested. +| +*/ +$api = $this->app->make('Dingo\Api\Routing\Router'); +$api->version(['v1'], function ($api) { + $api->group(['prefix' => 'admin', 'namespace' => 'Plugins\VehicleFuelOptions\Controllers\Admin', 'middleware' => 'apitracking'], function () use ($api) { + // FuelOptions admin side + $api->get('vehicle_fuel_options', 'AdminVehicleFuelOptionsController@index'); + $api->post('vehicle_fuel_options', 'AdminVehicleFuelOptionsController@store'); + $api->put('vehicle_fuel_options/{id}', 'AdminVehicleFuelOptionsController@update'); + $api->get('vehicle_fuel_options/{id}/edit', 'AdminVehicleFuelOptionsController@edit'); + $api->get('vehicle_fuel_options/{id}', 'AdminVehicleFuelOptionsController@show'); + $api->delete('vehicle_fuel_options/{id}', 'AdminVehicleFuelOptionsController@destroy'); + + // Vehicle Type FuelOptions admin side + $api->get('vehicle_type_fuel_options', 'AdminVehicleTypeFuelOptionsController@index'); + $api->post('vehicle_type_fuel_options', 'AdminVehicleTypeFuelOptionsController@store'); + $api->put('vehicle_type_fuel_options/{id}', 'AdminVehicleTypeFuelOptionsController@update'); + $api->get('vehicle_type_fuel_options/{id}/edit', 'AdminVehicleTypeFuelOptionsController@edit'); + $api->get('vehicle_type_fuel_options/{id}', 'AdminVehicleTypeFuelOptionsController@show'); + $api->delete('vehicle_type_fuel_options/{id}', 'AdminVehicleTypeFuelOptionsController@destroy'); + + }); + $api->group(['namespace' => 'Plugins\VehicleFuelOptions\Controllers', 'middleware' => 'apitracking'], function () use ($api) { + //fuel_options user side + $api->get('vehicle_fuel_options', 'VehicleFuelOptionsController@index'); + $api->get('vehicle_type_fuel_options', 'VehicleTypeFuelOptionsController@index'); + }); +}); diff --git a/app/Plugins/VehicleInsurances/Controllers/Admin/AdminVehicleInsurancesController.php b/app/Plugins/VehicleInsurances/Controllers/Admin/AdminVehicleInsurancesController.php new file mode 100644 index 0000000..c3a35f3 --- /dev/null +++ b/app/Plugins/VehicleInsurances/Controllers/Admin/AdminVehicleInsurancesController.php @@ -0,0 +1,190 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleInsurances\Controllers\Admin; + +use Illuminate\Http\Request; +use App\Http\Controllers\Controller; +use Plugins\VehicleInsurances\Model\VehicleInsurance; +use JWTAuth; +use Validator; +use Tymon\JWTAuth\Exceptions\JWTException; +use Plugins\VehicleInsurances\Transformers\AdminVehicleInsuranceTransformer; +use Plugins\VehicleInsurances\Transformers\VehicleInsuranceTransformer; +use EasySlug\EasySlug\EasySlugFacade as EasySlug; + +/** + * VehicleInsurances resource representation. + * @Resource("Admin/AdminVehicleInsurances") + */ +class AdminVehicleInsurancesController extends Controller +{ + /** + * AdminVehicleInsurancesController constructor. + */ + public function __construct() + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth'); + // Check the logged user role. + $this->middleware('role'); + } + + /** + * Show all vehicle_insurances + * Get a JSON representation of all the vehicle_insurances. + * + * @Get("/admin/vehicle_insurances?sort={sort}&sortby={sortby}&page={page}&q={q}") + * @Parameters({ + * @Parameter("sort", type="string", required=false, description="Sort the vehicle_insurances list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort vehicle_insurances by Ascending / Descending Order.", default=null), + * @Parameter("q", type="string", required=false, description="Search VehicleInsurances.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1) + * }) + */ + public function index(Request $request) + { + if($request->has('limit') && $request->limit == 'all') { + $vehicle_insurance_count = VehicleInsurance::count(); + $vehicle_insurances = VehicleInsurance::filterByActiveRecord($request)->filterByRequest($request)->select('id', 'name')->paginate($vehicle_insurance_count); + return $this->response->paginator($vehicle_insurances, new VehicleInsuranceTransformer); + } else { + $vehicle_insurances = VehicleInsurance::filterByRequest($request)->paginate(config('constants.ConstPageLimit')); + return $this->response->paginator($vehicle_insurances, new AdminVehicleInsuranceTransformer); + } + } + + /** + * Edit the specified vehicle_insurance. + * Edit the vehicle_insurance with a `id`. + * @Get("/admin/vehicle_insurances/{id}/edit") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body= {"id": 1, "name": "Service Insurance", "short_description": "The costs of service needed to support our business operations have escalated considerably.", "description": "The costs of service needed to support our business operations have escalated considerably. To offset the increasing costs of utilities, bus fuel, oil and grease, etc.,"}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function edit($id) + { + $vehicle_insurance = VehicleInsurance::find($id); + if (!$vehicle_insurance) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($vehicle_insurance, (new AdminVehicleInsuranceTransformer)); + } + + /** + * Show the specified vehicle_insurance. + * Show the vehicle_insurance with a `id`. + * @Get("/admin/vehicle_insurances/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body= {"id": 1, "name": "Service Insurance", "short_description": "The costs of service needed to support our business operations have escalated considerably.", "description": "The costs of service needed to support our business operations have escalated considerably. To offset the increasing costs of utilities, bus fuel, oil and grease, etc.,"}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function show($id) + { + $vehicle_insurance = VehicleInsurance::find($id); + if (!$vehicle_insurance) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($vehicle_insurance, (new AdminVehicleInsuranceTransformer)); + } + + /** + * Store a new vehicle_insurance. + * Store a new vehicle_insurance with a `name`, `short_description`, and `description`. + * @Post("/admin/vehicle_insurances") + * @Transaction({ + * @Request({"name": "Service Insurance", "short_description": "The costs of service needed to support our business operations have escalated considerably.", "description": "The costs of service needed to support our business operations have escalated considerably. To offset the increasing costs of utilities, bus fuel, oil and grease, etc.,"}), + * @Response(200, body={"success": "Record has been added."}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {"name": {}}, "status_code": 422}) + * }) + */ + public function store(Request $request) + { + $vehicle_insurance_data = $request->only('name', 'short_description', 'description'); + $validator = Validator::make($vehicle_insurance_data, VehicleInsurance::GetValidationRule(), VehicleInsurance::GetValidationMessage()); + $vehicle_insurance_data['slug'] = EasySlug::generateUniqueSlug($request->name, 'insurances'); + if ($validator->passes()) { + $vehicle_insurance_data['is_active'] = true; + $vehicle_insurance = VehicleInsurance::create($vehicle_insurance_data); + if ($vehicle_insurance) { + return response()->json(['Success' => 'VehicleInsurance has been added'], 200); + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('VehicleInsurance could not be updated. Please, try again.'); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('VehicleInsurance could not be updated. Please, try again.', $validator->errors()); + } + } + + + /** + * Update the specified vehicle_insurance + * Update the vehicle_insurance with a `id`. + * @Put("/admin/vehicle_insurances/{id}") + * @Transaction({ + * @Request({"id": 1, "name": "Energy Insurance", "short_description": "The costs of energy needed to support our business operations have escalated considerably.", "description": "The costs of energy needed to support our business operations have escalated considerably. To offset the increasing costs of utilities, bus fuel, oil and grease, etc.,", "is_active": 1}), + * @Response(200, body={"success": "Record has been updated."}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {"name": {}}, "status_code": 422}) + * }) + */ + public function update(Request $request, $id) + { + $vehicle_insurance_data = $request->only('name', 'short_description', 'description', 'is_active'); + $validator = Validator::make($vehicle_insurance_data, VehicleInsurance::GetValidationRule(), VehicleInsurance::GetValidationMessage()); + $vehicle_insurance = false; + if ($request->has('id')) { + $vehicle_insurance = VehicleInsurance::find($id); + $vehicle_insurance = ($request->id != $id) ? false : $vehicle_insurance; + if ($vehicle_insurance->name !== $request->name) { + $vehicle_insurance_data['slug'] = EasySlug::generateUniqueSlug($request->name, 'insurances'); + } + } + if ($validator->passes() && $vehicle_insurance) { + try { + $vehicle_insurance->update($vehicle_insurance_data); + return response()->json(['Success' => 'VehicleInsurance has been updated'], 200); + } catch (\Exception $e) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('VehicleInsurance could not be updated. Please, try again.'); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('VehicleInsurance could not be updated. Please, try again.', $validator->errors()); + } + } + + /** + * Delete the specified vehicle_insurance. + * Delete the vehicle_insurance with a `id`. + * @Delete("/admin/vehicle_insurances/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"success": "Record Deleted."}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function destroy($id) + { + $vehicle_insurance = VehicleInsurance::find($id); + if (!$vehicle_insurance) { + return $this->response->errorNotFound("Invalid Request"); + } else { + $vehicle_insurance->delete(); + } + return response()->json(['Success' => 'VehicleInsurance deleted'], 200); + } +} diff --git a/app/Plugins/VehicleInsurances/Controllers/Admin/AdminVehicleTypeInsurancesController.php b/app/Plugins/VehicleInsurances/Controllers/Admin/AdminVehicleTypeInsurancesController.php new file mode 100644 index 0000000..3cba4ec --- /dev/null +++ b/app/Plugins/VehicleInsurances/Controllers/Admin/AdminVehicleTypeInsurancesController.php @@ -0,0 +1,196 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleInsurances\Controllers\Admin; + +use Illuminate\Http\Request; +use App\Http\Requests; +use App\Http\Controllers\Controller; +use Plugins\VehicleInsurances\Model\VehicleTypeInsurance; +use JWTAuth; +use Validator; +use Plugins\VehicleInsurances\Transformers\VehicleTypeInsuranceTransformer; +use DB; + +/** + * VehicleTypeInsurances resource representation. + * @Resource("Admin/AdminVehicleTypeInsurances") + */ +class AdminVehicleTypeInsurancesController extends Controller +{ + /** + * AdminVehicleTypeInsurancesController constructor. + */ + public function __construct() + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth'); + // Check the logged user role. + $this->middleware('role'); + } + + /** + * Show all vehicle_type_insurances + * Get a JSON representation of all the vehicle_type_insurances. + * + * @Get("/admin/vehicle_type_insurances?sort={sort}&sortby={sortby}&page={page}&q={q}") + * @Parameters({ + * @Parameter("sort", type="string", required=false, description="Sort the vehicle_type_insurances list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort vehicle_type_insurances by Ascending / Descending Order.", default=null), + * @Parameter("q", type="string", required=false, description="Search VehicleTypeInsurances.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1) + * }) + */ + public function index(Request $request) + { + $vehicle_type_insurances_count = config('constants.ConstPageLimit'); + if($request->has('limit') && $request->limit == 'all') { + $vehicle_type_insurances_count = VehicleModel::count(); + $vehicle_type_insurances = VehicleTypeInsurance::filterByActiveRecord($request)->filterByRequest($request)->paginate($vehicle_type_insurances_count); + return $this->response->paginator($vehicle_type_insurances, new VehicleTypeInsuranceTransformer); + }else{ + $enabled_includes = array('vehicle_insurance', 'discount_type', 'duration_type', 'vehicle_type'); + $vehicle_type_insurances = VehicleTypeInsurance::with($enabled_includes) + ->select(DB::raw('vehicle_type_insurances.*')) + ->leftJoin(DB::raw('(select id,name from vehicle_types) as vehicle_type'), 'vehicle_type.id', '=', 'vehicle_type_insurances.vehicle_type_id') + ->leftJoin(DB::raw('(select id,name from insurances) as vehicle_insurance'), 'vehicle_insurance.id', '=', 'vehicle_type_insurances.insurance_id') + ->leftJoin(DB::raw('(select id,type from discount_types) as discount_type'), 'discount_type.id', '=', 'vehicle_type_insurances.discount_type_id') + ->leftJoin(DB::raw('(select id,name from duration_types) as duration_type'), 'duration_type.id', '=', 'vehicle_type_insurances.duration_type_id') + ->filterByRequest($request)->paginate($vehicle_type_insurances_count); + return $this->response->paginator($vehicle_type_insurances, (new VehicleTypeInsuranceTransformer)->setDefaultIncludes($enabled_includes)); + } + + } + + /** + * Edit the specified vehicle_type_insurance. + * Edit the vehicle_type_insurance with a `id`. + * @Get("/admin/vehicle_type_insurances/{id}/edit") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body= {"id": 1, "vehicle_type_id": 1, "insurance_id": 1, "discount_type_id": 1, "duration_type_id": 1, "rate": 200, "max_allowed_amount": 1000, "vehicle_type": {}, "vehicle_insurance": {}, "duration_type": {}, "discount_type": {}}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function edit($id) + { + $enabled_includes = array('vehicle_insurance', 'discount_type', 'duration_type', 'vehicle_type'); + $vehicle_type_insurance = VehicleTypeInsurance::with($enabled_includes)->find($id); + if (!$vehicle_type_insurance) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($vehicle_type_insurance, (new VehicleTypeInsuranceTransformer)->setDefaultIncludes($enabled_includes)); + } + + /** + * Show the specified vehicle_type_insurance. + * Show the vehicle_type_insurance with a `id`. + * @Get("/admin/vehicle_type_insurances/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body= {"id": 1, "vehicle_type_id": 1, "insurance_id": 1, "discount_type_id": 1, "duration_type_id": 1, "rate": 200, "max_allowed_amount": 1000, "vehicle_type": {}, "vehicle_insurance": {}, "duration_type": {}, "discount_type": {}}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function show($id) + { + $enabled_includes = array('vehicle_insurance', 'discount_type', 'duration_type', 'vehicle_type'); + $vehicle_type_insurance = VehicleTypeInsurance::with($enabled_includes)->find($id); + if (!$vehicle_type_insurance) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($vehicle_type_insurance, (new VehicleTypeInsuranceTransformer)->setDefaultIncludes($enabled_includes)); + } + + /** + * Store a new vehicle_type_insurance. + * Store a new vehicle_type_insurance with a `name`, `short_description`, and `description`. + * @Post("/admin/vehicle_type_insurances") + * @Transaction({ + * @Request({"vehicle_type_id": 1, "insurance_id": 1, "discount_type_id": 1, "duration_type_id": 1, "rate": 200, "max_allowed_amount": 1000}), + * @Response(200, body={"success": "Record has been added."}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {"name": {}}, "status_code": 422}) + * }) + */ + public function store(Request $request) + { + $vehicle_type_insurance_data = $request->only('vehicle_type_id', 'insurance_id', 'rate', 'discount_type_id', 'duration_type_id', 'max_allowed_amount'); + $validator = Validator::make($vehicle_type_insurance_data, VehicleTypeInsurance::GetValidationRule(), VehicleTypeInsurance::GetValidationMessage()); + $vehicle_type_insurance_data['is_active'] = true; + if ($validator->passes()) { + $vehicle_type_insurance = VehicleTypeInsurance::create($vehicle_type_insurance_data); + if ($vehicle_type_insurance) { + return response()->json(['Success' => 'VehicleTypeInsurance has been added'], 200); + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('VehicleTypeInsurance could not be added. Please, try again.'); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('VehicleTypeInsurance could not be added. Please, try again.', $validator->errors()); + } + } + + + /** + * Update the specified vehicle_type_insurance + * Update the vehicle_type_insurance with a `id`. + * @Put("/admin/vehicle_type_insurances/{id}") + * @Transaction({ + * @Request({"id": 1, "vehicle_type_id": 1, "insurance_id": 1, "discount_type_id": 1, "duration_type_id": 1, "rate": 200, "max_allowed_amount": 1000}), + * @Response(200, body={"success": "Record has been updated."}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {"name": {}}, "status_code": 422}) + * }) + */ + public function update(Request $request, $id) + { + $vehicle_type_insurance_data = $request->only('vehicle_type_id', 'insurance_id', 'rate', 'discount_type_id', 'duration_type_id', 'max_allowed_amount', 'is_active'); + $validator = Validator::make($vehicle_type_insurance_data, VehicleTypeInsurance::GetValidationRule(), VehicleTypeInsurance::GetValidationMessage()); + $vehicle_type_insurance = false; + if ($request->has('id')) { + $vehicle_type_insurance = VehicleTypeInsurance::find($id); + $vehicle_type_insurance = ($request->id != $id) ? false : $vehicle_type_insurance; + } + if ($validator->passes() && $vehicle_type_insurance) { + try { + $vehicle_type_insurance->update($vehicle_type_insurance_data); + return response()->json(['Success' => 'VehicleTypeInsurance has been updated'], 200); + } catch (\Exception $e) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('VehicleTypeInsurance could not be updated. Please, try again.'); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('VehicleTypeInsurance could not be updated. Please, try again.', $validator->errors()); + } + } + + /** + * Delete the specified vehicle_type_insurance. + * Delete the vehicle_type_insurance with a `id`. + * @Delete("/admin/vehicle_type_insurances/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"success": "Record Deleted."}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function destroy($id) + { + $vehicle_type_insurance = VehicleTypeInsurance::find($id); + if (!$vehicle_type_insurance) { + return $this->response->errorNotFound("Invalid Request"); + } else { + $vehicle_type_insurance->delete(); + } + return response()->json(['Success' => 'VehicleTypeInsurance deleted'], 200); + } +} diff --git a/app/Plugins/VehicleInsurances/Controllers/VehicleInsurancesController.php b/app/Plugins/VehicleInsurances/Controllers/VehicleInsurancesController.php new file mode 100644 index 0000000..7958544 --- /dev/null +++ b/app/Plugins/VehicleInsurances/Controllers/VehicleInsurancesController.php @@ -0,0 +1,58 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleInsurances\Controllers; + +use Illuminate\Http\Request; +use App\Http\Controllers\Controller; +use Plugins\VehicleInsurances\Model\VehicleInsurance; +use JWTAuth; +use Validator; +use Tymon\JWTAuth\Exceptions\JWTException; +use Plugins\VehicleInsurances\Transformers\VehicleInsuranceTransformer; + +/** + * VehicleInsurances resource representation. + * @Resource("VehicleInsurances") + */ +class VehicleInsurancesController extends Controller +{ + /** + * VehicleInsurancesController constructor. + */ + public function __construct() + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth'); + } + + /** + * Show all insurances + * Get a JSON representation of all the insurances. + * + * @Get("/vehicle_insurances?sort={sort}&sortby={sortby}&page={page}&q={q}") + * @Parameters({ + * @Parameter("sort", type="string", required=false, description="Sort the insurances list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort insurances by Ascending / Descending Order.", default=null), + * @Parameter("q", type="string", required=false, description="Search VehicleInsurances.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1) + * }) + */ + public function index(Request $request) + { + $insurances = VehicleInsurance::filterByRequest($request)->paginate(config('constants.ConstPageLimit')); + return $this->response->paginator($insurances, (new VehicleInsuranceTransformer)); + } +} diff --git a/app/Plugins/VehicleInsurances/Controllers/VehicleTypeInsurancesController.php b/app/Plugins/VehicleInsurances/Controllers/VehicleTypeInsurancesController.php new file mode 100644 index 0000000..49d12bd --- /dev/null +++ b/app/Plugins/VehicleInsurances/Controllers/VehicleTypeInsurancesController.php @@ -0,0 +1,59 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleInsurances\Controllers; + +use Illuminate\Http\Request; +use App\Http\Controllers\Controller; +use Plugins\VehicleInsurances\Model\VehicleTypeInsurance; +use JWTAuth; +use Validator; +use Tymon\JWTAuth\Exceptions\JWTException; +use Plugins\VehicleInsurances\Transformers\VehicleTypeInsuranceTransformer; + +/** + * VehicleInsurances resource representation. + * @Resource("VehicleInsurances") + */ +class VehicleTypeInsurancesController extends Controller +{ + /** + * VehicleInsurancesController constructor. + */ + public function __construct() + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth'); + } + + /** + * Show all insurances + * Get a JSON representation of all the insurances. + * + * @Get("/vehicle_insurances?sort={sort}&sortby={sortby}&page={page}&q={q}") + * @Parameters({ + * @Parameter("sort", type="string", required=false, description="Sort the insurances list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort insurances by Ascending / Descending Order.", default=null), + * @Parameter("q", type="string", required=false, description="Search VehicleInsurances.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1) + * }) + */ + public function index(Request $request) + { + $enabled_includes = array('vehicle_insurance', 'discount_type', 'duration_type', 'vehicle_type'); + $vehicle_type_insurances = VehicleTypeInsurance::with($enabled_includes)->filterByRequest($request)->paginate(config('constants.ConstPageLimit')); + return $this->response->paginator($vehicle_type_insurances, (new VehicleTypeInsuranceTransformer)->setDefaultIncludes($enabled_includes)); + } +} diff --git a/app/Plugins/VehicleInsurances/Model/VehicleInsurance.php b/app/Plugins/VehicleInsurances/Model/VehicleInsurance.php new file mode 100644 index 0000000..855992f --- /dev/null +++ b/app/Plugins/VehicleInsurances/Model/VehicleInsurance.php @@ -0,0 +1,101 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleInsurances\Model; + +use Illuminate\Http\Request; +use Illuminate\Database\Eloquent\Model; + +class VehicleInsurance extends Model +{ + /** + * @var string + */ + protected $table = "insurances"; + + protected $fillable = [ + 'name', 'short_description', 'description', 'is_active', 'slug' + ]; + + + /** + * @return \Illuminate\Database\Eloquent\Relations\HasMany + */ + public function vehicle_type_insurance() + { + return $this->hasMany(VehicleTypeInsurance::class); + } + /** + * @param $query + * @param Request $request + */ + public function scopeFilterByActiveRecord($query, Request $request) + { + $query->where('is_active', '=', 1); + } + /** + * @param $query + * @param Request $request + * @return mixed + */ + public function scopeFilterByRequest($query, Request $request) + { + $query->orderBy($request->input('sort', 'id'), $request->input('sortby', 'asc')); + if ($request->has('q')) { + $query->where('name', 'LIKE', '%' . $request->input('q') . '%') + ->orWhere('short_description', 'LIKE', '%' . $request->input('q') . '%') + ->orWhere('description', 'LIKE', '%' . $request->input('q') . '%'); + } + if ($request->has('filter')) { + $filter = false; + if ($request->input('filter') == 'active') { + $filter = true; + } + $query->where('is_active', '=', $filter); + } + return $query; + } + + /** + * @return array + */ + public function scopeGetValidationRule() + { + return [ + 'name' => 'required|min:5', + 'short_description' => 'required|min:10', + 'description' => 'required|min:15', + 'is_active' => 'sometimes|required|boolean' + ]; + } + + /** + * @return array + */ + public function scopeGetValidationMessage() + { + return [ + 'name.required' => 'Required', + 'name.min' => 'name - Minimum length is 5', + 'short_description.required' => 'Required', + 'short_description.min' => 'Short Description - Minimum length is 10', + 'description.required' => 'Required', + 'description.min' => 'Description - Minimum length is 15', + 'is_active.required' => 'Required', + 'is_active.boolean' => 'Possible values to be entered is 0 or 1' + ]; + } + +} diff --git a/app/Plugins/VehicleInsurances/Model/VehicleTypeInsurance.php b/app/Plugins/VehicleInsurances/Model/VehicleTypeInsurance.php new file mode 100644 index 0000000..8d3299a --- /dev/null +++ b/app/Plugins/VehicleInsurances/Model/VehicleTypeInsurance.php @@ -0,0 +1,160 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleInsurances\Model; + +use Illuminate\Http\Request; +use Illuminate\Database\Eloquent\Model; +use Illuminate\Support\Facades\App; +use App\DiscountType; +use App\DurationType; + +class VehicleTypeInsurance extends Model +{ + /** + * @var string + */ + protected $table = "vehicle_type_insurances"; + + protected $fillable = [ + 'vehicle_type_id', 'insurance_id', 'rate', 'discount_type_id', 'duration_type_id', 'max_allowed_amount', 'is_active' + ]; + + + /** + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function vehicle_insurance() + { + return $this->belongsTo(VehicleInsurance::class, 'insurance_id'); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function vehicle_type() + { + return $this->belongsTo(\Plugins\Vehicles\Model\VehicleType::class); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function discount_type() + { + return $this->belongsTo(DiscountType::class); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function duration_type() + { + return $this->belongsTo(DurationType::class); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\MorphMany + */ + public function vehicle_rental_additional_charges() + { + return $this->morphMany(\Plugins\VehicleRentals\Model\VehicleRentalAdditionalCharge::class, 'item_user_additional_chargable'); + } + + /** + * @param $query + * @param Request $request + */ + public function scopeFilterByActiveRecord($query, Request $request) + { + $query->where('is_active', '=', 1); + } + /** + * @param $query + * @param Request $request + * @return mixed + */ + public function scopeFilterByRequest($query, Request $request) + { + $query->orderBy($request->input('sort', 'id'), $request->input('sortby', 'asc')); + if ($request->has('q')) { + $query->WhereHas('vehicle_insurance', function ($q) use ($request) { + $q->where('name', 'like', '%' . $request->input('q') . '%'); + }); + $query->orWhereHas('vehicle_type', function ($q) use ($request) { + $q->where('name', 'like', '%' . $request->input('q') . '%'); + }); + $query->orWhereHas('discount_type', function ($q) use ($request) { + $q->where('type', 'like', '%' . $request->input('q') . '%'); + }); + $query->orWhereHas('duration_type', function ($q) use ($request) { + $q->where('name', 'like', '%' . $request->input('q') . '%'); + }); + } + + if ($request->has('filter')) { + $filter = false; + if ($request->filter == 'active') { + $filter = true; + } + $query->where('is_active', '=', $filter); + } + if($request->has('insurance_id')){ + $query->where('insurance_id', '=', $request->insurance_id); + } + return $query; + } + + /** + * @return array + */ + public function scopeGetValidationRule() + { + return [ + 'vehicle_type_id' => 'required|integer|exists:vehicle_types,id', + 'insurance_id' => 'required|integer|exists:insurances,id', + 'rate' => 'required|numeric', + 'discount_type_id' => 'required|integer|exists:discount_types,id', + 'duration_type_id' => 'required|integer|exists:duration_types,id', + 'max_allowed_amount' => 'required|numeric' + ]; + } + + /** + * @return array + */ + public function scopeGetValidationMessage() + { + return [ + 'vehicle_type_id.required' => 'Required', + 'vehicle_type_id.integer' => 'Vehicle Type Id must be integer', + 'vehicle_type_id.exists' => 'Invalid vehicle type id', + 'insurance_id.required' => 'Required', + 'insurance_id.integer' => 'Insurance Id must be integer', + 'insurance_id.exists' => 'Invalid insurance id', + 'rate.required' => 'Required', + 'rate.numeric' => 'Rate must be numeric', + 'discount_type_id.required' => 'Required', + 'discount_type_id.integer' => 'Discount Type Id must be integer', + 'discount_type_id.exists' => 'Invalid discount type id', + 'duration_type_id.required' => 'Required', + 'duration_type_id.integer' => 'Duration Type Id must be integer', + 'discount_type_id.exists' => 'Invalid duration type id', + 'max_allowed_amount.required' => 'Required', + 'max_allowed_amount.numeric' => 'Max allowed amount must be numeric' + ]; + } + +} diff --git a/app/Plugins/VehicleInsurances/Providers/VehicleInsuranceServiceProvider.php b/app/Plugins/VehicleInsurances/Providers/VehicleInsuranceServiceProvider.php new file mode 100644 index 0000000..a3346f7 --- /dev/null +++ b/app/Plugins/VehicleInsurances/Providers/VehicleInsuranceServiceProvider.php @@ -0,0 +1,44 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleInsurances\Providers; + +use Illuminate\Support\ServiceProvider; + +class VehicleInsuranceServiceProvider extends ServiceProvider +{ + /** + * Register any application services. + * + * @return void + */ + public function register() + { + include __DIR__ . '/../routes.php'; + $this->app->make('Plugins\VehicleInsurances\Controllers\VehicleInsurancesController'); + $this->app->make('Plugins\VehicleInsurances\Controllers\Admin\AdminVehicleInsurancesController'); + $this->app->make('Plugins\VehicleInsurances\Controllers\VehicleTypeInsurancesController'); + $this->app->make('Plugins\VehicleInsurances\Controllers\Admin\AdminVehicleTypeInsurancesController'); + } + + /** + * Bootstrap the application services. + * + * @return void + */ + public function boot() + { + } +} diff --git a/app/Plugins/VehicleInsurances/Services/VehicleInsuranceService.php b/app/Plugins/VehicleInsurances/Services/VehicleInsuranceService.php new file mode 100644 index 0000000..4708da7 --- /dev/null +++ b/app/Plugins/VehicleInsurances/Services/VehicleInsuranceService.php @@ -0,0 +1,71 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleInsurances\Services; + +use Plugins\VehicleInsurances\Model\VehicleTypeInsurance; +use Plugins\VehicleRentals\Model\VehicleRentalAdditionalCharge; + +class VehicleInsuranceService +{ + /** + * VehicleInsuranceService constructor. + */ + public function __construct() + { + } + + /** + * @param $item_user_id + * @param $amount + * @param $insurances + * @param $no_of_days + * @return int + */ + public function processInsuranceAmount($item_user_id, $amount, $insurances, $no_of_days) + { + $res_amount = 0; + $vehicle_type_insurances = VehicleTypeInsurance::whereIn('id', $insurances)->get(); + if (!empty($vehicle_type_insurances)) { + foreach ($vehicle_type_insurances as $vehicle_type_insurance) { + if (!empty($vehicle_type_insurance->rate)) { + if (!empty($vehicle_type_insurance->discount_type_id) && $vehicle_type_insurance->discount_type_id == 1) { + $insurance_amount = $amount * $vehicle_type_insurance->rate / 100; + } else if (!empty($vehicle_type_insurance->discount_type_id) && $vehicle_type_insurance->discount_type_id == 2) { + $insurance_amount = $vehicle_type_insurance->rate; + } + if (!empty($vehicle_type_insurance->duration_type_id) && $vehicle_type_insurance->duration_type_id == 1) { + $insurance_amount = $insurance_amount * $no_of_days; + } + if (!empty($vehicle_type_insurance->max_allowed_amount)) { + if ($insurance_amount > $vehicle_type_insurance->max_allowed_amount) { + $insurance_amount = $vehicle_type_insurance->max_allowed_amount; + } + } + } + $vehicle_rental_additional_data['item_user_id'] = $item_user_id; + $vehicle_rental_additional_data['amount'] = $insurance_amount; + $vehicle_rental_additional_charge = VehicleRentalAdditionalCharge::create($vehicle_rental_additional_data); + $vehicle_insurance = VehicleTypeInsurance::with(['vehicle_rental_additional_charges'])->where('id', '=', $vehicle_type_insurance->id)->first(); + $vehicle_insurance->vehicle_rental_additional_charges()->save($vehicle_rental_additional_charge); + $res_amount = $res_amount + $insurance_amount; + } + return $res_amount; + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Given Insurances not available. Please, try again.'); + } + } + +} diff --git a/app/Plugins/VehicleInsurances/Transformers/AdminVehicleInsuranceTransformer.php b/app/Plugins/VehicleInsurances/Transformers/AdminVehicleInsuranceTransformer.php new file mode 100644 index 0000000..7ec46c5 --- /dev/null +++ b/app/Plugins/VehicleInsurances/Transformers/AdminVehicleInsuranceTransformer.php @@ -0,0 +1,39 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleInsurances\Transformers; + +use League\Fractal; +use Plugins\VehicleInsurances\Model\VehicleInsurance; + +/** + * Class VehicleInsuranceTransformer + * @package VehicleInsurances\Transformers + */ +class AdminVehicleInsuranceTransformer extends Fractal\TransformerAbstract +{ + + /** + * @param VehicleInsurance $vehicle_insurance + * @return array + */ + public function transform(VehicleInsurance $vehicle_insurance) + { + $output = array_only($vehicle_insurance->toArray(), ['id', 'created_at', 'name', 'short_description', 'description', 'is_active']); + $output['is_active'] = ($output['is_active']) ? true : false; + return $output; + } + +} \ No newline at end of file diff --git a/app/Plugins/VehicleInsurances/Transformers/VehicleInsuranceTransformer.php b/app/Plugins/VehicleInsurances/Transformers/VehicleInsuranceTransformer.php new file mode 100644 index 0000000..12bc6f7 --- /dev/null +++ b/app/Plugins/VehicleInsurances/Transformers/VehicleInsuranceTransformer.php @@ -0,0 +1,37 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleInsurances\Transformers; + +use League\Fractal; +use Plugins\VehicleInsurances\Model\VehicleInsurance; + +/** + * Class VehicleInsuranceTransformer + * @package VehicleInsurances\Transformers + */ +class VehicleInsuranceTransformer extends Fractal\TransformerAbstract +{ + + /** + * @param VehicleInsurance $vehicle_insurance + * @return array + */ + public function transform(VehicleInsurance $vehicle_insurance) + { + $output = array_only($vehicle_insurance->toArray(), ['id', 'name', 'description']); + return $output; + } +} \ No newline at end of file diff --git a/app/Plugins/VehicleInsurances/Transformers/VehicleTypeInsuranceTransformer.php b/app/Plugins/VehicleInsurances/Transformers/VehicleTypeInsuranceTransformer.php new file mode 100644 index 0000000..1dc2006 --- /dev/null +++ b/app/Plugins/VehicleInsurances/Transformers/VehicleTypeInsuranceTransformer.php @@ -0,0 +1,104 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleInsurances\Transformers; + +use App\Transformers\DiscountTypeTransformer; +use App\Transformers\DurationTypeTransformer; +use League\Fractal; +use Plugins\VehicleInsurances\Model\VehicleTypeInsurance; + +/** + * Class VehicleInsuranceTransformer + * @package VehicleInsurances\Transformers + */ +class VehicleTypeInsuranceTransformer extends Fractal\TransformerAbstract +{ + /** + * List of resources possible to include + * + * @var array + */ + protected $availableIncludes = [ + 'VehicleInsurance', 'VehicleType', 'DurationType', 'DiscountType' + ]; + + /** + * @param VehicleTypeInsurance $vehicle_type_insurance + * @return array + */ + public function transform(VehicleTypeInsurance $vehicle_type_insurance) + { + $output = array_only($vehicle_type_insurance->toArray(), ['id', 'created_at', 'vehicle_type_id', 'insurance_id', 'rate', 'discount_type_id', 'duration_type_id', 'max_allowed_amount', 'is_active']); + $output['is_active'] = ($output['is_active']) ? true : false; + return $output; + } + + /** + * @param VehicleTypeInsurance $vehicle_type_insurance + * @return Fractal\Resource\Item|null + */ + public function includeVehicleInsurance(VehicleTypeInsurance $vehicle_type_insurance) + { + if ($vehicle_type_insurance->vehicle_insurance) { + return $this->item($vehicle_type_insurance->vehicle_insurance, new VehicleInsuranceTransformer()); + } else { + return null; + } + + } + + /** + * @param VehicleTypeInsurance $vehicle_type_insurance + * @return Fractal\Resource\Item|null + */ + public function includeVehicleType(VehicleTypeInsurance $vehicle_type_insurance) + { + if ($vehicle_type_insurance->vehicle_type) { + return $this->item($vehicle_type_insurance->vehicle_type, new \Plugins\Vehicles\Transformers\VehicleTypeTransformer()); + } else { + return null; + } + + } + + /** + * @param VehicleTypeInsurance $vehicle_type_insurance + * @return Fractal\Resource\Item|null + */ + public function includeDiscountType(VehicleTypeInsurance $vehicle_type_insurance) + { + if ($vehicle_type_insurance->discount_type) { + return $this->item($vehicle_type_insurance->discount_type, new DiscountTypeTransformer()); + } else { + return null; + } + + } + + /** + * @param VehicleTypeInsurance $vehicle_type_insurance + * @return Fractal\Resource\Item|null + */ + public function includeDurationType(VehicleTypeInsurance $vehicle_type_insurance) + { + if ($vehicle_type_insurance->duration_type) { + return $this->item($vehicle_type_insurance->duration_type, new DurationTypeTransformer()); + } else { + return null; + } + + } +} \ No newline at end of file diff --git a/app/Plugins/VehicleInsurances/plugin.json b/app/Plugins/VehicleInsurances/plugin.json new file mode 100644 index 0000000..7e13144 --- /dev/null +++ b/app/Plugins/VehicleInsurances/plugin.json @@ -0,0 +1,9 @@ +{ + "name": "VehicleInsurances", + "class": "fa fa-2x fa-university", + "description": "By enabling this, item owner can manage taxes based on vehicle types.", + "dependencies": "VehicleRentals", + "module_id": "", + "module_hash": "", + "display_order": "16" +} diff --git a/app/Plugins/VehicleInsurances/routes.php b/app/Plugins/VehicleInsurances/routes.php new file mode 100644 index 0000000..401b785 --- /dev/null +++ b/app/Plugins/VehicleInsurances/routes.php @@ -0,0 +1,51 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +/* +|-------------------------------------------------------------------------- +| Application Routes +|-------------------------------------------------------------------------- +| +| Here is where you can register all of the routes for an application. +| It is a breeze. Simply tell Lumen the URIs it should respond to +| and give it the Closure to call when that URI is requested. +| +*/ +$api = $this->app->make('Dingo\Api\Routing\Router'); +$api->version(['v1'], function ($api) { + $api->group(['prefix' => 'admin', 'namespace' => 'Plugins\VehicleInsurances\Controllers\Admin', 'middleware' => 'apitracking'], function () use ($api) { + // Insurances admin side + $api->get('vehicle_insurances', 'AdminVehicleInsurancesController@index'); + $api->post('vehicle_insurances', 'AdminVehicleInsurancesController@store'); + $api->put('vehicle_insurances/{id}', 'AdminVehicleInsurancesController@update'); + $api->get('vehicle_insurances/{id}/edit', 'AdminVehicleInsurancesController@edit'); + $api->get('vehicle_insurances/{id}', 'AdminVehicleInsurancesController@show'); + $api->delete('vehicle_insurances/{id}', 'AdminVehicleInsurancesController@destroy'); + + // Vehicle Type Insurances admin side + $api->get('vehicle_type_insurances', 'AdminVehicleTypeInsurancesController@index'); + $api->post('vehicle_type_insurances', 'AdminVehicleTypeInsurancesController@store'); + $api->put('vehicle_type_insurances/{id}', 'AdminVehicleTypeInsurancesController@update'); + $api->get('vehicle_type_insurances/{id}/edit', 'AdminVehicleTypeInsurancesController@edit'); + $api->get('vehicle_type_insurances/{id}', 'AdminVehicleTypeInsurancesController@show'); + $api->delete('vehicle_type_insurances/{id}', 'AdminVehicleTypeInsurancesController@destroy'); + + }); + $api->group(['namespace' => 'Plugins\VehicleInsurances\Controllers', 'middleware' => 'apitracking'], function () use ($api) { + //insurances user side + $api->get('vehicle_insurances', 'VehicleInsurancesController@index'); + $api->get('vehicle_type_insurances', 'VehicleTypeInsurancesController@index'); + }); +}); diff --git a/app/Plugins/VehicleRentals/Controllers/Admin/AdminVehicleRentalStatusesController.php b/app/Plugins/VehicleRentals/Controllers/Admin/AdminVehicleRentalStatusesController.php new file mode 100644 index 0000000..c358b0d --- /dev/null +++ b/app/Plugins/VehicleRentals/Controllers/Admin/AdminVehicleRentalStatusesController.php @@ -0,0 +1,63 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleRentals\Controllers\Admin; + +use Illuminate\Http\Request; + +use App\Http\Controllers\Controller; +use JWTAuth; +use Tymon\JWTAuth\Exceptions\JWTException; +use Plugins\VehicleRentals\Transformers\VehicleRentalStatusTransformer; +use Plugins\VehicleRentals\Model\VehicleRentalStatus; + +/** + * VehicleRentalStatuses resource representation. + * @Resource("Admin/VehicleRentalStatuses") + */ +class AdminVehicleRentalStatusesController extends Controller +{ + /** + * Create a new controller instance. + * + * @return void + */ + public function __construct() + { + // Check the logged user authentication. + $this->middleware('jwt.auth'); + // Check the logged user role. + $this->middleware('role'); + } + + /** + * Show all vehicle_rental status. + * Get a JSON representation of all the vehicle_rental status. + * + * @Get("/vehicle_rental_statuses?filter={filter}&sort={sort}&sortby={sortby}&q={q}&page={page}") + * @Parameters({ + * @Parameter("filter", type="integer", required=false, description="Filter the vehicle_rental status list by status.", default=null), + * @Parameter("sort", type="string", required=false, description="Sort the vehicle_rental status list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort vehicle_rental status by Ascending / Descending Order.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1) + * @Parameter("q", type="string", required=false, description="Search vehicle_rental status.", default=null) + * }) + */ + public function index(Request $request) + { + $vehicle_rental_statuses = VehicleRentalStatus::filterByRequest($request)->paginate(config('constants.ConstPageLimit')); + return $this->response->paginator($vehicle_rental_statuses, (new VehicleRentalStatusTransformer)); + } +} diff --git a/app/Plugins/VehicleRentals/Controllers/Admin/AdminVehicleRentalsController.php b/app/Plugins/VehicleRentals/Controllers/Admin/AdminVehicleRentalsController.php new file mode 100644 index 0000000..4090ecf --- /dev/null +++ b/app/Plugins/VehicleRentals/Controllers/Admin/AdminVehicleRentalsController.php @@ -0,0 +1,280 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleRentals\Controllers\Admin; + +use Illuminate\Http\Request; + +use App\Http\Controllers\Controller; +use JWTAuth; +use Validator; +use Tymon\JWTAuth\Exceptions\JWTException; +use Plugins\VehicleRentals\Transformers\VehicleRentalTransformer; +use Plugins\VehicleRentals\Model\VehicleRental; +use Plugins\VehicleRentals\Model\VehicleRentalStatus; +use Plugins\VehicleRentals\Services\VehicleRentalService; +use Plugins\Vehicles\Services\UnavailableVehicleService; +use App\Services\TransactionService; +use App\User; +use Carbon; +use DB; + +/** + * VehicleRentals resource representation. + * @Resource("Admin/AdminVehicleRentals") + */ +class AdminVehicleRentalsController extends Controller +{ + /** + * @var + */ + protected $vehicleRentalService; + + /** + * @var TransactionService + */ + protected $transactionService; + + /** + * @var unavailableVehicleService + */ + protected $unavailableVehicleService; + + /** + * AdminVehicleRentalsController constructor. + */ + public function __construct() + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth'); + // Check the logged user role. + $this->middleware('role'); + $this->setVehicleRentalService(); + $this->setTransactionService(); + $this->setUnavailableVehicleService(); + } + + public function setVehicleRentalService() + { + $this->vehicleRentalService = new VehicleRentalService(); + } + + public function setTransactionService() + { + $this->transactionService = new TransactionService(); + } + + public function setUnavailableVehicleService() + { + $this->unavailableVehicleService = new UnavailableVehicleService(); + } + + /** + * Show all vehicle_rentals. + * Get a JSON representation of all the vehicle_rentals. + * @Get("/vehicle_rentals?filter={filter}&sort={sort}&sortby={sortby}&q={q}&page={page}") + * @Parameters({ + * @Parameter("filter", type="integer", required=false, description="Filter vehicle_rentals list by status.", default=null), + * @Parameter("sort", type="string", required=false, description="Sort the vehicle_rentals list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort vehicle_rentals by Ascending / Descending Order.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1), + * @Parameter("q", type="string", required=false, description="Search vehicle_rentals.", default=null) + * }) + */ + public function index(Request $request) + { + $enabledIncludes = array('user', 'item_user_status'); + // check if plugin enabled and include + (isPluginEnabled('VehicleCoupons')) ? $enabledIncludes[] = 'vehicle_coupon' : ''; + $vehicle_rentals = VehicleRental::with($enabledIncludes) + ->select(DB::raw('item_users.*')) + ->leftJoin(DB::raw('(select id,username from users) as user'), 'user.id', '=', 'item_users.user_id') + ->leftJoin(DB::raw('(select id,name from vehicles) as item_userable'), 'item_userable.id', '=', 'item_users.item_userable_id') + ->leftJoin(DB::raw('(select id,name from item_user_statuses) as item_user_status'), 'item_user_status.id', '=', 'item_users.item_user_status_id') + ->filterByBooking($request) + ->filterByVehicleRental(false) + ->filterByRequest($request)->paginate(config('constants.ConstPageLimit')); + $enabledIncludes = array_merge($enabledIncludes, array('item_userable')); + return $this->response->paginator($vehicle_rentals, (new VehicleRentalTransformer)->setDefaultIncludes($enabledIncludes)); + } + + /** + * Show the vehicle_rental. + * Show the vehicle_rental with a `id`. + * @Get("/vehicle_rentals/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"id": 1, "user_id": 1, "item_user_status_id": 1, "coupon_id": 1, "quantity": 1, "total_amount": 100.00, "user": {}, "coupon": {}}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function show($id) + { + $enabledIncludes = array('user', 'item_user_status', 'pickup_counter_location', 'drop_counter_location', 'vehicle_rental_additional_chargable'); + // check if plugin enabled and include + (isPluginEnabled('VehicleCoupons')) ? $enabledIncludes[] = 'vehicle_coupon' : ''; + $vehicle_rental = VehicleRental::with($enabledIncludes)->find($id); + if (!$vehicle_rental) { + return $this->response->errorNotFound("Invalid Request"); + } + $enabledIncludes = array_merge($enabledIncludes, array('item_userable')); + return $this->response->item($vehicle_rental, (new VehicleRentalTransformer)->setDefaultIncludes($enabledIncludes)); + } + + /** + * Cancel the specified vehicle_rental. + * Cancel the vehicle_rental with a `id`. + * @Put("/vehicle_rentals/{id}/cancelled-by-admin") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"success": "VehicleRental has been cancelled"}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function CancelledByAdmin($id) + { + $enabledIncludes = $this->vehicleRentalService->getEnableGateway(); + $vehicle_rental = VehicleRental::with($enabledIncludes)->where('id', '=', $id)->first(); + if (!$vehicle_rental || is_null($vehicle_rental->item_userable)) { + return $this->response->errorNotFound("Invalid Request"); + } + try { + $error_msg = ''; + $is_payment_transaction = false; + $transaction_log = array(); + if (isPluginEnabled('Paypal') && !is_null($vehicle_rental->paypal_transaction_log)) { + $gateway_id = config('constants.ConstPaymentGateways.PayPal'); + if ($vehicle_rental->paypal_transaction_log->payment_type == 'authorized') { + $paypal = new \Plugins\Paypal\Services\PayPalService(); + $voidPayment = $paypal->voidPayment($vehicle_rental->paypal_transaction_log->authorization_id); + if (is_object($voidPayment)) { + $transaction_log['payment_type'] = $voidPayment->getState(); + $transaction_log['void_id'] = $voidPayment->getId(); + if ($transaction_log['payment_type'] == 'voided') { + $is_payment_transaction = true; + } + } else if (is_array($voidPayment) && $voidPayment['error']) { + $error_msg = $voidPayment['error_message']; + } + + $vehicle_rental->paypal_transaction_log->update($transaction_log); + } + if ($vehicle_rental->paypal_transaction_log->payment_type == 'completed') { + $paypal = new \Plugins\Paypal\Services\PayPalService(); + $refundPayment = $paypal->refundPayment($vehicle_rental->paypal_transaction_log); + if (is_object($refundPayment)) { + $transaction_log['status'] = 'refunded'; + $transaction_log['payment_type'] = $refundPayment->getState(); + $transaction_log['refund_id'] = $refundPayment->getId(); + if ($transaction_log['payment_type'] == 'completed') { + $is_payment_transaction = true; + } + } else if (is_array($refundPayment) && $refundPayment['error']) { + $error_msg = $refundPayment['error_message']; + } + $vehicle_rental->paypal_transaction_log->update($transaction_log); + } + } + if (isPluginEnabled('Sudopays') && !is_null($vehicle_rental->sudopay_transaction_logs)) { + $gateway_id = config('constants.ConstPaymentGateways.SudoPay'); + $sudopay = new \Plugins\Sudopays\Services\SudopayService(); + if ($vehicle_rental->sudopay_transaction_logs->status == 'Authorized') { + $voidPayment = $sudopay->voidPayment($vehicle_rental->sudopay_transaction_logs); + if (!empty($voidPayment) && ($voidPayment['status'] == 'Voided' || $voidPayment['status'] == 'Canceled')) { + $transaction_log['status'] = $voidPayment['status']; + $is_payment_transaction = true; + $vehicle_rental->sudopay_transaction_logs->update($transaction_log); + } else if (is_array($voidPayment) && $voidPayment['error']) { + $error_msg = $voidPayment['error_message']; + } + } elseif ($vehicle_rental->sudopay_transaction_logs->status == 'Captured') { + $refundPayment = $sudopay->refundPayment($vehicle_rental->sudopay_transaction_logs); + if (!empty($refundPayment) && $refundPayment['status'] == 'Refunded') { + $transaction_log['status'] = $refundPayment['status']; + $is_payment_transaction = true; + $vehicle_rental->sudopay_transaction_logs->update($transaction_log); + } else if (is_array($refundPayment) && $refundPayment['error']) { + $error_msg = $refundPayment['error_message']; + } + } + } + if (!is_null($vehicle_rental->wallet_transaction_log)) { + $gateway_id = config('constants.ConstPaymentGateways.Wallet'); + if ($vehicle_rental->wallet_transaction_log->payment_type == 'Captured') { + $walletService = new \App\Services\WalletService(); + $is_payment_transaction = $walletService->voidPayment($vehicle_rental); + } + } + if ($is_payment_transaction) { + $vehicle_rental_data['item_user_status_id'] = config('constants.ConstItemUserStatus.CancelledByAdmin'); + $vehicle_rental_data['status_updated_at'] = Carbon::now()->toDateTimeString(); + $vehicle_rental->update($vehicle_rental_data); + $this->unavailableVehicleService->clearUnavaialablelist($vehicle_rental->id); + $this->vehicleRentalService->updateItemUserCount(); + //Save transactions + $this->transactionService->log(config('constants.ConstUserTypes.Admin'), $vehicle_rental->user_id, config('constants.ConstTransactionTypes.RefundForRentingCanceledByAdmin'), $vehicle_rental->total_amount, $vehicle_rental->id, 'VehicleRentals', $gateway_id); + $this->vehicleRentalService->changeStatusMail($vehicle_rental, $vehicle_rental->item_userable, $vehicle_rental->item_user_status_id, config('constants.ConstItemUserStatus.CancelledByAdmin')); + return response()->json(['Success' => 'VehicleRental has been cancelled'], 200); + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('VehicleRental could not be updated. Please, try again.', array($error_msg)); + } + } catch (\Exception $e) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('VehicleRental could not be updated. Please, try again.', array($e->getMessage())); + } + } + + /** + * Checkin the specified vehicle_rental. + * Checkin the vehicle_rental with a `id`. + * @get("/vehicle_rentals/{id}/checkin") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"success": "Record has been checkin."}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {}, "status_code": 422}) + * }) + */ + public function checkin($id) + { + $enabledIncludes = array('item_user_status'); + $vehicle_rental = VehicleRental::with($enabledIncludes)->filterByStatus($id, config('constants.ConstItemUserStatus.Confirmed'))->first(); + if (!$vehicle_rental || is_null($vehicle_rental->item_userable)) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->vehicleRentalService->saveCheckInDetail($vehicle_rental); + } + + /** + * Checkout the specified vehicle_rental. + * Checkout the vehicle_rental with a `id`. + * @get("/vehicle_rentals/{id}/checkout") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"success": "Record has been checkout."}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {}, "status_code": 422}) + * }) + */ + public function checkout(Request $request, $id) + { + $enabledIncludes = array('item_user_status', 'late_payment_detail'); + $vehicle_rental = VehicleRental::with($enabledIncludes)->filterByStatus($id, config('constants.ConstItemUserStatus.Attended'))->first(); + if (!$vehicle_rental || is_null($vehicle_rental->item_userable)) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->vehicleRentalService->saveCheckoutDetail($vehicle_rental, $request->claim_request_amount); + } +} + diff --git a/app/Plugins/VehicleRentals/Controllers/VehicleRentalStatusesController.php b/app/Plugins/VehicleRentals/Controllers/VehicleRentalStatusesController.php new file mode 100644 index 0000000..fa5b892 --- /dev/null +++ b/app/Plugins/VehicleRentals/Controllers/VehicleRentalStatusesController.php @@ -0,0 +1,98 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleRentals\Controllers; + +use Illuminate\Http\Request; + +use App\Http\Controllers\Controller; +use JWTAuth; +use Tymon\JWTAuth\Exceptions\JWTException; +use Plugins\VehicleRentals\Transformers\VehicleRentalStatusTransformer; +use Plugins\VehicleRentals\Model\VehicleRentalStatus; + +/** + * VehicleRentalStatuses resource representation. + * @Resource("VehicleRentalStatuses") + */ +class VehicleRentalStatusesController extends Controller +{ + /** + * Create a new controller instance. + * + * @return void + */ + public function __construct() + { + // Check the logged user authentication. + $this->middleware('jwt.auth'); + } + + /** + * Show all withdrawal statuses. + * Get a JSON representation of all the withdrawal statuses. + * + * @Get("/vehicle_rental_statuses?sort={sort}&sortby={sortby}") + * @Parameters({ + * @Parameter("sort", type="string", required=false, description="Sort the vehicle_rental status list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort vehicle_rental status by Ascending / Descending Order.", default=null) + * }) + */ + public function index(Request $request) + { + $vehicle_rental_statuses = VehicleRentalStatus::filterByRequest($request)->get(); + if ($request->has('filter') && $request->filter == 'booker') { + $item_status_array = array( + 'Confirmed', + 'Waiting for Review', + 'Completed', + 'Attended', + 'Waiting For Acceptance', + 'Cancelled', + 'Rejected', + 'Expired', + 'Payment Pending' + ); + } else if ($request->has('filter') && $request->filter == 'host') { + $item_status_array = array( + 'Confirmed', + 'Waiting for Review', + 'Completed', + 'Attended', + 'Waiting For Acceptance', + 'Cancelled', + 'Rejected', + 'Expired', + 'Host Reviewed', + 'Waiting For Payment Cleared' + ); + } + $status_array['item_user_statuses'] = array(); + foreach ($vehicle_rental_statuses as $key => $val) { + if (in_array($val['name'], $item_status_array)) { + if($val['name'] == 'Host Reviewed') { + $val['name'] = 'Waiting For Booker Review'; + } + if(!isPluginEnabled('VehicleFeedbacks')) { + if($val['name'] == 'Waiting for Review') { + $val['name'] = 'Waiting For Next Update'; + } + } + $status_array['item_user_statuses'][] = $val; + } + } + return $status_array; + } +} diff --git a/app/Plugins/VehicleRentals/Controllers/VehicleRentalsController.php b/app/Plugins/VehicleRentals/Controllers/VehicleRentalsController.php new file mode 100644 index 0000000..5504a5d --- /dev/null +++ b/app/Plugins/VehicleRentals/Controllers/VehicleRentalsController.php @@ -0,0 +1,859 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleRentals\Controllers; + +use App\Services\IpService; +use Illuminate\Http\Request; + +use App\Http\Controllers\Controller; +use Plugins\VehicleRentals\Model\VehicleRental; +use Plugins\VehicleRentals\Model\VehicleRentalAdditionalCharge; +use Plugins\Vehicles\Model\Vehicle; +use Plugins\Vehicles\Model\UnavailableVehicle; +use Plugins\Vehicles\Model\VehicleSpecialPrice; +use Plugins\VehicleRentals\Model\VehicleRentalLatePaymentDetail; +use Plugins\VehicleRentals\Services\VehicleRentalService; +use Plugins\VehicleRentals\Services\VehicleRentalBookerDetailService; +use Plugins\Vehicles\Model\VehicleType; +use Plugins\Vehicles\Services\VehicleService; +use Plugins\Vehicles\Services\UnavailableVehicleService; +use App\Services\UserService; +use JWTAuth; +use Validator; +use Plugins\VehicleRentals\Transformers\VehicleRentalTransformer; +use Carbon; +use App\User; +use App\Services\TransactionService; +use Log; + +/** + * VehicleRentals resource representation. + * @Resource("VehicleRentals") + */ +class VehicleRentalsController extends Controller +{ + /** + * @var VehicleRentalService + */ + protected $vehicleRentalService; + /** + * @var $ipservice + */ + protected $ipservice; + /** + * @var $userservice + */ + protected $userservice; + + /** + * @var TransactionService + */ + protected $transactionService; + + /** + * @var TaxService + */ + protected $vehicleTaxService; + + /** + * @var SurchargeService + */ + protected $vehicleSurchargeService; + + /** + * @var vehicleService + */ + protected $vehicleService; + + /** + * @var unavailableVehicleService + */ + protected $unavailableVehicleService; + + /** + * @var vehicleRentalBookerDetailService + */ + protected $vehicleRentalBookerDetailService; + + /** + * VehicleRentalsController constructor. + * @param VehicleRentalMailService $service + */ + public function __construct(UserService $userservice) + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth'); + $this->setVehicleRentalService(); + $this->setVehicleService(); + $this->setUnavailableVehicleService(); + $this->setIpService(); + $this->setTransactionService(); + $this->setVehicleRentalBookerDetailService(); + $this->UserService = $userservice; + } + + public function setVehicleRentalService() + { + $this->vehicleRentalService = new VehicleRentalService(); + } + + public function setVehicleService() + { + $this->vehicleService = new VehicleService(); + } + + public function setUnavailableVehicleService() + { + $this->unavailableVehicleService = new UnavailableVehicleService(); + } + + public function setIpService() + { + $this->IpService = new IpService(); + } + + public function setTransactionService() + { + $this->transactionService = new TransactionService(); + } + + public function setVehicleRentalBookerDetailService() + { + $this->vehicleRentalBookerDetailService = new VehicleRentalBookerDetailService(); + } + + /** + * Show all vehicle_rentals. + * Get a JSON representation of all the vehicle_rentals. + * @Get("/vehicle_rentals?filter={filter}&sort={sort}&sortby={sortby}&q={q}&page={page}") + * @Parameters({ + * @Parameter("filter", type="integer", required=false, description="Filter vehicle_rentals list by status.", default=null), + * @Parameter("sort", type="string", required=false, description="Sort the vehicle_rentals list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort vehicle_rentals by Ascending / Descending Order.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1), + * @Parameter("q", type="string", required=false, description="Search vehicle_rentals.", default=null) + * }) + */ + public function index(Request $request) + { + $user = $this->auth->user(); + $enabledIncludes = array('user', 'item_user_status'); + // check if plugin enabled and include + (isPluginEnabled('VehicleCoupons')) ? $enabledIncludes[] = 'vehicle_coupon' : ''; + $status_arr = array(); + if ($request->has('item_user_status_id') && $request->item_user_status_id == config('constants.ConstItemUserStatus.WaitingForReview')) { + $status_arr = [config('constants.ConstItemUserStatus.WaitingForReview'), config('constants.ConstItemUserStatus.HostReviewed')]; + } + if ($request->has('item_user_status_id') && $request->item_user_status_id == config('constants.ConstItemUserStatus.Completed')) { + $status_arr = [config('constants.ConstItemUserStatus.BookerReviewed'), config('constants.ConstItemUserStatus.Completed'), config('constants.ConstItemUserStatus.WaitingForPaymentCleared')]; + } + $bookings_count = config('constants.ConstPageLimit'); + if($request->has('limit') && $request->limit == 'all') { + $bookings_count = VehicleRental::with($enabledIncludes)->filterByVehicleRental()->filterByRequest($request, $status_arr)->count(); + } + $vehicle_rentals = VehicleRental::with($enabledIncludes)->filterByVehicleRental()->filterByRequest($request, $status_arr)->paginate($bookings_count); + $enabledIncludes = array_merge($enabledIncludes, array('item_userable')); + return $this->response->paginator($vehicle_rentals, (new VehicleRentalTransformer)->setDefaultIncludes($enabledIncludes)); + } + + /** + * Show all items orders. + * Get a JSON representation of all the items orders. + * @Get("/item_orders?filter={filter}&sort={sort}&sortby={sortby}&q={q}") + * @Parameters({ + * @Parameter("filter", type="integer", required=false, description="Filter the items list by status.", default=null), + * @Parameter("sort", type="string", required=false, description="Sort the items list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort items by Ascending / Descending Order.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1) + * }) + */ + public function itemOrders(Request $request) + { + $user = $this->auth->user(); + $vehicles = Vehicle::with('user')->where('user_id', $user->id)->pluck('id')->all(); + $status_arr = array(); + if ($request->has('item_user_status_id') && $request->item_user_status_id == config('constants.ConstItemUserStatus.WaitingForReview')) { + $status_arr = [config('constants.ConstItemUserStatus.WaitingForReview'), config('constants.ConstItemUserStatus.BookerReviewed')]; + } + $order_count = config('constants.ConstPageLimit'); + if($request->has('limit') && $request->limit == 'all') { + $order_count = VehicleRental::whereIn('item_userable_id', $vehicles)->whereNotIn('item_user_status_id', [config('constants.ConstItemUserStatus.PaymentPending')])->where('item_userable_type', 'MorphVehicle')->filterByRequest($request, $status_arr)->count(); + } + $item_orders = VehicleRental::whereIn('item_userable_id', $vehicles)->whereNotIn('item_user_status_id', [config('constants.ConstItemUserStatus.PaymentPending')])->where('item_userable_type', 'MorphVehicle')->filterByRequest($request, $status_arr)->paginate($order_count); + return $this->response->paginator($item_orders, (new \Plugins\VehicleRentals\Transformers\VehicleRentalTransformer)->setDefaultIncludes(['user', 'item_userable'])); + } + + /** + * Show the vehicle_rental. + * Show the vehicle_rental with a `id`. + * @Get("/vehicle_rentals/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"id": 1, "user_id": 1, "item_user_status_id": 1, "coupon_id": 1, "quantity": 1, "total_amount": 100.00, "user": {}, "coupon": {}, "item_user_status": {}}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function show($id, Request $request) + { + $enabledIncludes = array('user', 'item_user_status', 'pickup_counter_location', 'drop_counter_location', 'vehicle_rental_additional_chargable'); + // check if plugin enabled and include + (isPluginEnabled('VehicleCoupons')) ? $enabledIncludes[] = 'vehicle_coupon' : ''; + $vehicle_rental = VehicleRental::with($enabledIncludes)->find($id); + if (!$vehicle_rental) { + return $this->response->errorNotFound("Invalid Request"); + } + if($request->has('type') && $request->type == 'rental') { + $unavailable_vehicles = $this->unavailableVehicleService->checkBookingAvailability($vehicle_rental); + if ($unavailable_vehicles) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Vehicle not available for the given dates. Please try again with different dates'); + } + } + $enabledIncludes = array_merge($enabledIncludes, array('item_userable', 'booker_detail')); + return $this->response->item($vehicle_rental, (new VehicleRentalTransformer)->setDefaultIncludes($enabledIncludes)); + } + + /** + * Edit the vehicle_rental. + * Edit the vehicle_rental with a `id`. + * @Get("/vehicle_rentals/{id}/edit") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"id": 1, "user_id": 1, "item_user_status_id": 1, "coupon_id": 1, "quantity": 1, "total_amount": 100.00, "user": {}, "coupon": {}}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function edit($id) + { + $enabledIncludes = array('user', 'item_user_status'); + // check if plugin enabled and include + (isPluginEnabled('VehicleCoupons')) ? $enabledIncludes[] = 'vehicle_coupon' : ''; + $vehicle_rental = VehicleRental::with($enabledIncludes)->find($id); + if (!$vehicle_rental) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($vehicle_rental, (new VehicleRentalTransformer)->setDefaultIncludes($enabledIncludes)); + } + + /** + * Store a vehicle_rental. + * Store a new vehicle_rental with a a `vehicle_id`, `item_booking_start_date`, `item_booking_end_date`, `quantity` and `coupon_code`. + * @Post("/vehicle_rentals") + * @Transaction({ + * @Request({"item_booking_start_date": "01-01-2016 00:00:00", "item_booking_end_date": "31-01-2016 00:00:00", "quantity": 1, "coupon_code": "XXXXXX"}), + * @Response(200, body={"success": "Record has been added."}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {}, "status_code": 422}) + * }) + */ + public function store(Request $request) + { + $vehicle_rental_data = $request->only('vehicle_id', 'item_booking_start_date', 'item_booking_end_date', 'pickup_counter_location_id', 'drop_counter_location_id'); + $vehicle_rental_data['item_booking_start_date'] = $request->item_booking_start_date = date("Y-m-d H:i:s", strtotime($vehicle_rental_data['item_booking_start_date'])); + $vehicle_rental_data['item_booking_end_date'] = $request->item_booking_end_date = date("Y-m-d H:i:s", strtotime($vehicle_rental_data['item_booking_end_date'])); + $user = $this->auth->user(); + if (isPluginEnabled('Vehicles')) { + $vehicle = Vehicle::with(['vehicle_type'])->find($request->vehicle_id); + if (!$vehicle) { + return $this->response->errorNotFound("Invalid Request"); + } + if ($user) { + $vehicle_rental_data['user_id'] = $user->id; + if ($vehicle->user_id == $user->id) { + return $this->response->errorNotFound("Invalid Request"); + } + } + $cur_date = Carbon::now()->toDateTimeString(); + if ($cur_date > $vehicle_rental_data['item_booking_start_date'] || $vehicle_rental_data['item_booking_start_date'] > $vehicle_rental_data['item_booking_end_date']) { + return $this->response->errorNotFound("Invalid Request"); + } + $unavailable_vehicle = UnavailableVehicle::where('vehicle_id', $request->vehicle_id) + ->where(function ($query) use ($request) { + $query->whereBetween('start_date', [$request->item_booking_start_date, $request->item_booking_end_date]) + ->orWhereBetween('end_date', [$request->item_booking_start_date, $request->item_booking_end_date]) + ->orwhere(function ($query) use ($request) { + $query->where('start_date', '>', $request->item_booking_start_date) + ->where('end_date', '<', $request->item_booking_start_date); + })->orwhere(function ($query) use ($request) { + $query->where('start_date', '<', $request->item_booking_end_date) + ->where('end_date', '>', $request->item_booking_end_date); + }); + }) + ->where('is_dummy', '!=', 1)->first(); + if ($unavailable_vehicle) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Vehicle not available for the given dates. Please try again with different dates'); + } + } else { + return $this->response->errorNotFound("Invalid Request"); + } + $vehicle_rental_data['item_user_status_id'] = config('constants.ConstItemUserStatus.PaymentPending'); + $validator = Validator::make($vehicle_rental_data, VehicleRental::GetValidationRule(), VehicleRental::GetValidationMessage()); + if ($validator->passes()) { + try { + if (!is_null($vehicle->vehicle_type)) { + if ($vehicle->vehicle_type->deposit_amount > 0) { + $vehicle_rental_data['deposit_amount'] = $vehicle->vehicle_type->deposit_amount; + } + } + // quantity default set as 1 + $vehicle_rental_data['quantity'] = 1; + $vehicle_rental = VehicleRental::create($vehicle_rental_data); + $booking_calculated_details = $this->vehicleService->calculateBookingAmount($vehicle_rental_data['item_booking_start_date'], $vehicle_rental_data['item_booking_end_date'], $vehicle); + $vehicle_rental_data['booking_amount'] = $booking_calculated_details['booking_amount']; + if ($booking_calculated_details['special_price_discount_amount'] > $booking_calculated_details['type_price_discount_amount']) { + $vehicle_rental_data['special_discount_amount'] = $booking_calculated_details['special_price_discount_amount']; + } else { + $vehicle_rental_data['type_discount_amount'] = $booking_calculated_details['type_price_discount_amount']; + } + if (isPluginEnabled('VehicleTaxes')) { + $vehicleTaxService = new \Plugins\VehicleTaxes\Services\VehicleTaxService(); + $vehicle_rental_data['tax_amount'] = $vehicleTaxService->processTaxAmount($vehicle->vehicle_type_id, $vehicle_rental->id, $booking_calculated_details); + } + if (isPluginEnabled('VehicleSurcharges')) { + $vehicleSurchargeService = new \Plugins\VehicleSurcharges\Services\VehicleSurchargeService(); + $vehicle_rental_data['surcharge_amount'] = $vehicleSurchargeService->processSurchargeAmount($vehicle->vehicle_type_id, $vehicle_rental->id, $booking_calculated_details); + } + if ($vehicle_rental_data['pickup_counter_location_id'] != $vehicle_rental_data['drop_counter_location_id']) { + $drop_location_differ_details = $this->vehicleService->processDifferLocationDropAmount($vehicle_rental_data['pickup_counter_location_id'], $vehicle_rental_data['drop_counter_location_id'], $vehicle->vehicle_type_id); + $vehicle_rental_data['drop_location_differ_charges'] = $drop_location_differ_details['diff_location_drop_amount']; + } + $vehicle_rental->update($vehicle_rental_data); + if ($vehicle_rental) { + $curVehicle = Vehicle::with(['vehicle_rentals'])->where('id', '=', $request->vehicle_id)->first(); + $curVehicle->vehicle_rentals()->save($vehicle_rental); + $vehicle_rental = VehicleRental::find($vehicle_rental->id); + $vehicle_rental = $this->vehicleService->updateTotalAmount($vehicle_rental); + $this->vehicleRentalService->updateItemUserCount(); + } + return $this->response->item($vehicle_rental, new VehicleRentalTransformer); + } catch (\Exception $e) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Vehicle Rental could not be added. Please, try again.', + array($e->getMessage())); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Vehicle Rental could not be added. Please, try again.', $validator->errors()); + } + } + + /** + * @param Request $request + * @return \Dingo\Api\Http\Response|void + */ + public function update(Request $request, $id) + { + $user = $this->auth->user(); + $vehicle_rental_data = array(); + try { + $vehicle_rental = VehicleRental::with('vehicle_rental_additional_chargable')->where('id', $request->id)->first(); + if ($vehicle_rental->user_id != $user->id) { + return $this->response->errorNotFound("Invalid Request"); + } + // add booking details + $booker_details = $this->vehicleRentalBookerDetailService->addRentalBookerDetail($request); + if (isset($booker_details['Error'])) { + if (isset($booker_details['type']) && $booker_details['type'] == 'catch') { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Vehicle Rental could not be updated. Please, try again.', $booker_details['Error']); + } else if (isset($booker_details['type']) && $booker_details['type'] == 'validate') { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Vehicle Rental could not be updated. Please, try again.', $booker_details['Error']->errors()); + } else { + return $this->response->errorNotFound("Invalid Request"); + } + } + // delete the records from item_user_additional_charges, if the user modify their choice of picking insurance, extra accessory, fuel option + if (!empty($vehicle_rental->vehicle_rental_additional_chargable)) { + foreach ($vehicle_rental->vehicle_rental_additional_chargable as $vehicle_rental_additional_charge) { + if ($vehicle_rental_additional_charge->item_user_additional_chargable_type == 'MorphInsurance' || $vehicle_rental_additional_charge->item_user_additional_chargable_type == 'MorphExtraAccessory' || $vehicle_rental_additional_charge->item_user_additional_chargable_type == 'MorphFuelOption') { + $vehicle_rental_additional_charge->delete(); + } + } + } + $date_diff = $this->vehicleService->getDateDiff($vehicle_rental->item_booking_start_date, $vehicle_rental->item_booking_end_date); + if (isPluginEnabled('VehicleInsurances') && $request->has('vehicle_type_insurances') && !empty($request->vehicle_type_insurances)) { + $vehicleInsuranceService = new \Plugins\VehicleInsurances\Services\VehicleInsuranceService(); + $vehicle_rental_data['insurance_amount'] = $vehicleInsuranceService->processInsuranceAmount($request->id, $vehicle_rental->booking_amount, $request->vehicle_type_insurances, $date_diff['total_days']); + }else{ + $vehicle_rental_data['insurance_amount'] = 0.00; + } + if (isPluginEnabled('VehicleExtraAccessories') && $request->has('vehicle_type_extra_accessories') && !empty($request->vehicle_type_extra_accessories)) { + $vehicleExtraAccessoryService = new \Plugins\VehicleExtraAccessories\Services\VehicleExtraAccessoryService(); + $vehicle_rental_data['extra_accessory_amount'] = $vehicleExtraAccessoryService->processExtraAccessoryAmount($request->id, $vehicle_rental->booking_amount, $request->vehicle_type_extra_accessories, $date_diff['total_days']); + }else{ + $vehicle_rental_data['extra_accessory_amount'] = 0.00; + } + if (isPluginEnabled('VehicleFuelOptions') && $request->has('vehicle_type_fuel_options') && !empty($request->vehicle_type_fuel_options)) { + $vehicleFuelOptionService = new \Plugins\VehicleFuelOptions\Services\VehicleFuelOptionService(); + $vehicle_rental_data['fuel_option_amount'] = $vehicleFuelOptionService->processFuelOptionAmount($request->id, $vehicle_rental->booking_amount, $request->vehicle_type_fuel_options, $date_diff['total_days']); + }else{ + $vehicle_rental_data['fuel_option_amount'] = 0.00; + } + if (!empty($vehicle_rental_data)) { + $vehicle_rental->update($vehicle_rental_data); + } + $vehicle_rental = $this->vehicleService->updateTotalAmount($vehicle_rental); + return $this->response->item($vehicle_rental, new VehicleRentalTransformer); + } catch (\Exception $e) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Vehicle Rental could not be added. Please, try again.', + array($e->getMessage())); + } + } + + /** + * Reject the specified vehicle_rental. + * Reject the vehicle_rental with a `id`. + * @Put("/vehicle_rentals/{id}/reject") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"success": "Record has been rejected."}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {}, "status_code": 422}) + * }) + */ + public function reject($id) + { + $enabledIncludes = $this->vehicleRentalService->getEnableGateway(); + $vehicle_rental = VehicleRental::with($enabledIncludes)->where(['item_user_status_id' => config('constants.ConstItemUserStatus.WaitingForAcceptance'), 'id' => $id])->first(); + if (!$vehicle_rental || is_null($vehicle_rental->item_userable)) { + return $this->response->errorNotFound("Invalid Request"); + } + $user = $this->auth->user(); + if ($vehicle_rental->item_userable->user_id != $user->id) { + return $this->response->errorNotFound("Invalid Request"); + } + try { + $error_msg = ''; + $is_payment_transaction = false; + $transaction_log = array(); + if (isPluginEnabled('Paypal') && !is_null($vehicle_rental->paypal_transaction_log)) { + $gateway_id = config('constants.ConstPaymentGateways.PayPal'); + if ($vehicle_rental->paypal_transaction_log->payment_type == 'authorized') { + $paypal = new \Plugins\Paypal\Services\PayPalService(); + $voidPayment = $paypal->voidPayment($vehicle_rental->paypal_transaction_log->authorization_id); + if (is_object($voidPayment)) { + $transaction_log['payment_type'] = $voidPayment->getState(); + $transaction_log['void_id'] = $voidPayment->getId(); + if ($transaction_log['payment_type'] == 'voided') { + $is_payment_transaction = true; + } + } else if (is_array($voidPayment) && $voidPayment['error']) { + if ($voidPayment['error']['message']) { + $error_msg = $voidPayment['error']['message']; + } else { + $error_msg = $voidPayment['error_message']; + } + } + $vehicle_rental->paypal_transaction_log->update($transaction_log); + } + } + if (isPluginEnabled('Sudopays') && !is_null($vehicle_rental->sudopay_transaction_logs)) { + $gateway_id = config('constants.ConstPaymentGateways.SudoPay'); + $sudopayService = new \Plugins\Sudopays\Services\SudopayService(); + if ($vehicle_rental->sudopay_transaction_logs->status == 'Authorized') { + $voidPayment = $sudopayService->voidPayment($vehicle_rental->sudopay_transaction_logs); + if (!empty($voidPayment) && $voidPayment['status'] == 'Canceled') { + $transaction_log['status'] = $voidPayment['status']; + $is_payment_transaction = true; + $vehicle_rental->sudopay_transaction_logs->update($transaction_log); + } else if (is_array($voidPayment) && $voidPayment['error']) { + if ($voidPayment['error']['message']) { + $error_msg = $voidPayment['error']['message']; + } else { + $error_msg = $voidPayment['error_message']; + } + } + } elseif ($vehicle_rental->sudopay_transaction_logs->status == 'Captured') { + $refundPayment = $sudopayService->refundPayment($vehicle_rental->sudopay_transaction_logs); + if (!empty($refundPayment) && $refundPayment['status'] == 'Refunded') { + $transaction_log['status'] = $refundPayment['status']; + $is_payment_transaction = true; + $vehicle_rental->sudopay_transaction_logs->update($transaction_log); + } else if (is_array($refundPayment) && $refundPayment['error']) { + if ($refundPayment['error']['message']) { + $error_msg = $refundPayment['error']['message']; + } else { + $error_msg = $refundPayment['error_message']; + } + + } + } + } + if (!is_null($vehicle_rental->wallet_transaction_log)) { + $gateway_id = config('constants.ConstPaymentGateways.Wallet'); + if ($vehicle_rental->wallet_transaction_log->payment_type == 'Captured') { + $walletService = new \App\Services\WalletService(); + $is_payment_transaction = $walletService->voidPayment($vehicle_rental); + } + } + if ($is_payment_transaction) { + $vehicle_rental_data['item_user_status_id'] = config('constants.ConstItemUserStatus.Rejected'); + $vehicle_rental_data['status_updated_at'] = Carbon::now()->toDateTimeString(); + $vehicle_rental->update($vehicle_rental_data); + $this->unavailableVehicleService->clearUnavaialablelist($vehicle_rental->id); + $this->vehicleRentalService->updateItemUserCount(); + //Save transactions + $this->transactionService->log(config('constants.ConstUserTypes.Admin'), $vehicle_rental->user_id, config('constants.ConstTransactionTypes.RefundForRejectedRenting'), $vehicle_rental->total_amount, $vehicle_rental->id, 'VehicleRentals', $gateway_id); + $this->vehicleRentalService->changeStatusMail($vehicle_rental, $vehicle_rental->item_userable, config('constants.ConstItemUserStatus.WaitingForAcceptance'), config('constants.ConstItemUserStatus.Rejected')); + return response()->json(['Success' => 'Vehicle Rental has been rejected'], 200); + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Vehicle Rental could not be updated. Please, try again.'); + } + } catch (\Exception $e) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Vehicle Rental could not be updated. Please, try again.', array($e->getMessage())); + } + } + + /** + * Cancel the specified vehicle_rental. + * Cancel the vehicle_rental with a `id`. + * @Put("/vehicle_rentals/{id}/cancel") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"success": "Record has been cancelled."}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {}, "status_code": 422}) + * }) + */ + public function cancel($id) + { + $enabledIncludes = $this->vehicleRentalService->getEnableGateway(); + $user = $this->auth->user(); + $vehicle_rental = VehicleRental::with($enabledIncludes)->where(['item_user_status_id' => config('constants.ConstItemUserStatus.WaitingForAcceptance'), 'user_id' => $user->id, 'id' => $id])->first(); + if (!$vehicle_rental || !$vehicle_rental->item_userable) { + return $this->response->errorNotFound("Invalid Request"); + } + try { + $error_msg = ''; + $is_payment_transaction = false; + $transaction_log = array(); + if (isPluginEnabled('Paypal') && !is_null($vehicle_rental->paypal_transaction_log)) { + $gateway_id = config('constants.ConstPaymentGateways.PayPal'); + if ($vehicle_rental->paypal_transaction_log->payment_type == 'authorized') { + $paypal = new \Plugins\Paypal\Services\PayPalService(); + $voidPayment = $paypal->voidPayment($vehicle_rental->paypal_transaction_log->authorization_id); + if (is_object($voidPayment)) { + $transaction_log['payment_type'] = $voidPayment->getState(); + $transaction_log['void_id'] = $voidPayment->getId(); + if ($transaction_log['payment_type'] == 'voided') { + $is_payment_transaction = true; + } + } else if (is_array($voidPayment) && $voidPayment['error']) { + if ($voidPayment['error']['message']) { + $error_msg = $voidPayment['error']['message']; + } else { + $error_msg = $voidPayment['error_message']; + } + } + $vehicle_rental->paypal_transaction_log->update($transaction_log); + } + } + if (isPluginEnabled('Sudopays') && !is_null($vehicle_rental->sudopay_transaction_logs)) { + $gateway_id = config('constants.ConstPaymentGateways.SudoPay'); + $sudopay = new \Plugins\Sudopays\Services\SudopayService(); + if ($vehicle_rental->sudopay_transaction_logs->status == 'Authorized') { + $voidPayment = $sudopay->voidPayment($vehicle_rental->sudopay_transaction_logs); + if (!empty($voidPayment) && ($voidPayment['status'] == 'Voided' || $voidPayment['status'] == 'Canceled')) { + $transaction_log['status'] = $voidPayment['status']; + $is_payment_transaction = true; + $vehicle_rental->sudopay_transaction_logs->update($transaction_log); + } else if (is_array($voidPayment) && $voidPayment['error']) { + if ($voidPayment['error']['message']) { + $error_msg = $voidPayment['error']['message']; + } else if ($voidPayment['error_message']) { + $error_msg = $voidPayment['error_message']; + } + } + } elseif ($vehicle_rental->sudopay_transaction_logs->status == 'Captured') { + $refundPayment = $sudopay->refundPayment($vehicle_rental->sudopay_transaction_logs); + if (!empty($refundPayment) && $refundPayment['status'] == 'Refunded') { + $transaction_log['status'] = $refundPayment['status']; + $is_payment_transaction = true; + $vehicle_rental->sudopay_transaction_logs->update($transaction_log); + } else if (is_array($refundPayment) && $refundPayment['error']) { + if ($refundPayment['error']['message']) { + $error_msg = $refundPayment['error']['message']; + } else { + $error_msg = $refundPayment['error_message']; + } + } + } + } + if (!is_null($vehicle_rental->wallet_transaction_log)) { + $gateway_id = config('constants.ConstPaymentGateways.Wallet'); + if ($vehicle_rental->wallet_transaction_log->payment_type == 'Captured') { + $walletService = new \App\Services\WalletService(); + $is_payment_transaction = $walletService->voidPayment($vehicle_rental); + } + } + if ($is_payment_transaction) { + $vehicle_rental_data['item_user_status_id'] = config('constants.ConstItemUserStatus.Cancelled'); + $vehicle_rental_data['status_updated_at'] = Carbon::now()->toDateTimeString(); + $vehicle_rental->update($vehicle_rental_data); + $this->unavailableVehicleService->clearUnavaialablelist($vehicle_rental->id); + $this->vehicleRentalService->updateItemUserCount(); + $this->transactionService->log(config('constants.ConstUserTypes.Admin'), $vehicle_rental->user_id, config('constants.ConstTransactionTypes.RefundForCanceledRenting'), $vehicle_rental->total_amount, $vehicle_rental->id, 'VehicleRentals', $gateway_id); + $this->vehicleRentalService->changeStatusMail($vehicle_rental, $vehicle_rental->item_userable, config('constants.ConstItemUserStatus.WaitingForAcceptance'), config('constants.ConstItemUserStatus.Cancelled')); + return response()->json(['Success' => 'Vehicle Rental has been cancelled'], 200); + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Vehicle Rental could not be updated. Please, try again.', $error_msg); + } + } catch (\Exception $e) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Vehicle Rental could not be updated. Please, try again.', array($e->getMessage())); + } + } + + + /** + * Confirm the specified vehicle_rental. + * Confirm the vehicle_rental with a `id`. + * @Put("/vehicle_rentals/{id}/confirm") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"success": "Record has been Confirmed."}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {}, "status_code": 422}) + * }) + */ + public function confirmed($id) + { + $enabledIncludes = $this->vehicleRentalService->getEnableGateway(); + $vehicle_rental = VehicleRental::with($enabledIncludes)->where(['item_user_status_id' => config('constants.ConstItemUserStatus.WaitingForAcceptance'), 'id' => $id])->first(); + if (!$vehicle_rental || is_null($vehicle_rental->item_userable)) { + return $this->response->errorNotFound("Invalid Request"); + } + $user = $this->auth->user(); + if ($vehicle_rental->item_userable->user_id != $user->id) { + return $this->response->errorNotFound("Invalid Request"); + } + try { + $error_msg = ''; + $is_payment_transaction = false; + $vehicle_rental_data = array(); + if (isPluginEnabled('Paypal') && !is_null($vehicle_rental->paypal_transaction_log)) { + if ($vehicle_rental->paypal_transaction_log->payment_type == 'authorized') { + $paypal = new \Plugins\Paypal\Services\PayPalService(); + $authorization = $paypal->authorizePayment($vehicle_rental->paypal_transaction_log->authorization_id); + if (is_object($authorization)) { + $capturePayment = $paypal->capturePayment($authorization, $vehicle_rental->paypal_transaction_log); + if (is_object($capturePayment)) { + $transaction_log['payment_type'] = $capturePayment->getState(); + $transaction_log['status'] = 'captured'; + $transaction_log['capture_id'] = $capturePayment->getId(); + $is_payment_transaction = true; + $vehicle_rental->paypal_transaction_log->update($transaction_log); + } elseif (is_array($capturePayment) && $capturePayment['error']) { + if ($capturePayment['error']['message']) { + $error_msg = $capturePayment['error']['message']; + } else { + $error_msg = $capturePayment['error_message']; + } + } + } else if (is_array($authorization) && $authorization['error']) { + if ($authorization['error']['message']) { + $error_msg = $authorization['error']['message']; + } else { + $error_msg = $authorization['error_message']; + } + } + } + } + if (isPluginEnabled('Sudopays') && !is_null($vehicle_rental->sudopay_transaction_logs)) { + if ($vehicle_rental->sudopay_transaction_logs->status == 'Authorized') { + $sudopay = new \Plugins\Sudopays\Services\SudopayService(); + $capturePayment = $sudopay->capturePayment($vehicle_rental->sudopay_transaction_logs); + if ($capturePayment['status'] == 'Captured') { + $transaction_log['status'] = $capturePayment['status']; + $vehicle_rental->sudopay_transaction_logs->update($transaction_log); + $is_payment_transaction = true; + $vehicle_rental->sudopay_transaction_logs->update($transaction_log); + } elseif (is_array($capturePayment) && $capturePayment['error']) { + if ($capturePayment['error']['message']) { + $error_msg = $capturePayment['error']['message']; + } else { + $error_msg = $capturePayment['error_message']; + } + } + } + } + if (!is_null($vehicle_rental->wallet_transaction_log)) { + if ($vehicle_rental->wallet_transaction_log->payment_type == 'Captured') { + $is_payment_transaction = true; + } + } + if ($is_payment_transaction) { + $vehicle_rental_data['item_user_status_id'] = config('constants.ConstItemUserStatus.Confirmed'); + $vehicle_rental_data['status_updated_at'] = Carbon::now()->toDateTimeString(); + $vehicle_rental->update($vehicle_rental_data); + $this->vehicleRentalService->updateItemUserCount(); + $this->vehicleRentalService->sendConfirmationMail($vehicle_rental, $vehicle_rental->item_userable); + $this->vehicleRentalService->changeStatusMail($vehicle_rental, $vehicle_rental->item_userable, config('constants.ConstItemUserStatus.WaitingForAcceptance'), config('constants.ConstItemUserStatus.Confirmed')); + return response()->json(['Success' => 'Vehicle Rental has been Confirmed'], 200); + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Vehicle Rental could not be updated. Please, try again.', $error_msg); + } + } catch (\Exception $e) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Vehicle Rental could not be updated. Please, try again.', array($e->getMessage())); + } + } + + /** + * @param Request $request + * @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response + */ + public function payNow(Request $request, $vehicle_rental_id) + { + $user = $this->auth->user(); + $request_amount = $request->only('amount'); + if ($request->has('gateway_id') && ((isPluginEnabled('Paypal') && $request->gateway_id == config('constants.ConstPaymentGateways.PayPal')) || (isPluginEnabled('Sudopays') && $request->gateway_id == config('constants.ConstPaymentGateways.SudoPay')) || ($request->gateway_id == config('constants.ConstPaymentGateways.Wallet')))) { + $data['amount'] = $request->amount; + if ($request->gateway_id == config('constants.ConstPaymentGateways.PayPal')) { + $paypalLogService = new \Plugins\Paypal\Services\PaypalTransactionLogService(); + $paypalService = new \Plugins\Paypal\Services\PayPalService(); + $paypal_vehicle_rental = VehicleRental::with('paypal_transaction_log')->where('id', $request->vehicle_rental_id)->first(); + if (!$paypal_vehicle_rental || is_null($paypal_vehicle_rental->item_userable)) { + return $this->response->errorNotFound("Invalid Request"); + } + // Already user have try and not paid case + if (!is_null($paypal_vehicle_rental->paypal_transaction_log)) { + $paypalLogService->updateLogById($data, $paypal_vehicle_rental->paypal_transaction_log->id); + $paypal_transaction = $paypal_vehicle_rental->paypal_transaction_log; + } else { + $paypal_transaction = $paypalLogService->log($data); + $paypal_vehicle_rental = VehicleRental::with('paypal_transaction_log')->where('id', $request->vehicle_rental_id)->first(); + $paypal_vehicle_rental->paypal_transaction_log()->save($paypal_transaction); + } + if (config('vehicle_rental.is_auto_approve')) { + $response = $paypalService->createPayment($paypal_transaction->id, config('constants.ConstPaypalGatewaysProcess.sale')); + } else { + $response = $paypalService->createPayment($paypal_transaction->id, config('constants.ConstPaypalGatewaysProcess.authorize')); + } + return response()->json(['url' => $response], 200); + } elseif ($request->gateway_id == config('constants.ConstPaymentGateways.SudoPay')) { + $sudopay_data = array('address', 'city', 'country', 'email', 'gateway_id', 'payment_id', 'phone', 'state', 'zip_code'); + if ($request->has('credit_card_code')) { + $sudopay_data = array_merge($sudopay_data, array('credit_card_code', 'credit_card_expire', 'credit_card_name_on_card', 'credit_card_number')); + } + if ($request->has('payment_note')) { + $sudopay_data = array_merge($sudopay_data, array('payment_note')); + } + $sudopay_data = $request->only($sudopay_data); + $log_data['amount'] = $request_amount['amount']; + $log_data['gateway_id'] = $request['payment_id']; + $this->logtService = new \Plugins\Sudopays\Services\SudopayTransactionLogService(); + $this->paymentService = new \Plugins\Sudopays\Services\SudopayService(); + $cur_vehicle_rental = VehicleRental::with(['sudopay_transaction_logs'])->where('id', '=', $request->vehicle_rental_id)->first(); + if (is_null(!$cur_vehicle_rental || $cur_vehicle_rental->item_userable)) { + return $this->response->errorNotFound("Invalid Request"); + } + // Already user have try and not paid case + if (!is_null($cur_vehicle_rental->sudopay_transaction_logs)) { + $this->logtService->updateLogById($log_data, $cur_vehicle_rental->sudopay_transaction_logs->id); + $cur_transaction = $cur_vehicle_rental->sudopay_transaction_logs; + } else { + $cur_transaction = $this->logtService->log($log_data); + $cur_vehicle_rental = VehicleRental::with('sudopay_transaction_logs')->where('id', $request->vehicle_rental_id)->first(); + $cur_vehicle_rental->sudopay_transaction_logs()->save($cur_transaction); + } + $response = $this->paymentService->createPayment($cur_transaction->id, $sudopay_data); + if (!empty($response['gateway_callback_url'])) { + return response()->json(['url' => $response['gateway_callback_url']], 200); + } + if (!empty($response['pending'])) { + return response()->json(['Success' => 'Once payment is received, it will be processed'], 200); + } elseif (!empty($response['success'])) { + return response()->json(['Success' => 'Vehicle booked successfully'], 200); + } elseif (!empty($response['error'])) { + return response()->json(['Success' => 'Your payment could not be completed'], 200); + } + } elseif ($request->gateway_id == config('constants.ConstPaymentGateways.Wallet')) { + $walletLogService = new \App\Services\WalletTransactionLogService(); + $walletService = new \App\Services\WalletService(); + $wallet_vehicle_rental = VehicleRental::with('wallet_transaction_log')->where('id', $request->vehicle_rental_id)->first(); + if (!$wallet_vehicle_rental || is_null($wallet_vehicle_rental->item_userable)) { + return $this->response->errorNotFound("Invalid Request"); + } + $data['amount'] = $request->amount; + // Already user have try and not paid case + if (is_null($wallet_vehicle_rental->wallet_transaction_log)) { + $wallet_log = $walletLogService->log($data); + $wallet_vehicle_rental = VehicleRental::with('wallet_transaction_log')->where('id', $request->vehicle_rental_id)->first(); + $wallet_vehicle_rental->wallet_transaction_log()->save($wallet_log); + } else { + $walletLogService->updateLogById($data, $wallet_vehicle_rental->wallet_transaction_log->id); + $wallet_log = $wallet_vehicle_rental->wallet_transaction_log; + } + $response = $walletService->createPayment($wallet_log->id); + if ($response) { + $exe_response = $walletService->executePayment($wallet_vehicle_rental, 'MorphVehicleRental', $wallet_log->id); + return response()->json(['data' => 'wallet'], 200); + } + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Payment gateway could not be set. Please, try again.'); + } + } + + /** + * Checkin the specified vehicle_rental. + * Checkin the vehicle_rental with a `id`. + * @get("/vehicle_rentals/{id}/checkin") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"success": "Record has been checkin."}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {}, "status_code": 422}) + * }) + */ + public function checkin($id) + { + $enabledIncludes = array('item_user_status'); + $user = $this->auth->user(); + $vehicle_rental = VehicleRental::with($enabledIncludes)->filterByStatus($id, config('constants.ConstItemUserStatus.Confirmed'))->first(); + if (!$vehicle_rental || is_null($vehicle_rental->item_userable)) { + return $this->response->errorNotFound("Invalid Request"); + } + if ($user->role_id == config('constants.ConstUserTypes.Admin') || ($user->id == $vehicle_rental->item_userable->user_id && config('vehicle_rental.is_host_checkin_and_checkout') == 1)) { + return $this->vehicleRentalService->saveCheckInDetail($vehicle_rental); + } else { + return $this->response->errorNotFound("Invalid Request"); + } + } + + /** + * Checkout the specified vehicle_rental. + * Checkout the vehicle_rental with a `id`. + * @get("/vehicle_rentals/{id}/checkout") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"success": "Record has been checkout."}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {}, "status_code": 422}) + * }) + */ + public function checkout(Request $request, $id) + { + $enabledIncludes = array('item_user_status', 'late_payment_detail', 'unavailable_vehicle'); + $user = $this->auth->user(); + $vehicle_rental = VehicleRental::with($enabledIncludes)->filterByStatus($id, config('constants.ConstItemUserStatus.Attended'))->first(); + if (!$vehicle_rental || is_null($vehicle_rental->item_userable)) { + return $this->response->errorNotFound("Invalid Request"); + } + if ($user->role_id == config('constants.ConstUserTypes.Admin') || ($user->id == $vehicle_rental->item_userable->user_id && config('vehicle_rental.is_host_checkin_and_checkout') == 1)) { + $claim_request_amount = 0; + if ($request->has('claim_request_amount')) { + $claim_request_amount = $request->claim_request_amount; + } + return $this->vehicleRentalService->saveCheckoutDetail($vehicle_rental, $claim_request_amount); + } + return $this->response->errorNotFound("Invalid Request"); + } +} diff --git a/app/Plugins/VehicleRentals/Model/VehicleRental.php b/app/Plugins/VehicleRentals/Model/VehicleRental.php new file mode 100644 index 0000000..3def62e --- /dev/null +++ b/app/Plugins/VehicleRentals/Model/VehicleRental.php @@ -0,0 +1,319 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleRentals\Model; + +use Illuminate\Http\Request; +use Illuminate\Database\Eloquent\Model; + +use JWTAuth; +use Plugins\VehicleFeedbacks\Model\VehicleFeedback; +use Plugins\Vehicles\Model\UnavailableVehicle; +use Tymon\JWTAuth\Exceptions\JWTException; +use App\User; +use Plugins\Vehicles\Model\CounterLocation; +use Illuminate\Support\Facades\Auth; +use DB; +use Carbon; +use Plugins\Vehicles\Services\VehicleService; + +/** + * Class VehicleRental + * @package App + */ +class VehicleRental extends Model +{ + /** + * @var string + */ + protected $table = "item_users"; + /** + * The attributes that are mass assignable. + * @var array + */ + protected $fillable = [ + 'user_id', 'item_booking_start_date', 'item_booking_end_date', 'pickup_counter_location_id', 'drop_counter_location_id', 'coupon_code', 'item_user_status_id', 'status_updated_at', 'is_payment_cleared', 'booking_amount', 'deposit_amount', 'surcharge_amount', 'extra_accessory_amount', 'tax_amount', 'insurance_amount', 'fuel_option_amount', 'drop_location_differ_charges', 'additional_fee', 'total_amount', 'payment_gateway_id', 'coupon_id', 'coupon_discount_amount', 'special_discount_amount', 'type_discount_amount', 'admin_commission_amount', 'host_service_amount', 'late_fee', 'claim_request_amount', 'quantity', 'is_dispute', 'paid_deposit_amount', 'paid_manual_amount', 'booker_amount' + ]; + + /** + * Get all of the owning likeable models. + */ + public function item_userable() + { + return $this->morphTo(); + } + + /** + * @return mixed + */ + public function sudopay_transaction_logs() + { + return $this->morphOne(\Plugins\Sudopays\Model\SudopayTransactionLog::class, 'sudopay_transaction_logable'); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function user() + { + return $this->belongsTo(User::class); + } + + + /** + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function item_user_status() + { + return $this->belongsTo(VehicleRentalStatus::class); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function vehicle_coupon() + { + return $this->belongsTo(\Plugins\VehicleCoupons\Model\VehicleCoupon::class); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\MorphOne + */ + public function transactions() + { + return $this->morphOne(\App\Transaction::class, 'transactionable'); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\MorphMany + */ + public function message() + { + return $this->morphMany(\App\Message::class, 'messageable'); + } + + + /** + * @return \Illuminate\Database\Eloquent\Relations\MorphOne + */ + public function item_user_dispute() + { + return $this->morphOne(\Plugins\VehicleDisputes\Model\VehicleDispute::class, 'item_user_disputable'); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\MorphMany + */ + public function paypal_transaction_log() + { + return $this->morphOne(\Plugins\Paypal\Model\PaypalTransactionLog::class, 'paypal_transaction_logable'); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\MorphMany + */ + public function wallet_transaction_log() + { + return $this->morphOne(\App\WalletTransactionLog::class, 'wallet_transaction_logable'); + } + + /** + * @return mixed + */ + public function pickup_counter_location() + { + return $this->belongsTo(CounterLocation::class, 'pickup_counter_location_id'); + } + + /** + * @return mixed + */ + public function drop_counter_location() + { + return $this->belongsTo(CounterLocation::class, 'drop_counter_location_id'); + } + +// todo: vehicle_rental_additional_chargable need to fix relation + public function vehicle_rental_additional_chargable() + { + return $this->hasMany(VehicleRentalAdditionalCharge::class, 'item_user_id'); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\HasOne + */ + public function late_payment_detail() + { + return $this->hasOne(VehicleRentalLatePaymentDetail::class, 'item_user_id'); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\HasOne + */ + public function booker_detail() + { + return $this->hasOne(VehicleRentalBookerDetail::class, 'item_user_id'); + } + + public function vehicle_feedback() + { + return $this->hasMany(VehicleFeedback::class, 'item_user_id'); + } + + public function unavailable_vehicle() + { + return $this->hasOne(UnavailableVehicle::class, 'item_user_id'); + } + + /** + * @param $query + * @param Request $request + * @param string $status + * @return mixed + */ + public function scopeFilterByRequest($query, Request $request, $status = '') + { + $query->orderBy($request->input('sort', 'id'), $request->input('sortby', 'desc')); + if ($request->has('q')) { + // vehicle search + // polymoric relation q search unable to do it. + // user search + $query->WhereHas('user', function ($q) use ($request) { + $q->where('username', 'like', '%' . $request->input('q') . '%'); + }); + $query->orWhereHas('item_user_status', function ($q) use ($request) { + $q->where('name', 'like', '%' . $request->input('q') . '%'); + }); + $query->orWhere('item_userable.name', 'LIKE', '%' . $request->input('q') . '%'); + } + if ($request->has('start_date')) { + $query->where('item_booking_start_date', '>=', $request->input('start_date')); + } + if ($request->has('end_date')) { + $query->where('item_booking_end_date', '<=', $request->input('end_date')); + } + if ($request->input('filter') === 'payment_pending') { + $query->where('item_user_status_id', '=', config('constants.ConstItemUserStatus.PaymentPending')); + } else if ($request->input('filter') === 'waiting_for_acceptance') { + $query->where('item_user_status_id', '=', config('constants.ConstItemUserStatus.WaitingForAcceptance')); + } else if ($request->input('filter') === 'rejected') { + $query->where('item_user_status_id', '=', config('constants.ConstItemUserStatus.Rejected')); + } else if ($request->input('filter') === 'cancelled') { + $query->where('item_user_status_id', '=', config('constants.ConstItemUserStatus.Cancelled')); + } else if ($request->input('filter') === 'expired') { + $query->where('item_user_status_id', '=', config('constants.ConstItemUserStatus.Expired')); + } else if ($request->input('filter') === 'confirmed') { + $query->where('item_user_status_id', '=', config('constants.ConstItemUserStatus.Confirmed')); + } else if ($request->input('filter') === 'waiting_for_review') { + $query->where('item_user_status_id', '=', config('constants.ConstItemUserStatus.WaitingForReview')); + } else if ($request->input('filter') === 'completed') { + $query->where('item_user_status_id', '=', config('constants.ConstItemUserStatus.Completed')); + } + if (!empty($status)) { + $query->whereIn('item_user_status_id', $status); + } + if (empty($status) && $request->has('item_user_status_id')) { + $query->where('item_user_status_id', '=', $request->item_user_status_id); + } + // filter records for particular vehicle + if ($request->has('vehicle_id')) { + $query->where('item_userable_id', '=', $request->vehicle_id); + } + + // filter records for calendar page + if ($request->has('cal_start_date') && $request->has('cal_end_date')) { + $request->cal_start_date = date("Y-m-d H:i:s", strtotime($request->cal_start_date)); + $request->cal_end_date = date("Y-m-d H:i:s", strtotime($request->cal_end_date)); + $query->where(function ($query) use ($request) { + $query->whereBetween('item_booking_start_date', [$request->cal_start_date, $request->cal_end_date]) + ->orWhereBetween('item_booking_end_date', [$request->cal_start_date, $request->cal_end_date]) + ->orwhere(function ($query) use ($request) { + $query->where('item_booking_start_date', '>', $request->cal_start_date) + ->where('item_booking_end_date', '<', $request->cal_start_date); + })->orwhere(function ($query) use ($request) { + $query->where('item_booking_start_date', '<', $request->cal_end_date) + ->where('item_booking_end_date', '>', $request->cal_end_date); + }); + }); + } + return $query; + } + + public function scopeFilterByVehicleRental($query, $is_user_check = true) + { + $user = Auth::user(); + $query->where('item_userable_type', 'MorphVehicle'); + if ($is_user_check) { + $query->where('user_id', $user->id); + } + return $query; + } + + public function scopeFilterByBooking($query, $request) { + if($request->has('type') && $request->type == 'booking' && $request->has('vehicle_id')) { + $query->where('item_userable_id', $request->vehicle_id)->where('item_userable_type', 'MorphVehicle'); + } + return $query; + } + + public function scopeFilterByStatus($query, $id, $status_id) + { + $current_date = Carbon::now()->toDateTimeString(); + $query->where('id', '=', $id); + $query->where('item_user_status_id', '=', $status_id); + if ($status_id == config('constants.ConstItemUserStatus.Confirmed')) { + $query->where('item_booking_start_date', '<=', $current_date); + } + return $query; + } + + /** + * @return array + */ + public function scopeGetValidationRule() + { + return [ + 'vehicle_id' => 'sometimes|required|integer', + 'item_booking_start_date' => 'required|date|date_format:Y-m-d H:i:s', + 'item_booking_end_date' => 'required|date|date_format:Y-m-d H:i:s', + 'pickup_counter_location_id' => 'required|integer', + 'drop_counter_location_id' => 'required|integer', + 'quantity' => 'sometimes|integer', + 'coupon_code' => 'sometimes|required' + ]; + } + + public function scopeGetValidationMessage() + { + return [ + 'vehicle_id.required' => 'Required', + 'vehicle_id.integer' => 'Vehicle id must be a number!', + 'item_booking_start_date.required' => 'Required', + 'item_booking_start_date.date' => 'Start date should be a date!', + 'item_booking_start_date.date_format' => 'Date should be in Y-m-d H:i:s format', + 'item_booking_end_date.required' => 'Required', + 'item_booking_end_date.date' => 'Start date should be a date!', + 'item_booking_end_date.date_format' => 'Date should be in Y-m-d H:i:s format', + 'pickup_counter_location_id.required' => 'Required', + 'pickup_counter_location_id.integer' => 'pickup location must be a number!', + 'drop_counter_location_id.required' => 'Required', + 'drop_counter_location_id.integer' => 'drop location must be a number!', + 'coupon_code.required' => 'Required', + 'quantity.required' => 'Required', + 'quantity.integer' => 'Quantity must be a number', + ]; + } + +} diff --git a/app/Plugins/VehicleRentals/Model/VehicleRentalAdditionalCharge.php b/app/Plugins/VehicleRentals/Model/VehicleRentalAdditionalCharge.php new file mode 100644 index 0000000..ff9bf7a --- /dev/null +++ b/app/Plugins/VehicleRentals/Model/VehicleRentalAdditionalCharge.php @@ -0,0 +1,58 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleRentals\Model; + +use Illuminate\Http\Request; +use Illuminate\Database\Eloquent\Model; + +use JWTAuth; +use DB; + + +/** + * Class VehicleRentalAdditionalCharge + * @package Plugins\VehicleRentals\Model + */ +class VehicleRentalAdditionalCharge extends Model +{ + /** + * @var string + */ + protected $table = "item_user_additional_charges"; + /** + * The attributes that are mass assignable. + * @var array + */ + protected $fillable = [ + 'item_user_id', 'additional_chargable_type', 'additional_chargable_id', 'amount' + ]; + + /** + * Get all of the owning likeable models. + */ + public function vehicle_rental_additional_chargable() + { + return $this->morphTo(); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function vehicle_rental() + { + return $this->belongsTo(VehicleRental::class, 'item_user_id'); + } +} diff --git a/app/Plugins/VehicleRentals/Model/VehicleRentalBookerDetail.php b/app/Plugins/VehicleRentals/Model/VehicleRentalBookerDetail.php new file mode 100644 index 0000000..e078ea3 --- /dev/null +++ b/app/Plugins/VehicleRentals/Model/VehicleRentalBookerDetail.php @@ -0,0 +1,79 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleRentals\Model; + +use Illuminate\Http\Request; +use Illuminate\Database\Eloquent\Model; + +use JWTAuth; + + +/** + * Class VehicleRentalBookerDetail + * @package Plugins\VehicleRentals\Model + */ +class VehicleRentalBookerDetail extends Model +{ + /** + * @var string + */ + protected $table = "booker_details"; + /** + * The attributes that are mass assignable. + * @var array + */ + protected $fillable = [ + 'item_user_id', 'email', 'first_name', 'last_name', 'mobile', 'address' + ]; + + /** + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function vehicle_rental() + { + return $this->belongsTo(VehicleRental::class); + } + + /** + * @return array + */ + public function scopeGetValidationRule() + { + return [ + 'item_user_id' => 'required|integer', + 'first_name' => 'required', + 'last_name' => 'required', + 'email' => 'required|email', + 'mobile' => 'required', + 'address' => 'required' + ]; + } + + public function scopeGetValidationMessage() + { + return [ + 'item_user_id.required' => 'Required', + 'item_user_id.integer' => 'Vehicle id must be a number!', + 'first_name.required' => 'Required', + 'last_name.required' => 'Required', + 'email.required' => 'Required', + 'email.email' => 'Given email is not valid!', + 'mobile.required' => 'Required', + 'address.required' => 'Required' + ]; + } + +} diff --git a/app/Plugins/VehicleRentals/Model/VehicleRentalLatePaymentDetail.php b/app/Plugins/VehicleRentals/Model/VehicleRentalLatePaymentDetail.php new file mode 100644 index 0000000..374779a --- /dev/null +++ b/app/Plugins/VehicleRentals/Model/VehicleRentalLatePaymentDetail.php @@ -0,0 +1,50 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleRentals\Model; + +use Illuminate\Http\Request; +use Illuminate\Database\Eloquent\Model; + +use JWTAuth; + + +/** + * Class VehicleRentalLatePaymentDetail + * @package Plugins\VehicleRentals\Model + */ +class VehicleRentalLatePaymentDetail extends Model +{ + /** + * @var string + */ + protected $table = "late_payment_details"; + /** + * The attributes that are mass assignable. + * @var array + */ + protected $fillable = [ + 'item_user_id', 'booking_start_date', 'booking_end_date', 'checkin_date', 'checkout_date', 'booking_amount', 'late_checkout_fee', 'extra_time_taken' + ]; + + /** + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function vehicle_rental() + { + return $this->belongsTo(VehicleRental::class); + } + +} diff --git a/app/Plugins/VehicleRentals/Model/VehicleRentalStatus.php b/app/Plugins/VehicleRentals/Model/VehicleRentalStatus.php new file mode 100644 index 0000000..21d74fe --- /dev/null +++ b/app/Plugins/VehicleRentals/Model/VehicleRentalStatus.php @@ -0,0 +1,55 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleRentals\Model; + +use Illuminate\Http\Request; +use Illuminate\Database\Eloquent\Model; + +class VehicleRentalStatus extends Model +{ + /** + * @var string + */ + protected $table = "item_user_statuses"; + + /** + * @return \Illuminate\Database\Eloquent\Relations\HasMany + */ + public function vehicle_rental() + { + return $this->hasMany(VehicleRental::class); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\HasMany + */ + public function message() + { + return $this->hasMany(\App\Message::class); + } + + /** + * @param $query + * @param Request $request + * @return mixed + */ + public function scopeFilterByRequest($query, Request $request) + { + $query->orderBy($request->input('sort', 'display_order'), $request->input('sortby', 'ASC')); + return $query; + } + +} diff --git a/app/Plugins/VehicleRentals/Providers/VehicleRentalServiceProvider.php b/app/Plugins/VehicleRentals/Providers/VehicleRentalServiceProvider.php new file mode 100644 index 0000000..134a8ae --- /dev/null +++ b/app/Plugins/VehicleRentals/Providers/VehicleRentalServiceProvider.php @@ -0,0 +1,64 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleRentals\Providers; + +use Illuminate\Database\Eloquent\Relations\Relation; +use Illuminate\Support\ServiceProvider; +class VehicleRentalServiceProvider extends ServiceProvider +{ + /** + * Register any application services. + * + * @return void + */ + public function register() + { + include __DIR__ . '/../routes.php'; + $this->app->make('Plugins\VehicleRentals\Controllers\Admin\AdminVehicleRentalsController'); + $this->app->make('Plugins\VehicleRentals\Controllers\Admin\AdminVehicleRentalStatusesController'); + $this->app->make('Plugins\VehicleRentals\Controllers\VehicleRentalsController'); + $this->app->make('Plugins\VehicleRentals\Controllers\VehicleRentalStatusesController'); + } + + /** + * Bootstrap the application services. + * + * @return void + */ + public function boot() + { + $enabledIncludes = array(); + $enabledIncludes['MorphVehicle'] = \Plugins\Vehicles\Model\Vehicle::class; + if (isPluginEnabled('VehicleInsurances')) { + $enabledIncludes['MorphInsurance'] = \Plugins\VehicleInsurances\Model\VehicleTypeInsurance::class; + } + if (isPluginEnabled('VehicleFuelOptions')) { + $enabledIncludes['MorphFuelOption'] = \Plugins\VehicleFuelOptions\Model\VehicleTypeFuelOption::class; + } + if (isPluginEnabled('VehicleExtraAccessories')) { + $enabledIncludes['MorphExtraAccessory'] = \Plugins\VehicleExtraAccessories\Model\VehicleTypeExtraAccessory::class; + } + if (isPluginEnabled('VehicleTaxes')) { + $enabledIncludes['MorphTax'] = \Plugins\VehicleTaxes\Model\VehicleTypeTax::class; + } + if (isPluginEnabled('VehicleSurcharges')) { + $enabledIncludes['MorphSurcharge'] = \Plugins\VehicleSurcharges\Model\VehicleTypeSurcharge::class; + } + if (!empty($enabledIncludes)) { + Relation::morphMap($enabledIncludes); + } + } +} diff --git a/app/Plugins/VehicleRentals/Services/VehicleRentalBookerDetailService.php b/app/Plugins/VehicleRentals/Services/VehicleRentalBookerDetailService.php new file mode 100644 index 0000000..41e1898 --- /dev/null +++ b/app/Plugins/VehicleRentals/Services/VehicleRentalBookerDetailService.php @@ -0,0 +1,60 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleRentals\Services; + +use Plugins\VehicleRentals\Model\VehicleRentalBookerDetail; +use Carbon; +use Validator; +use Illuminate\Http\Request; + +class VehicleRentalBookerDetailService +{ + + /** + * VehicleRentalService constructor. + */ + public function __construct() + { + + } + + public function addRentalBookerDetail($request) + { + $vehicle_rental_booker_data = $request->only('email', 'first_name', 'last_name', 'mobile', 'address'); + if($request->has('id')){ + $vehicle_rental_booker_data['item_user_id'] = $request->id; + }else{ + return ['Error' => "invalid request", 'type' => 'invalid']; + } + $validator = Validator::make($vehicle_rental_booker_data, VehicleRentalBookerDetail::GetValidationRule(), VehicleRentalBookerDetail::GetValidationMessage()); + if ($validator->passes()) { + $booker_detail = VehicleRentalBookerDetail::where('item_user_id', '=', $request->id)->first(); + try { + if (!empty($booker_detail)) { + $booker_detail->update($vehicle_rental_booker_data); + } else { + VehicleRentalBookerDetail::create($vehicle_rental_booker_data); + } + + return ['Success' => 'Booker details has been added successfully']; + } catch (\Exception $e) { + return ['Error' => array($e->getMessage()), 'type' => 'catch']; + } + } else { + return ['Error' => $validator, 'type' => 'validate']; + } + } +} diff --git a/app/Plugins/VehicleRentals/Services/VehicleRentalLatePaymentDetailService.php b/app/Plugins/VehicleRentals/Services/VehicleRentalLatePaymentDetailService.php new file mode 100644 index 0000000..0fa5d98 --- /dev/null +++ b/app/Plugins/VehicleRentals/Services/VehicleRentalLatePaymentDetailService.php @@ -0,0 +1,49 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleRentals\Services; + +use Plugins\VehicleRentals\Model\VehicleRentalLatePaymentDetail; +use Carbon; + +class VehicleRentalLatePaymentDetailService +{ + + /** + * VehicleRentalService constructor. + */ + public function __construct() + { + + } + + public function addRentalDetail($vehicle_rental) + { + $vehicle_rental_late_payment_data['item_user_id'] = $vehicle_rental->id; + $vehicle_rental_late_payment_data['booking_start_date'] = $vehicle_rental->item_booking_start_date; + $vehicle_rental_late_payment_data['booking_end_date'] = $vehicle_rental->item_booking_end_date; + $vehicle_rental_late_payment_data['checkin_date'] = Carbon::now()->toDateTimeString(); + $vehicle_rental_late_payment_data['booking_amount'] = $vehicle_rental->total_amount; + VehicleRentalLatePaymentDetail::create($vehicle_rental_late_payment_data); + } + + public function updateRentalDetail($vehicle_rental, $total_late_hours) + { + $vehicle_rental_late_payment_data['late_checkout_fee'] = $vehicle_rental->late_fee; + $vehicle_rental_late_payment_data['extra_time_taken'] = ($total_late_hours > 0) ? $total_late_hours : 0; + $vehicle_rental_late_payment_data['checkout_date'] = Carbon::now()->toDateTimeString(); + VehicleRentalLatePaymentDetail::where('id', '=', $vehicle_rental->late_payment_detail->id)->update($vehicle_rental_late_payment_data); + } +} diff --git a/app/Plugins/VehicleRentals/Services/VehicleRentalService.php b/app/Plugins/VehicleRentals/Services/VehicleRentalService.php new file mode 100644 index 0000000..7c20b8d --- /dev/null +++ b/app/Plugins/VehicleRentals/Services/VehicleRentalService.php @@ -0,0 +1,927 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleRentals\Services; + +use App\Services\MailService; +use App\Services\MessageService; +use App\Services\TransactionService; +use App\User; +use Plugins\VehicleRentals\Model\VehicleRental; +use Plugins\VehicleRentals\Model\VehicleRentalStatus; +use Plugins\Vehicles\Services\VehicleService; +use Plugins\Vehicles\Services\UnavailableVehicleService; +use Plugins\Vehicles\Model\Vehicle; +use Carbon; +use DB; +use Log; +use Cache; +use Plugins\Vehicles\Model\UnavailableVehicle; + +class VehicleRentalService +{ + /** + * @var + */ + protected $transactionService; + + /** + * @var + */ + protected $vehicleRentalLatePaymentDetailService; + + /** + * @var + */ + protected $vehicleService; + + /** + * @var + */ + protected $unavailableVehicleService; + + /** + * VehicleRentalService constructor. + */ + public function __construct() + { + $this->setMailService(); + $this->setMessageService(); + $this->setTransactionService(); + $this->setVehicleRentalLatePaymentDetailService(); + $this->setVehicleService(); + $this->setUnavailableVehicleService(); + $this->setVehicleCouponService(); + } + + public function setMailService() + { + $this->mailService = new MailService(); + } + + public function setTransactionService() + { + $this->transactionService = new TransactionService(); + } + + public function setMessageService() + { + $this->messageService = new MessageService(); + } + + public function setVehicleCouponService() + { + $this->vehicleCouponService = new \Plugins\VehicleCoupons\Services\VehicleCouponService(); + } + + /** + * setVehicleRentalLatePaymentDetailService + */ + public function setVehicleRentalLatePaymentDetailService() + { + $this->vehicleRentalLatePaymentDetailService = new VehicleRentalLatePaymentDetailService(); + } + + /** + * setVehicleService + */ + public function setVehicleService() + { + $this->vehicleService = new VehicleService(); + } + + /** + * setUnavailableVehicleService + */ + public function setUnavailableVehicleService() + { + $this->unavailableVehicleService = new UnavailableVehicleService(); + } + + /** + * get last vehicle_rental record for admin dashboard + * @param $request + * @return VehicleRental created_at + */ + public function getLastVehicleRental() + { + $vehicle_rental_details = VehicleRental::select('created_at')->where('item_user_status_id', '!=', config('constants.ConstItemUserStatus.PaymentPending'))->filterByVehicleRental(false)->orderBy('created_at', 'desc')->first(); + return ($vehicle_rental_details) ? $vehicle_rental_details->created_at->diffForHumans() : "-"; + } + + /** + * @param $request + * @param string $type + * @return mixed + */ + public function getVehicleRentalCount($request, $type = 'filter') + { + if ($type == 'filter') { + $check_date = $this->getDateFilter($request); + $check_date = Carbon::parse($check_date)->format('Y-m-d'); + $booking_count = VehicleRental::where('created_at', '>=', $check_date) + ->filterByVehicleRental(false) + ->count(); + } else { + $booking_count = VehicleRental::filterByVehicleRental(false)->count(); + } + return $booking_count; + } + + /** + * get the date filter + * @return $check_date + */ + public function getDateFilter($request) + { + $check_date = Carbon::now()->subDays(7); + if ($request->has('filter')) { + if ($request->filter == 'lastDays') { + $check_date = Carbon::now()->subDays(7); + } else if ($request->filter == 'lastWeeks') { + $check_date = Carbon::now()->subWeeks(4); + } else if ($request->filter == 'lastMonths') { + $check_date = Carbon::now()->subMonths(3); + } else if ($request->filter == 'lastYears') { + $check_date = Carbon::now()->subYears(3); + } + } + return $check_date; + } + + /** + * Send vehicle_rental mail + * @param $vehicle_rental + * @param $item + */ + public function sendVehicleRentalMail($vehicle_rental, $item) + { + $from = config('constants.ConstUserIds.Admin'); + $host = $item->user; + $booker = $vehicle_rental->user; + $default_content = array( + '##SITE_NAME##' => config('site.name'), + '##SITE_URL##' => '' . url('/') . '', + '##FROM_EMAIL##' => config('site.from_email'), + '##CONTACT_MAIL##' => config('site.contact_email'), + '##CONTACT_URL##' => 'Contact Us' + ); + //VehicleRental mail to booker + $template = $this->mailService->getTemplate('New VehicleRental Message To Booker'); + if (config('vehicle_rental.is_auto_approve')) { + $cancel_url = 'cancel'; + } else { + $cancel_url = 'Cancel'; + } + $item_link = '' . $item->name . ''; + $order_link = '' . $vehicle_rental->id . ''; + $host_link = '' . $host->username . ''; + $booker_link = '' . $booker->username . ''; + $emailFindReplace = array( + '##USERNAME##' => $booker->username, + '##HOST_NAME##' => $host_link, + '##ITEM_NAME##' => $item_link, + '##ORDER_NO##' => $order_link, + '##ITEM_FULL_NAME##' => $item_link, + '##ITEM_DESCRIPTION##' => $item->description, + '##FROM_DATE##' => $vehicle_rental->item_booking_start_date, + '##HOST_CONTACT_LINK##' => $host_link, + '##CANCEL_URL##' => $cancel_url, + '##ITEM_AUTO_EXPIRE_DATE##' => config('vehicle_rental.auto_expire') + ); + $this->mailService->sendMail($template, $emailFindReplace, $booker->email, $booker->username); + //Save vehicle_rental message to booker + $vehicle_rental_mail_template = array_merge($emailFindReplace, $default_content); + $message_content_arr = array(); + $message_content_arr['message'] = strtr($template['body_content'], $vehicle_rental_mail_template); + $message_content_arr['subject'] = strtr($template['subject'], $vehicle_rental_mail_template); + $this->messageService->saveMessageContent($message_content_arr, $item->id, $vehicle_rental->id, $from, $vehicle_rental->user_id, config('constants.ConstItemUserStatus.PaymentPending'), 'VehicleRental'); + //VehicleRental mail to host + if (config('vehicle_rental.is_auto_approve')) { + $template = $this->mailService->getTemplate('New VehicleRental Message To Host On Auto Approve'); + } else { + $template = $this->mailService->getTemplate('New VehicleRental Message To Host'); + } + $emailFindReplace = array( + '##USERNAME##' => $host->username, + '##BOOKER_USERNAME##' => $booker_link, + '##ITEM_NAME##' => $item_link, + '##ORDER_NO##' => $order_link, + '##ACCEPT_URL##' => 'Accept', + '##REJECT_URL##' => 'Reject' + ); + $this->mailService->sendMail($template, $emailFindReplace, $host->email, $host->username); + //Save vehicle_rental message to host + $vehicle_rental_mail_template = array_merge($emailFindReplace, $default_content); + $message_content_arr = array(); + $message_content_arr['message'] = strtr($template['body_content'], $vehicle_rental_mail_template); + $message_content_arr['subject'] = strtr($template['subject'], $vehicle_rental_mail_template); + $this->messageService->saveMessageContent($message_content_arr, $item->id, $vehicle_rental->id, $from, $item->user_id, config('constants.ConstItemUserStatus.PaymentPending'), 'VehicleRental'); + } + + /** + * return enable gateways + * @return array + */ + public function getEnableGateway() + { + $enabledIncludes = array(); + $enabledIncludes[] = 'wallet_transaction_log'; + // check if plugin enabled and include + (isPluginEnabled('Paypal')) ? $enabledIncludes[] = 'paypal_transaction_log' : ''; + (isPluginEnabled('Sudopays')) ? $enabledIncludes[] = 'sudopay_transaction_logs' : ''; + return $enabledIncludes; + } + + /** + * @param $vehicle_rental + * @param $item + */ + public function sendConfirmationMail($vehicle_rental, $item) + { + $host = $item->user; + $booker = $vehicle_rental->user; + $item_link = '' . $item->name . ''; + $order_link = '' . $vehicle_rental->id . ''; + $host_link = '' . $host->username . ''; + $site_link = '' . url('/') . ''; + $default_content = array( + '##SITE_NAME##' => config('site.name'), + '##SITE_URL##' => $site_link, + '##FROM_EMAIL##' => config('site.from_email'), + '##CONTACT_MAIL##' => config('site.contact_email') + ); + //VehicleRental mail to booker + $template = $this->mailService->getTemplate('Accepted VehicleRental Message To Booker'); + $emailFindReplace = array( + '##USERNAME##' => $booker->username, + '##ITEM_NAME##' => $item_link, + '##HOST_CONTACT_LINK##' => $host_link + ); + $this->mailService->sendMail($template, $emailFindReplace, $booker->email, $booker->username); + //VehicleRental mail to host + $template = $this->mailService->getTemplate('Accepted VehicleRental Message To Host'); + $emailFindReplace = array( + '##USERNAME##' => $host->username, + '##ITEM_NAME##' => $item_link, + '##ORDER_NO##' => $order_link + ); + $this->mailService->sendMail($template, $emailFindReplace, $host->email, $host->username); + } + + /** + * @param $vehicle_rental + * @param $item + * @param $previous_status + * @param $current_status + */ + public function changeStatusMail($vehicle_rental, $item, $previous_status, $current_status) + { + $from = config('constants.ConstUserIds.Admin'); + $host = $item->user; + $booker = $vehicle_rental->user; + $item_link = '' . $item->name . ''; + $order_link = '' . $vehicle_rental->id . ''; + $site_link = '' . Cache::get('site_url_for_shell') . ''; + $default_content = array( + '##SITE_NAME##' => config('site.name'), + '##SITE_URL##' => $site_link, + '##FROM_EMAIL##' => config('site.from_email'), + '##CONTACT_MAIL##' => config('site.contact_email') + ); + $status_arr = [$previous_status, $current_status]; + $status = VehicleRentalStatus::whereIn('id', $status_arr)->lists('name', 'id')->all(); + $template = $this->mailService->getTemplate('Item User Change Status Alert'); + $emailFindReplace = array( + '##SITE_NAME##' => config('site.name'), + '##SITE_URL##' => $site_link, + '##ITEM##' => $item->name, + '##PREVIOUS_STATUS##' => $status[$previous_status], + '##CURRENT_STATUS##' => $status[$current_status], + '##ITEM_NAME##' => $item_link, + '##ITEM_URL##' => $item_link, + '##ORDER_NO##' => $order_link, + ); + //Status change mail and message to booker + $this->mailService->sendMail($template, $emailFindReplace, $booker->email, $booker->username); + $vehicle_rental_mail_template = array_merge($emailFindReplace, $default_content); + $message_content_arr = array(); + $message_content_arr['message'] = strtr($template['body_content'], $vehicle_rental_mail_template); + $message_content_arr['subject'] = strtr($template['subject'], $vehicle_rental_mail_template); + $this->messageService->saveMessageContent($message_content_arr, $item->id, $vehicle_rental->id, $from, $vehicle_rental->user_id, $current_status, 'VehicleRental'); + //Status change mail and message to host + $this->mailService->sendMail($template, $emailFindReplace, $host->email, $host->username); + $vehicle_rental_mail_template = array_merge($emailFindReplace, $default_content); + $message_content_arr = array(); + $message_content_arr['message'] = strtr($template['body_content'], $vehicle_rental_mail_template); + $message_content_arr['subject'] = strtr($template['subject'], $vehicle_rental_mail_template); + $this->messageService->saveMessageContent($message_content_arr, $item->id, $vehicle_rental->id, $from, $item->user_id, $current_status, 'VehicleRental'); + } + + + /** + * Update VehicleRental count in item user status table + */ + public function updateItemUserCount() + { + $vehicle_rental_status = VehicleRentalStatus::select('id', 'booking_count')->get(); + $status_count = DB::table('item_users') + ->where('item_userable_type', 'MorphVehicle') + ->select('item_user_status_id', DB::raw('count(*) as total')) + ->groupBy('item_user_status_id') + ->lists('total', 'item_user_status_id'); + foreach ($status_count as $key => $value) { + VehicleRentalStatus::where('id', '=', $key)->update(['booking_count' => $value]); + } + foreach ($vehicle_rental_status as $value) { + if (!array_key_exists($value->id, $status_count)) { + VehicleRentalStatus::where('id', '=', $value->id)->update(['booking_count' => 0]); + } + } + } + + public function updateVehicleItemUserCount($vehicle_id) + { + $vehicle = Vehicle::find($vehicle_id); + if ($vehicle) { + $data['vehicle_rental_count'] = VehicleRental::where('item_userable_type', 'MorphVehicle')->where('item_userable_id', $vehicle_id)->whereNotIn('item_user_status_id', array(config('ConstItemUserStatus.PaymentPending', 'ConstItemUserStatus.PrivateConversation')))->count(); + $vehicle->update($data); + } + } + + public function updateUserItemUserCount($user_id) + { + $user = User::find($user_id); + if ($user) { + $data['vehicle_rental_count'] = VehicleRental::where('user_id', $user_id)->whereNotIn('item_user_status_id', array(config('ConstItemUserStatus.PaymentPending', 'ConstItemUserStatus.PrivateConversation')))->count(); + $user->update($data); + } + } + + public function getBookAndOrderCount($user_id) + { + $data = array(); + $data['booking'] = array(); + $data['host'] = array(); + if ($user_id) { + // get status + $vehicle_rental_status = VehicleRentalStatus::where('id', '!=', config('constants.ConstItemUserStatus.PrivateConversation'))->orderBy('display_order', 'ASC')->select('id', 'name', 'slug')->get(); + $vehicle_rental_status = $vehicle_rental_status->toArray(); + // get booking count + $status_count = DB::table('item_users') + ->where('user_id', $user_id) + ->where('item_userable_type', 'MorphVehicle') + ->select('item_user_status_id', DB::raw('count(*) as total')) + ->groupBy('item_user_status_id') + ->lists('total', 'item_user_status_id'); + + // get host order count + $vehicle_list = Vehicle::where('user_id', $user_id)->lists('id', 'id'); + $vehicle_list = $vehicle_list->toArray(); + $host_status_count = DB::table('item_users') + ->where('item_userable_type', 'MorphVehicle') + ->whereIN('item_userable_id', $vehicle_list) + ->select('item_user_status_id', DB::raw('count(*) as total')) + ->groupBy('item_user_status_id') + ->lists('total', 'item_user_status_id'); + + // response process + $total_booking_count = 0; + $total_order_count = 0; + if (!isset($status_count[config('constants.ConstItemUserStatus.WaitingForReview')])) { + $status_count[config('constants.ConstItemUserStatus.WaitingForReview')] = 0; + } + if (!isset($status_count[config('constants.ConstItemUserStatus.HostReviewed')])) { + $status_count[config('constants.ConstItemUserStatus.HostReviewed')] = 0; + } + $status_count[config('constants.ConstItemUserStatus.WaitingForReview')] = $status_count[config('constants.ConstItemUserStatus.WaitingForReview')] + $status_count[config('constants.ConstItemUserStatus.HostReviewed')]; + if (!isset($status_count[config('constants.ConstItemUserStatus.Completed')])) { + $status_count[config('constants.ConstItemUserStatus.Completed')] = 0; + } + if (!isset($status_count[config('constants.ConstItemUserStatus.BookerReviewed')])) { + $status_count[config('constants.ConstItemUserStatus.BookerReviewed')] = 0; + } + if (!isset($status_count[config('constants.ConstItemUserStatus.WaitingForPaymentCleared')])) { + $status_count[config('constants.ConstItemUserStatus.WaitingForPaymentCleared')] = 0; + } + $status_count[config('constants.ConstItemUserStatus.Completed')] = $status_count[config('constants.ConstItemUserStatus.Completed')] + $status_count[config('constants.ConstItemUserStatus.BookerReviewed')] + +$status_count[config('constants.ConstItemUserStatus.WaitingForPaymentCleared')]; + foreach ($vehicle_rental_status as $status) { + $tmp = $status; + $tmp1 = $status; + if ($status['id'] != config('constants.ConstItemUserStatus.CancelledByAdmin')) { + if (!in_array($status['id'], array(config('constants.ConstItemUserStatus.HostReviewed'), config('constants.ConstItemUserStatus.BookerReviewed'), config('constants.ConstItemUserStatus.WaitingForPaymentCleared')))) { + if (isset($status_count[$status['id']])) { + $tmp['booking_count'] = $status_count[$status['id']]; + } else { + $tmp['booking_count'] = 0; + } + $total_booking_count = $total_booking_count + $tmp['booking_count']; + $data['booking'][] = $tmp; + } + if(!in_array($status['id'], array(config('constants.ConstItemUserStatus.PaymentPending')))) { + if (isset($host_status_count[$status['id']])) { + $tmp1['host_count'] = $host_status_count[$status['id']]; + } else { + $tmp1['host_count'] = 0; + } + $data['host'][] = $tmp1; + $total_order_count = $total_order_count + $tmp1['host_count']; + } + } + } + $data['booking'] = array_merge(array(array( + 'id' => 0, + 'name' => 'All', + 'slug' => 'all', + 'booking_count' => $total_booking_count + )), $data['booking']); + $data['host'] = array_merge(array(array( + 'id' => 0, + 'name' => 'All', + 'slug' => 'all', + 'host_count' => $total_order_count + )), $data['host']); + $data['total_booking_count'] = $total_booking_count; + $data['total_order_count'] = $total_order_count; + } + return $data; + } + + public function updateUserOrderCount($user_id) + { + $user = User::find($user_id); + if ($user) { + $data['vehicle_rental_order_count'] = Vehicle::where('user_id', $user_id)->sum('vehicle_rental_count'); + $user->update($data); + } + } + + /** + * status update calls + */ + public function autoUpdateStatus() + { + $this->updateCompletedStatus(); + $this->updatePendingPaymentClearedStatus(); + $this->autoExpire(); + $this->autoExpirePaymentPendingVehicleRental(); + $this->autoDeleteUnavailableVehicleRecords(); + $this->autoCompleteUnattendedRecords(); + } + + /** + * This updates the status from waiting for review to Pending payment cleared status + */ + public function updatePendingPaymentClearedStatus() + { + $auto_expire_days = config('vehicle_rental.auto_update_pending_payment_status'); + $expire_date = Carbon::now()->subDays($auto_expire_days); + $expire_date = $expire_date->toDateTimeString(); + $vehicle_rentals = VehicleRental::where('item_user_status_id', '=', config('constants.ConstItemUserStatus.WaitingForReview'))->where('is_dispute', '!=', 1) + ->filterByVehicleRental(false) + ->where('status_updated_at', '<=', $expire_date)->get(); + if ($vehicle_rentals) { + foreach ($vehicle_rentals as $vehicle_rental) { + $item = $vehicle_rental->item_userable; + if (!is_null($item)) { + $item_user_data['id'] = $vehicle_rental->id; + $item_user_data['item_user_status_id'] = config('constants.ConstItemUserStatus.WaitingForPaymentCleared'); + $item_user_data['status_updated_at'] = Carbon::now()->toDateTimeString(); + try { + $vehicle_rental->update($item_user_data); + $this->updateItemUserCount(); + //Send Mail to Booker and save message contents and messages + $this->changeStatusMail($vehicle_rental, $item, config('constants.ConstItemUserStatus.WaitingForReview'), config('constants.ConstItemUserStatus.WaitingForPaymentCleared')); + + } catch (\Exception $e) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Status could not be changed'); + } + } + } + } + } + + /** + * This updates the status from Pending payment cleared status to complete and amount released to host + */ + public function updateCompletedStatus() + { + $auto_expire_days = config('vehicle_rental.days_after_amount_cleared_to_host'); + $expire_date = Carbon::now()->subDays($auto_expire_days); + $expire_date = $expire_date->toDateTimeString(); + $vehicle_rentals = VehicleRental::where('item_user_status_id', '=', config('constants.ConstItemUserStatus.WaitingForPaymentCleared')) + ->filterByVehicleRental(false) + ->where('status_updated_at', '<=', $expire_date)->get(); + if ($vehicle_rentals) { + foreach ($vehicle_rentals as $vehicle_rental) { + $item = $vehicle_rental->item_userable; + if (!is_null($item)) { + $item_user_data['id'] = $vehicle_rental->id; + $item_user_data['item_user_status_id'] = config('constants.ConstItemUserStatus.Completed'); + $item_user_data['status_updated_at'] = Carbon::now()->toDateTimeString(); + + } + try { + $vehicle_rental->update($item_user_data); + $this->updateItemUserCount(); + // all transactions + $this->completeTransactionAmounts($vehicle_rental); + //Send Mail to Booker and save message contents and messages + $this->changeStatusMail($vehicle_rental, $item, config('constants.ConstItemUserStatus.WaitingForPaymentCleared'), config('constants.ConstItemUserStatus.Completed')); + } catch (\Exception $e) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Status could not be changed'); + } + } + } + } + + /** + * This updates the status from pending payment status to expired and amount refunded to booker + */ + public function autoExpirePaymentPendingVehicleRental() + { + $expire_date = Carbon::now()->toDateTimeString(); + $vehicle_rentals = VehicleRental::where('item_user_status_id', '=', config('constants.ConstItemUserStatus.PaymentPending')) + ->filterByVehicleRental(false) + ->where('item_booking_start_date', '<', $expire_date)->get(); + if ($vehicle_rentals) { + foreach ($vehicle_rentals as $vehicle_rental) { + if (!is_null($vehicle_rental->item_userable)) { + $item = $vehicle_rental->item_userable; + $item_user_data['id'] = $vehicle_rental->id; + $item_user_data['item_user_status_id'] = config('constants.ConstItemUserStatus.Expired'); + $item_user_data['status_updated_at'] = Carbon::now()->toDateTimeString(); + try { + $vehicle_rental->update($item_user_data); + $this->updateItemUserCount(); + //Send Mail to Booker and save message contents and messages + $this->changeStatusMail($vehicle_rental, $item, config('constants.ConstItemUserStatus.PaymentPending'), config('constants.ConstItemUserStatus.Expired')); + } catch (\Exception $e) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Status could not be changed', array($e->getMessage())); + } + } + } + } + + } + + /** + * This updates the status from waiting for acceptance to Expired and amount refunded to booker + */ + public function autoExpire() + { + $auto_expire_days = config('vehicle_rental.auto_expire'); + $expire_date = Carbon::now()->subDays($auto_expire_days); + $expire_date = $expire_date->toDateTimeString(); + $enabledIncludes = $this->getEnableGateway(); + $vehicle_rentals = VehicleRental::with($enabledIncludes) + ->where('item_user_status_id', '=', config('constants.ConstItemUserStatus.WaitingForAcceptance')) + ->filterByVehicleRental(false) + ->where('status_updated_at', '<=', $expire_date)->get(); + if ($vehicle_rentals) { + foreach ($vehicle_rentals as $vehicle_rental) { + if (!is_null($vehicle_rental->item_userable) && !is_null($vehicle_rental->user)) { + try { + $error_msg = ''; + $is_payment_transaction = false; + $transaction_log = array(); + if (isPluginEnabled('Paypal') && !is_null($vehicle_rental->paypal_transaction_log)) { + $gateway_id = config('constants.ConstPaymentGateways.PayPal'); + if ($vehicle_rental->paypal_transaction_log->payment_type == 'authorized') { + $paypal = new \Plugins\Paypal\Services\PayPalService(); + $voidPayment = $paypal->voidPayment($vehicle_rental->paypal_transaction_log->authorization_id); + if (is_object($voidPayment)) { + $transaction_log['payment_type'] = $voidPayment->getState(); + $transaction_log['void_id'] = $voidPayment->getId(); + if ($transaction_log['payment_type'] == 'voided') { + $is_payment_transaction = true; + } + } else if (is_array($voidPayment) && $voidPayment['error']) { + if ($voidPayment['error']['message']) { + $error_msg = $voidPayment['error']['message']; + } else if($voidPayment['error_message']) { + $error_msg = $voidPayment['error_message']; + } + } + $vehicle_rental->paypal_transaction_log->update($transaction_log); + } + } + if (isPluginEnabled('Sudopays') && !is_null($vehicle_rental->sudopay_transaction_logs)) { + $gateway_id = config('constants.ConstPaymentGateways.SudoPay'); + $sudopayService = new \Plugins\Sudopays\Services\SudopayService(); + if ($vehicle_rental->sudopay_transaction_logs->status == 'Authorized') { + $voidPayment = $sudopayService->voidPayment($vehicle_rental->sudopay_transaction_logs); + if (!empty($voidPayment) && ($voidPayment['status'] == 'Voided' || $voidPayment['status'] == 'Canceled')) { + $transaction_log['status'] = $voidPayment['status']; + $is_payment_transaction = true; + $vehicle_rental->sudopay_transaction_logs->update($transaction_log); + } else if (is_array($voidPayment) && $voidPayment['error']) { + if ($voidPayment['error']['message']) { + $error_msg = $voidPayment['error']['message']; + } else if($voidPayment['error_message']) { + $error_msg = $voidPayment['error_message']; + } + } + } elseif ($vehicle_rental->sudopay_transaction_logs->status == 'Captured') { + $refundPayment = $sudopayService->refundPayment($vehicle_rental->sudopay_transaction_logs); + if (!empty($refundPayment) && $refundPayment['status'] == 'Refunded') { + $transaction_log['status'] = $refundPayment['status']; + $is_payment_transaction = true; + $vehicle_rental->sudopay_transaction_logs->update($transaction_log); + } else if (is_array($refundPayment) && $refundPayment['error']) { + if ($refundPayment['error']['message']) { + $error_msg = $refundPayment['error']['message']; + } else if($refundPayment['error_message']) { + $error_msg = $refundPayment['error_message']; + } + } + } + } + if (!is_null($vehicle_rental->wallet_transaction_log)) { + $gateway_id = config('constants.ConstPaymentGateways.Wallet'); + if ($vehicle_rental->wallet_transaction_log->payment_type == 'Captured') { + $walletService = new \App\Services\WalletService(); + $is_payment_transaction = $walletService->voidPayment($vehicle_rental); + } + } + if ($is_payment_transaction) { + $vehicle_rental_data['item_user_status_id'] = config('constants.ConstItemUserStatus.Expired'); + $vehicle_rental_data['status_updated_at'] = Carbon::now()->toDateTimeString(); + $vehicle_rental->update($vehicle_rental_data); + $this->updateItemUserCount(); + //Save transactions + $this->transactionService->log(config('constants.ConstUserTypes.Admin'), $vehicle_rental->user_id, config('constants.ConstTransactionTypes.RefundForExpiredRenting'), $vehicle_rental->total_amount, $vehicle_rental->id, 'VehicleRentals', $gateway_id); + //Send Mail to Booker and save message contents and messages + $this->changeStatusMail($vehicle_rental, $vehicle_rental->item_userable, $vehicle_rental->item_user_status_id, config('constants.ConstItemUserStatus.Expired')); + } else { + Log::info($error_msg); + } + } catch (\Exception $e) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Status could not be changed', array($e->getMessage())); + } + } + } + } + } + + public function updateVehicleRental($vehicle_rental_id, $gateway_id) + { + $vehicle_rental = VehicleRental::find($vehicle_rental_id); + $item = $vehicle_rental->item_userable; + if (!is_null($item) && $vehicle_rental->item_user_status_id == config('constants.ConstItemUserStatus.PaymentPending')) { + $vehicle_rental_data['item_user_status_id'] = config('constants.ConstItemUserStatus.WaitingForAcceptance'); + if (config('vehicle_rental.is_auto_approve')) { + $vehicle_rental_data['item_user_status_id'] = config('constants.ConstItemUserStatus.Confirmed'); + } + $vehicle_rental_data['status_updated_at'] = Carbon::now()->toDateTimeString(); + $vehicle_rental->update($vehicle_rental_data); + // Status table update count + $this->updateItemUserCount(); + // Vehicle table update count + $this->updateVehicleItemUserCount($item->id); + // User table update count + $this->updateUserItemUserCount($vehicle_rental->user_id); + // vehicle owner order count update on user table + $this->updateUserOrderCount($item->user_id); + // Update coupon quantity used count + if (isPluginEnabled('VehicleCoupons')) { + $this->vehicleCouponService->updateCouponquantity($vehicle_rental->coupon_id); + } + // unavailable vehicle dummy record put changes + $this->vehicleService->addVehicleSearchRecord($item->id, $vehicle_rental_id, $vehicle_rental->item_booking_start_date, $vehicle_rental->item_booking_end_date, 0); + + if (config('vehicle_rental.is_auto_approve')) { + $this->sendVehicleRentalMail($vehicle_rental, $item); + $this->changeStatusMail($vehicle_rental, $item, config('constants.ConstItemUserStatus.PaymentPending'), config('constants.ConstItemUserStatus.Confirmed')); + } else { + //Send VehicleRental mail and status change mail to host and booker + $this->sendVehicleRentalMail($vehicle_rental, $item); + $this->changeStatusMail($vehicle_rental, $item, config('constants.ConstItemUserStatus.PaymentPending'), config('constants.ConstItemUserStatus.WaitingForAcceptance')); + } + $this->transactionService->log($vehicle_rental->user_id, config('constants.ConstUserTypes.Admin'), config('constants.ConstTransactionTypes.RentItem'), $vehicle_rental->total_amount, $vehicle_rental->id, 'VehicleRentals', $gateway_id); + } + } + + /** + * @param $vehicle_rental_id + * @param $gateway_id + */ + public function updateVoid($vehicle_rental_id, $gateway_id) + { + $vehicle_rental = VehicleRental::find($vehicle_rental_id); + if ($vehicle_rental && !is_null($vehicle_rental->item_userable)) { + if ($vehicle_rental['item_user_status_id'] == config('constants.ConstItemUserStatus.WaitingForAcceptance')) { + $vehicle_rental_data['item_user_status_id'] = config('constants.ConstItemUserStatus.CancelledByAdmin'); + $vehicle_rental_data['status_updated_at'] = Carbon::now()->toDateTimeString(); + $vehicle_rental->update($vehicle_rental_data); + $this->changeStatusMail($vehicle_rental, $vehicle_rental->item_userable, config('constants.ConstItemUserStatus.WaitingForAcceptance'), config('constants.ConstItemUserStatus.CancelledByAdmin')); + $this->transactionService->log(config('constants.ConstUserTypes.Admin'), $vehicle_rental->user_id, config('constants.ConstTransactionTypes.RefundForRentingCanceledByAdmin'), $vehicle_rental->total_amount, $vehicle_rental->id, 'VehicleRentals', $gateway_id); + } + } + } + + /** + * @param $vehicle_rental_id + * @param $gateway_id + */ + public function updateRefund($vehicle_rental_id, $gateway_id) + { + $vehicle_rental = VehicleRental::find($vehicle_rental_id); + if ($vehicle_rental && !is_null($vehicle_rental->item_userable)) { + if ($vehicle_rental['item_user_status_id'] == config('constants.ConstItemUserStatus.Confirmed')) { + $vehicle_rental_data['item_user_status_id'] = config('constants.ConstItemUserStatus.CancelledByAdmin'); + $vehicle_rental_data['status_updated_at'] = Carbon::now()->toDateTimeString(); + $vehicle_rental->update($vehicle_rental_data); + $this->changeStatusMail($vehicle_rental, $vehicle_rental->item_userable, config('constants.ConstItemUserStatus.Confirmed'), config('constants.ConstItemUserStatus.CancelledByAdmin')); + $this->transactionService->log(config('constants.ConstUserTypes.Admin'), $vehicle_rental->user_id, config('constants.ConstTransactionTypes.RefundForRentingCanceledByAdmin'), $vehicle_rental->total_amount, $vehicle_rental->id, 'VehicleRentals', $gateway_id); + } + } + } + + /** + * This updates the status from confirmed to waiting for review status + */ + public function updateWaitingForReview() + { + $expire_date = Carbon::now()->toDateTimeString(); + $vehicle_rentals = VehicleRental::where('item_user_status_id', '=', config('constants.ConstItemUserStatus.Confirmed')) + ->filterByVehicleRental(false) + ->where('item_booking_start_date', '<', $expire_date)->get(); + if ($vehicle_rentals) { + foreach ($vehicle_rentals as $vehicle_rental) { + if (!is_null($vehicle_rental->item_userable)) { + $item_user_data['id'] = $vehicle_rental->id; + $item_user_data['item_user_status_id'] = config('constants.ConstItemUserStatus.WaitingForReview'); + $item_user_data['status_updated_at'] = Carbon::now()->toDateTimeString(); + try { + $vehicle_rental->update($item_user_data); + $this->updateItemUserCount(); + //Send Mail to Booker and save message contents and messages + + $this->changeStatusMail($vehicle_rental, $vehicle_rental->item_userable, config('constants.ConstItemUserStatus.Confirmed'), config('constants.ConstItemUserStatus.WaitingForReview')); + + } catch (\Exception $e) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Status could not be changed'); + } + } + } + } + } + + /** + * Update dispute status in item users + * @param $id + */ + public function updateDispute($id) + { + $vehicle_rental_data['is_dispute'] = 1; + VehicleRental::where('id', '=', $id)->update($vehicle_rental_data); + } + + /** + * Save the checkin status + * @param $vehicle_rental + * @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response + */ + public function saveCheckInDetail($vehicle_rental) + { + if (!$vehicle_rental) { + return $this->response->errorNotFound("Invalid Request"); + } + try { + $vehicle_rental_data['item_user_status_id'] = config('constants.ConstItemUserStatus.Attended'); + $vehicle_rental_data['status_updated_at'] = Carbon::now()->toDateTimeString(); + $vehicle_rental->update($vehicle_rental_data); + $this->updateItemUserCount(); + $this->changeStatusMail($vehicle_rental, $vehicle_rental->item_userable, config('constants.ConstItemUserStatus.Confirmed'), config('constants.ConstItemUserStatus.Attended')); + // insert record into late_payment_detail table + $this->vehicleRentalLatePaymentDetailService->addRentalDetail($vehicle_rental); + return response()->json(['Success' => 'VehicleRental has been checked-in successfully'], 200); + } catch (\Exception $e) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('VehicleRental could not be updated. Please, try again.', array($e->getMessage())); + } + } + + /** + * Save the checkout status and calcualte late payment fee if any + * @param $vehicle_rental + * @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response + */ + public function saveCheckoutDetail($vehicle_rental, $claim_request_amount) + { + if (!$vehicle_rental) { + return $this->response->errorNotFound("Invalid Request"); + } + try { + // calculate late payment charge + $late_fee_details = $this->vehicleService->processCheckoutLateFee($vehicle_rental, $claim_request_amount); + $vehicle_rental_data['item_user_status_id'] = config('constants.ConstItemUserStatus.WaitingForReview'); + $vehicle_rental_data['status_updated_at'] = $late_fee_details['current_date']; + $vehicle_rental_data['late_fee'] = $late_fee_details['late_checkout_total_fee']; + $vehicle_rental_data['paid_manual_amount'] = $late_fee_details['late_checkout_total_fee']; + $vehicle_rental_data['claim_request_amount'] = $claim_request_amount; + $vehicle_rental_data['paid_deposit_amount'] = $late_fee_details['paid_deposit_amount']; + $vehicle_rental_data['paid_manual_amount'] = $late_fee_details['paid_manual_amount']; + $vehicle_rental->update($vehicle_rental_data); + $this->updateItemUserCount(); + $this->vehicleService->updateTotalAmount($vehicle_rental); + // clear records in unavailable vehicles + $this->unavailableVehicleService->clearUnavaialablelist($vehicle_rental->id); + $this->changeStatusMail($vehicle_rental, $vehicle_rental->item_userable, config('constants.ConstItemUserStatus.Attended'), config('constants.ConstItemUserStatus.WaitingForReview')); + // insert record into late_payment_detail table + $this->vehicleRentalLatePaymentDetailService->updateRentalDetail($vehicle_rental, $late_fee_details['total_late_hours']); + return response()->json(['Success' => 'VehicleRental has been checked-out successfully'], 200); + } catch (\Exception $e) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('VehicleRental could not be updated. Please, try again.', array($e->getMessage())); + } + } + + /** + * automatically delete records from unavailable_vehicles table records once the booking_date completes + */ + public function autoDeleteUnavailableVehicleRecords() + { + $current_date = Carbon::now()->toDateTimeString(); + try { + UnavailableVehicle::where('end_date', '<', $current_date)->where(['is_dummy' => 0])->delete(); + } catch (\Exception $e) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Unavaialable Records Could not be deleted. Please, try again.'); + } + } + + /** + * this cfunction makes all transactions on complete status + * @param $vehicle_rental + */ + public function completeTransactionAmounts($vehicle_rental, $is_from_dispute = 0) + { + $walletService = new \App\Services\WalletService(); + + // transaction for booker + if ($vehicle_rental->booker_amount > 0 && !$is_from_dispute) { + $walletService->updateWalletForUser($vehicle_rental->user_id, $vehicle_rental->booker_amount, $vehicle_rental->id, 'VehicleRentals'); + $this->transactionService->log(config('constants.ConstUserIds.Admin'), $vehicle_rental->user_id, config('constants.ConstTransactionTypes.SecuirtyDepositAmountRefundedToBooker'), $vehicle_rental->booker_amount, $vehicle_rental->id, 'VehicleRentals', config('constants.ConstPaymentGateways.Wallet')); + } + + //Save transactions for host. Ad transaction logs are moved in common function while change to completed status (specification dispute closed in favour of booker type host amount is set to 0) + if ($vehicle_rental->host_service_amount > 0) { + $amount_from_booking = $vehicle_rental->host_service_amount - $vehicle_rental->paid_manual_amount; + $walletService->updateWalletForUser($vehicle_rental->item_userable->user_id, $amount_from_booking, $vehicle_rental->id, 'VehicleRentals'); + $this->transactionService->log(config('constants.ConstUserIds.Admin'), $vehicle_rental->item_userable->user_id, config('constants.ConstTransactionTypes.RentingHostAmountCleared'), $amount_from_booking, $vehicle_rental->id, 'VehicleRentals', config('constants.ConstPaymentGateways.Wallet')); + } + + if ($vehicle_rental->paid_manual_amount > 0 && $vehicle_rental->claim_request_amount > 0) { + // manually paid claim + $walletService->updateWalletForUser($vehicle_rental->item_userable->user_id, $vehicle_rental->claim_request_amount, $vehicle_rental->id, 'VehicleRentals'); + $this->transactionService->log($vehicle_rental->user_id, $vehicle_rental->item_userable->user_id, config('constants.ConstTransactionTypes.ManualTransferForClaimRequestAmount'), $vehicle_rental->claim_request_amount, $vehicle_rental->id, 'VehicleRentals'); + } + if ($vehicle_rental->paid_manual_amount > 0 && $vehicle_rental->late_fee > 0) { + // manually paid late fee + $this->transactionService->log($vehicle_rental->user_id, $vehicle_rental->item_userable->user_id, config('constants.ConstTransactionTypes.ManualTransferForLateFee'), $vehicle_rental->late_fee, $vehicle_rental->id, 'VehicleRentals'); + } + // transactions fo admin + if ($vehicle_rental->admin_commission_amount > 0) { + $walletService->updateWalletForUser(config('constants.ConstUserIds.Admin'), $vehicle_rental->admin_commission_amount, $vehicle_rental->id, 'VehicleRentals'); + $this->transactionService->log($vehicle_rental->item_userable->user_id, config('constants.ConstUserIds.Admin'), config('constants.ConstTransactionTypes.AdminCommission'), $vehicle_rental->admin_commission_amount, $vehicle_rental->id, 'VehicleRentals', config('constants.ConstPaymentGateways.Wallet')); + } + } + + public function autoCompleteUnattendedRecords() + { + $expire_date = Carbon::now()->toDateTimeString(); + $vehicle_rentals = VehicleRental::where('item_user_status_id', '=', config('constants.ConstItemUserStatus.Confirmed')) + ->filterByVehicleRental(false) + ->where('item_booking_end_date', '<', $expire_date)->get(); + if ($vehicle_rentals) { + foreach ($vehicle_rentals as $vehicle_rental) { + if (!is_null($vehicle_rental->item_userable)) { + $item_user_data['id'] = $vehicle_rental->id; + $item_user_data['item_user_status_id'] = config('constants.ConstItemUserStatus.Completed'); + $item_user_data['status_updated_at'] = Carbon::now()->toDateTimeString(); + try { + $vehicle_rental->update($item_user_data); + $this->updateItemUserCount(); + // all transactions + $this->completeTransactionAmounts($vehicle_rental); + //Send Mail to Booker and save message contents and messages + $this->changeStatusMail($vehicle_rental, $vehicle_rental->item_userable, config('constants.ConstItemUserStatus.Confirmed'), config('constants.ConstItemUserStatus.Completed')); + } catch (\Exception $e) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Status could not be changed'); + } + } + } + } + } +} diff --git a/app/Plugins/VehicleRentals/Transformers/VehicleRentalAdditionalChargeTransformer.php b/app/Plugins/VehicleRentals/Transformers/VehicleRentalAdditionalChargeTransformer.php new file mode 100644 index 0000000..e9bbbe1 --- /dev/null +++ b/app/Plugins/VehicleRentals/Transformers/VehicleRentalAdditionalChargeTransformer.php @@ -0,0 +1,45 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleRentals\Transformers; + +use League\Fractal; +use Plugins\VehicleRentals\Model\VehicleRentalAdditionalCharge; +use App\Transformers\UserSimpleTransformer; + +/** + * Class VehicleRentalAdditionalChargeTransformer + * @package App\Transformers + */ +class VehicleRentalAdditionalChargeTransformer extends Fractal\TransformerAbstract +{ + /** + * List of resources possible to include + * @var array + */ + protected $availableIncludes = [ + + ]; + + /** + * @param VehicleRental $vehicle_rental + * @return array + */ + public function transform(VehicleRentalAdditionalCharge $vehicle_rental_additional_chargable) + { + $output = array_only($vehicle_rental_additional_chargable->toArray(), ['id', 'item_user_id', 'item_user_additional_chargable_type', 'item_user_additional_chargable_id']); + return $output; + } +} diff --git a/app/Plugins/VehicleRentals/Transformers/VehicleRentalBookerDetailTransformer.php b/app/Plugins/VehicleRentals/Transformers/VehicleRentalBookerDetailTransformer.php new file mode 100644 index 0000000..3b04e66 --- /dev/null +++ b/app/Plugins/VehicleRentals/Transformers/VehicleRentalBookerDetailTransformer.php @@ -0,0 +1,38 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleRentals\Transformers; + +use League\Fractal; +use Plugins\VehicleRentals\Model\VehicleRentalBookerDetail; + +/** + * Class VehicleRentalBookerDetailTransformer + * @package App\Transformers + */ +class VehicleRentalBookerDetailTransformer extends Fractal\TransformerAbstract +{ + /** + * @param VehicleRentalBookerDetail $vehicle_rental_booker_detail + * @return array + */ + public function transform(VehicleRentalBookerDetail $vehicle_rental_booker_detail) + { + $output = array_only($vehicle_rental_booker_detail->toArray(), ['id', 'email', 'first_name', 'last_name', 'mobile', 'address']); + return $output; + } +} + +?> \ No newline at end of file diff --git a/app/Plugins/VehicleRentals/Transformers/VehicleRentalLatePaymentDetailTransformer.php b/app/Plugins/VehicleRentals/Transformers/VehicleRentalLatePaymentDetailTransformer.php new file mode 100644 index 0000000..e74b00f --- /dev/null +++ b/app/Plugins/VehicleRentals/Transformers/VehicleRentalLatePaymentDetailTransformer.php @@ -0,0 +1,38 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleRentals\Transformers; + +use League\Fractal; +use Plugins\VehicleRentals\Model\VehicleRentalLatePaymentDetail; + +/** + * Class VehicleRentalLatePaymentDetailTransformer + * @package App\Transformers + */ +class VehicleRentalLatePaymentDetailTransformer extends Fractal\TransformerAbstract +{ + /** + * @param VehicleRentalLatePaymentDetail $vehicle_rental_late_payment_detail + * @return array + */ + public function transform(VehicleRentalLatePaymentDetail $vehicle_rental_late_payment_detail) + { + $output = array_only($vehicle_rental_late_payment_detail->toArray(), ['id']); + return $output; + } +} + +?> \ No newline at end of file diff --git a/app/Plugins/VehicleRentals/Transformers/VehicleRentalStatusTransformer.php b/app/Plugins/VehicleRentals/Transformers/VehicleRentalStatusTransformer.php new file mode 100644 index 0000000..6680a0b --- /dev/null +++ b/app/Plugins/VehicleRentals/Transformers/VehicleRentalStatusTransformer.php @@ -0,0 +1,44 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleRentals\Transformers; + +use League\Fractal; +use Plugins\VehicleRentals\Model\VehicleRentalStatus; + +/** + * Class VehicleRentalStatusTransformer + * @package App\Transformers + */ +class VehicleRentalStatusTransformer extends Fractal\TransformerAbstract +{ + /** + * @param VehicleRentalStatus $vehicle_rental_status + * @return array + */ + public function transform(VehicleRentalStatus $vehicle_rental_status) + { + $output = array_only($vehicle_rental_status->toArray(), ['id', 'name', 'description']); + if(!isPluginEnabled('VehicleFeedbacks')) { + if ($output['name'] == 'Waiting for Review') { + $output['name'] = 'Waiting for Next Update'; + } + } + + return $output; + } +} + +?> \ No newline at end of file diff --git a/app/Plugins/VehicleRentals/Transformers/VehicleRentalTransformer.php b/app/Plugins/VehicleRentals/Transformers/VehicleRentalTransformer.php new file mode 100644 index 0000000..71e0d24 --- /dev/null +++ b/app/Plugins/VehicleRentals/Transformers/VehicleRentalTransformer.php @@ -0,0 +1,245 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleRentals\Transformers; + +use League\Fractal; +use Plugins\VehicleRentals\Model\VehicleRental; +use App\Transformers\UserSimpleTransformer; +use Plugins\Vehicles\Services\VehicleService; +use Carbon; + +/** + * Class VehicleRentalTransformer + * @package App\Transformers + */ +class VehicleRentalTransformer extends Fractal\TransformerAbstract +{ + /** + * List of resources possible to include + * @var array + */ + protected $availableIncludes = [ + 'User', 'ItemUserStatus', 'VehicleCoupon', 'ItemUserable', 'ItemUserDispute', 'VehicleFeedback', 'DropCounterLocation', 'PickupCounterLocation', 'VehicleRentalAdditionalChargable', 'LatePaymentDetail', 'BookerDetail', 'UnavailableVehicle' + ]; + + /** + * @param VehicleRental $vehicle_rental + * @return array + */ + public function transform(VehicleRental $vehicle_rental) + { + $output = array_only($vehicle_rental->toArray(), ['id', 'user_id', 'created_at', 'quantity', 'total_amount', 'item_user_status_id', 'coupon_id', 'admin_commission_amount', 'item_userable_id', 'item_userable_type', 'is_payment_cleared', 'coupon_discount_amount', 'special_discount_amount', 'type_discount_amount', 'item_booking_start_date', 'item_booking_end_date', 'is_dispute', 'booking_amount', 'pickup_counter_location_id', 'drop_counter_location_id', 'deposit_amount', 'surcharge_amount', 'extra_accessory_amount', 'tax_amount', 'insurance_amount', 'fuel_option_amount', 'drop_location_differ_charges', 'additional_fee', 'claim_request_amount', 'late_fee']); + $output['item_user_status_id'] = (integer)$output['item_user_status_id']; + $vehicle_service = new VehicleService(); + $output['date_diff'] = $vehicle_service->getDateDiff($output['item_booking_start_date'], $output['item_booking_end_date']); + $current_date = Carbon::now()->toDateTimeString(); + $check_in = 0; + $check_out = 0; + if ($output['item_booking_start_date'] <= $current_date && $output['item_booking_end_date'] > $current_date && $output['item_user_status_id'] == config('constants.ConstItemUserStatus.Confirmed')) { + $check_in = 1; + } + if ($output['item_user_status_id'] == config('constants.ConstItemUserStatus.Attended')) { + $check_out = 1; + $late_fee_details = $vehicle_service->processCheckoutLateFee($vehicle_rental, 0); + if (!empty($late_fee_details['late_checkout_total_fee'])) { + $output['late_checkout_total_fee'] = $late_fee_details['late_checkout_total_fee']; + } + if (!empty($late_fee_details['grace_time'])) { + $output['grace_time'] = $late_fee_details['grace_time']; + } + if (!empty($late_fee_details['revised_late_hours_from_gracetime'])) { + $output['revised_late_hours_from_gracetime'] = $late_fee_details['revised_late_hours_from_gracetime']; + } + if (!empty($late_fee_details['late_checkout_hours'])) { + $output['late_checkout_hours'] = $late_fee_details['late_checkout_hours']; + $output['late_checkout_hours_fee'] = $late_fee_details['late_checkout_hours_fee']; + } + if (!empty($late_fee_details['late_checkout_days'])) { + $output['late_checkout_days'] = $late_fee_details['late_checkout_days']; + $output['late_checkout_days_fee'] = $late_fee_details['late_checkout_days_fee']; + } + if (!empty($late_fee_details['vehicle_type_late_checkout_fee'])) { + $output['vehicle_type_late_checkout_fee'] = $late_fee_details['vehicle_type_late_checkout_fee']; + } + } + if (isset($output['is_payment_cleared'])) { + $output['is_payment_cleared'] = (int)$output['is_payment_cleared']; + } + if (isset($output['is_dispute'])) { + $output['is_dispute'] = (int)$output['is_dispute']; + } + $output['checkin'] = $check_in; + $output['checkout'] = $check_out; + if ($vehicle_rental->drop_location_differ_charges > 0 && !is_null($vehicle_rental->item_userable) &&!is_null($vehicle_rental->item_userable->vehicle_type)) { + if ($vehicle_rental->item_userable->vehicle_type->drop_location_differ_additional_fee > 0) { + $output['drop_location_differ_additional_fee'] = $vehicle_rental->item_userable->vehicle_type->drop_location_differ_additional_fee; + } + $output['total_distance'] = ceil($vehicle_rental->drop_location_differ_charges / $vehicle_rental->item_userable->vehicle_type->drop_location_differ_unit_price); + $output['distance_unit'] = config('vehicle.unit'); + } + return $output; + } + + + /** + * @param VehicleRental $vehicle_rental + * @return Fractal\Resource\Item + */ + public function includeUser(VehicleRental $vehicle_rental) + { + if ($vehicle_rental->user) { + return $this->item($vehicle_rental->user, new UserSimpleTransformer()); + } else { + return null; + } + } + + /** + * @param VehicleRental $vehicle_rental + * @return Fractal\Resource\Item + */ + public function includeItemUserStatus(VehicleRental $vehicle_rental) + { + if ($vehicle_rental->item_user_status) { + return $this->item($vehicle_rental->item_user_status, new VehicleRentalStatusTransformer()); + } else { + return null; + } + } + + /** + * @param VehicleRental $vehicle_rental + * @return Fractal\Resource\Item + */ + public function includeVehicleCoupon(VehicleRental $vehicle_rental) + { + if ($vehicle_rental->vehicle_coupon) { + return $this->item($vehicle_rental->vehicle_coupon, new \Plugins\VehicleCoupons\Transformers\VehicleCouponTransformer()); + } else { + return null; + } + } + + /** + * @param VehicleRental $vehicle_rental + * @return Fractal\Resource\Item + */ + public function includeItemUserable(VehicleRental $vehicle_rental) + { + if ($vehicle_rental->item_userable) { + if ($vehicle_rental->item_userable_type == 'MorphVehicle') { + return $this->item($vehicle_rental->item_userable, (new \Plugins\Vehicles\Transformers\VehicleTransformer)->setDefaultIncludes(['user', 'vehicle_company', 'vehicle_type', 'vehicle_make', 'vehicle_model', 'attachments', 'counter_location'])); + } + } else { + return null; + } + } + + /** + * @param VehicleRental $vehicle_rental + * @return Fractal\Resource\Item + */ + public function includeItemUserDispute(VehicleRental $vehicle_rental) + { + if ($vehicle_rental->item_user_dispute) { + if ($vehicle_rental->item_user_dispute->item_user_disputable_type == 'MorphVehicleRental') { + return $this->item($vehicle_rental->item_user_dispute, (new \Plugins\VehicleDisputes\Transformers\VehicleDisputeTransformer)->setDefaultIncludes(['user', 'dispute_type', 'dispute_closed_type', 'dispute_status'])); + } + } else { + return null; + } + } + + /** + * @param VehicleRental $vehicle_rental + * @return Fractal\Resource\Item|null + */ + public function includeVehicleFeedback(VehicleRental $vehicle_rental) + { + if ($vehicle_rental->vehicle_feedback) { + return $this->item($vehicle_rental->vehicle_feedback, (new \Plugins\VehicleFeedbacks\Transformers\VehicleFeedbackTransformer)->setDefaultIncludes(['user'])); + } else { + return null; + } + } + + /** + * @param VehicleRental $vehicle_rental + * @return Fractal\Resource\Item + */ + public function includeLatePaymentDetail(VehicleRental $vehicle_rental) + { + if ($vehicle_rental->late_payment_detail) { + return $this->item($vehicle_rental->late_payment_detail, new VehicleRentalLatePaymentDetailTransformer()); + } else { + return null; + } + } + + public function includePickupCounterLocation(VehicleRental $vehicle_rental) + { + if ($vehicle_rental->pickup_counter_location) { + return $this->item($vehicle_rental->pickup_counter_location, new \Plugins\Vehicles\Transformers\CounterLocationTransformer); + } else { + return null; + } + } + + public function includeDropCounterLocation(VehicleRental $vehicle_rental) + { + if ($vehicle_rental->drop_counter_location) { + return $this->item($vehicle_rental->drop_counter_location, new \Plugins\Vehicles\Transformers\CounterLocationTransformer); + } else { + return null; + } + } + + public function includeVehicleRentalAdditionalChargable(VehicleRental $vehicle_rental) + { + if ($vehicle_rental->vehicle_rental_additional_chargable) { + return $this->collection($vehicle_rental->vehicle_rental_additional_chargable, new VehicleRentalAdditionalChargeTransformer()); + } else { + return null; + } + } + + /** + * @param VehicleRental $vehicle_rental + * @return Fractal\Resource\Item + */ + public function includeBookerDetail(VehicleRental $vehicle_rental) + { + if ($vehicle_rental->booker_detail) { + return $this->item($vehicle_rental->booker_detail, new VehicleRentalBookerDetailTransformer()); + } else { + return null; + } + } + + /** + * @param VehicleRental $vehicle_rental + * @return Fractal\Resource\Item + */ + public function includeUnavailableVehicle(VehicleRental $vehicle_rental) + { + if ($vehicle_rental->unavailable_vehicle) { + return $this->item($vehicle_rental->unavailable_vehicle, new \Plugins\Vehicles\Transformers\UnavailableVehicleTransformer()); + } else { + return null; + } + } + +} diff --git a/app/Plugins/VehicleRentals/plugin.json b/app/Plugins/VehicleRentals/plugin.json new file mode 100644 index 0000000..26cd7aa --- /dev/null +++ b/app/Plugins/VehicleRentals/plugin.json @@ -0,0 +1,9 @@ +{ + "name": "VehicleRentals", + "class": "fa fa-2x fa-hourglass", + "description": "By enabling this plugin, instructor can book.", + "dependencies": "Vehicles", + "module_id": "", + "module_hash": "", + "display_order": "10" +} diff --git a/app/Plugins/VehicleRentals/routes.php b/app/Plugins/VehicleRentals/routes.php new file mode 100644 index 0000000..0d23e36 --- /dev/null +++ b/app/Plugins/VehicleRentals/routes.php @@ -0,0 +1,53 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +/* +|-------------------------------------------------------------------------- +| Application Routes +|-------------------------------------------------------------------------- +| +| Here is where you can register all of the routes for an application. +| It is a breeze. Simply tell Lumen the URIs it should respond to +| and give it the Closure to call when that URI is requested. +| +*/ +$api = $this->app->make('Dingo\Api\Routing\Router'); +$api->version(['v1'], function ($api) { + + //Admin VehicleRental + $api->group(['prefix' => 'admin', 'namespace' => 'Plugins\VehicleRentals\Controllers\Admin', 'middleware' => 'apitracking'], function () use ($api) { + $api->get('vehicle_rentals', 'AdminVehicleRentalsController@index'); + $api->get('vehicle_rentals/{id}', 'AdminVehicleRentalsController@show'); + $api->put('vehicle_rentals/{id}/cancelled-by-admin', 'AdminVehicleRentalsController@CancelledByAdmin'); + $api->get('vehicle_rentals/{id}/checkin', 'AdminVehicleRentalsController@checkin'); + $api->post('vehicle_rentals/{id}/checkout', 'AdminVehicleRentalsController@checkout'); + }); + //User VehicleRental + $api->group(['namespace' => 'Plugins\VehicleRentals\Controllers', 'middleware' => 'apitracking'], function () use ($api) { + $api->get('vehicle_rentals', 'VehicleRentalsController@index'); + $api->post('vehicle_rentals', 'VehicleRentalsController@store'); + $api->get('vehicle_rentals/{id}/edit', 'VehicleRentalsController@edit'); + $api->put('vehicle_rentals/{id}', 'VehicleRentalsController@update'); + $api->get('vehicle_rentals/{id}', 'VehicleRentalsController@show'); + $api->post('vehicle_rentals/{id}/paynow', 'VehicleRentalsController@payNow'); + $api->get('vehicle_rentals/{id}/reject', 'VehicleRentalsController@reject'); + $api->get('vehicle_rentals/{id}/cancel', 'VehicleRentalsController@cancel'); + $api->get('vehicle_rentals/{id}/confirm', 'VehicleRentalsController@confirmed'); + $api->get('vehicle_rentals/{id}/checkin', 'VehicleRentalsController@checkin'); + $api->post('vehicle_rentals/{id}/checkout', 'VehicleRentalsController@checkout'); + $api->get('item_orders', 'VehicleRentalsController@itemOrders'); + $api->get('vehicle_rental_status', 'VehicleRentalStatusesController@index'); + }); +}); diff --git a/app/Plugins/VehicleSurcharges/Controllers/Admin/AdminVehicleSurchargesController.php b/app/Plugins/VehicleSurcharges/Controllers/Admin/AdminVehicleSurchargesController.php new file mode 100644 index 0000000..8ae28e5 --- /dev/null +++ b/app/Plugins/VehicleSurcharges/Controllers/Admin/AdminVehicleSurchargesController.php @@ -0,0 +1,190 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleSurcharges\Controllers\Admin; + +use Illuminate\Http\Request; +use App\Http\Controllers\Controller; +use Plugins\VehicleSurcharges\Model\VehicleSurcharge; +use JWTAuth; +use Validator; +use Tymon\JWTAuth\Exceptions\JWTException; +use Plugins\VehicleSurcharges\Transformers\AdminVehicleSurchargeTransformer; +use Plugins\VehicleSurcharges\Transformers\VehicleSurchargeTransformer; +use EasySlug\EasySlug\EasySlugFacade as EasySlug; + +/** + * VehicleSurcharges resource representation. + * @Resource("Admin/AdminVehicleSurcharges") + */ +class AdminVehicleSurchargesController extends Controller +{ + /** + * AdminVehicleSurchargesController constructor. + */ + public function __construct() + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth'); + // Check the logged user role. + $this->middleware('role'); + } + + /** + * Show all vehicle_surcharges + * Get a JSON representation of all the vehicle_surcharges. + * + * @Get("/admin/vehicle_surcharges?sort={sort}&sortby={sortby}&page={page}&q={q}") + * @Parameters({ + * @Parameter("sort", type="string", required=false, description="Sort the vehicle_surcharges list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort vehicle_surcharges by Ascending / Descending Order.", default=null), + * @Parameter("q", type="string", required=false, description="Search VehicleSurcharges.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1) + * }) + */ + public function index(Request $request) + { + if($request->has('limit') && $request->limit == 'all') { + $vehicle_count = VehicleSurcharge::count(); + $vehicles = VehicleSurcharge::filterByActiveRecord($request)->filterByRequest($request)->select('id', 'name')->paginate($vehicle_count); + return $this->response->paginator($vehicles, new VehicleSurchargeTransformer); + } else { + $vehicle_surcharges = VehicleSurcharge::filterByRequest($request)->paginate(config('constants.ConstPageLimit')); + return $this->response->paginator($vehicle_surcharges, new AdminVehicleSurchargeTransformer); + } + } + + /** + * Edit the specified vehicle_surcharge. + * Edit the vehicle_surcharge with a `id`. + * @Get("/admin/vehicle_surcharges/{id}/edit") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body= {"id": 1, "name": "Energy Surcharge", "short_description": "The costs of energy needed to support our business operations have escalated considerably.", "description": "The costs of energy needed to support our business operations have escalated considerably. To offset the increasing costs of utilities, bus fuel, oil and grease, etc.,"}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function edit($id) + { + $vehicle_surcharge = VehicleSurcharge::find($id); + if (!$vehicle_surcharge) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($vehicle_surcharge, (new AdminVehicleSurchargeTransformer)); + } + + /** + * Show the specified vehicle_surcharge. + * show the vehicle_surcharge with a `id`. + * @Get("/admin/vehicle_surcharges/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body= {"id": 1, "name": "Energy Surcharge", "short_description": "The costs of energy needed to support our business operations have escalated considerably.", "description": "The costs of energy needed to support our business operations have escalated considerably. To offset the increasing costs of utilities, bus fuel, oil and grease, etc.,"}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function show($id) + { + $vehicle_surcharge = VehicleSurcharge::find($id); + if (!$vehicle_surcharge) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($vehicle_surcharge, (new AdminVehicleSurchargeTransformer)); + } + + /** + * Store a new vehicle_surcharge. + * Store a new vehicle_surcharge with a `name`, `short_description`, and `description`. + * @Post("/admin/vehicle_surcharges") + * @Transaction({ + * @Request({"name": "Energy Surcharge", "short_description": "The costs of energy needed to support our business operations have escalated considerably.", "description": "The costs of energy needed to support our business operations have escalated considerably. To offset the increasing costs of utilities, bus fuel, oil and grease, etc.,"}), + * @Response(200, body={"success": "Record has been added."}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {"name": {}}, "status_code": 422}) + * }) + */ + public function store(Request $request) + { + $vehicle_surcharge_data = $request->only('name', 'short_description', 'description'); + $validator = Validator::make($vehicle_surcharge_data, VehicleSurcharge::GetValidationRule(), VehicleSurcharge::GetValidationMessage()); + $vehicle_surcharge_data['slug'] = EasySlug::generateUniqueSlug($request->name, 'surcharges'); + if ($validator->passes()) { + $vehicle_surcharge_data['is_active'] = true; + $vehicle_surcharge = VehicleSurcharge::create($vehicle_surcharge_data); + if ($vehicle_surcharge) { + return response()->json(['Success' => 'VehicleSurcharge has been added'], 200); + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('VehicleSurcharge could not be updated. Please, try again.'); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('VehicleSurcharge could not be updated. Please, try again.', $validator->errors()); + } + } + + + /** + * Update the specified vehicle_surcharge + * Update the vehicle_surcharge with a `id`. + * @Put("/admin/vehicle_surcharges/{id}") + * @Transaction({ + * @Request({"id": 1, "name": "Energy Surcharge", "short_description": "The costs of energy needed to support our business operations have escalated considerably.", "description": "The costs of energy needed to support our business operations have escalated considerably. To offset the increasing costs of utilities, bus fuel, oil and grease, etc.,", "is_active": 1}), + * @Response(200, body={"success": "Record has been updated."}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {"name": {}}, "status_code": 422}) + * }) + */ + public function update(Request $request, $id) + { + $vehicle_surcharge_data = $request->only('name', 'short_description', 'description', 'is_active'); + $validator = Validator::make($vehicle_surcharge_data, VehicleSurcharge::GetValidationRule(), VehicleSurcharge::GetValidationMessage()); + $vehicle_surcharge = false; + if ($request->has('id')) { + $vehicle_surcharge = VehicleSurcharge::find($id); + $vehicle_surcharge = ($request->id != $id) ? false : $vehicle_surcharge; + if ($vehicle_surcharge->name !== $request->name) { + $vehicle_surcharge_data['slug'] = EasySlug::generateUniqueSlug($request->name, 'surcharges'); + } + } + if ($validator->passes() && $vehicle_surcharge) { + try { + $vehicle_surcharge->update($vehicle_surcharge_data); + return response()->json(['Success' => 'VehicleSurcharge has been updated'], 200); + } catch (\Exception $e) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('VehicleSurcharge could not be updated. Please, try again.'); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('VehicleSurcharge could not be updated. Please, try again.', $validator->errors()); + } + } + + /** + * Delete the specified vehicle_surcharge. + * Delete the vehicle_surcharge with a `id`. + * @Delete("/admin/vehicle_surcharges/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"success": "Record Deleted."}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function destroy($id) + { + $vehicle_surcharge = VehicleSurcharge::find($id); + if (!$vehicle_surcharge) { + return $this->response->errorNotFound("Invalid Request"); + } else { + $vehicle_surcharge->delete(); + } + return response()->json(['Success' => 'VehicleSurcharge deleted'], 200); + } +} diff --git a/app/Plugins/VehicleSurcharges/Controllers/Admin/AdminVehicleTypeSurchargesController.php b/app/Plugins/VehicleSurcharges/Controllers/Admin/AdminVehicleTypeSurchargesController.php new file mode 100644 index 0000000..bd6b0d8 --- /dev/null +++ b/app/Plugins/VehicleSurcharges/Controllers/Admin/AdminVehicleTypeSurchargesController.php @@ -0,0 +1,187 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleSurcharges\Controllers\Admin; + +use Illuminate\Http\Request; +use App\Http\Controllers\Controller; +use Plugins\VehicleSurcharges\Model\VehicleTypeSurcharge; +use JWTAuth; +use Validator; +use Plugins\VehicleSurcharges\Transformers\VehicleTypeSurchargeTransformer; +use DB; + +/** + * VehicleTypeSurcharges resource representation. + * @Resource("Admin/AdminVehicleTypeSurcharges") + */ +class AdminVehicleTypeSurchargesController extends Controller +{ + /** + * AdminVehicleTypeSurchargesController constructor. + */ + public function __construct() + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth'); + // Check the logged user role. + $this->middleware('role'); + } + + /** + * Show all vehicle_type_surcharges + * Get a JSON representation of all the vehicle_type_surcharges. + * + * @Get("/admin/vehicle_type_surcharges?sort={sort}&sortby={sortby}&page={page}&q={q}") + * @Parameters({ + * @Parameter("sort", type="string", required=false, description="Sort the vehicle_type_surcharges list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort vehicle_type_surcharges by Ascending / Descending Order.", default=null), + * @Parameter("q", type="string", required=false, description="Search VehicleTypeSurcharges.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1) + * }) + */ + public function index(Request $request) + { + $enabled_includes = array('vehicle_surcharge', 'discount_type', 'duration_type', 'vehicle_type'); + $vehicle_type_surcharges = VehicleTypeSurcharge::with($enabled_includes) + ->select(DB::raw('vehicle_type_surcharges.*')) + ->leftJoin(DB::raw('(select id,name from vehicle_types) as vehicle_type'), 'vehicle_type.id', '=', 'vehicle_type_surcharges.vehicle_type_id') + ->leftJoin(DB::raw('(select id,name from surcharges) as vehicle_surcharge'), 'vehicle_surcharge.id', '=', 'vehicle_type_surcharges.surcharge_id') + ->leftJoin(DB::raw('(select id,type from discount_types) as discount_type'), 'discount_type.id', '=', 'vehicle_type_surcharges.discount_type_id') + ->leftJoin(DB::raw('(select id,name from duration_types) as duration_type'), 'duration_type.id', '=', 'vehicle_type_surcharges.duration_type_id') + ->filterByRequest($request)->paginate(config('constants.ConstPageLimit')); + return $this->response->paginator($vehicle_type_surcharges, (new VehicleTypeSurchargeTransformer)->setDefaultIncludes($enabled_includes)); + } + + /** + * Edit the specified vehicle_type_surcharge. + * Edit the vehicle_type_surcharge with a `id`. + * @Get("/admin/vehicle_type_surcharges/{id}/edit") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body= {"id": 1, "vehicle_type_id": 1, "surcharge_id": 1, "discount_type_id": 1, "duration_type_id": 1, "rate": 200, "max_allowed_amount": 1000, "vehicle_type": {}, "vehicle_surcharge": {}, "duration_type": {}, "discount_type": {}}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function edit($id) + { + $enabled_includes = array('vehicle_surcharge', 'discount_type', 'duration_type', 'vehicle_type'); + $vehicle_type_surcharge = VehicleTypeSurcharge::with($enabled_includes)->find($id); + if (!$vehicle_type_surcharge) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($vehicle_type_surcharge, (new VehicleTypeSurchargeTransformer)->setDefaultIncludes($enabled_includes)); + } + + /** + * Show the specified vehicle_type_surcharge. + * Show the vehicle_type_surcharge with a `id`. + * @Get("/admin/vehicle_type_surcharges/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body= {"id": 1, "vehicle_type_id": 1, "surcharge_id": 1, "discount_type_id": 1, "duration_type_id": 1, "rate": 200, "max_allowed_amount": 1000, "vehicle_type": {}, "vehicle_surcharge": {}, "duration_type": {}, "discount_type": {}}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function show($id) + { + $enabled_includes = array('vehicle_surcharge', 'discount_type', 'duration_type', 'vehicle_type'); + $vehicle_type_surcharge = VehicleTypeSurcharge::with($enabled_includes)->find($id); + if (!$vehicle_type_surcharge) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($vehicle_type_surcharge, (new VehicleTypeSurchargeTransformer)->setDefaultIncludes($enabled_includes)); + } + + /** + * Store a new vehicle_type_surcharge. + * Store a new vehicle_type_surcharge with a `name`, `short_description`, and `description`. + * @Post("/admin/vehicle_type_surcharges") + * @Transaction({ + * @Request({"vehicle_type_id": 1, "surcharge_id": 1, "discount_type_id": 1, "duration_type_id": 1, "rate": 200, "max_allowed_amount": 1000}), + * @Response(200, body={"success": "Record has been added."}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {"name": {}}, "status_code": 422}) + * }) + */ + public function store(Request $request) + { + $vehicle_type_surcharge_data = $request->only('vehicle_type_id', 'surcharge_id', 'rate', 'discount_type_id', 'duration_type_id', 'max_allowed_amount'); + $validator = Validator::make($vehicle_type_surcharge_data, VehicleTypeSurcharge::GetValidationRule(), VehicleTypeSurcharge::GetValidationMessage()); + $vehicle_type_surcharge_data['is_active'] = true; + if ($validator->passes()) { + $vehicle_type_surcharge = VehicleTypeSurcharge::create($vehicle_type_surcharge_data); + if ($vehicle_type_surcharge) { + return response()->json(['Success' => 'VehicleTypeSurcharge has been added'], 200); + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('VehicleTypeSurcharge could not be Added. Please, try again.'); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('VehicleTypeSurcharge could not be Added. Please, try again.', $validator->errors()); + } + } + + + /** + * Update the specified vehicle_type_surcharge + * Update the vehicle_type_surcharge with a `id`. + * @Put("/admin/vehicle_type_surcharges/{id}") + * @Transaction({ + * @Request({"id": 1, "vehicle_type_id": 1, "surcharge_id": 1, "discount_type_id": 1, "duration_type_id": 1, "rate": 200, "max_allowed_amount": 1000}), + * @Response(200, body={"success": "Record has been updated."}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {"name": {}}, "status_code": 422}) + * }) + */ + public function update(Request $request, $id) + { + $vehicle_type_surcharge_data = $request->only('vehicle_type_id', 'surcharge_id', 'rate', 'discount_type_id', 'duration_type_id', 'max_allowed_amount', 'is_active'); + $validator = Validator::make($vehicle_type_surcharge_data, VehicleTypeSurcharge::GetValidationRule(), VehicleTypeSurcharge::GetValidationMessage()); + $vehicle_type_surcharge = false; + if ($request->has('id')) { + $vehicle_type_surcharge = VehicleTypeSurcharge::find($id); + $vehicle_type_surcharge = ($request->id != $id) ? false : $vehicle_type_surcharge; + } + if ($validator->passes() && $vehicle_type_surcharge) { + try { + $vehicle_type_surcharge->update($vehicle_type_surcharge_data); + return response()->json(['Success' => 'VehicleTypeSurcharge has been updated'], 200); + } catch (\Exception $e) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('VehicleTypeSurcharge could not be updated. Please, try again.'); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('VehicleTypeSurcharge could not be updated. Please, try again.', $validator->errors()); + } + } + + /** + * Delete the specified vehicle_type_surcharge. + * Delete the vehicle_type_surcharge with a `id`. + * @Delete("/admin/vehicle_type_surcharges/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"success": "Record Deleted."}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function destroy($id) + { + $vehicle_type_surcharge = VehicleTypeSurcharge::find($id); + if (!$vehicle_type_surcharge) { + return $this->response->errorNotFound("Invalid Request"); + } else { + $vehicle_type_surcharge->delete(); + } + return response()->json(['Success' => 'VehicleTypeSurcharge deleted'], 200); + } +} diff --git a/app/Plugins/VehicleSurcharges/Controllers/VehicleSurchargesController.php b/app/Plugins/VehicleSurcharges/Controllers/VehicleSurchargesController.php new file mode 100644 index 0000000..aa699cf --- /dev/null +++ b/app/Plugins/VehicleSurcharges/Controllers/VehicleSurchargesController.php @@ -0,0 +1,58 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleSurcharges\Controllers; + +use Illuminate\Http\Request; +use App\Http\Controllers\Controller; +use Plugins\VehicleSurcharges\Model\VehicleSurcharge; +use JWTAuth; +use Validator; +use Tymon\JWTAuth\Exceptions\JWTException; +use Plugins\VehicleSurcharges\Transformers\VehicleSurchargeTransformer; + +/** + * VehicleSurcharges resource representation. + * @Resource("VehicleSurcharges") + */ +class VehicleSurchargesController extends Controller +{ + /** + * VehicleSurchargesController constructor. + */ + public function __construct() + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth'); + } + + /** + * Show all surcharges + * Get a JSON representation of all the surcharges. + * + * @Get("/vehicle_surcharges?sort={sort}&sortby={sortby}&page={page}&q={q}") + * @Parameters({ + * @Parameter("sort", type="string", required=false, description="Sort the surcharges list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort surcharges by Ascending / Descending Order.", default=null), + * @Parameter("q", type="string", required=false, description="Search VehicleSurcharges.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1) + * }) + */ + public function index(Request $request) + { + $surcharges = VehicleSurcharge::filterByRequest($request)->paginate(config('constants.ConstPageLimit')); + return $this->response->paginator($surcharges, (new VehicleSurchargeTransformer)); + } +} diff --git a/app/Plugins/VehicleSurcharges/Controllers/VehicleTypeSurchargesController.php b/app/Plugins/VehicleSurcharges/Controllers/VehicleTypeSurchargesController.php new file mode 100644 index 0000000..2a7f8d5 --- /dev/null +++ b/app/Plugins/VehicleSurcharges/Controllers/VehicleTypeSurchargesController.php @@ -0,0 +1,59 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleSurcharges\Controllers; + +use Illuminate\Http\Request; +use App\Http\Controllers\Controller; +use Plugins\VehicleSurcharges\Model\VehicleTypeSurcharge; +use JWTAuth; +use Validator; +use Tymon\JWTAuth\Exceptions\JWTException; +use Plugins\VehicleSurcharges\Transformers\VehicleTypeSurchargeTransformer; + +/** + * VehicleSurcharges resource representation. + * @Resource("VehicleSurcharges") + */ +class VehicleTypeSurchargesController extends Controller +{ + /** + * VehicleSurchargesController constructor. + */ + public function __construct() + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth'); + } + + /** + * Show all surcharges + * Get a JSON representation of all the surcharges. + * + * @Get("/surcharges?sort={sort}&sortby={sortby}&page={page}&q={q}") + * @Parameters({ + * @Parameter("sort", type="string", required=false, description="Sort the surcharges list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort surcharges by Ascending / Descending Order.", default=null), + * @Parameter("q", type="string", required=false, description="Search VehicleSurcharges.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1) + * }) + */ + public function index(Request $request) + { + $enabled_includes = array('vehicle_surcharge', 'discount_type', 'duration_type', 'vehicle_type'); + $vehicle_type_surcharges = VehicleTypeSurcharge::with($enabled_includes)->filterByRequest($request)->paginate(config('constants.ConstPageLimit')); + return $this->response->paginator($vehicle_type_surcharges, (new VehicleTypeSurchargeTransformer)->setDefaultIncludes($enabled_includes)); + } +} diff --git a/app/Plugins/VehicleSurcharges/Model/VehicleSurcharge.php b/app/Plugins/VehicleSurcharges/Model/VehicleSurcharge.php new file mode 100644 index 0000000..fe54974 --- /dev/null +++ b/app/Plugins/VehicleSurcharges/Model/VehicleSurcharge.php @@ -0,0 +1,101 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleSurcharges\Model; + +use Illuminate\Http\Request; +use Illuminate\Database\Eloquent\Model; + +class VehicleSurcharge extends Model +{ + /** + * @var string + */ + protected $table = "surcharges"; + + protected $fillable = [ + 'name', 'short_description', 'description', 'is_active', 'slug' + ]; + + + /** + * @return \Illuminate\Database\Eloquent\Relations\HasMany + */ + public function vehicle_type_surcharge() + { + return $this->hasMany(VehicleTypeSurcharge::class); + } + /** + * @param $query + * @param Request $request + */ + public function scopeFilterByActiveRecord($query, Request $request) + { + $query->where('is_active', '=', 1); + } + /** + * @param $query + * @param Request $request + * @return mixed + */ + public function scopeFilterByRequest($query, Request $request) + { + $query->orderBy($request->input('sort', 'id'), $request->input('sortby', 'asc')); + if ($request->has('q')) { + $query->where('name', 'LIKE', '%' . $request->input('q') . '%') + ->orWhere('short_description', 'LIKE', '%' . $request->input('q') . '%') + ->orWhere('description', 'LIKE', '%' . $request->input('q') . '%'); + } + if ($request->has('filter')) { + $filter = false; + if ($request->input('filter') == 'active') { + $filter = true; + } + $query->where('is_active', '=', $filter); + } + return $query; + } + + /** + * @return array + */ + public function scopeGetValidationRule() + { + return [ + 'name' => 'required|min:5', + 'short_description' => 'required|min:10', + 'description' => 'required|min:15', + 'is_active' => 'sometimes|required|boolean' + ]; + } + + /** + * @return array + */ + public function scopeGetValidationMessage() + { + return [ + 'name.required' => 'Required', + 'name.min' => 'name - Minimum length is 5', + 'short_description.required' => 'Required', + 'short_description.min' => 'Short Description - Minimum length is 10', + 'description.required' => 'Required', + 'description.min' => 'Description - Minimum length is 15', + 'is_active.required' => 'Required', + 'is_active.boolean' => 'Possible values to be entered is 0 or 1' + ]; + } + +} diff --git a/app/Plugins/VehicleSurcharges/Model/VehicleTypeSurcharge.php b/app/Plugins/VehicleSurcharges/Model/VehicleTypeSurcharge.php new file mode 100644 index 0000000..928006d --- /dev/null +++ b/app/Plugins/VehicleSurcharges/Model/VehicleTypeSurcharge.php @@ -0,0 +1,151 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleSurcharges\Model; + +use Illuminate\Http\Request; +use Illuminate\Database\Eloquent\Model; +use Illuminate\Support\Facades\App; +use App\DiscountType; +use App\DurationType; + +class VehicleTypeSurcharge extends Model +{ + /** + * @var string + */ + protected $table = "vehicle_type_surcharges"; + + protected $fillable = [ + 'vehicle_type_id', 'surcharge_id', 'rate', 'discount_type_id', 'duration_type_id', 'max_allowed_amount', 'is_active' + ]; + + + /** + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function vehicle_surcharge() + { + return $this->belongsTo(VehicleSurcharge::class, 'surcharge_id'); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function vehicle_type() + { + return $this->belongsTo(\Plugins\Vehicles\Model\VehicleType::class); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function discount_type() + { + return $this->belongsTo(DiscountType::class); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function duration_type() + { + return $this->belongsTo(DurationType::class); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\MorphMany + */ + public function vehicle_rental_additional_charges() + { + return $this->morphMany(\Plugins\VehicleRentals\Model\VehicleRentalAdditionalCharge::class, 'item_user_additional_chargable'); + } + + /** + * @param $query + * @param Request $request + * @return mixed + */ + public function scopeFilterByRequest($query, Request $request) + { + $query->orderBy($request->input('sort', 'id'), $request->input('sortby', 'asc')); + if ($request->has('q')) { + $query->WhereHas('vehicle_surcharge', function ($q) use ($request) { + $q->where('name', 'like', '%' . $request->input('q') . '%'); + }); + $query->orWhereHas('vehicle_type', function ($q) use ($request) { + $q->where('name', 'like', '%' . $request->input('q') . '%'); + }); + $query->orWhereHas('discount_type', function ($q) use ($request) { + $q->where('type', 'like', '%' . $request->input('q') . '%'); + }); + $query->orWhereHas('duration_type', function ($q) use ($request) { + $q->where('name', 'like', '%' . $request->input('q') . '%'); + }); + } + if ($request->has('filter')) { + $filter = false; + if ($request->filter == 'active') { + $filter = true; + } + $query->where('is_active', '=', $filter); + } + if($request->has('surcharge_id')){ + $query->where('surcharge_id', '=', $request->surcharge_id); + } + return $query; + } + + /** + * @return array + */ + public function scopeGetValidationRule() + { + return [ + 'vehicle_type_id' => 'required|integer|exists:vehicle_types,id', + 'surcharge_id' => 'required|integer|exists:surcharges,id', + 'rate' => 'required|numeric', + 'discount_type_id' => 'required|integer|exists:discount_types,id', + 'duration_type_id' => 'required|integer|exists:duration_types,id', + 'max_allowed_amount' => 'required|numeric' + ]; + } + + /** + * @return array + */ + public function scopeGetValidationMessage() + { + return [ + 'vehicle_type_id.required' => 'Required', + 'vehicle_type_id.integer' => 'Vehicle Type Id must be integer', + 'vehicle_type_id.exists' => 'Invalid vehicle type id', + 'surcharge_id.required' => 'Required', + 'surcharge_id.integer' => 'Surcharge Id must be integer', + 'surcharge_id.exists' => 'Invalid surcharge id', + 'rate.required' => 'Required', + 'rate.numeric' => 'Rate must be numeric', + 'discount_type_id.required' => 'Required', + 'discount_type_id.integer' => 'Discount Type Id must be integer', + 'discount_type_id.exists' => 'Invalid discount type id', + 'duration_type_id.required' => 'Required', + 'duration_type_id.integer' => 'Duration Type Id must be integer', + 'discount_type_id.exists' => 'Invalid duration type id', + 'max_allowed_amount.required' => 'Required', + 'max_allowed_amount.numeric' => 'Max allowed amount must be numeric' + ]; + } + +} diff --git a/app/Plugins/VehicleSurcharges/Providers/VehicleSurchargeServiceProvider.php b/app/Plugins/VehicleSurcharges/Providers/VehicleSurchargeServiceProvider.php new file mode 100644 index 0000000..2f6537c --- /dev/null +++ b/app/Plugins/VehicleSurcharges/Providers/VehicleSurchargeServiceProvider.php @@ -0,0 +1,44 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleSurcharges\Providers; + +use Illuminate\Support\ServiceProvider; + +class VehicleSurchargeServiceProvider extends ServiceProvider +{ + /** + * Register any application services. + * + * @return void + */ + public function register() + { + include __DIR__ . '/../routes.php'; + $this->app->make('Plugins\VehicleSurcharges\Controllers\VehicleSurchargesController'); + $this->app->make('Plugins\VehicleSurcharges\Controllers\Admin\AdminVehicleSurchargesController'); + $this->app->make('Plugins\VehicleSurcharges\Controllers\VehicleTypeSurchargesController'); + $this->app->make('Plugins\VehicleSurcharges\Controllers\Admin\AdminVehicleTypeSurchargesController'); + } + + /** + * Bootstrap the application services. + * + * @return void + */ + public function boot() + { + } +} diff --git a/app/Plugins/VehicleSurcharges/Services/VehicleSurchargeService.php b/app/Plugins/VehicleSurcharges/Services/VehicleSurchargeService.php new file mode 100644 index 0000000..6ccca98 --- /dev/null +++ b/app/Plugins/VehicleSurcharges/Services/VehicleSurchargeService.php @@ -0,0 +1,73 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleSurcharges\Services; + +use Plugins\VehicleSurcharges\Model\VehicleTypeSurcharge; +use Plugins\VehicleRentals\Model\VehicleRentalAdditionalCharge; + +class VehicleSurchargeService +{ + /** + * VehicleSurchargeService constructor. + */ + public function __construct() + { + } + + /** + * @param $vehicle_type_id + * @param $item_user_id + * @param $booking_calculated_details + * @return int + */ + public function processSurchargeAmount($vehicle_type_id, $item_user_id, $booking_calculated_details) + { + $res_amount = 0; + $vehicle_type_surcharges = VehicleTypeSurcharge::where('vehicle_type_id', $vehicle_type_id)->get(); + if(!empty($vehicle_type_surcharges)) { + foreach ($vehicle_type_surcharges as $vehicle_type_surcharge) { + if (!empty($vehicle_type_surcharge->rate)) { + if (!empty($vehicle_type_surcharge->discount_type_id) && $vehicle_type_surcharge->discount_type_id == 1) { + $surcharge_amount = $booking_calculated_details['booking_amount'] * $vehicle_type_surcharge->rate / 100; + } else if (!empty($vehicle_type_surcharge->discount_type_id) && $vehicle_type_surcharge->discount_type_id == 2) { + $surcharge_amount = $vehicle_type_surcharge->rate; + } + if (!empty($vehicle_type_surcharge->duration_type_id) && $vehicle_type_surcharge->duration_type_id == 1) { + if (!empty($booking_calculated_details['total_hours'])) { + $booking_calculated_details['total_days'] = $booking_calculated_details['total_days'] + 1; + } + $surcharge_amount = $surcharge_amount * $booking_calculated_details['total_days']; + } + if (!empty($vehicle_type_surcharge->max_allowed_amount)) { + if ($surcharge_amount > $vehicle_type_surcharge->max_allowed_amount) { + $surcharge_amount = $vehicle_type_surcharge->max_allowed_amount; + } + } + } + $vehicle_rental_additional_data['item_user_id'] = $item_user_id; + $vehicle_rental_additional_data['amount'] = $surcharge_amount; + $vehicle_rental_additional_charge = VehicleRentalAdditionalCharge::create($vehicle_rental_additional_data); + $vehicle_surcharge = VehicleTypeSurcharge::with(['vehicle_rental_additional_charges'])->where('id', '=', $vehicle_type_surcharge->id)->first(); + $vehicle_surcharge->vehicle_rental_additional_charges()->save($vehicle_rental_additional_charge); + $res_amount = $res_amount + $surcharge_amount; + } + return $res_amount; + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Given Surcharges not available. Please, try again.'); + } + } + +} diff --git a/app/Plugins/VehicleSurcharges/Transformers/AdminVehicleSurchargeTransformer.php b/app/Plugins/VehicleSurcharges/Transformers/AdminVehicleSurchargeTransformer.php new file mode 100644 index 0000000..522eb26 --- /dev/null +++ b/app/Plugins/VehicleSurcharges/Transformers/AdminVehicleSurchargeTransformer.php @@ -0,0 +1,40 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleSurcharges\Transformers; + +use League\Fractal; +use Plugins\VehicleSurcharges\Model\VehicleSurcharge; + +/** + * Class VehicleSurchargeTransformer + * @package VehicleSurcharges\Transformers + */ +class AdminVehicleSurchargeTransformer extends Fractal\TransformerAbstract +{ + + /** + * @param VehicleSurcharge $vehicle_surcharge + * @return array + */ + public function transform(VehicleSurcharge $vehicle_surcharge) + { + $output = array_only($vehicle_surcharge->toArray(), ['id', 'created_at', 'name', 'short_description', 'description', 'is_active']); + $output['is_active'] = ($output['is_active']) ? true : false; + return $output; + } + + +} \ No newline at end of file diff --git a/app/Plugins/VehicleSurcharges/Transformers/VehicleSurchargeTransformer.php b/app/Plugins/VehicleSurcharges/Transformers/VehicleSurchargeTransformer.php new file mode 100644 index 0000000..37a0948 --- /dev/null +++ b/app/Plugins/VehicleSurcharges/Transformers/VehicleSurchargeTransformer.php @@ -0,0 +1,36 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleSurcharges\Transformers; + +use League\Fractal; +use Plugins\VehicleSurcharges\Model\VehicleSurcharge; + +/** + * Class VehicleSurchargeTransformer + * @package VehicleSurcharges\Transformers + */ +class VehicleSurchargeTransformer extends Fractal\TransformerAbstract +{ + /** + * @param VehicleSurcharge $vehicle_surcharge + * @return array + */ + public function transform(VehicleSurcharge $vehicle_surcharge) + { + $output = array_only($vehicle_surcharge->toArray(), ['id', 'name']); + return $output; + } +} \ No newline at end of file diff --git a/app/Plugins/VehicleSurcharges/Transformers/VehicleTypeSurchargeTransformer.php b/app/Plugins/VehicleSurcharges/Transformers/VehicleTypeSurchargeTransformer.php new file mode 100644 index 0000000..777992a --- /dev/null +++ b/app/Plugins/VehicleSurcharges/Transformers/VehicleTypeSurchargeTransformer.php @@ -0,0 +1,104 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleSurcharges\Transformers; + +use App\Transformers\DiscountTypeTransformer; +use App\Transformers\DurationTypeTransformer; +use League\Fractal; +use Plugins\VehicleSurcharges\Model\VehicleTypeSurcharge; + +/** + * Class VehicleSurchargeTransformer + * @package VehicleSurcharges\Transformers + */ +class VehicleTypeSurchargeTransformer extends Fractal\TransformerAbstract +{ + /** + * List of resources possible to include + * + * @var array + */ + protected $availableIncludes = [ + 'VehicleSurcharge', 'VehicleType', 'DurationType', 'DiscountType' + ]; + + /** + * @param VehicleTypeSurcharge $vehicle_type_surcharge + * @return array + */ + public function transform(VehicleTypeSurcharge $vehicle_type_surcharge) + { + $output = array_only($vehicle_type_surcharge->toArray(), ['id', 'created_at', 'vehicle_type_id', 'surcharge_id', 'rate', 'discount_type_id', 'duration_type_id', 'max_allowed_amount', 'is_active']); + $output['is_active'] = ($output['is_active']) ? true : false; + return $output; + } + + /** + * @param VehicleTypeSurcharge $vehicle_type_surcharge + * @return Fractal\Resource\Item|null + */ + public function includeVehicleSurcharge(VehicleTypeSurcharge $vehicle_type_surcharge) + { + if ($vehicle_type_surcharge->vehicle_surcharge) { + return $this->item($vehicle_type_surcharge->vehicle_surcharge, new VehicleSurchargeTransformer()); + } else { + return null; + } + + } + + /** + * @param VehicleTypeSurcharge $vehicle_type_surcharge + * @return Fractal\Resource\Item|null + */ + public function includeVehicleType(VehicleTypeSurcharge $vehicle_type_surcharge) + { + if ($vehicle_type_surcharge->vehicle_type) { + return $this->item($vehicle_type_surcharge->vehicle_type, new \Plugins\Vehicles\Transformers\VehicleTypeTransformer()); + } else { + return null; + } + + } + + /** + * @param VehicleTypeSurcharge $vehicle_type_surcharge + * @return Fractal\Resource\Item|null + */ + public function includeDiscountType(VehicleTypeSurcharge $vehicle_type_surcharge) + { + if ($vehicle_type_surcharge->discount_type) { + return $this->item($vehicle_type_surcharge->discount_type, new DiscountTypeTransformer()); + } else { + return null; + } + + } + + /** + * @param VehicleTypeSurcharge $vehicle_type_surcharge + * @return Fractal\Resource\Item|null + */ + public function includeDurationType(VehicleTypeSurcharge $vehicle_type_surcharge) + { + if ($vehicle_type_surcharge->duration_type) { + return $this->item($vehicle_type_surcharge->duration_type, new DurationTypeTransformer()); + } else { + return null; + } + + } +} \ No newline at end of file diff --git a/app/Plugins/VehicleSurcharges/plugin.json b/app/Plugins/VehicleSurcharges/plugin.json new file mode 100644 index 0000000..4b34b18 --- /dev/null +++ b/app/Plugins/VehicleSurcharges/plugin.json @@ -0,0 +1,9 @@ +{ + "name": "VehicleSurcharges", + "class": "fa fa-2x fa-download", + "description": "By enabling this, item owner can manage surcharges based on vehicle types.", + "dependencies": "VehicleRentals", + "module_id": "", + "module_hash": "", + "display_order": "15" +} diff --git a/app/Plugins/VehicleSurcharges/routes.php b/app/Plugins/VehicleSurcharges/routes.php new file mode 100644 index 0000000..1e18f26 --- /dev/null +++ b/app/Plugins/VehicleSurcharges/routes.php @@ -0,0 +1,51 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +/* +|-------------------------------------------------------------------------- +| Application Routes +|-------------------------------------------------------------------------- +| +| Here is where you can register all of the routes for an application. +| It is a breeze. Simply tell Lumen the URIs it should respond to +| and give it the Closure to call when that URI is requested. +| +*/ +$api = $this->app->make('Dingo\Api\Routing\Router'); +$api->version(['v1'], function ($api) { + $api->group(['prefix' => 'admin', 'namespace' => 'Plugins\VehicleSurcharges\Controllers\Admin', 'middleware' => 'apitracking'], function () use ($api) { + // Surcharges admin side + $api->get('vehicle_surcharges', 'AdminVehicleSurchargesController@index'); + $api->post('vehicle_surcharges', 'AdminVehicleSurchargesController@store'); + $api->put('vehicle_surcharges/{id}', 'AdminVehicleSurchargesController@update'); + $api->get('vehicle_surcharges/{id}/edit', 'AdminVehicleSurchargesController@edit'); + $api->get('vehicle_surcharges/{id}', 'AdminVehicleSurchargesController@show'); + $api->delete('vehicle_surcharges/{id}', 'AdminVehicleSurchargesController@destroy'); + + // Vehicle Type Surcharges admin side + $api->get('vehicle_type_surcharges', 'AdminVehicleTypeSurchargesController@index'); + $api->post('vehicle_type_surcharges', 'AdminVehicleTypeSurchargesController@store'); + $api->put('vehicle_type_surcharges/{id}', 'AdminVehicleTypeSurchargesController@update'); + $api->get('vehicle_type_surcharges/{id}/edit', 'AdminVehicleTypeSurchargesController@edit'); + $api->get('vehicle_type_surcharges/{id}', 'AdminVehicleTypeSurchargesController@show'); + $api->delete('vehicle_type_surcharges/{id}', 'AdminVehicleTypeSurchargesController@destroy'); + + }); + $api->group(['namespace' => 'Plugins\VehicleSurcharges\Controllers', 'middleware' => 'apitracking'], function () use ($api) { + //surcharges user side + $api->get('vehicle_surcharges', 'VehicleSurchargesController@index'); + $api->get('vehicle_type_surcharges', 'VehicleTypeSurchargesController@index'); + }); +}); diff --git a/app/Plugins/VehicleTaxes/Controllers/Admin/AdminVehicleTaxesController.php b/app/Plugins/VehicleTaxes/Controllers/Admin/AdminVehicleTaxesController.php new file mode 100644 index 0000000..9c86dd2 --- /dev/null +++ b/app/Plugins/VehicleTaxes/Controllers/Admin/AdminVehicleTaxesController.php @@ -0,0 +1,191 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + + +namespace Plugins\VehicleTaxes\Controllers\Admin; + +use Illuminate\Http\Request; +use App\Http\Controllers\Controller; +use Plugins\VehicleTaxes\Model\VehicleTax; +use JWTAuth; +use Validator; +use Tymon\JWTAuth\Exceptions\JWTException; +use Plugins\VehicleTaxes\Transformers\AdminVehicleTaxTransformer; +use Plugins\VehicleTaxes\Transformers\VehicleTaxTransformer; +use EasySlug\EasySlug\EasySlugFacade as EasySlug; + +/** + * VehicleTaxes resource representation. + * @Resource("Admin/AdminVehicleTaxes") + */ +class AdminVehicleTaxesController extends Controller +{ + /** + * AdminVehicleTaxesController constructor. + */ + public function __construct() + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth'); + // Check the logged user role. + $this->middleware('role'); + } + + /** + * Show all vehicle_taxes + * Get a JSON representation of all the vehicle_taxes. + * + * @Get("/admin/vehicle_taxes?sort={sort}&sortby={sortby}&page={page}&q={q}") + * @Parameters({ + * @Parameter("sort", type="string", required=false, description="Sort the vehicle_taxes list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort vehicle_taxes by Ascending / Descending Order.", default=null), + * @Parameter("q", type="string", required=false, description="Search VehicleTaxes.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1) + * }) + */ + public function index(Request $request) + { + if($request->has('limit') && $request->limit == 'all') { + $vehicle_tax_count = VehicleTax::count(); + $vehicle_taxes = VehicleTax::filterByActiveRecord($request)->filterByRequest($request)->select('id', 'name')->paginate($vehicle_tax_count); + return $this->response->paginator($vehicle_taxes, new VehicleTaxTransformer); + } else { + $vehicle_taxes = VehicleTax::filterByRequest($request)->paginate(config('constants.ConstPageLimit')); + return $this->response->paginator($vehicle_taxes, new AdminVehicleTaxTransformer); + } + } + + /** + * Edit the specified vehicle_tax. + * Edit the vehicle_tax with a `id`. + * @Get("/admin/vehicle_taxes/{id}/edit") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body= {"id": 1, "name": "Service Tax", "short_description": "The costs of service needed to support our business operations have escalated considerably.", "description": "The costs of service needed to support our business operations have escalated considerably. To offset the increasing costs of utilities, bus fuel, oil and grease, etc.,"}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function edit($id) + { + $vehicle_tax = VehicleTax::find($id); + if (!$vehicle_tax) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($vehicle_tax, (new AdminVehicleTaxTransformer)); + } + + /** + * Show the specified vehicle_tax. + * Show the vehicle_tax with a `id`. + * @Get("/admin/vehicle_taxes/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body= {"id": 1, "name": "Service Tax", "short_description": "The costs of service needed to support our business operations have escalated considerably.", "description": "The costs of service needed to support our business operations have escalated considerably. To offset the increasing costs of utilities, bus fuel, oil and grease, etc.,"}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function show($id) + { + $vehicle_tax = VehicleTax::find($id); + if (!$vehicle_tax) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($vehicle_tax, (new AdminVehicleTaxTransformer)); + } + + /** + * Store a new vehicle_tax. + * Store a new vehicle_tax with a `name`, `short_description`, and `description`. + * @Post("/admin/vehicle_taxes") + * @Transaction({ + * @Request({"name": "Service Tax", "short_description": "The costs of service needed to support our business operations have escalated considerably.", "description": "The costs of service needed to support our business operations have escalated considerably. To offset the increasing costs of utilities, bus fuel, oil and grease, etc.,"}), + * @Response(200, body={"success": "Record has been added."}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {"name": {}}, "status_code": 422}) + * }) + */ + public function store(Request $request) + { + $vehicle_tax_data = $request->only('name', 'short_description', 'description'); + $validator = Validator::make($vehicle_tax_data, VehicleTax::GetValidationRule(), VehicleTax::GetValidationMessage()); + $vehicle_tax_data['slug'] = EasySlug::generateUniqueSlug($request->name, 'taxes'); + if ($validator->passes()) { + $vehicle_tax_data['is_active'] = true; + $vehicle_tax = VehicleTax::create($vehicle_tax_data); + if ($vehicle_tax) { + return response()->json(['Success' => 'VehicleTax has been added'], 200); + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('VehicleTax could not be updated. Please, try again.'); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('VehicleTax could not be updated. Please, try again.', $validator->errors()); + } + } + + + /** + * Update the specified vehicle_tax + * Update the vehicle_tax with a `id`. + * @Put("/admin/vehicle_taxes/{id}") + * @Transaction({ + * @Request({"id": 1, "name": "Energy Tax", "short_description": "The costs of energy needed to support our business operations have escalated considerably.", "description": "The costs of energy needed to support our business operations have escalated considerably. To offset the increasing costs of utilities, bus fuel, oil and grease, etc.,", "is_active": 1}), + * @Response(200, body={"success": "Record has been updated."}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {"name": {}}, "status_code": 422}) + * }) + */ + public function update(Request $request, $id) + { + $vehicle_tax_data = $request->only('name', 'short_description', 'description', 'is_active'); + $validator = Validator::make($vehicle_tax_data, VehicleTax::GetValidationRule(), VehicleTax::GetValidationMessage()); + $vehicle_tax = false; + if ($request->has('id')) { + $vehicle_tax = VehicleTax::find($id); + $vehicle_tax = ($request->id != $id) ? false : $vehicle_tax; + if ($vehicle_tax->name !== $request->name) { + $vehicle_tax_data['slug'] = EasySlug::generateUniqueSlug($request->name, 'taxes'); + } + } + if ($validator->passes() && $vehicle_tax) { + try { + $vehicle_tax->update($vehicle_tax_data); + return response()->json(['Success' => 'VehicleTax has been updated'], 200); + } catch (\Exception $e) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('VehicleTax could not be updated. Please, try again.'); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('VehicleTax could not be updated. Please, try again.', $validator->errors()); + } + } + + /** + * Delete the specified vehicle_tax. + * Delete the vehicle_tax with a `id`. + * @Delete("/admin/vehicle_taxes/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"success": "Record Deleted."}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function destroy($id) + { + $vehicle_tax = VehicleTax::find($id); + if (!$vehicle_tax) { + return $this->response->errorNotFound("Invalid Request"); + } else { + $vehicle_tax->delete(); + } + return response()->json(['Success' => 'VehicleTax deleted'], 200); + } +} diff --git a/app/Plugins/VehicleTaxes/Controllers/Admin/AdminVehicleTypeTaxesController.php b/app/Plugins/VehicleTaxes/Controllers/Admin/AdminVehicleTypeTaxesController.php new file mode 100644 index 0000000..c9884e9 --- /dev/null +++ b/app/Plugins/VehicleTaxes/Controllers/Admin/AdminVehicleTypeTaxesController.php @@ -0,0 +1,188 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleTaxes\Controllers\Admin; + +use Illuminate\Http\Request; +use App\Http\Requests; +use App\Http\Controllers\Controller; +use Plugins\VehicleTaxes\Model\VehicleTypeTax; +use JWTAuth; +use Validator; +use Plugins\VehicleTaxes\Transformers\VehicleTypeTaxTransformer; +use DB; + +/** + * VehicleTypeTaxes resource representation. + * @Resource("Admin/AdminVehicleTypeTaxes") + */ +class AdminVehicleTypeTaxesController extends Controller +{ + /** + * AdminVehicleTypeTaxesController constructor. + */ + public function __construct() + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth'); + // Check the logged user role. + $this->middleware('role'); + } + + /** + * Show all vehicle_type_taxes + * Get a JSON representation of all the vehicle_type_taxes. + * + * @Get("/admin/vehicle_type_taxes?sort={sort}&sortby={sortby}&page={page}&q={q}") + * @Parameters({ + * @Parameter("sort", type="string", required=false, description="Sort the vehicle_type_taxes list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort vehicle_type_taxes by Ascending / Descending Order.", default=null), + * @Parameter("q", type="string", required=false, description="Search VehicleTypeTaxes.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1) + * }) + */ + public function index(Request $request) + { + $enabled_includes = array('vehicle_tax', 'discount_type', 'duration_type', 'vehicle_type'); + $vehicle_type_taxes = VehicleTypeTax::with($enabled_includes) + ->select(DB::raw('vehicle_type_taxes.*')) + ->leftJoin(DB::raw('(select id,name from vehicle_types) as vehicle_type'), 'vehicle_type.id', '=', 'vehicle_type_taxes.vehicle_type_id') + ->leftJoin(DB::raw('(select id,name from taxes) as vehicle_tax'), 'vehicle_tax.id', '=', 'vehicle_type_taxes.tax_id') + ->leftJoin(DB::raw('(select id,type from discount_types) as discount_type'), 'discount_type.id', '=', 'vehicle_type_taxes.discount_type_id') + ->leftJoin(DB::raw('(select id,name from duration_types) as duration_type'), 'duration_type.id', '=', 'vehicle_type_taxes.duration_type_id') + ->filterByRequest($request)->paginate(config('constants.ConstPageLimit')); + return $this->response->paginator($vehicle_type_taxes, (new VehicleTypeTaxTransformer)->setDefaultIncludes($enabled_includes)); + } + + /** + * Edit the specified vehicle_type_tax. + * Edit the vehicle_type_tax with a `id`. + * @Get("/admin/vehicle_type_taxes/{id}/edit") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body= {"id": 1, "vehicle_type_id": 1, "tax_id": 1, "discount_type_id": 1, "duration_type_id": 1, "rate": 200, "max_allowed_amount": 1000, "vehicle_type": {}, "vehicle_tax": {}, "duration_type": {}, "discount_type": {}}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function edit($id) + { + $enabled_includes = array('vehicle_tax', 'discount_type', 'duration_type', 'vehicle_type'); + $vehicle_type_tax = VehicleTypeTax::with($enabled_includes)->find($id); + if (!$vehicle_type_tax) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($vehicle_type_tax, (new VehicleTypeTaxTransformer)->setDefaultIncludes($enabled_includes)); + } + + /** + * Show the specified vehicle_type_tax. + * Show the vehicle_type_tax with a `id`. + * @Get("/admin/vehicle_type_taxes/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body= {"id": 1, "vehicle_type_id": 1, "tax_id": 1, "discount_type_id": 1, "duration_type_id": 1, "rate": 200, "max_allowed_amount": 1000, "vehicle_type": {}, "vehicle_tax": {}, "duration_type": {}, "discount_type": {}}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function show($id) + { + $enabled_includes = array('vehicle_tax', 'discount_type', 'duration_type', 'vehicle_type'); + $vehicle_type_tax = VehicleTypeTax::with($enabled_includes)->find($id); + if (!$vehicle_type_tax) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($vehicle_type_tax, (new VehicleTypeTaxTransformer)->setDefaultIncludes($enabled_includes)); + } + + /** + * Store a new vehicle_type_tax. + * Store a new vehicle_type_tax with a `name`, `short_description`, and `description`. + * @Post("/admin/vehicle_type_taxes") + * @Transaction({ + * @Request({"vehicle_type_id": 1, "tax_id": 1, "discount_type_id": 1, "duration_type_id": 1, "rate": 200, "max_allowed_amount": 1000}), + * @Response(200, body={"success": "Record has been added."}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {"name": {}}, "status_code": 422}) + * }) + */ + public function store(Request $request) + { + $vehicle_type_tax_data = $request->only('vehicle_type_id', 'tax_id', 'rate', 'discount_type_id', 'duration_type_id', 'max_allowed_amount'); + $validator = Validator::make($vehicle_type_tax_data, VehicleTypeTax::GetValidationRule(), VehicleTypeTax::GetValidationMessage()); + $vehicle_type_tax_data['is_active'] = true; + if ($validator->passes()) { + $vehicle_type_tax = VehicleTypeTax::create($vehicle_type_tax_data); + if ($vehicle_type_tax) { + return response()->json(['Success' => 'VehicleTypeTax has been added'], 200); + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('VehicleTypeTax could not be added. Please, try again.'); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('VehicleTypeTax could not be added. Please, try again.', $validator->errors()); + } + } + + + /** + * Update the specified vehicle_type_tax + * Update the vehicle_type_tax with a `id`. + * @Put("/admin/vehicle_type_taxes/{id}") + * @Transaction({ + * @Request({"id": 1, "vehicle_type_id": 1, "tax_id": 1, "discount_type_id": 1, "duration_type_id": 1, "rate": 200, "max_allowed_amount": 1000}), + * @Response(200, body={"success": "Record has been updated."}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {"name": {}}, "status_code": 422}) + * }) + */ + public function update(Request $request, $id) + { + $vehicle_type_tax_data = $request->only('vehicle_type_id', 'tax_id', 'rate', 'discount_type_id', 'duration_type_id', 'max_allowed_amount', 'is_active'); + $validator = Validator::make($vehicle_type_tax_data, VehicleTypeTax::GetValidationRule(), VehicleTypeTax::GetValidationMessage()); + $vehicle_type_tax = false; + if ($request->has('id')) { + $vehicle_type_tax = VehicleTypeTax::find($id); + $vehicle_type_tax = ($request->id != $id) ? false : $vehicle_type_tax; + } + if ($validator->passes() && $vehicle_type_tax) { + try { + $vehicle_type_tax->update($vehicle_type_tax_data); + return response()->json(['Success' => 'VehicleTypeTax has been updated'], 200); + } catch (\Exception $e) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('VehicleTypeTax could not be updated. Please, try again.'); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('VehicleTypeTax could not be updated. Please, try again.', $validator->errors()); + } + } + + /** + * Delete the specified vehicle_type_tax. + * Delete the vehicle_type_tax with a `id`. + * @Delete("/admin/vehicle_type_taxes/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"success": "Record Deleted."}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function destroy($id) + { + $vehicle_type_tax = VehicleTypeTax::find($id); + if (!$vehicle_type_tax) { + return $this->response->errorNotFound("Invalid Request"); + } else { + $vehicle_type_tax->delete(); + } + return response()->json(['Success' => 'VehicleTypeTax deleted'], 200); + } +} diff --git a/app/Plugins/VehicleTaxes/Controllers/VehicleTaxesController.php b/app/Plugins/VehicleTaxes/Controllers/VehicleTaxesController.php new file mode 100644 index 0000000..ad32708 --- /dev/null +++ b/app/Plugins/VehicleTaxes/Controllers/VehicleTaxesController.php @@ -0,0 +1,58 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleTaxes\Controllers; + +use Illuminate\Http\Request; +use App\Http\Controllers\Controller; +use Plugins\VehicleTaxes\Model\VehicleTax; +use JWTAuth; +use Validator; +use Tymon\JWTAuth\Exceptions\JWTException; +use Plugins\VehicleTaxes\Transformers\VehicleTaxTransformer; + +/** + * VehicleTaxes resource representation. + * @Resource("VehicleTaxes") + */ +class VehicleTaxesController extends Controller +{ + /** + * VehicleTaxesController constructor. + */ + public function __construct() + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth'); + } + + /** + * Show all taxes + * Get a JSON representation of all the taxes. + * + * @Get("/vehicle_taxes?sort={sort}&sortby={sortby}&page={page}&q={q}") + * @Parameters({ + * @Parameter("sort", type="string", required=false, description="Sort the taxes list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort taxes by Ascending / Descending Order.", default=null), + * @Parameter("q", type="string", required=false, description="Search VehicleTaxes.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1) + * }) + */ + public function index(Request $request) + { + $taxes = VehicleTax::filterByRequest($request)->paginate(config('constants.ConstPageLimit')); + return $this->response->paginator($taxes, (new VehicleTaxTransformer)); + } +} diff --git a/app/Plugins/VehicleTaxes/Controllers/VehicleTypeTaxesController.php b/app/Plugins/VehicleTaxes/Controllers/VehicleTypeTaxesController.php new file mode 100644 index 0000000..62f5fd8 --- /dev/null +++ b/app/Plugins/VehicleTaxes/Controllers/VehicleTypeTaxesController.php @@ -0,0 +1,59 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleTaxes\Controllers; + +use Illuminate\Http\Request; +use App\Http\Controllers\Controller; +use Plugins\VehicleTaxes\Model\VehicleTypeTax; +use JWTAuth; +use Validator; +use Tymon\JWTAuth\Exceptions\JWTException; +use Plugins\VehicleTaxes\Transformers\VehicleTypeTaxTransformer; + +/** + * VehicleTaxes resource representation. + * @Resource("VehicleTaxes") + */ +class VehicleTypeTaxesController extends Controller +{ + /** + * VehicleTaxesController constructor. + */ + public function __construct() + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth'); + } + + /** + * Show all taxes + * Get a JSON representation of all the taxes. + * + * @Get("/taxes?sort={sort}&sortby={sortby}&page={page}&q={q}") + * @Parameters({ + * @Parameter("sort", type="string", required=false, description="Sort the taxes list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort taxes by Ascending / Descending Order.", default=null), + * @Parameter("q", type="string", required=false, description="Search VehicleTaxes.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1) + * }) + */ + public function index(Request $request) + { + $enabled_includes = array('tax', 'discount_type', 'duration_type', 'vehicle_type'); + $vehicle_type_taxes = VehicleTypeTax::with($enabled_includes)->filterByRequest($request)->paginate(config('constants.ConstPageLimit')); + return $this->response->paginator($vehicle_type_taxes, (new VehicleTypeTaxTransformer)->setDefaultIncludes($enabled_includes)); + } +} diff --git a/app/Plugins/VehicleTaxes/Model/VehicleTax.php b/app/Plugins/VehicleTaxes/Model/VehicleTax.php new file mode 100644 index 0000000..4227c50 --- /dev/null +++ b/app/Plugins/VehicleTaxes/Model/VehicleTax.php @@ -0,0 +1,101 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleTaxes\Model; + +use Illuminate\Http\Request; +use Illuminate\Database\Eloquent\Model; + +class VehicleTax extends Model +{ + /** + * @var string + */ + protected $table = "taxes"; + + protected $fillable = [ + 'name', 'short_description', 'description', 'is_active', 'slug' + ]; + + + /** + * @return \Illuminate\Database\Eloquent\Relations\HasMany + */ + public function vehicle_type_tax() + { + return $this->hasMany(VehicleTypeTax::class); + } + /** + * @param $query + * @param Request $request + */ + public function scopeFilterByActiveRecord($query, Request $request) + { + $query->where('is_active', '=', 1); + } + /** + * @param $query + * @param Request $request + * @return mixed + */ + public function scopeFilterByRequest($query, Request $request) + { + $query->orderBy($request->input('sort', 'id'), $request->input('sortby', 'asc')); + if ($request->has('q')) { + $query->where('name', 'LIKE', '%' . $request->input('q') . '%') + ->orWhere('short_description', 'LIKE', '%' . $request->input('q') . '%') + ->orWhere('description', 'LIKE', '%' . $request->input('q') . '%'); + } + if ($request->has('filter')) { + $filter = false; + if ($request->input('filter') == 'active') { + $filter = true; + } + $query->where('is_active', '=', $filter); + } + return $query; + } + + /** + * @return array + */ + public function scopeGetValidationRule() + { + return [ + 'name' => 'required|min:5', + 'short_description' => 'required|min:10', + 'description' => 'required|min:15', + 'is_active' => 'sometimes|required|boolean' + ]; + } + + /** + * @return array + */ + public function scopeGetValidationMessage() + { + return [ + 'name.required' => 'Required', + 'name.min' => 'name - Minimum length is 5', + 'short_description.required' => 'Required', + 'short_description.min' => 'Short Description - Minimum length is 10', + 'description.required' => 'Required', + 'description.min' => 'Description - Minimum length is 15', + 'is_active.required' => 'Required', + 'is_active.boolean' => 'Possible values to be entered is 0 or 1' + ]; + } + +} diff --git a/app/Plugins/VehicleTaxes/Model/VehicleTypeTax.php b/app/Plugins/VehicleTaxes/Model/VehicleTypeTax.php new file mode 100644 index 0000000..bd7712f --- /dev/null +++ b/app/Plugins/VehicleTaxes/Model/VehicleTypeTax.php @@ -0,0 +1,151 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleTaxes\Model; + +use Illuminate\Http\Request; +use Illuminate\Database\Eloquent\Model; +use Illuminate\Support\Facades\App; +use App\DiscountType; +use App\DurationType; + +class VehicleTypeTax extends Model +{ + /** + * @var string + */ + protected $table = "vehicle_type_taxes"; + + protected $fillable = [ + 'vehicle_type_id', 'tax_id', 'rate', 'discount_type_id', 'duration_type_id', 'max_allowed_amount', 'is_active' + ]; + + + /** + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function vehicle_tax() + { + return $this->belongsTo(VehicleTax::class, 'tax_id'); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function vehicle_type() + { + return $this->belongsTo(\Plugins\Vehicles\Model\VehicleType::class); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function discount_type() + { + return $this->belongsTo(DiscountType::class); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function duration_type() + { + return $this->belongsTo(DurationType::class); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\MorphMany + */ + public function vehicle_rental_additional_charges() + { + return $this->morphMany(\Plugins\VehicleRentals\Model\VehicleRentalAdditionalCharge::class, 'item_user_additional_chargable'); + } + + /** + * @param $query + * @param Request $request + * @return mixed + */ + public function scopeFilterByRequest($query, Request $request) + { + $query->orderBy($request->input('sort', 'id'), $request->input('sortby', 'asc')); + if ($request->has('q')) { + $query->WhereHas('vehicle_tax', function ($q) use ($request) { + $q->where('name', 'like', '%' . $request->input('q') . '%'); + }); + $query->orWhereHas('vehicle_type', function ($q) use ($request) { + $q->where('name', 'like', '%' . $request->input('q') . '%'); + }); + $query->orWhereHas('discount_type', function ($q) use ($request) { + $q->where('type', 'like', '%' . $request->input('q') . '%'); + }); + $query->orWhereHas('duration_type', function ($q) use ($request) { + $q->where('name', 'like', '%' . $request->input('q') . '%'); + }); + } + if ($request->has('filter')) { + $filter = false; + if ($request->filter == 'active') { + $filter = true; + } + $query->where('is_active', '=', $filter); + } + if($request->has('tax_id')){ + $query->where('tax_id', '=', $request->tax_id); + } + return $query; + } + + /** + * @return array + */ + public function scopeGetValidationRule() + { + return [ + 'vehicle_type_id' => 'required|integer|exists:vehicle_types,id', + 'tax_id' => 'required|integer|exists:taxes,id', + 'rate' => 'required|numeric', + 'discount_type_id' => 'required|integer|exists:discount_types,id', + 'duration_type_id' => 'required|integer|exists:duration_types,id', + 'max_allowed_amount' => 'required|numeric' + ]; + } + + /** + * @return array + */ + public function scopeGetValidationMessage() + { + return [ + 'vehicle_type_id.required' => 'Required', + 'vehicle_type_id.integer' => 'Vehicle Type Id must be integer', + 'vehicle_type_id.exists' => 'Invalid vehicle type id', + 'tax_id.required' => 'Required', + 'tax_id.integer' => 'Tax Id must be integer', + 'tax_id.exists' => 'Invalid tax id', + 'rate.required' => 'Required', + 'rate.numeric' => 'Rate must be numeric', + 'discount_type_id.required' => 'Required', + 'discount_type_id.integer' => 'Discount Type Id must be integer', + 'discount_type_id.exists' => 'Invalid discount type id', + 'duration_type_id.required' => 'Required', + 'duration_type_id.integer' => 'Duration Type Id must be integer', + 'discount_type_id.exists' => 'Invalid duration type id', + 'max_allowed_amount.required' => 'Required', + 'max_allowed_amount.numeric' => 'Max allowed amount must be numeric' + ]; + } + +} diff --git a/app/Plugins/VehicleTaxes/Providers/VehicleTaxServiceProvider.php b/app/Plugins/VehicleTaxes/Providers/VehicleTaxServiceProvider.php new file mode 100644 index 0000000..e74fcca --- /dev/null +++ b/app/Plugins/VehicleTaxes/Providers/VehicleTaxServiceProvider.php @@ -0,0 +1,44 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleTaxes\Providers; + +use Illuminate\Support\ServiceProvider; + +class VehicleTaxServiceProvider extends ServiceProvider +{ + /** + * Register any application services. + * + * @return void + */ + public function register() + { + include __DIR__ . '/../routes.php'; + $this->app->make('Plugins\VehicleTaxes\Controllers\VehicleTaxesController'); + $this->app->make('Plugins\VehicleTaxes\Controllers\Admin\AdminVehicleTaxesController'); + $this->app->make('Plugins\VehicleTaxes\Controllers\VehicleTypeTaxesController'); + $this->app->make('Plugins\VehicleTaxes\Controllers\Admin\AdminVehicleTypeTaxesController'); + } + + /** + * Bootstrap the application services. + * + * @return void + */ + public function boot() + { + } +} diff --git a/app/Plugins/VehicleTaxes/Services/VehicleTaxService.php b/app/Plugins/VehicleTaxes/Services/VehicleTaxService.php new file mode 100644 index 0000000..80710d5 --- /dev/null +++ b/app/Plugins/VehicleTaxes/Services/VehicleTaxService.php @@ -0,0 +1,73 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleTaxes\Services; + +use Plugins\VehicleTaxes\Model\VehicleTypeTax; +use Plugins\VehicleRentals\Model\VehicleRentalAdditionalCharge; + +class VehicleTaxService +{ + /** + * VehicleTaxService constructor. + */ + public function __construct() + { + } + + /** + * @param $vehicle_type_id + * @param $item_user_id + * @param $booking_calculated_details + * @return int + */ + public function processTaxAmount($vehicle_type_id, $item_user_id, $booking_calculated_details) + { + $res_amount = 0; + $vehicle_type_taxes = VehicleTypeTax::where('vehicle_type_id', $vehicle_type_id)->get(); + if (!empty($vehicle_type_taxes)) { + foreach ($vehicle_type_taxes as $vehicle_type_tax) { + if (!empty($vehicle_type_tax->rate)) { + if (!empty($vehicle_type_tax->discount_type_id) && $vehicle_type_tax->discount_type_id == 1) { + $tax_amount = $booking_calculated_details['booking_amount'] * $vehicle_type_tax->rate / 100; + } else if (!empty($vehicle_type_tax->discount_type_id) && $vehicle_type_tax->discount_type_id == 2) { + $tax_amount = $vehicle_type_tax->rate; + } + if (!empty($vehicle_type_tax->duration_type_id) && $vehicle_type_tax->duration_type_id == 1) { + if (!empty($booking_calculated_details['total_hours'])) { + $booking_calculated_details['total_days'] = $booking_calculated_details['total_days'] + 1; + } + $tax_amount = $tax_amount * $booking_calculated_details['total_days']; + } + if (!empty($vehicle_type_tax->max_allowed_amount)) { + if ($tax_amount > $vehicle_type_tax->max_allowed_amount) { + $tax_amount = $vehicle_type_tax->max_allowed_amount; + } + } + } + $vehicle_rental_additional_data['item_user_id'] = $item_user_id; + $vehicle_rental_additional_data['amount'] = $tax_amount; + $vehicle_rental_additional_charge = VehicleRentalAdditionalCharge::create($vehicle_rental_additional_data); + $vehicle_tax = VehicleTypeTax::with(['vehicle_rental_additional_charges'])->where('id', '=', $vehicle_type_tax->id)->first(); + $vehicle_tax->vehicle_rental_additional_charges()->save($vehicle_rental_additional_charge); + $res_amount = $res_amount + $tax_amount; + } + return $res_amount; + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Given Taxes not available. Please, try again.'); + } + } + +} diff --git a/app/Plugins/VehicleTaxes/Transformers/AdminVehicleTaxTransformer.php b/app/Plugins/VehicleTaxes/Transformers/AdminVehicleTaxTransformer.php new file mode 100644 index 0000000..a9eea55 --- /dev/null +++ b/app/Plugins/VehicleTaxes/Transformers/AdminVehicleTaxTransformer.php @@ -0,0 +1,40 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleTaxes\Transformers; + +use League\Fractal; +use Plugins\VehicleTaxes\Model\VehicleTax; + +/** + * Class VehicleTaxTransformer + * @package VehicleTaxes\Transformers + */ +class AdminVehicleTaxTransformer extends Fractal\TransformerAbstract +{ + + /** + * @param VehicleTax $vehicle_tax + * @return array + */ + public function transform(VehicleTax $vehicle_tax) + { + $output = array_only($vehicle_tax->toArray(), ['id', 'created_at', 'name', 'short_description', 'description', 'is_active']); + $output['is_active'] = ($output['is_active']) ? true : false; + return $output; + } + + +} \ No newline at end of file diff --git a/app/Plugins/VehicleTaxes/Transformers/VehicleTaxTransformer.php b/app/Plugins/VehicleTaxes/Transformers/VehicleTaxTransformer.php new file mode 100644 index 0000000..c2678ba --- /dev/null +++ b/app/Plugins/VehicleTaxes/Transformers/VehicleTaxTransformer.php @@ -0,0 +1,37 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleTaxes\Transformers; + +use League\Fractal; +use Plugins\VehicleTaxes\Model\VehicleTax; +use Plugins\VehicleTaxes\Model\VehicleTypeTax; + +/** + * Class VehicleTaxTransformer + * @package VehicleTaxes\Transformers + */ +class VehicleTaxTransformer extends Fractal\TransformerAbstract +{ + /** + * @param VehicleTax $vehicle_tax + * @return array + */ + public function transform(VehicleTax $vehicle_tax) + { + $output = array_only($vehicle_tax->toArray(), ['id', 'name']); + return $output; + } +} \ No newline at end of file diff --git a/app/Plugins/VehicleTaxes/Transformers/VehicleTypeTaxTransformer.php b/app/Plugins/VehicleTaxes/Transformers/VehicleTypeTaxTransformer.php new file mode 100644 index 0000000..034aebe --- /dev/null +++ b/app/Plugins/VehicleTaxes/Transformers/VehicleTypeTaxTransformer.php @@ -0,0 +1,104 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\VehicleTaxes\Transformers; + +use App\Transformers\DiscountTypeTransformer; +use App\Transformers\DurationTypeTransformer; +use League\Fractal; +use Plugins\VehicleTaxes\Model\VehicleTypeTax; + +/** + * Class VehicleTaxTransformer + * @package VehicleTaxes\Transformers + */ +class VehicleTypeTaxTransformer extends Fractal\TransformerAbstract +{ + /** + * List of resources possible to include + * + * @var array + */ + protected $availableIncludes = [ + 'VehicleTax', 'VehicleType', 'DurationType', 'DiscountType' + ]; + + /** + * @param VehicleTypeTax $vehicle_type_tax + * @return array + */ + public function transform(VehicleTypeTax $vehicle_type_tax) + { + $output = array_only($vehicle_type_tax->toArray(), ['id', 'created_at', 'vehicle_type_id', 'tax_id', 'rate', 'discount_type_id', 'duration_type_id', 'max_allowed_amount', 'is_active']); + $output['is_active'] = ($output['is_active']) ? true : false; + return $output; + } + + /** + * @param VehicleTypeTax $vehicle_type_tax + * @return Fractal\Resource\Item|null + */ + public function includeVehicleTax(VehicleTypeTax $vehicle_type_tax) + { + if ($vehicle_type_tax->vehicle_tax) { + return $this->item($vehicle_type_tax->vehicle_tax, new VehicleTaxTransformer()); + } else { + return null; + } + + } + + /** + * @param VehicleTypeTax $vehicle_type_tax + * @return Fractal\Resource\Item|null + */ + public function includeVehicleType(VehicleTypeTax $vehicle_type_tax) + { + if ($vehicle_type_tax->vehicle_type) { + return $this->item($vehicle_type_tax->vehicle_type, new \Plugins\Vehicles\Transformers\AdminVehicleTypeTransformer()); + } else { + return null; + } + + } + + /** + * @param VehicleTypeTax $vehicle_type_tax + * @return Fractal\Resource\Item|null + */ + public function includeDiscountType(VehicleTypeTax $vehicle_type_tax) + { + if ($vehicle_type_tax->discount_type) { + return $this->item($vehicle_type_tax->discount_type, new DiscountTypeTransformer()); + } else { + return null; + } + + } + + /** + * @param VehicleTypeTax $vehicle_type_tax + * @return Fractal\Resource\Item|null + */ + public function includeDurationType(VehicleTypeTax $vehicle_type_tax) + { + if ($vehicle_type_tax->duration_type) { + return $this->item($vehicle_type_tax->duration_type, new DurationTypeTransformer()); + } else { + return null; + } + + } +} \ No newline at end of file diff --git a/app/Plugins/VehicleTaxes/plugin.json b/app/Plugins/VehicleTaxes/plugin.json new file mode 100644 index 0000000..2b2af78 --- /dev/null +++ b/app/Plugins/VehicleTaxes/plugin.json @@ -0,0 +1,9 @@ +{ + "name": "VehicleTaxes", + "class": "fa fa-2x fa-text-width", + "description": "By enabling this, item owner can manage taxes based on vehicle types.", + "dependencies": "VehicleRentals", + "module_id": "", + "module_hash": "", + "display_order": "14" +} diff --git a/app/Plugins/VehicleTaxes/routes.php b/app/Plugins/VehicleTaxes/routes.php new file mode 100644 index 0000000..806f5e1 --- /dev/null +++ b/app/Plugins/VehicleTaxes/routes.php @@ -0,0 +1,51 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +/* +|-------------------------------------------------------------------------- +| Application Routes +|-------------------------------------------------------------------------- +| +| Here is where you can register all of the routes for an application. +| It is a breeze. Simply tell Lumen the URIs it should respond to +| and give it the Closure to call when that URI is requested. +| +*/ +$api = $this->app->make('Dingo\Api\Routing\Router'); +$api->version(['v1'], function ($api) { + $api->group(['prefix' => 'admin', 'namespace' => 'Plugins\VehicleTaxes\Controllers\Admin', 'middleware' => 'apitracking'], function () use ($api) { + // Taxes admin side + $api->get('vehicle_taxes', 'AdminVehicleTaxesController@index'); + $api->post('vehicle_taxes', 'AdminVehicleTaxesController@store'); + $api->put('vehicle_taxes/{id}', 'AdminVehicleTaxesController@update'); + $api->get('vehicle_taxes/{id}/edit', 'AdminVehicleTaxesController@edit'); + $api->get('vehicle_taxes/{id}', 'AdminVehicleTaxesController@show'); + $api->delete('vehicle_taxes/{id}', 'AdminVehicleTaxesController@destroy'); + + // Vehicle Type Taxes admin side + $api->get('vehicle_type_taxes', 'AdminVehicleTypeTaxesController@index'); + $api->post('vehicle_type_taxes', 'AdminVehicleTypeTaxesController@store'); + $api->put('vehicle_type_taxes/{id}', 'AdminVehicleTypeTaxesController@update'); + $api->get('vehicle_type_taxes/{id}/edit', 'AdminVehicleTypeTaxesController@edit'); + $api->get('vehicle_type_taxes/{id}', 'AdminVehicleTypeTaxesController@show'); + $api->delete('vehicle_type_taxes/{id}', 'AdminVehicleTypeTaxesController@destroy'); + + }); + $api->group(['namespace' => 'Plugins\VehicleTaxes\Controllers', 'middleware' => 'apitracking'], function () use ($api) { + //taxes user side + $api->get('vehicle_taxes', 'VehicleTaxesController@index'); + $api->get('vehicle_type_taxes', 'VehicleTypeTaxesController@index'); + }); +}); diff --git a/app/Plugins/Vehicles/Controllers/Admin/AdminCounterLocationsController.php b/app/Plugins/Vehicles/Controllers/Admin/AdminCounterLocationsController.php new file mode 100644 index 0000000..5ad0a3b --- /dev/null +++ b/app/Plugins/Vehicles/Controllers/Admin/AdminCounterLocationsController.php @@ -0,0 +1,205 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Vehicles\Controllers\Admin; + + +use Illuminate\Http\Request; +use App\Http\Requests; +use App\Http\Controllers\Controller; +use Plugins\Vehicles\Model\CounterLocation; +use JWTAuth; +use Validator; +use Plugins\Vehicles\Transformers\AdminCounterLocationTransformer; +use Plugins\Vehicles\Transformers\CounterLocationTransformer; + + +/** + * Class AdminCounterLocationsController + * @package Plugins\Vehicles\Controllers\Admin + */ +class AdminCounterLocationsController extends Controller +{ + + public function __construct() + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth'); + // Check the logged user role. + $this->middleware('role'); + } + + /** + * Show all counter locations. + * Get a JSON representation of all the counter locations. + * + * @Get("/counter_locations?filter={filter}&sort={sort}&sortby={sortby}&q={q}") + * @Parameters({ + * @Parameter("filter", type="integer", required=false, description="Filter the counter_locations list by status.", default=null), + * @Parameter("sort", type="string", required=false, description="Sort the counter_locations list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort counter_locations by Ascending / Descending Order.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1) + * }) + */ + public function index(Request $request) + { + $counter_location_count = config('constants.ConstPageLimit'); + if ($request->has('limit') && $request->limit == 'all') { + $counter_location_count = CounterLocation::filterByRequest($request)->count(); + $counter_locations = CounterLocation::filterByRequest($request)->paginate($counter_location_count); + return $this->response->paginator($counter_locations, new CounterLocationTransformer); + } elseif ($request->has('vehicle_id')) { + $counter_locations = CounterLocation::filterByRequest($request)->paginate($counter_location_count); + return $this->response->paginator($counter_locations, new CounterLocationTransformer); + } else { + $counter_locations = CounterLocation::filterByRequest($request)->paginate($counter_location_count); + return $this->response->paginator($counter_locations, new AdminCounterLocationTransformer); + } + } + + /** + * Store a new counter_location. + * Store a new counter_location with a 'address', 'latitude', 'longitude'. + * @Post("/items") + * @Transaction({ + * @Request({"address": 1000, "user_id": 1, "name": "house for rent", "booking_type_id": 1, "description": "This house is for rent"}), + * @Response(200, body={"success": "Record has been added."}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {"amount": {}}, "status_code": 422}) + * }) + */ + public function store(Request $request) + { + $counter_location_data = $request->only('address', 'latitude', 'longitude', 'fax', 'phone', 'mobile', 'email'); + $validator = Validator::make($counter_location_data, CounterLocation::GetValidationRule(), CounterLocation::GetValidationMessage()); + $check_location = CounterLocation::where('address', $request->address)->first(); + if ($check_location) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Location could not be updated. Location already exists.'); + } + if ($validator->passes()) { + try { + $counter_location = CounterLocation::create($counter_location_data); + if ($counter_location) { + return response()->json(['Success' => 'Counter location has been added'], 200); + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Counter location could not be added. Please, try again.'); + } + } catch (\Exception $e) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Counter location could not be added. Please, try again.', + array($e->getMessage())); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Counter location could not be added. Please, try again.', $validator->errors()); + } + } + + /** + * Edit the specified counter_location. + * Edit the counter_location with a `id`. + * @Get("/admin/counter_locations/{id}/edit") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body= {"id": 1, "address": "chennai airport", "mobile": "123546853"}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function edit($id) + { + $counter_location = CounterLocation::find($id); + if (!$counter_location) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($counter_location, (new AdminCounterLocationTransformer)); + } + + /** + * Update the specified counter_location + * Update the counter_location with a `id`. + * @Put("/admin/counter_locations/{id}") + * @Transaction({ + * @Request({"id": 1, "address": "chennai airport", "mobile": "123546853"}), + * @Response(200, body={"success": "Record has been updated."}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {"name": {}}, "status_code": 422}) + * }) + */ + public function update(Request $request, $id) + { + $counter_location_data = $request->only('id', 'address', 'latitude', 'longitude', 'fax', 'phone', 'mobile', 'email'); + $counter_location = false; + $validation_rules = CounterLocation::GetValidationRule(); + if ($request->has('id')) { + $counter_location = CounterLocation::find($id); + $counter_location = ($request->id != $id) ? false : $counter_location; + if ($counter_location->address == $counter_location_data['address']) { + $validation_rules['address'] = 'required|min:5'; + } + } + $validator = Validator::make($counter_location_data, $validation_rules, CounterLocation::GetValidationMessage()); + $check_location = CounterLocation::where('address', $request->address)->where('id', '!=', $id)->first(); + if ($check_location) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Location could not be updated. Location already exists.'); + } + if ($validator->passes() && $counter_location) { + try { + $counter_location->update($counter_location_data); + return response()->json(['Success' => 'Counter Location has been updated'], 200); + } catch (\Exception $e) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Counter Location could not be updated. Please, try again.'); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Counter Location could not be updated. Please, try again.', $validator->errors()); + } + } + + /** + * Delete the specified Counter Location. + * Delete the Counter Location with a `id`. + * @Delete("/counter_locations/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"success": "Record Deleted."}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function destroy($id) + { + $counter_location = CounterLocation::find($id); + if (!$counter_location) { + return $this->response->errorNotFound("Invalid Request"); + } else { + $counter_location->delete(); + } + return response()->json(['Success' => 'Counter location deleted'], 200); + } + + /** + * Show the specified counter locations. + * Show the counter locations with a `id`. + * @Get("/counter_locations/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"id": 1), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + * + */ + public function show($id) + { + $counter_location = CounterLocation::find($id); + if (!$counter_location) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($counter_location, (new AdminCounterLocationTransformer)); + } +} diff --git a/app/Plugins/Vehicles/Controllers/Admin/AdminFuelTypesController.php b/app/Plugins/Vehicles/Controllers/Admin/AdminFuelTypesController.php new file mode 100644 index 0000000..d6abe13 --- /dev/null +++ b/app/Plugins/Vehicles/Controllers/Admin/AdminFuelTypesController.php @@ -0,0 +1,183 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Vehicles\Controllers\Admin; + +use Illuminate\Http\Request; +use App\Http\Requests; +use App\Http\Controllers\Controller; +use Plugins\Vehicles\Model\FuelType; +use JWTAuth; +use Validator; +use Plugins\Vehicles\Transformers\AdminFuelTypeTransformer; +use EasySlug\EasySlug\EasySlugFacade as EasySlug; + +/** + * Class AdminFuelTypesController + * @package Plugins\Vehicles\Controllers\Admin + */ +class AdminFuelTypesController extends Controller +{ + + public function __construct() + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth'); + // Check the logged user role. + $this->middleware('role'); + } + + /** + * Show all fuel types. + * Get a JSON representation of all the fuel types. + * + * @Get("/fuel_types?filter={filter}&sort={sort}&sortby={sortby}&q={q}") + * @Parameters({ + * @Parameter("filter", type="integer", required=false, description="Filter the fuel types list by status.", default=null), + * @Parameter("sort", type="string", required=false, description="Sort the fuel types list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort fuel types by Ascending / Descending Order.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1) + * }) + */ + public function index(Request $request) + { + $fuel_type_count = config('constants.ConstPageLimit'); + if ($request->has('type') && $request->type == 'list') { + $fuel_type_count = FuelType::count(); + } + $fuel_types = FuelType::filterByRequest($request)->paginate($fuel_type_count); + return $this->response->paginator($fuel_types, new AdminFuelTypeTransformer); + } + + /** + * Store a new fuel type. + * Store a new fuel type with a 'amount', 'user_id', 'name', 'booking_type_id', 'description'. + * @Post("/fuel_types") + * @Transaction({ + * @Request({}), + * @Response(200, body={"success": "Record has been added."}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {"amount": {}}, "status_code": 422}) + * }) + */ + public function store(Request $request) + { + $fuel_type_data = $request->only('name', 'is_active'); + $validator = Validator::make($fuel_type_data, FuelType::GetValidationRule(), FuelType::GetValidationMessage()); + if ($validator->passes()) { + try { + $fuel_type = FuelType::create($fuel_type_data); + if ($fuel_type) { + return response()->json(['Success' => 'Fuel type has been added'], 200); + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Fuel type could not be added. Please, try again.'); + } + } catch (\Exception $e) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Fuel type could not be added. Please, try again.', + array($e->getMessage())); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Fuel type could not be added. Please, try again.', $validator->errors()); + } + } + + /** + * Edit the specified fuel type. + * Edit the fuel type with a `id`. + * @Get("/fuel_types/{id}/edit") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"id": 1}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function edit($id) + { + $fuel_type = FuelType::find($id); + if (!$fuel_type) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($fuel_type, (new AdminFuelTypeTransformer)); + } + + /** + * Update the specified fuel type. + * Update the fuel type with a `id`. + * @Put("/fuel_types/{id}") + * @Transaction({ + * @Response(200, body={"success": "Record has been updated."}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {}, "status_code": 422}) + * }) + */ + public function update(Request $request, $id) + { + $fuel_type_data = $request->only('id', 'name', 'is_active'); + $fuel_type = false; + if ($request->has('id')) { + $fuel_type = FuelType::find($id); + $fuel_type = ($request->id != $id) ? false : $fuel_type; + } + $validator = Validator::make($fuel_type_data, FuelType::GetValidationRule(), FuelType::GetValidationMessage()); + if ($validator->passes() && $fuel_type) { + try { + $fuel_type->update($fuel_type_data); + return response()->json(['Success' => 'Fuel Type has been updated'], 200); + } catch (\Exception $e) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Fuel Type could not be updated. Please, try again.'); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Fuel Type could not be updated. Please, try again.', $validator->errors()); + } + } + + /** + * Delete the specified fuel type. + * Delete the fuel type with a `id`. + * @Delete("/fuel_types/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"success": "Record Deleted."}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function destroy($id) + { + $fuel_type = FuelType::find($id); + if (!$fuel_type) { + return $this->response->errorNotFound("Invalid Request"); + } else { + $fuel_type->delete(); + } + return response()->json(['Success' => 'Fuel Type deleted'], 200); + } + + /** + * Show the specified fuel type. + * Show the fuel type with a `id`. + * @Get("/fuel_types/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"id": 1}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function show($id) + { + $fuel_type = FuelType::find($id); + if (!$fuel_type) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($fuel_type, (new AdminFuelTypeTransformer)); + } +} diff --git a/app/Plugins/Vehicles/Controllers/Admin/AdminUnavailableVehiclesController.php b/app/Plugins/Vehicles/Controllers/Admin/AdminUnavailableVehiclesController.php new file mode 100644 index 0000000..5968071 --- /dev/null +++ b/app/Plugins/Vehicles/Controllers/Admin/AdminUnavailableVehiclesController.php @@ -0,0 +1,261 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Vehicles\Controllers\Admin; + + +use Illuminate\Http\Request; +use App\Http\Requests; +use App\Http\Controllers\Controller; +use Plugins\Vehicles\Model\UnavailableVehicle; +use Plugins\Vehicles\Model\Vehicle; +use JWTAuth; +use Validator; +use Plugins\Vehicles\Transformers\UnavailableVehicleTransformer; +use App\User; +use Carbon; + +/** + * Class UnavailableVehiclesController + * @package Plugins\Vehicles\Controllers + */ +class AdminUnavailableVehiclesController extends Controller +{ + /** + * UnavailableVehiclesController constructor. + */ + public function __construct() + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth'); + // Check the logged user role. + $this->middleware('role'); + } + + /** + * Show own all vehicle unavailable dates. + * Get a JSON representation of vehicle unavailable dates. + * @Get("GET /admin/unavailable_vehicles?filter={filter}&sort={sort}&sortby={sortby}&q={q}") + * @Parameters({ + * @Parameter("vehicle_id", type="integer", required=false, description="Filter the vehicles ", default=null), + * @Parameter("filter", type="integer", required=false, description="Filter the vehicles list by status.", default=null), + * @Parameter("sort", type="string", required=false, description="Sort the vehicles list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort vehicles by Ascending / Descending Order.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1) + * }) + */ + public function index(Request $request) + { + $user = $this->auth->user(); + $enabled_includes = array('vehicle'); + $vehicles = UnavailableVehicle::with($enabled_includes)->filterByRequest($request)->paginate(config('constants.ConstPageLimit')); + return $this->response->paginator($vehicles, (new UnavailableVehicleTransformer)->setDefaultIncludes($enabled_includes)); + } + + /** + * Store a new unavailable vehicle. + * Store a new unavailable vehicle with a 'vehicle_id', 'start_date', 'end_date'. + * @Post("/admin/unavailable_vehicles") + * @Transaction({ + * @Request({"vehicle_id": 1, "start_date": 2016-08-09, "end_date": "2016-09-09"}), + * @Response(200, body={"success": "Record has been added."}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {"amount": {}}, "status_code": 422}) + * }) + */ + public function store(Request $request) + { + $unavailable_vehicle_data = $request->only('vehicle_id', 'start_date', 'end_date'); + $vehicle = Vehicle::with('vehicle_company', 'user')->find($request->vehicle_id); + if (!$vehicle) { + return $this->response->errorNotFound("Invalid Request"); + } + if (!is_null($request['start_date'])) { + $unavailable_vehicle_data['start_date'] = date("Y-m-d H:i:s", strtotime($request['start_date'])); + } + if (!is_null($request['end_date'])) { + $unavailable_vehicle_data['end_date'] = date("Y-m-d H:i:s", strtotime($request['end_date'])); + } + $cur_date = Carbon::now()->toDateTimeString(); + if ($cur_date > $request->start_date || $request->start_date > $request->end_date) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Start date should be less than end date and greater than current date.'); + } + //check whether the given date already in list + $unavailable_vehicle = UnavailableVehicle::where('vehicle_id', $request->vehicle_id) + ->where(function ($query) use ($request) { + $query->whereBetween('start_date', [$request->start_date, $request->end_date]) + ->orWhereBetween('end_date', [$request->start_date, $request->end_date]) + ->orwhere(function ($query) use ($request) { + $query->where('start_date', '>', $request->start_date) + ->where('end_date', '<', $request->start_date); + })->orwhere(function ($query) use ($request) { + $query->where('start_date', '<', $request->end_date) + ->where('end_date', '>', $request->end_date); + }); + })->first(); + if ($unavailable_vehicle) { + if ($unavailable_vehicle->is_dummy == 2) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Maintenance date already updated. Please, try again some other date.'); + } else if ($unavailable_vehicle->is_dummy == 0) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Vehicle booked that day. Please, try again some other date.'); + } + + } + $unavailable_vehicle_data['is_dummy'] = 2; + $validator = Validator::make($unavailable_vehicle_data, UnavailableVehicle::GetValidationRule(), UnavailableVehicle::GetValidationMessage()); + if ($validator->passes()) { + try { + $unavailable_vehicle = UnavailableVehicle::create($unavailable_vehicle_data); + if ($unavailable_vehicle) { + return response()->json(['Success' => 'Vehicle maintenance date has been added'], 200); + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Vehicle maintenance date could not be added. Please, try again.'); + } + } catch (\Exception $e) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Vehicle maintenance date could not be added. Please, try again.', array($e->getMessage())); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Vehicle maintenance date could not be added. Please, try again.', $validator->errors()); + } + } + + /** + * Edit the specified unavailable vehicle. + * Edit the unavailable vehicle with a `id`. + * @Get("/admin/unavailable_vehicles/{id}/edit") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"id": 1}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function edit($id) + { + $unavailable_vehicle = UnavailableVehicle::with(['vehicle'])->where('id', $id)->where('is_dummy', 2)->find($id); + if (!$unavailable_vehicle) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($unavailable_vehicle, (new UnavailableVehicleTransformer)->setDefaultIncludes(['vehicle'])); + } + + /** + * Update the specified unavailable vehicle. + * Update the unavailable vehicle with a `id`. + * @Put("/admin/unavailable_vehicles/{id}") + * @Transaction({ + * @Request({"id": 1, "vehicle_id": 1, "start_date": 2016-08-09, "end_date": "2016-09-09"}), + * @Response(200, body={"success": "Record has been updated."}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {}, "status_code": 422}) + * }) + */ + public function update(Request $request, $id) + { + $user = $this->auth->user(); + $unavailable_vehicle_data = $request->only('id', 'start_date', 'end_date'); + $unavailable_vehicle = false; + if ($request->has('id')) { + $unavailable_vehicle = UnavailableVehicle::with(['vehicle'])->where('is_dummy', 2)->find($id); + $unavailable_vehicle = ($request->id != $id) ? false : $unavailable_vehicle; + } + if (!$unavailable_vehicle) { + return $this->response->errorNotFound("Invalid Request"); + } + if ($request->start_date > $request->end_date) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Start date should be less than end date '); + } + + if (!is_null($request['start_date'])) { + $unavailable_vehicle_data['start_date'] = date("Y-m-d H:i:s", strtotime($request['start_date'])); + } + if (!is_null($request['end_date'])) { + $unavailable_vehicle_data['end_date'] = date("Y-m-d H:i:s", strtotime($request['end_date'])); + } + //check whether the given date already in list + $unavailable_vehicle = UnavailableVehicle::with(['vehicle'])->where('vehicle_id', $unavailable_vehicle->vehicle_id) + ->where('id', '!=', [$id]) + ->where(function ($query) use ($request) { + $query->whereBetween('start_date', [$request->start_date, $request->end_date]) + ->orWhereBetween('end_date', [$request->start_date, $request->end_date]) + ->orwhere(function ($query) use ($request) { + $query->where('start_date', '>', $request->start_date) + ->where('end_date', '<', $request->start_date); + })->orwhere(function ($query) use ($request) { + $query->where('start_date', '<', $request->end_date) + ->where('end_date', '>', $request->end_date); + }); + })->first(); + if ($unavailable_vehicle) { + if ($unavailable_vehicle->is_dummy == 2) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Maintenance date already updated. Please, try again some other date.'); + } else if ($unavailable_vehicle->is_dummy == 0) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Vehicle booked that day. Please, try again some other date.'); + } + } else { + $unavailable_vehicle = UnavailableVehicle::with(['vehicle'])->where('is_dummy', 2)->find($id); + } + $validator = Validator::make($unavailable_vehicle_data, UnavailableVehicle::GetValidationRule(), UnavailableVehicle::GetValidationMessage()); + if ($validator->passes()) { + try { + $unavailable_vehicle->update($unavailable_vehicle_data); + return response()->json(['Success' => 'Maintenance date has been updated'], 200); + } catch (\Exception $e) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Maintenance date could not be updated. Please, try again.', array($e->getMessage())); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Maintenance date could not be updated. Please, try again.', $validator->errors()); + } + } + + /** + * show the specified unavailable vehicle. + * show the unavailable vehicle with a `id`. + * @Get("/admin/unavailable_vehicles/{id}/edit") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"id": 1}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function show($id) + { + $unavailable_vehicle = UnavailableVehicle::with(['vehicle'])->where('id', $id)->where('is_dummy', 2)->find($id); + if (!$unavailable_vehicle) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($unavailable_vehicle, (new UnavailableVehicleTransformer)->setDefaultIncludes(['vehicle'])); + } + + /** + * Delete the specified unavailable vehicle. + * Delete the unavailable vehicle with a `id`. + * @Delete("/admin/unavailable_vehicles/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"success": "Record Deleted."}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function destroy($id) + { + $user = $this->auth->user(); + $unavailable_vehicle = UnavailableVehicle::with(['vehicle'])->where('is_dummy', 2)->find($id); + if (!$unavailable_vehicle) { + return $this->response->errorNotFound("Invalid Request"); + } else { + $unavailable_vehicle->delete(); + } + return response()->json(['Success' => 'Maintenance date deleted'], 200); + } + +} diff --git a/app/Plugins/Vehicles/Controllers/Admin/AdminVehicleCompaniesController.php b/app/Plugins/Vehicles/Controllers/Admin/AdminVehicleCompaniesController.php new file mode 100644 index 0000000..03d6fe5 --- /dev/null +++ b/app/Plugins/Vehicles/Controllers/Admin/AdminVehicleCompaniesController.php @@ -0,0 +1,266 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Vehicles\Controllers\Admin; + + +use Illuminate\Http\Request; +use App\Http\Requests; +use App\Http\Controllers\Controller; +use Plugins\Vehicles\Model\VehicleCompany; +use JWTAuth; +use Validator; +use App\User; +use Plugins\Vehicles\Transformers\AdminVehicleCompanyTransformer; +use EasySlug\EasySlug\EasySlugFacade as EasySlug; +use DB; + +/** + * Class AdminVehicleCompaniesController + * @package Plugins\Vehicles\Controllers\Admin + */ +class AdminVehicleCompaniesController extends Controller +{ + + public function __construct() + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth'); + // Check the logged user role. + $this->middleware('role'); + } + + /** + * Show all vehicle companies. + * Get a JSON representation of all the Vehicle Companies. + * + * @Get("/vehicle_companies?filter={filter}&sort={sort}&sortby={sortby}&q={q}") + * @Parameters({ + * @Parameter("filter", type="integer", required=false, description="Filter the Vehicle Companies list by status.", default=null), + * @Parameter("sort", type="string", required=false, description="Sort the Vehicle Companies list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort Vehicle Companies by Ascending / Descending Order.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1) + * }) + */ + public function index(Request $request) + { + $vehicle_company_count = config('constants.ConstPageLimit'); + if ($request->has('type') && $request->type == 'list') { + $vehicle_company_count = VehicleCompany::count(); + } + $vehicle_companies = VehicleCompany::with('user') + ->select(DB::raw('vehicle_companies.*')) + ->leftJoin(DB::raw('(select id,username from users) as user'), 'user.id', '=', 'vehicle_companies.user_id') + ->filterByRequest($request)->paginate($vehicle_company_count); + return $this->response->paginator($vehicle_companies, (new AdminVehicleCompanyTransformer)->setDefaultIncludes(['user'])); + } + + /** + * Store a new vehicle company. + * @Post("/vehicle_companies") + * @Transaction({ + * @Request({"name":"compan", "address":"chennai", "latitude":"45.1265", "longitude":"45.1325", "fax":"d336256", "phone":"546546546", "mobile":"54654654", "email":"sdfds@df.cin", "is_active":"1", "user_id":1}), + * @Response(200, body={"success": "Record has been added."}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {"amount": {}}, "status_code": 422}) + * }) + */ + public function store(Request $request) + { + $vehicle_company_data = $request->only('user_id','name', 'address', 'latitude', 'longitude', 'phone', 'fax', 'mobile', 'email', 'is_active'); + $vehicle_company_data['slug'] = EasySlug::generateUniqueSlug($request->name, 'vehicle_companies'); + $validator = Validator::make($vehicle_company_data, VehicleCompany::GetValidationRule(), VehicleCompany::GetValidationMessage()); + if ($validator->passes()) { + try { + $vehicle_company = VehicleCompany::create($vehicle_company_data); + if ($vehicle_company) { + return response()->json(['Success' => 'Vehicle company has been added'], 200); + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Vehicle company could not be added. Please, try again.'); + } + } catch (\Exception $e) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Vehicle company could not be added. Please, try again.', + array($e->getMessage())); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Vehicle company could not be added. Please, try again.', $validator->errors()); + } + } + + /** + * Edit the specified vehicle_company. + * Edit the vehicle_company with a `id`. + * @Get("/vehicle_companies/{id}/edit") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"id": 1}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function edit($id) + { + $vehicle_company = VehicleCompany::find($id); + if (!$vehicle_company) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($vehicle_company, (new AdminVehicleCompanyTransformer)); + } + + /** + * Update the specified Vehicle Company. + * Update the Vehicle Company with a `id`. + * @Put("/vehicle_companies/{id}") + * @Transaction({ + * @Request({"id": 1, "name":"compan", "address":"chennai", "latitude":"45.1265", "longitude":"45.1325", "fax":"d336256", "phone":"546546546", "mobile":"54654654", "email":"sdfds@df.cin", "is_active":"1", "user_id":1}), + * @Response(200, body={"success": "Record has been updated."}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {}, "status_code": 422}) + * }) + */ + public function update(Request $request, $id) + { + $vehicle_company_data = $request->only('id', 'name', 'address', 'latitude', 'longitude', 'fax', 'phone', 'mobile', 'email', 'is_active', 'user_id'); + $vehicle_company = false; + $validation_rules = VehicleCompany::GetValidationRule(); + if ($request->has('id')) { + $vehicle_company = VehicleCompany::find($id); + $vehicle_company = ($request->id != $id) ? false : $vehicle_company; + if ($vehicle_company->name !== $request->name) { + $vehicle_company_data['slug'] = EasySlug::generateUniqueSlug($request->name, 'vehicle_companies'); + } else { + $vehicle_company_data['slug'] = $vehicle_company->slug; + } + if ($vehicle_company->user_id == $vehicle_company_data['user_id']) { + $validation_rules['user_id'] = 'required'; + } + } + $validator = Validator::make($vehicle_company_data, $validation_rules, VehicleCompany::GetValidationMessage()); + if ($validator->passes() && $vehicle_company) { + try { + $vehicle_company->update($vehicle_company_data); + return response()->json(['Success' => 'Vehicle Company has been updated'], 200); + } catch (\Exception $e) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Vehicle company could not be updated. Please, try again.', + array($e->getMessage())); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Vehicle Company could not be updated. Please, try again.', $validator->errors()); + } + } + + /** + * Delete the specified Vehicle Company. + * Delete the Vehicle Company with a `id`. + * @Delete("/vehicle_companies/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"success": "Record Deleted."}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function destroy($id) + { + $vehicle_company = VehicleCompany::find($id); + if (!$vehicle_company) { + return $this->response->errorNotFound("Invalid Request"); + } else { + $vehicle_company->delete(); + } + return response()->json(['Success' => 'Vehicle company deleted'], 200); + } + + /** + * Show the specified Vehicle Company. + * Show the Vehicle Company with a `id`. + * @Get("/vehicle_companies/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"id": 1, "amount": 1000, "user_id": 1, "name": "house for rent", "booking_type_id": 1, "description": "This house is for rent", "User": {}}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function show($id) + { + $vehicle_company = VehicleCompany::with('user')->find($id); + if (!$vehicle_company) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($vehicle_company, (new AdminVehicleCompanyTransformer)->setDefaultIncludes(['user'])); + } + + /** + * Deactivate the company. + * @Put("/vehicle_companies/{id}/deactive") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"success": "Record has been deactivated!."}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}), + * }) + */ + public function deactive(Request $request, $id) + { + $vehicle_company = VehicleCompany::find($id); + if (!$vehicle_company) { + return $this->response->errorNotFound("Invalid Request"); + } else { + $user_data['is_active'] = 0; + if ($vehicle_company->update($user_data)) { + return response()->json(['Success' => 'Record has been deactivated!'], 200); + } + } + } + + /** + * Activate the company. + * @Put("/vehicle_companies/{id}/active") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"success": "Record has been activated!."}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}), + * }) + */ + public function active(Request $request, $id) + { + $vehicle_company = VehicleCompany::find($id); + if (!$vehicle_company) { + return $this->response->errorNotFound("Invalid Request"); + } else { + $user_data['is_active'] = 1; + if ($vehicle_company->update($user_data)) { + return response()->json(['Success' => 'Record has been activated!'], 200); + } + } + } + + /** + * Rejected the company. + * @Put("/vehicle_companies/{id}/reject") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"success": "Record has been activated!."}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}), + * }) + */ + public function reject(Request $request, $id) + { + $vehicle_company = VehicleCompany::find($id); + if (!$vehicle_company) { + return $this->response->errorNotFound("Invalid Request"); + } else { + $user_data['is_active'] = 2; + if ($vehicle_company->update($user_data)) { + return response()->json(['Success' => 'Record has been rejected!'], 200); + } + } + } +} diff --git a/app/Plugins/Vehicles/Controllers/Admin/AdminVehicleMakesController.php b/app/Plugins/Vehicles/Controllers/Admin/AdminVehicleMakesController.php new file mode 100644 index 0000000..e98d08d --- /dev/null +++ b/app/Plugins/Vehicles/Controllers/Admin/AdminVehicleMakesController.php @@ -0,0 +1,197 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Vehicles\Controllers\Admin; + +use Illuminate\Http\Request; +use App\Http\Requests; +use App\Http\Controllers\Controller; +use Plugins\Vehicles\Model\VehicleMake; +use JWTAuth; +use Validator; +use Plugins\Vehicles\Transformers\AdminVehicleMakeTransformer; +use Plugins\Vehicles\Transformers\VehicleMakeTransformer; +use EasySlug\EasySlug\EasySlugFacade as EasySlug; + +/** + * Class AdminVehicleMakesController + * @package Plugins\Vehicles\Controllers\Admin + */ +class AdminVehicleMakesController extends Controller +{ + + public function __construct() + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth'); + // Check the logged user role. + $this->middleware('role'); + } + + /** + * Show all vehicle makes. + * Get a JSON representation of all the vehicle makes. + * + * @Get("/vehicle_makes?filter={filter}&sort={sort}&sortby={sortby}&q={q}") + * @Parameters({ + * @Parameter("filter", type="integer", required=false, description="Filter the vehicle makes list by status.", default=null), + * @Parameter("sort", type="string", required=false, description="Sort the vehicle makes list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort vehicle makes by Ascending / Descending Order.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1) + * }) + */ + public function index(Request $request) + { + $vehicle_make_count = config('constants.ConstPageLimit'); + if ($request->has('type') && $request->type == 'list') { + $vehicle_make_count = VehicleMake::count(); + } + if($request->has('limit') && $request->limit == 'all') { + $vehicle_make_count = VehicleMake::count(); + $vehicle_makes = VehicleMake::filterByRequest($request)->select('id', 'name')->paginate($vehicle_make_count); + return $this->response->paginator($vehicle_makes, new VehicleMakeTransformer); + } else { + $vehicle_makes = VehicleMake::filterByRequest($request)->paginate($vehicle_make_count); + return $this->response->paginator($vehicle_makes, new AdminVehicleMakeTransformer); + } + } + + /** + * Store a new vehicle make. + * Store a new vehicle make with a 'amount', 'user_id', 'name', 'booking_type_id', 'description'. + * @Post("/vehicle_makes") + * @Transaction({ + * @Request({"name":"maruti", "is_active": 1}), + * @Response(200, body={"success": "Record has been added."}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {"amount": {}}, "status_code": 422}) + * }) + */ + public function store(Request $request) + { + $vehicle_make_data = $request->only('name', 'is_active'); + $vehicle_make_data['slug'] = EasySlug::generateUniqueSlug($request->name, 'vehicle_makes'); + $validator = Validator::make($vehicle_make_data, VehicleMake::GetValidationRule(), VehicleMake::GetValidationMessage()); + if ($validator->passes()) { + try { + $vehicle_make = VehicleMake::create($vehicle_make_data); + if ($vehicle_make) { + return response()->json(['Success' => 'Vehicle make has been added'], 200); + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Vehicle make could not be added. Please, try again.'); + } + } catch (\Exception $e) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Vehicle make could not be added. Please, try again.', + array($e->getMessage())); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Vehicle make could not be added. Please, try again.', $validator->errors()); + } + } + + /** + * Edit the specified vehicle make. + * Edit the vehicle make with a `id`. + * @Get("/vehicle_makes/{id}/edit") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"id": 1}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function edit($id) + { + $vehicle_make = VehicleMake::find($id); + if (!$vehicle_make) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($vehicle_make, (new AdminVehicleMakeTransformer)); + } + + /** + * Update the specified vehicle make. + * Update the vehicle make with a `id`. + * @Put("/vehicle_makes/{id}") + * @Transaction({ + * @Request({"id": 1, "name":"maruti", "is_active": 1}), + * @Response(200, body={"success": "Record has been updated."}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {}, "status_code": 422}) + * }) + */ + public function update(Request $request, $id) + { + $vehicle_make_data = $request->only('id', 'name', 'is_active'); + $vehicle_make = false; + if ($request->has('id')) { + $vehicle_make = VehicleMake::find($id); + $vehicle_make = ($request->id != $id) ? false : $vehicle_make; + if ($vehicle_make->name !== $request->name) { + $vehicle_make_data['slug'] = EasySlug::generateUniqueSlug($request->name, 'vehicle_makes'); + } else { + $vehicle_make_data['slug'] = $vehicle_make->slug; + } + } + $validator = Validator::make($vehicle_make_data, VehicleMake::GetValidationRule(), VehicleMake::GetValidationMessage()); + if ($validator->passes() && $vehicle_make) { + try { + $vehicle_make->update($vehicle_make_data); + return response()->json(['Success' => 'Vehicle Make has been updated'], 200); + } catch (\Exception $e) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Vehicle Make could not be updated. Please, try again.'); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Vehicle Make could not be updated. Please, try again.', $validator->errors()); + } + } + + /** + * Delete the specified vehicle make. + * Delete the vehicle make with a `id`. + * @Delete("/vehicle_makes/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"success": "Record Deleted."}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function destroy($id) + { + $vehicle_make = VehicleMake::find($id); + if (!$vehicle_make) { + return $this->response->errorNotFound("Invalid Request"); + } else { + $vehicle_make->delete(); + } + return response()->json(['Success' => 'Vehicle Make deleted'], 200); + } + + /** + * Show the specified vehicle make. + * Show the vehicle make with a `id`. + * @Get("/vehicle_makes/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"id": 1}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function show($id) + { + $vehicle_make = VehicleMake::find($id); + if (!$vehicle_make) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($vehicle_make, (new AdminVehicleMakeTransformer)); + } +} diff --git a/app/Plugins/Vehicles/Controllers/Admin/AdminVehicleModelsController.php b/app/Plugins/Vehicles/Controllers/Admin/AdminVehicleModelsController.php new file mode 100644 index 0000000..8b94494 --- /dev/null +++ b/app/Plugins/Vehicles/Controllers/Admin/AdminVehicleModelsController.php @@ -0,0 +1,211 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Vehicles\Controllers\Admin; + + +use Illuminate\Http\Request; +use App\Http\Requests; +use App\Http\Controllers\Controller; +use Plugins\Vehicles\Model\VehicleModel; +use JWTAuth; +use Validator; +use Plugins\Vehicles\Transformers\AdminVehicleModelTransformer; +use EasySlug\EasySlug\EasySlugFacade as EasySlug; +use Plugins\Vehicles\Services\VehicleModelService; +use DB; + +/** + * Class AdminVehicleModelsController + * @package Plugins\Vehicles\Controllers\Admin + */ +class AdminVehicleModelsController extends Controller +{ + /** + * @var $vehicleModelService + */ + protected $vehicleModelService; + + public function __construct() + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth'); + // Check the logged user role. + $this->middleware('role'); + + $this->setVehicleModelService(); + } + + public function setVehicleModelService() + { + $this->vehicleModelService = new VehicleModelService(); + } + + /** + * Show all vehicle models. + * Get a JSON representation of all the vehicle models. + * + * @Get("/vehicle_models?filter={filter}&sort={sort}&sortby={sortby}&q={q}") + * @Parameters({ + * @Parameter("filter", type="integer", required=false, description="Filter the vehicle models list by status.", default=null), + * @Parameter("sort", type="string", required=false, description="Sort the vehicle models list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort vehicle models by Ascending / Descending Order.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1) + * }) + */ + public function index(Request $request) + { + $vehicle_model_count = config('constants.ConstPageLimit'); + if ($request->has('type') && $request->type == 'list') { + $vehicle_model_count = VehicleModel::count(); + } + $vehicle_models = VehicleModel::with('vehicle_make') + ->select(DB::raw('vehicle_models.*')) + ->leftJoin(DB::raw('(select id,name from vehicle_makes) as vehicle_make'), 'vehicle_make.id', '=', 'vehicle_models.vehicle_make_id') + ->filterByRequest($request)->paginate($vehicle_model_count); + return $this->response->paginator($vehicle_models, (new AdminVehicleModelTransformer)->setDefaultIncludes(['vehicle_make'])); + } + + /** + * Store a new vehicle model. + * @Post("/vehicle_models") + * @Transaction({ + * @Request({"name": "suzuki", "vehicle_make_id":"1", "is_active": 1}), + * @Response(200, body={"success": "Record has been added."}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {"amount": {}}, "status_code": 422}) + * }) + */ + public function store(Request $request) + { + $vehicle_model_data = $request->only('name', 'vehicle_make_id', 'is_active'); + $vehicle_model_data['slug'] = EasySlug::generateUniqueSlug($request->name, 'vehicle_models'); + $validator = Validator::make($vehicle_model_data, VehicleModel::GetValidationRule(), VehicleModel::GetValidationMessage()); + if ($validator->passes()) { + try { + $vehicle_model = VehicleModel::create($vehicle_model_data); + if ($vehicle_model) { + // after save count update + $this->vehicleModelService->afterSave($vehicle_model, false); + return response()->json(['Success' => 'Vehicle model has been added'], 200); + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Vehicle model could not be added. Please, try again.'); + } + } catch (\Exception $e) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Vehicle Model could not be added. Please, try again.', + array($e->getMessage())); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Vehicle model could not be added. Please, try again.', $validator->errors()); + } + } + + /** + * Edit the specified vehicle model. + * Edit the vehicle model with a `id`. + * @Get("/vehicle_models/{id}/edit") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"id": 1, "amount": 1000, "user_id": 1, "name": "house for rent", "booking_type_id": 1, "description": "This house is for rent", "User": {}}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function edit($id) + { + $vehicle_type = VehicleModel::find($id); + if (!$vehicle_type) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($vehicle_type, (new AdminVehicleModelTransformer)); + } + + /** + * Update the specified vehicle model. + * Update the vehicle model with a `id`. + * @Put("/vehicle_models/{id}") + * @Transaction({ + * @Request({"id": 1, "name": "suzuki", "vehicle_make_id":"1", "is_active": 1}), + * @Response(200, body={"success": "Record has been updated."}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {}, "status_code": 422}) + * }) + */ + public function update(Request $request, $id) + { + $vehicle_model_data = $request->only('id', 'name', 'vehicle_make_id', 'is_active'); + $vehicle_model = $vehicle_model_old = false; + if ($request->has('id')) { + $vehicle_model = $vehicle_model_old = VehicleModel::find($id); + $vehicle_model = ($request->id != $id) ? false : $vehicle_model; + if ($vehicle_model->name !== $request->name) { + $vehicle_model_data['slug'] = EasySlug::generateUniqueSlug($request->name, 'vehicle_models'); + } else { + $vehicle_model_data['slug'] = $vehicle_model->slug; + } + } + $validator = Validator::make($vehicle_model_data, VehicleModel::GetValidationRule(), VehicleModel::GetValidationMessage()); + if ($validator->passes() && $vehicle_model) { + try { + $vehicle_model->update($vehicle_model_data); + // after save count update + $this->vehicleModelService->afterSave($vehicle_model, $vehicle_model_old); + return response()->json(['Success' => 'Vehicle Model has been updated'], 200); + } catch (\Exception $e) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Vehicle Model could not be updated. Please, try again.', + array($e->getMessage())); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Vehicle Model could not be updated. Please, try again.', $validator->errors()); + } + } + + /** + * Delete the specified vehicle model. + * Delete the vehicle model with a `id`. + * @Delete("/vehicle_models/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"success": "Record Deleted."}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function destroy($id) + { + $vehicle_model = VehicleModel::find($id); + if (!$vehicle_model) { + return $this->response->errorNotFound("Invalid Request"); + } else { + $vehicle_model->delete(); + } + return response()->json(['Success' => 'Vehicle model deleted'], 200); + } + + /** + * Show the specified vehicle model. + * Show the vehicle model with a `id`. + * @Get("/vehicle_models/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"id": 1}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function show($id) + { + $vehicle_model = VehicleModel::find($id); + if (!$vehicle_model) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($vehicle_model, (new AdminVehicleModelTransformer)); + } +} diff --git a/app/Plugins/Vehicles/Controllers/Admin/AdminVehicleSpecialPricesController.php b/app/Plugins/Vehicles/Controllers/Admin/AdminVehicleSpecialPricesController.php new file mode 100644 index 0000000..e6cdeae --- /dev/null +++ b/app/Plugins/Vehicles/Controllers/Admin/AdminVehicleSpecialPricesController.php @@ -0,0 +1,245 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Vehicles\Controllers\Admin; + +use Illuminate\Http\Request; +use App\Http\Controllers\Controller; +use Plugins\Vehicles\Model\VehicleSpecialPrice; +use JWTAuth; +use Validator; +use Carbon; +use Plugins\Vehicles\Transformers\AdminVehicleSpecialPriceTransformer; +use DB; + +/** + * VehicleSpecialPrices resource representation. + * @Resource("Admin/AdminVehicleSpecialPrices") + */ +class AdminVehicleSpecialPricesController extends Controller +{ + /** + * AdminVehicleSpecialPricesController constructor. + */ + public function __construct() + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth'); + // Check the logged user role. + $this->middleware('role'); + } + + /** + * Show all vehicle_special_prices + * Get a JSON representation of all the vehicle_special_prices. + * + * @Get("/admin/vehicle_special_prices?sort={sort}&sortby={sortby}&page={page}&q={q}") + * @Parameters({ + * @Parameter("sort", type="string", required=false, description="Sort the vehicle_special_prices list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort vehicle_special_prices by Ascending / Descending Order.", default=null), + * @Parameter("q", type="string", required=false, description="Search VehicleSpecialPrices.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1) + * }) + */ + public function index(Request $request) + { + $vehicle_special_price_count = config('constants.ConstPageLimit'); + if ($request->has('type') && $request->type == 'list') { + $vehicle_special_price_count = VehicleSpecialPrice::count(); + } + $vehicle_special_prices = VehicleSpecialPrice::with('vehicle_type') + ->select(DB::raw('vehicle_special_prices.*')) + ->leftJoin(DB::raw('(select id,name from vehicle_types) as vehicle_type'), 'vehicle_type.id', '=', 'vehicle_special_prices.vehicle_type_id') + ->filterByRequest($request)->paginate($vehicle_special_price_count); + return $this->response->paginator($vehicle_special_prices, (new AdminVehicleSpecialPriceTransformer)->setDefaultIncludes(array('vehicle_type'))); + } + + /** + * Edit the specified vehicle_special_price. + * Edit the vehicle_special_price with a `id`. + * @Get("/admin/vehicle_special_prices/{id}/edit") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body= {"id": 1, "vehicle_special_id": 1, "price_id": 1, "discount_type_id": 1, "duration_type_id": 1, "rate": 200, "max_allowed_amount": 1000, "vehicle_type": {}, "vehicle_price": {}, "duration_type": {}, "discount_type": {}}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function edit($id) + { + $vehicle_special_price = VehicleSpecialPrice::with('vehicle_type')->find($id); + if (!$vehicle_special_price) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($vehicle_special_price, (new AdminVehicleSpecialPriceTransformer)->setDefaultIncludes(array('vehicle_type'))); + } + + /** + * Edit the specified vehicle_special_price. + * Edit the vehicle_special_price with a `id`. + * @Get("/admin/vehicle_special_prices/{id}/edit") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body= {"id": 1, "vehicle_type_id": 1, "minimum_no_of_day": 1, "maximum_no_of_day": 1, "discount_percentage": 1, "is_active": 1, "vehicle_type": {}}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function show($id) + { + $vehicle_special_price = VehicleSpecialPrice::with('vehicle_type')->find($id); + if (!$vehicle_special_price) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($vehicle_special_price, (new AdminVehicleSpecialPriceTransformer)->setDefaultIncludes(array('vehicle_type'))); + } + + /** + * Store a new vehicle_special_price. + * Store a new vehicle_special_price with a `name`, `short_description`, and `description`. + * @Post("/admin/vehicle_special_prices") + * @Transaction({ + * @Request({"vehicle_type_id": 1, "start_date": 2016-05-05, "end_date": 2016-05-06, "discount_percentage": 1., "is_active": 1}), + * @Response(200, body={"success": "Record has been added."}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {"name": {}}, "status_code": 422}) + * }) + */ + public function store(Request $request) + { + $vehicle_special_price_data = $request->only('start_date', 'end_date', 'vehicle_type_id', 'discount_percentage', 'is_active'); + if (!is_null($request['start_date'])) { + $vehicle_special_price_data['start_date'] = date("Y-m-d H:i:s", strtotime($request['start_date'])); + } + if (!is_null($request['end_date'])) { + $vehicle_special_price_data['end_date'] = date("Y-m-d H:i:s", strtotime($request['end_date'])); + } + $validator = Validator::make($vehicle_special_price_data, VehicleSpecialPrice::GetValidationRule(), VehicleSpecialPrice::GetValidationMessage()); + if ($validator->passes()) { + $cur_date = Carbon::now()->toDateTimeString(); + if($cur_date > $vehicle_special_price_data['start_date'] || $vehicle_special_price_data['start_date'] > $vehicle_special_price_data['end_date']) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Start date should be less than end date and greater than current date.'); + } + //check whether the given special price date already in list + $vehicle_special_price = VehicleSpecialPrice::where('vehicle_type_id', $request['vehicle_type_id']) + ->where(function ($query) use ($request) { + $query->whereBetween('start_date', [$request->start_date, $request->end_date]) + ->orWhereBetween('end_date', [$request->start_date, $request->end_date]) + ->orwhere(function ($query) use ($request) { + $query->where('start_date', '>', $request->start_date) + ->where('end_date', '<', $request->start_date); + })->orwhere(function ($query) use ($request) { + $query->where('start_date', '<', $request->end_date) + ->where('end_date', '>', $request->end_date); + }); + })->first(); + if ($vehicle_special_price) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Vehicle special Price already added for the given dates. Please try with different dates'); + } + try { + $vehicle_special_price = VehicleSpecialPrice::create($vehicle_special_price_data); + if ($vehicle_special_price) { + return response()->json(['Success' => 'Vehicle special discount price has been added'], 200); + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Vehicle special discount price could not be added. Please, try again.'); + } + } catch (\Exception $e) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Vehicle special discount price could not be added. Please, try again.', + array($e->getMessage())); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Vehicle special discount price could not be added. Please, try again.', $validator->errors()); + } + } + + + /** + * Update the specified vehicle_special_price + * Update the vehicle_special_price with a `id`. + * @Put("/admin/vehicle_special_prices/{id}") + * @Transaction({ + * @Request({"id": 1, "vehicle_type_id": 1, "start_date": 2016-05-05, "end_date": 2016-05-06, "discount_percentage": 1., "is_active": 1}), + * @Response(200, body={"success": "Record has been updated."}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {"name": {}}, "status_code": 422}) + * }) + */ + public function update(Request $request, $id) + { + $vehicle_special_price_data = $request->only('start_date', 'end_date', 'vehicle_type_id', 'discount_percentage', 'is_active'); + if (!is_null($request['start_date'])) { + $vehicle_special_price_data['start_date'] = date("Y-m-d H:i:s", strtotime($request['start_date'])); + } + if (!is_null($request['end_date'])) { + $vehicle_special_price_data['end_date'] = date("Y-m-d H:i:s", strtotime($request['end_date'])); + } + $validator = Validator::make($vehicle_special_price_data, VehicleSpecialPrice::GetValidationRule(), VehicleSpecialPrice::GetValidationMessage()); + $vehicle_special_price = false; + if ($request->has('id')) { + $vehicle_special_price = VehicleSpecialPrice::find($id); + $vehicle_special_price = ($request->id != $id) ? false : $vehicle_special_price; + } + $cur_date = Carbon::now()->toDateTimeString(); + if($cur_date > $vehicle_special_price_data['start_date'] || $vehicle_special_price_data['start_date'] > $vehicle_special_price_data['end_date']) { + //if($vehicle_special_price_data['start_date'] > $vehicle_special_price_data['end_date']) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Start date should be less than end date and greater than current date'); + } + if ($validator->passes() && $vehicle_special_price) { + //check whether the given special price date already in list + $vehicle_special_price_check = VehicleSpecialPrice::where('vehicle_type_id', $request['vehicle_type_id']) + ->where('id', '!=', [$id]) + ->where(function ($query) use ($request) { + $query->whereBetween('start_date', [$request->start_date, $request->end_date]) + ->orWhereBetween('end_date', [$request->start_date, $request->end_date]) + ->orwhere(function ($query) use ($request) { + $query->where('start_date', '>', $request->start_date) + ->where('end_date', '<', $request->start_date); + })->orwhere(function ($query) use ($request) { + $query->where('start_date', '<', $request->end_date) + ->where('end_date', '>', $request->end_date); + }); + })->first(); + if($vehicle_special_price_check) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Special Price already added for the given dates. Please try with different dates'); + } + try { + $vehicle_special_price->update($vehicle_special_price_data); + return response()->json(['Success' => 'Vehicle special discount price has been updated'], 200); + } catch (\Exception $e) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Vehicle special discount price could not be updated. Please, try again.', + array($e->getMessage())); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Vehicle special discount price could not be updated. Please, try again.', $validator->errors()); + } + } + + /** + * Delete the specified vehicle_special_price. + * Delete the vehicle_special_price with a `id`. + * @Delete("/admin/vehicle_special_prices/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"success": "Record Deleted."}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function destroy($id) + { + $vehicle_special_price = VehicleSpecialPrice::find($id); + if (!$vehicle_special_price) { + return $this->response->errorNotFound("Invalid Request"); + } else { + $vehicle_special_price->delete(); + } + return response()->json(['Success' => 'Vehicle special discount price deleted'], 200); + } +} diff --git a/app/Plugins/Vehicles/Controllers/Admin/AdminVehicleTypePricesController.php b/app/Plugins/Vehicles/Controllers/Admin/AdminVehicleTypePricesController.php new file mode 100644 index 0000000..5d18ad0 --- /dev/null +++ b/app/Plugins/Vehicles/Controllers/Admin/AdminVehicleTypePricesController.php @@ -0,0 +1,232 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Vehicles\Controllers\Admin; + +use Illuminate\Http\Request; +use App\Http\Requests; +use App\Http\Controllers\Controller; +use Plugins\Vehicles\Model\VehicleTypePrice; +use JWTAuth; +use Validator; +use Plugins\Vehicles\Transformers\AdminVehicleTypePriceTransformer; +use DB; + +/** + * VehicleTypePrices resource representation. + * @Resource("Admin/AdminVehicleTypePrices") + */ +class AdminVehicleTypePricesController extends Controller +{ + /** + * AdminVehicleTypePricesController constructor. + */ + public function __construct() + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth'); + // Check the logged user role. + $this->middleware('role'); + } + + /** + * Show all vehicle_type_prices + * Get a JSON representation of all the vehicle_type_prices. + * + * @Get("/admin/vehicle_type_prices?sort={sort}&sortby={sortby}&page={page}&q={q}") + * @Parameters({ + * @Parameter("sort", type="string", required=false, description="Sort the vehicle_type_prices list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort vehicle_type_prices by Ascending / Descending Order.", default=null), + * @Parameter("q", type="string", required=false, description="Search VehicleTypePrices.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1) + * }) + */ + public function index(Request $request) + { + $vehicle_type_price_count = config('constants.ConstPageLimit'); + if ($request->has('type') && $request->type == 'list') { + $vehicle_type_price_count = VehicleTypePrice::count(); + } + $vehicle_type_prices = VehicleTypePrice::with('vehicle_type') + ->select(DB::raw('vehicle_type_prices.*')) + ->leftJoin(DB::raw('(select id,name from vehicle_types) as vehicle_type'), 'vehicle_type.id', '=', 'vehicle_type_prices.vehicle_type_id') + ->filterByRequest($request)->paginate($vehicle_type_price_count); + return $this->response->paginator($vehicle_type_prices, (new AdminVehicleTypePriceTransformer)->setDefaultIncludes(array('vehicle_type'))); + } + + /** + * Edit the specified vehicle_type_price. + * Edit the vehicle_type_price with a `id`. + * @Get("/admin/vehicle_type_prices/{id}/edit") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body= {"id": 1, "vehicle_type_id": 1, "price_id": 1, "discount_type_id": 1, "duration_type_id": 1, "rate": 200, "max_allowed_amount": 1000, "vehicle_type": {}, "vehicle_price": {}, "duration_type": {}, "discount_type": {}}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function edit($id) + { + $vehicle_type_price = VehicleTypePrice::with('vehicle_type')->find($id); + if (!$vehicle_type_price) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($vehicle_type_price, (new AdminVehicleTypePriceTransformer)->setDefaultIncludes(array('vehicle_type'))); + } + + /** + * Edit the specified vehicle_type_price. + * Edit the vehicle_type_price with a `id`. + * @Get("/admin/vehicle_type_prices/{id}/edit") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body= {"id": 1, "vehicle_type_id": 1, "minimum_no_of_day": 1, "maximum_no_of_day": 1, "discount_percentage": 1, "is_active": 1, "vehicle_type": {}}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function show($id) + { + $vehicle_type_price = VehicleTypePrice::with('vehicle_type')->find($id); + if (!$vehicle_type_price) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($vehicle_type_price, (new AdminVehicleTypePriceTransformer)->setDefaultIncludes(array('vehicle_type'))); + } + + /** + * Store a new vehicle_type_price. + * Store a new vehicle_type_price with a `name`, `short_description`, and `description`. + * @Post("/admin/vehicle_type_prices") + * @Transaction({ + * @Request({"vehicle_type_id": 1, "minimum_no_of_day": 1, "maximum_no_of_day": 1, "discount_percentage": 1, "is_active": 1}), + * @Response(200, body={"success": "Record has been added."}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {"name": {}}, "status_code": 422}) + * }) + */ + public function store(Request $request) + { + $vehicle_type_price_data = $request->only('vehicle_type_id', 'minimum_no_of_day', 'maximum_no_of_day', 'discount_percentage', 'is_active'); + $validator = Validator::make($vehicle_type_price_data, VehicleTypePrice::GetValidationRule(), VehicleTypePrice::GetValidationMessage()); + if ($validator->passes()) { + try { + //check whether the given type price date already in list + $vehicle_type_price = VehicleTypePrice::where('vehicle_type_id', $request['vehicle_type_id']) + ->where(function ($query) use ($request) { + $query->whereBetween('minimum_no_of_day', [$request->minimum_no_of_day, $request->maximum_no_of_day]) + ->orWhereBetween('maximum_no_of_day', [$request->minimum_no_of_day, $request->maximum_no_of_day]) + ->orwhere(function ($query) use ($request) { + $query->where('minimum_no_of_day', '>', $request->minimum_no_of_day) + ->where('maximum_no_of_day', '<', $request->minimum_no_of_day); + })->orwhere(function ($query) use ($request) { + $query->where('minimum_no_of_day', '<', $request->maximum_no_of_day) + ->where('maximum_no_of_day', '>', $request->maximum_no_of_day); + }); + })->first(); + if ($vehicle_type_price) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Type Price already added for the given days. Please try with different days'); + } + if ($request->minimum_no_of_day < $request->maximum_no_of_day) { + $vehicle_type_price = VehicleTypePrice::create($vehicle_type_price_data); + if ($vehicle_type_price) { + return response()->json(['Success' => 'Vehicle discount Price has been added'], 200); + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Vehicle discount Price could not be added. Please, try again.'); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Minimum number of day should be less than maximum number of day'); + } + } catch (\Exception $e) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Vehicle discount Price could not be added. Please, try again.', + array($e->getMessage())); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Vehicle discount Price could not be added. Please, try again.', $validator->errors()); + } + } + + + /** + * Update the specified vehicle_type_price + * Update the vehicle_type_price with a `id`. + * @Put("/admin/vehicle_type_prices/{id}") + * @Transaction({ + * @Request({"id": 1, "vehicle_type_id": 1, "minimum_no_of_day": 1, "maximum_no_of_day": 1, "discount_percentage": 1, "is_active":1}), + * @Response(200, body={"success": "Record has been updated."}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {"name": {}}, "status_code": 422}) + * }) + */ + public function update(Request $request, $id) + { + $vehicle_type_price_data = $request->only('vehicle_type_id', 'minimum_no_of_day', 'maximum_no_of_day', 'discount_percentage', 'is_active'); + $validator = Validator::make($vehicle_type_price_data, VehicleTypePrice::GetValidationRule(), VehicleTypePrice::GetValidationMessage()); + $vehicle_type_price = false; + if ($request->has('id')) { + $vehicle_type_price = VehicleTypePrice::find($id); + $vehicle_type_price = ($request->id != $id) ? false : $vehicle_type_price; + } + if ($validator->passes() && $vehicle_type_price) { + try { + //check whether the given type price date already in list + $vehicle_type_price_check = VehicleTypePrice::where('vehicle_type_id', $request['vehicle_type_id']) + ->where('id', '!=', [$id]) + ->where(function ($query) use ($request) { + $query->whereBetween('minimum_no_of_day', [$request->minimum_no_of_day, $request->maximum_no_of_day]) + ->orWhereBetween('maximum_no_of_day', [$request->minimum_no_of_day, $request->maximum_no_of_day]) + ->orwhere(function ($query) use ($request) { + $query->where('minimum_no_of_day', '>', $request->minimum_no_of_day) + ->where('maximum_no_of_day', '<', $request->minimum_no_of_day); + })->orwhere(function ($query) use ($request) { + $query->where('minimum_no_of_day', '<', $request->maximum_no_of_day) + ->where('maximum_no_of_day', '>', $request->maximum_no_of_day); + }); + })->first(); + if ($vehicle_type_price_check) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Type Price already added for the given days. Please try with different days'); + } + if ($request->minimum_no_of_day < $request->maximum_no_of_day) { + $vehicle_type_price->update($vehicle_type_price_data); + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Minimum number of day should be less than maximum number of day'); + } + return response()->json(['Success' => 'Vehicle discount Price has been updated'], 200); + } catch (\Exception $e) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Vehicle discount Price could not be updated. Please, try again.', + array($e->getMessage())); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Vehicle discount Price could not be updated. Please, try again.', $validator->errors()); + } + } + + /** + * Delete the specified vehicle_type_price. + * Delete the vehicle_type_price with a `id`. + * @Delete("/admin/vehicle_type_prices/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"success": "Record Deleted."}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function destroy($id) + { + $vehicle_type_price = VehicleTypePrice::find($id); + if (!$vehicle_type_price) { + return $this->response->errorNotFound("Invalid Request"); + } else { + $vehicle_type_price->delete(); + } + return response()->json(['Success' => 'Vehicle discount Price deleted'], 200); + } +} diff --git a/app/Plugins/Vehicles/Controllers/Admin/AdminVehicleTypesController.php b/app/Plugins/Vehicles/Controllers/Admin/AdminVehicleTypesController.php new file mode 100644 index 0000000..ed98ff0 --- /dev/null +++ b/app/Plugins/Vehicles/Controllers/Admin/AdminVehicleTypesController.php @@ -0,0 +1,210 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Vehicles\Controllers\Admin; + + +use Illuminate\Http\Request; +use App\Http\Requests; +use App\Http\Controllers\Controller; +use Plugins\Vehicles\Model\VehicleType; +use JWTAuth; +use Validator; +use Plugins\Vehicles\Transformers\AdminVehicleTypeTransformer; +use Plugins\Vehicles\Transformers\VehicleTypeSimpleTransformer; +use EasySlug\EasySlug\EasySlugFacade as EasySlug; + +/** + * Class AdminVehicleTypesController + * @package Plugins\Vehicles\Controllers\Admin + */ +class AdminVehicleTypesController extends Controller +{ + + public function __construct() + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth'); + // Check the logged user role. + $this->middleware('role'); + } + + /** + * Show all vehicle types. + * Get a JSON representation of all the vehicle types. + * + * @Get("/vehicle_types?filter={filter}&sort={sort}&sortby={sortby}&q={q}") + * @Parameters({ + * @Parameter("filter", type="integer", required=false, description="Filter the vehicle types list by status.", default=null), + * @Parameter("sort", type="string", required=false, description="Sort the vehicle types list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort vehicle types by Ascending / Descending Order.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1) + * }) + */ + public function index(Request $request) + { + $vehicle_type_count = config('constants.ConstPageLimit'); + if ($request->has('type') && $request->type == 'list') { + $vehicle_type_count = VehicleType::count(); + } + if ($request->has('limit') && $request->limit == 'all') { + $vehicle_type_count = VehicleType::count(); + $vehicle_types = VehicleType::filterByRequest($request)->filterByActiveRecord($request)->select('id', 'name')->paginate($vehicle_type_count); + return $this->response->paginator($vehicle_types, new VehicleTypeSimpleTransformer); + } else { + $vehicle_types = VehicleType::filterByRequest($request)->paginate($vehicle_type_count); + return $this->response->paginator($vehicle_types, new AdminVehicleTypeTransformer); + } + } + + /** + * Store a new vehicle type. + * Store a new vehicle type with a 'name'. + * @Post("/vehicle_types") + * @Transaction({ + * @Request({}), + * @Response(200, body={"success": "Record has been added."}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {"amount": {}}, "status_code": 422}) + * }) + */ + public function store(Request $request) + { + $vehicle_type_data = $request->only('name', 'minimum_hour_price', 'maximum_hour_price', 'minimum_day_price', 'maximum_day_price', 'drop_location_differ_unit_price', 'drop_location_differ_additional_fee', 'deposit_amount', 'is_active'); + $vehicle_type_data['slug'] = EasySlug::generateUniqueSlug($request->name, 'vehicle_types'); + $validator = Validator::make($vehicle_type_data, VehicleType::GetValidationRule(), VehicleType::GetValidationMessage()); + if ($vehicle_type_data['minimum_hour_price'] >= $vehicle_type_data['maximum_hour_price']) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Maximum hour price should be greater than minimum hour price'); + } + if ($vehicle_type_data['minimum_day_price'] >= $vehicle_type_data['maximum_day_price']) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Maximum day price should be greater than minimum day price'); + } + if ($validator->passes()) { + try { + $vehicle_type = VehicleType::create($vehicle_type_data); + if ($vehicle_type) { + return response()->json(['Success' => 'Vehicle type has been added'], 200); + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Vehicle type could not be updated. Please, try again.'); + } + } catch (\Exception $e) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Vehicle type could not be added. Please, try again.', + array($e->getMessage())); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Vehicle type could not be updated. Please, try again.', $validator->errors()); + } + } + + /** + * Edit the specified vehicle type. + * Edit the vehicle type with a `id`. + * @Get("/vehicle_types/{id}/edit") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"id": 1}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function edit($id) + { + $vehicle_type = VehicleType::find($id); + if (!$vehicle_type) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($vehicle_type, (new AdminVehicleTypeTransformer)); + } + + /** + * Update the specified vehicle type. + * Update the vehicle type with a `id`. + * @Put("/vehicle_types/{id}") + * @Transaction({ + * @Response(200, body={"success": "Record has been updated."}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {}, "status_code": 422}) + * }) + */ + public function update(Request $request, $id) + { + $vehicle_type_data = $request->only('id', 'name', 'minimum_hour_price', 'maximum_hour_price', 'minimum_day_price', 'maximum_day_price', 'drop_location_differ_unit_price', 'drop_location_differ_additional_fee', 'deposit_amount', 'is_active'); + $vehicle_type = false; + if ($request->has('id')) { + $vehicle_type = VehicleType::find($id); + $vehicle_type = ($request->id != $id) ? false : $vehicle_type; + if ($vehicle_type->name !== $request->name) { + $vehicle_type_data['slug'] = EasySlug::generateUniqueSlug($request->name, 'vehicle_types'); + } else { + $vehicle_type_data['slug'] = $vehicle_type->slug; + } + } + $validator = Validator::make($vehicle_type_data, VehicleType::GetValidationRule(), VehicleType::GetValidationMessage()); + if ($vehicle_type_data['minimum_hour_price'] >= $vehicle_type_data['maximum_hour_price']) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Maximum hour price should be greater than minimum hour price'); + } + if ($vehicle_type_data['minimum_day_price'] >= $vehicle_type_data['maximum_day_price']) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Maximum day price should be greater than minimum day price'); + } + if ($validator->passes() && $vehicle_type) { + try { + $vehicle_type->update($vehicle_type_data); + return response()->json(['Success' => 'VehicleType has been updated'], 200); + } catch (\Exception $e) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Vehicle type could not be updated. Please, try again.', + array($e->getMessage())); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('VehicleType could not be updated. Please, try again.', $validator->errors()); + } + } + + /** + * Delete the specified vehicle type. + * Delete the vehicle type with a `id`. + * @Delete("/vehicle_types/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"success": "Record Deleted."}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function destroy($id) + { + $vehicle_type = VehicleType::find($id); + if (!$vehicle_type) { + return $this->response->errorNotFound("Invalid Request"); + } else { + $vehicle_type->delete(); + } + return response()->json(['Success' => 'Vehicle type deleted'], 200); + } + + /** + * Show the specified vehicle type. + * Show the vehicle type with a `id`. + * @Get("/vehicle_types/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"id": 1}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function show($id) + { + $vehicle_type = VehicleType::find($id); + if (!$vehicle_type) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($vehicle_type, (new AdminVehicleTypeTransformer)); + } +} diff --git a/app/Plugins/Vehicles/Controllers/Admin/AdminVehiclesController.php b/app/Plugins/Vehicles/Controllers/Admin/AdminVehiclesController.php new file mode 100644 index 0000000..6a4c7b4 --- /dev/null +++ b/app/Plugins/Vehicles/Controllers/Admin/AdminVehiclesController.php @@ -0,0 +1,473 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Vehicles\Controllers\Admin; + + +use Illuminate\Http\Request; +use App\Http\Requests; +use App\Http\Controllers\Controller; +use Plugins\Vehicles\Model\Vehicle; +use JWTAuth; +use Validator; +use Plugins\Vehicles\Transformers\AdminVehicleTransformer; +use Plugins\Vehicles\Transformers\VehicleSimpleTransformer; +use Plugins\Vehicles\Services\VehicleService; +use Plugins\Vehicles\Services\VehicleCompanyService; +use Plugins\Vehicles\Services\VehicleMakeService; +use Plugins\Vehicles\Services\VehicleModelService; +use Plugins\Vehicles\Services\VehicleTypeService; +use Plugins\Vehicles\Services\CounterLocationService; +use Plugins\Vehicles\Services\FuelTypeService; +use Plugins\Vehicles\Model\VehicleMake; +use Plugins\Vehicles\Model\VehicleModel; +use Plugins\Vehicles\Model\VehicleCompany; +use EasySlug\EasySlug\EasySlugFacade as EasySlug; +use File; +use Image; +use App\Attachment; +use DB; + +/** + * Class AdminVehiclesController + * @package Plugins\Vehicles\Controllers\Admin + */ +class AdminVehiclesController extends Controller +{ + /** + * @var + */ + protected $vehicleService; + /** + * @var $vehicleCompanyService + */ + protected $vehicleCompanyService; + /** + * @var $vehicleMakeService + */ + protected $vehicleMakeService; + /** + * @var $vehicleModelService + */ + protected $vehicleModelService; + /** + * @var $vehicleTypeService + */ + protected $vehicleTypeService; + /** + * @var $counterLocationService + */ + protected $counterLocationService; + /** + * @var $fuelTypeService + */ + protected $fuelTypeService; + + /** + * AdminVehiclesController constructor. + */ + public function __construct() + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth'); + // Check the logged user role. + $this->middleware('role'); + + $this->setVehicleService(); + $this->setVehicleCompanyService(); + $this->setVehicleMakeService(); + $this->setVehicleModelService(); + $this->setVehicleTypeService(); + $this->setCounterLocationService(); + $this->setFuelTypeService(); + } + + /** + * setVehicleService + */ + public function setVehicleService() + { + $this->vehicleService = new VehicleService(); + } + + public function setVehicleCompanyService() + { + $this->vehicleCompanyService = new VehicleCompanyService(); + } + + public function setVehicleMakeService() + { + $this->vehicleMakeService = new VehicleMakeService(); + } + + public function setVehicleModelService() + { + $this->vehicleModelService = new VehicleModelService(); + } + + public function setVehicleTypeService() + { + $this->vehicleTypeService = new VehicleTypeService(); + } + + public function setCounterLocationService() + { + $this->counterLocationService = new CounterLocationService(); + } + + public function setFuelTypeService() + { + $this->fuelTypeService = new FuelTypeService(); + } + + /** + * Show all vehicles. + * Get a JSON representation of all the vehicles. + * + * @Get("/vehicles?filter={filter}&sort={sort}&sortby={sortby}&q={q}") + * @Parameters({ + * @Parameter("filter", type="integer", required=false, description="Filter the vehicles list by status.", default=null), + * @Parameter("sort", type="string", required=false, description="Sort the vehicles list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort vehicles by Ascending / Descending Order.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1) + * }) + */ + public function index(Request $request) + { + $enabled_includes = array('counter_location', 'vehicle_make', 'vehicle_model', 'vehicle_type', 'vehicle_company', 'fuel_type', 'attachments'); + $vehicle_count = config('constants.ConstPageLimit'); + if ($request->has('type') && $request->type == 'list') { + $vehicle_count = Vehicle::count(); + } + if ($request->has('limit') && $request->limit == 'all') { + $vehicle_count = Vehicle::count(); + $vehicles = Vehicle::filterByRequest($request)->select('id', 'name')->paginate($vehicle_count); + return $this->response->paginator($vehicles, new VehicleSimpleTransformer); + } else if ($request->has('limit') && $request->limit != 'all') { + $vehicle_count = $request->limit; + $vehicles = Vehicle::with($enabled_includes) + ->select(DB::raw('vehicles.*')) + ->leftJoin(DB::raw('(select id,name from vehicle_companies) as vehicle_company'), 'vehicle_company.id', '=', 'vehicles.vehicle_company_id') + ->leftJoin(DB::raw('(select id,name from vehicle_makes) as vehicle_make'), 'vehicle_make.id', '=', 'vehicles.vehicle_make_id') + ->leftJoin(DB::raw('(select id,name from vehicle_models) as vehicle_model'), 'vehicle_model.id', '=', 'vehicles.vehicle_model_id') + ->leftJoin(DB::raw('(select id,name from vehicle_types) as vehicle_type'), 'vehicle_type.id', '=', 'vehicles.vehicle_type_id') + ->filterByRequest($request)->paginate($vehicle_count); + return $this->response->paginator($vehicles, (new AdminVehicleTransformer)->setDefaultIncludes($enabled_includes)); + } else { + $vehicles = Vehicle::with($enabled_includes) + ->select(DB::raw('vehicles.*')) + ->leftJoin(DB::raw('(select id,name from vehicle_companies) as vehicle_company'), 'vehicle_company.id', '=', 'vehicles.vehicle_company_id') + ->leftJoin(DB::raw('(select id,name from vehicle_makes) as vehicle_make'), 'vehicle_make.id', '=', 'vehicles.vehicle_make_id') + ->leftJoin(DB::raw('(select id,name from vehicle_models) as vehicle_model'), 'vehicle_model.id', '=', 'vehicles.vehicle_model_id') + ->leftJoin(DB::raw('(select id,name from vehicle_types) as vehicle_type'), 'vehicle_type.id', '=', 'vehicles.vehicle_type_id') + ->filterByRequest($request)->paginate($vehicle_count); + return $this->response->paginator($vehicles, (new AdminVehicleTransformer)->setDefaultIncludes($enabled_includes)); + } + } + + /** + * Store a new vehicle. + * Store a new vehicle with a 'amount', 'user_id', 'name', 'booking_type_id', 'description'. + * @Post("/vehicles") + * @Transaction({ + * @Request({"vehicle_company_id": 1, "vehicle_make_id":1, "vehicle_model_id":1, "vehicle_type_id":!, "driven_kilometer":100, "vehicle_no":"tn109879", "no_of_seats":10, "no_of_doors":10, "no_of_gears":5, "is_manual_transmission":1, "no_small_bags":4, "no_large_bags":4, "is_ac":1, "minimum_age_of_driver":20, "mileage":200, "is_km":1, "is_airbag":1, "no_of_airbags":10, "is_abs":1, "per_hour_amount":100, "per_day_amount":500, "fuel_type_id":1, "feedback_count":20, "is_active":1}), + * @Response(200, body={"success": "Record has been added."}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {"amount": {}}, "status_code": 422}) + * }) + */ + public function store(Request $request) + { + $vehicle_data = $request->only('vehicle_company_id', 'vehicle_make_id', 'vehicle_model_id', 'vehicle_type_id', 'driven_kilometer', 'vehicle_no', 'no_of_seats', 'no_of_doors', 'no_of_gears', 'is_manual_transmission', 'no_small_bags', 'no_large_bags', 'is_ac', 'minimum_age_of_driver', 'mileage', 'is_km', 'is_airbag', 'no_of_airbags', 'is_abs', 'per_hour_amount', 'per_day_amount', 'fuel_type_id', 'feedback_count', 'is_paid', 'is_active'); + $vehicle_data['is_active'] = ($vehicle_data['is_active']) ? true : false; + $vehicle_data['is_paid'] = ($vehicle_data['is_paid']) ? true : false; + $validator = Validator::make($vehicle_data, Vehicle::GetValidationRule(), Vehicle::GetValidationMessage()); + if ($validator->passes() && ($request->file('file')->isValid())) { + try { + $vehicle_company = VehicleCompany::where('id', $request->vehicle_company_id)->first(); + $vehicle_data['user_id'] = $vehicle_company->user_id; + $vehicle_make = VehicleMake::where('id', $request->vehicle_make_id)->first(); + $vehicle_model = VehicleModel::where('id', $request->vehicle_model_id)->first(); + $vehicle_data['name'] = $vehicle_make->name . ':' . $vehicle_model->name; + $vehicle_data['slug'] = EasySlug::generateUniqueSlug($vehicle_data['name'], 'vehicles'); + $vehicle = Vehicle::create($vehicle_data); + if ($vehicle) { + $vehicle_data['name'] = $vehicle_make->name . ':' . $vehicle_model->name . ' #' . $vehicle->id; + $vehicle_data['slug'] = EasySlug::generateUniqueSlug($vehicle_data['name'], 'vehicles'); + $vehicle->update($vehicle_data); + // afterSave count updatae & dummy record put + $this->vehicleService->afterSave($vehicle); + if (!empty($request->pickup_counter_locations) || !empty($request->drop_counter_locations)) { + $common_loctions = array_intersect($request->pickup_counter_locations, $request->drop_counter_locations); + $diff_in_pickup = array_diff($request->pickup_counter_locations, $request->drop_counter_locations); + $diff_in_drop = array_diff($request->drop_counter_locations, $request->pickup_counter_locations); + if ($common_loctions) { + foreach ($common_loctions as $key => $value) { + $vehicle->counter_location()->attach([$value => ['is_pickup' => 1, 'is_drop' => 1]]); + } + } + if ($diff_in_pickup) { + foreach ($diff_in_pickup as $key => $value) { + $vehicle->counter_location()->attach([$value => ['is_pickup' => 1, 'is_drop' => 0]]); + } + } + if ($diff_in_drop) { + foreach ($diff_in_drop as $key => $value) { + $vehicle->counter_location()->attach([$value => ['is_pickup' => 0, 'is_drop' => 1]]); + } + } + } + if ($request->hasFile('file')) { + $path = storage_path('app/Vehicle/' . $vehicle->id . '/'); + if (!File::isDirectory($path)) { + File::makeDirectory($path, 0777, true); + } + $img = Image::make($_FILES['file']['tmp_name']); + $path = storage_path('app/Vehicle/' . $vehicle->id . '/' . $_FILES['file']['name']); + if ($img->save($path)) { + $attachment = array(); + $attachment['filename'] = $_FILES['file']['name']; + $attachment['dir'] = 'app/Vehicle/' . $vehicle->id . '/'; + $attachment['mimetype'] = $request->file('file')->getClientMimeType(); + $attachment['filesize'] = $request->file('file')->getClientSize(); + $att = Attachment::create($attachment); + $curuser = Vehicle::with(['attachments'])->where('id', '=', $vehicle->id)->first(); + $curuser->attachments()->save($att); + } + } + return response()->json(['Success' => 'Vehicle has been added', 'id' => $vehicle->id], 200); + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Vehicle could not be added. Please, try again.'); + } + } catch (\Exception $e) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Vehicle could not be added. Please, try again.', + array($e->getMessage())); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Vehicle could not be added. Please, try again.', $validator->errors()); + } + } + + /** + * Edit the specified vehicle. + * Edit the vehicle with a `id`. + * @Get("/vehicles/{id}/edit") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"id": 1, "amount": 1000, "user_id": 1, "name": "house for rent", "booking_type_id": 1, "description": "This house is for rent", "User": {}}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function edit($id) + { + $enabled_includes = array('counter_location', 'vehicle_make', 'vehicle_model', 'vehicle_type', 'vehicle_company', 'fuel_type', 'attachments'); + $vehicle = Vehicle::with($enabled_includes)->find($id); + if (!$vehicle) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($vehicle, (new AdminVehicleTransformer)->setDefaultIncludes($enabled_includes)); + } + + /** + * Update the specified vehicle. + * Update the vehicle with a `id`. + * @Put("/vehicles/{id}") + * @Transaction({ + * @Request({"id":1,"vehicle_company_id": 1, "vehicle_make_id":1, "vehicle_model_id":1, "vehicle_type_id":!, "driven_kilometer":100, "vehicle_no":"tn109879", "no_of_seats":10, "no_of_doors":10, "no_of_gears":5, "is_manual_transmission":1, "no_small_bags":4, "no_large_bags":4, "is_ac":1, "minimum_age_of_driver":20, "mileage":200, "is_km":1, "is_airbag":1, "no_of_airbags":10, "is_abs":1, "per_hour_amount":100, "per_day_amount":500, "fuel_type_id":1, "feedback_count":20, "is_active":1}), + * @Response(200, body={"success": "Record has been updated."}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {}, "status_code": 422}) + * }) + */ + public function update(Request $request, $id) + { + $vehicle_data = $request->only('id', 'vehicle_company_id', 'vehicle_make_id', 'vehicle_model_id', 'vehicle_type_id', 'driven_kilometer', 'vehicle_no', 'no_of_seats', 'no_of_doors', 'no_of_gears', 'is_manual_transmission', 'no_small_bags', 'no_large_bags', 'is_ac', 'minimum_age_of_driver', 'mileage', 'is_km', 'is_airbag', 'no_of_airbags', 'is_abs', 'per_hour_amount', 'per_day_amount', 'fuel_type_id', 'feedback_count', 'is_paid', 'is_active'); + $vehicle_data['is_active'] = ($vehicle_data['is_active']) ? true : false; + $vehicle_data['is_paid'] = ($vehicle_data['is_paid']) ? true : false; + $vehicle = false; + if ($request->has('id')) { + $vehicle = Vehicle::find($id); + $vehicle = ($request->id != $id) ? false : $vehicle; + } + $validator = Validator::make($vehicle_data, Vehicle::GetValidationRule(), Vehicle::GetValidationMessage()); + if ($validator->passes() && $vehicle && (($request->hasFile('file') && $request->file('file')->isValid()) || (!$request->hasFile('file')))) { + try { + $vehicle_company = VehicleCompany::where('id', $request->vehicle_company_id)->first(); + $vehicle_data['user_id'] = $vehicle_company->user_id; + $vehicle_make = VehicleMake::where('id', $request->vehicle_make_id)->first(); + $vehicle_model = VehicleModel::where('id', $request->vehicle_model_id)->first(); + $vehicle_data['name'] = $vehicle_make->name . ':' . $vehicle_model->name. '#'.$vehicle->id;; + $vehicle_data['slug'] = EasySlug::generateUniqueSlug($vehicle_data['name'], 'vehicles'); + $vehicle->update($vehicle_data); + // afterSave count updatae & dummy record put + $this->vehicleService->afterSave($vehicle); + if (!empty($request->pickup_counter_locations) || !empty($request->drop_counter_locations)) { + $common_loctions = array_intersect($request->pickup_counter_locations, $request->drop_counter_locations); + $diff_in_pickup = array_diff($request->pickup_counter_locations, $request->drop_counter_locations); + $diff_in_drop = array_diff($request->drop_counter_locations, $request->pickup_counter_locations); + $vehicle->counter_location()->detach(); + if ($common_loctions) { + foreach ($common_loctions as $key => $value) { + $vehicle->counter_location()->attach([$value => ['is_pickup' => 1, 'is_drop' => 1]]); + } + } + if ($diff_in_pickup) { + foreach ($diff_in_pickup as $key => $value) { + $vehicle->counter_location()->attach([$value => ['is_pickup' => 1, 'is_drop' => 0]]); + } + } + if ($diff_in_drop) { + foreach ($diff_in_drop as $key => $value) { + $vehicle->counter_location()->attach([$value => ['is_pickup' => 0, 'is_drop' => 1]]); + } + } + } + if ($request->hasFile('file')) { + $path = storage_path('app/Vehicle/' . $vehicle->id . '/'); + if (!File::isDirectory($path)) { + File::makeDirectory($path, 0777, true); + } + $img = Image::make($_FILES['file']['tmp_name']); + $path = storage_path('app/Vehicle/' . $vehicle->id . '/' . $_FILES['file']['name']); + if ($img->save($path)) { + $curVehicle = Vehicle::with(['attachments'])->where('id', '=', $vehicle->id)->first(); + $attachment = array(); + $attachment['filename'] = $_FILES['file']['name']; + $attachment['dir'] = 'app/Vehicle/' . $vehicle->id . '/'; + $attachment['mimetype'] = $request->file('file')->getClientMimeType(); + $attachment['filesize'] = $request->file('file')->getClientSize(); + if ($curVehicle->attachments) { + $curVehicle->attachments()->update($attachment); + } else { + $att = Attachment::create($attachment); + $curVehicle = Vehicle::with(['attachments'])->where('id', '=', $vehicle->id)->first(); + $curVehicle->attachments()->save($att); + } + } + } + return response()->json(['Success' => 'Vehicle has been updated'], 200); + } catch (\Exception $e) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Vehicle could not be updated. Please, try again.', + array($e->getMessage())); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Vehicle could not be updated. Please, try again.', $validator->errors()); + } + } + + /** + * Delete the specified vehicle. + * Delete the vehicle with a `id`. + * @Delete("/vehicles/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"success": "Record Deleted."}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function destroy($id) + { + $vehicle = Vehicle::find($id); + if (!$vehicle) { + return $this->response->errorNotFound("Invalid Request"); + } else { + $vehicle->delete(); + } + return response()->json(['Success' => 'Vehicle deleted'], 200); + } + + /** + * Show the specified vehicle. + * Show the vehicle with a `id`. + * @Get("/vehicles/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"id": 1, "amount": 1000, "user_id": 1, "name": "house for rent", "booking_type_id": 1, "description": "This house is for rent", "User": {}}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function show($id) + { + $enabled_includes = array('counter_location', 'vehicle_make', 'vehicle_model', 'vehicle_type', 'vehicle_company', 'fuel_type', 'attachments'); + $vehicle = Vehicle::with($enabled_includes)->find($id); + if (!$vehicle) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($vehicle, (new AdminVehicleTransformer)->setDefaultIncludes($enabled_includes)); + } + + public function getVehicleRelatedDetail() + { + $vehicle_company_list = $this->vehicleCompanyService->getVehicleCompanyList(); + $vehicle_make_list = $this->vehicleMakeService->getVehicleMakeList(); + $vehicle_model_list = $this->vehicleModelService->getVehicleModelList(); + $vehicle_type_list = $this->vehicleTypeService->getVehicleTypeList(); + $counter_location_list = $this->counterLocationService->getCounterLocationList(); + $fuel_type_list = $this->fuelTypeService->getFuelTypeList(); + $settings = array(); + $settings['seats'] = config('vehicle.no_of_seats'); + $settings['doors'] = config('vehicle.no_of_doors'); + $settings['gears'] = config('vehicle.no_of_gears'); + $settings['small_bags'] = config('vehicle.no_small_bags'); + $settings['large_bags'] = config('vehicle.no_large_bags'); + $settings['airbags'] = config('vehicle.no_of_airbags'); + return response()->json(compact('vehicle_company_list', 'vehicle_make_list', 'vehicle_model_list', 'vehicle_type_list', 'counter_location_list', 'fuel_type_list', 'settings')); + } + + /** + * Deactivate the vehicle. + * @Put("/vehicles/{id}/deactive") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"success": "Record has been deactivated!."}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}), + * }) + */ + public function deactive(Request $request, $id) + { + $vehicle = Vehicle::find($id); + if (!$vehicle) { + return $this->response->errorNotFound("Invalid Request"); + } else { + $vehicle_data['is_active'] = false; + if ($vehicle->update($vehicle_data)) { + // vehicle count update to realted table + $this->vehicleService->updateVehicleCount($vehicle->vehicle_make_id, $vehicle->vehicle_model_id, $vehicle->vehicle_type_id, $vehicle->vehicle_company_id); + return response()->json(['Success' => 'Record has been deactivated!'], 200); + } + } + } + + /** + * Activate the vehicle. + * @Put("/vehicles/{id}/active") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"success": "Record has been activated!."}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}), + * }) + */ + public function active(Request $request, $id) + { + $vehicle = Vehicle::find($id); + if (!$vehicle) { + return $this->response->errorNotFound("Invalid Request"); + } else { + $vehicle_data['is_active'] = true; + if ($vehicle->update($vehicle_data)) { + $this->vehicleService->afterSave($vehicle); + return response()->json(['Success' => 'Record has been activated!'], 200); + } + } + } +} diff --git a/app/Plugins/Vehicles/Controllers/CounterLocationsController.php b/app/Plugins/Vehicles/Controllers/CounterLocationsController.php new file mode 100644 index 0000000..3efcd50 --- /dev/null +++ b/app/Plugins/Vehicles/Controllers/CounterLocationsController.php @@ -0,0 +1,63 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Vehicles\Controllers; + + +use Illuminate\Http\Request; +use App\Http\Requests; +use App\Http\Controllers\Controller; +use Plugins\Vehicles\Model\CounterLocation; +use JWTAuth; +use Validator; +use Plugins\Vehicles\Transformers\CounterLocationTransformer; + + +/** + * Class CounterLocationsController + * @package Plugins\Vehicles\Controllers + */ +class CounterLocationsController extends Controller +{ + + public function __construct() + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth', ['except' => ['index']]); + } + + /** + * Show all counter locations. + * Get a JSON representation of all the counter locations. + * + * @Get("/counter_locations?filter={filter}&sort={sort}&sortby={sortby}&q={q}") + * @Parameters({ + * @Parameter("filter", type="integer", required=false, description="Filter the counter_locations list by status.", default=null), + * @Parameter("sort", type="string", required=false, description="Sort the counter_locations list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort counter_locations by Ascending / Descending Order.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1) + * }) + */ + public function index(Request $request) + { + $counter_location_count = config('constants.ConstPageLimit'); + if ($request->has('type') && $request->type == 'list') { + $counter_location_count = CounterLocation::count(); + } + $counter_locations = CounterLocation::filterByRequest($request)->paginate($counter_location_count); + return $this->response->paginator($counter_locations, new CounterLocationTransformer); + } + +} diff --git a/app/Plugins/Vehicles/Controllers/FuelTypesController.php b/app/Plugins/Vehicles/Controllers/FuelTypesController.php new file mode 100644 index 0000000..538619c --- /dev/null +++ b/app/Plugins/Vehicles/Controllers/FuelTypesController.php @@ -0,0 +1,61 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Vehicles\Controllers; + +use Illuminate\Http\Request; +use App\Http\Requests; +use App\Http\Controllers\Controller; +use Plugins\Vehicles\Model\FuelType; +use JWTAuth; +use Validator; +use Plugins\Vehicles\Transformers\FuelTypeTransformer; + +/** + * Class FuelTypesController + * @package Plugins\Vehicles\Controllers + */ +class FuelTypesController extends Controller +{ + + public function __construct() + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth'); + } + + /** + * Show all fuel types. + * Get a JSON representation of all the fuel types. + * + * @Get("/fuel_types?filter={filter}&sort={sort}&sortby={sortby}&q={q}") + * @Parameters({ + * @Parameter("filter", type="integer", required=false, description="Filter the fuel types list by status.", default=null), + * @Parameter("sort", type="string", required=false, description="Sort the fuel types list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort fuel types by Ascending / Descending Order.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1) + * }) + */ + public function index(Request $request) + { + $fuel_type_count = config('constants.ConstPageLimit'); + if ($request->has('type') && $request->type == 'list') { + $fuel_type_count = FuelType::count(); + } + $fuel_types = FuelType::filterByRequest($request)->paginate($fuel_type_count); + return $this->response->paginator($fuel_types, new FuelTypeTransformer); + } + +} diff --git a/app/Plugins/Vehicles/Controllers/UnavailableVehiclesController.php b/app/Plugins/Vehicles/Controllers/UnavailableVehiclesController.php new file mode 100644 index 0000000..d622322 --- /dev/null +++ b/app/Plugins/Vehicles/Controllers/UnavailableVehiclesController.php @@ -0,0 +1,241 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Vehicles\Controllers; + + +use Illuminate\Http\Request; +use App\Http\Requests; +use App\Http\Controllers\Controller; +use Plugins\Vehicles\Model\UnavailableVehicle; +use Plugins\Vehicles\Model\Vehicle; +use JWTAuth; +use Validator; +use Plugins\Vehicles\Transformers\UnavailableVehicleTransformer; +use App\User; +use Carbon; + +/** + * Class UnavailableVehiclesController + * @package Plugins\Vehicles\Controllers + */ +class UnavailableVehiclesController extends Controller +{ + /** + * UnavailableVehiclesController constructor. + */ + public function __construct() + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth'); + } + + /** + * Show own all vehicle unavailable dates. + * Get a JSON representation of vehicle unavailable dates. + * @Get("GET /unavailable_vehicles?filter={filter}&sort={sort}&sortby={sortby}&q={q}") + * @Parameters({ + * @Parameter("vehicle_id", type="integer", required=false, description="Filter the vehicles ", default=null), + * @Parameter("filter", type="integer", required=false, description="Filter the vehicles list by status.", default=null), + * @Parameter("sort", type="string", required=false, description="Sort the vehicles list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort vehicles by Ascending / Descending Order.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1) + * }) + */ + public function index(Request $request) + { + $user = $this->auth->user(); + $enabled_includes = array('vehicle'); + $vehicles = UnavailableVehicle::with($enabled_includes)->filterByRequest($request)->filterByMyVehicle($user->id)->paginate(config('constants.ConstPageLimit')); + return $this->response->paginator($vehicles, (new UnavailableVehicleTransformer)->setDefaultIncludes($enabled_includes)); + } + + /** + * Store a new unavailable vehicle. + * Store a new unavailable vehicle with a 'vehicle_id', 'start_date', 'end_date'. + * @Post("/unavailable_vehicles") + * @Transaction({ + * @Request({"vehicle_id": 1, "start_date": 2016-08-09, "end_date": "2016-09-09"}), + * @Response(200, body={"success": "Record has been added."}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {"amount": {}}, "status_code": 422}) + * }) + */ + public function store(Request $request) + { + $unavailable_vehicle_data = $request->only('vehicle_id', 'start_date', 'end_date'); + $user = $this->auth->user(); + $vehicle = Vehicle::with('vehicle_company', 'user')->find($request->vehicle_id); + if (!$vehicle || !$user || $vehicle->user_id != $user->id || $vehicle->vehicle_company->user_id != $user->id) { + return $this->response->errorNotFound("Invalid Request"); + } + if (!is_null($request['start_date'])) { + $unavailable_vehicle_data['start_date'] = date("Y-m-d H:i:s", strtotime($request['start_date'])); + } + if (!is_null($request['end_date'])) { + $unavailable_vehicle_data['end_date'] = date("Y-m-d H:i:s", strtotime($request['end_date'])); + } + $cur_date = Carbon::now()->toDateTimeString(); + if ($cur_date > $request->start_date || $request->start_date > $request->end_date) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Start date should be less than end date and greater than current date.'); + } + //check whether the given date already in list + $unavailable_vehicle = UnavailableVehicle::where('vehicle_id', $request->vehicle_id) + ->where(function ($query) use ($unavailable_vehicle_data) { + $query->whereBetween('start_date', [$unavailable_vehicle_data['start_date'], $unavailable_vehicle_data['end_date']]) + ->orWhereBetween('end_date', [$unavailable_vehicle_data['start_date'], $unavailable_vehicle_data['end_date']]) + ->orwhere(function ($query) use ($unavailable_vehicle_data) { + $query->where('start_date', '>=', $unavailable_vehicle_data['start_date']) + ->where('end_date', '<=', $unavailable_vehicle_data['start_date']); + })->orwhere(function ($query) use ($unavailable_vehicle_data) { + $query->where('start_date', '<', $unavailable_vehicle_data['end_date']) + ->where('end_date', '>', $unavailable_vehicle_data['end_date']); + }); + })->first(); + if ($unavailable_vehicle) { + if ($unavailable_vehicle->is_dummy == 2) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Maintenance date already updated. Please, try again some other date.'); + } else if ($unavailable_vehicle->is_dummy == 0) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Vehicle booked that day. Please, try again some other date.'); + } + + } + $unavailable_vehicle_data['is_dummy'] = 2; + $validator = Validator::make($unavailable_vehicle_data, UnavailableVehicle::GetValidationRule(), UnavailableVehicle::GetValidationMessage()); + if ($validator->passes()) { + try { + $unavailable_vehicle = UnavailableVehicle::create($unavailable_vehicle_data); + if ($unavailable_vehicle) { + return response()->json(['Success' => 'Vehicle maintenance date has been added'], 200); + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Vehicle maintenance date could not be added. Please, try again.'); + } + } catch (\Exception $e) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Vehicle maintenance date could not be added. Please, try again.', array($e->getMessage())); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Vehicle maintenance date could not be added. Please, try again.', $validator->errors()); + } + } + + /** + * Edit the specified unavailable vehicle. + * Edit the unavailable vehicle with a `id`. + * @Get("/unavailable_vehicles/{id}/edit") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"id": 1}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function edit($id) + { + $user = $this->auth->user(); + $unavailable_vehicle = UnavailableVehicle::with(['vehicle'])->where('id', $id)->where('is_dummy', 2)->filterByMyVehicle($user->id)->find($id); + if (!$unavailable_vehicle) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($unavailable_vehicle, (new UnavailableVehicleTransformer)->setDefaultIncludes(['vehicle'])); + } + + /** + * Update the specified unavailable vehicle. + * Update the unavailable vehicle with a `id`. + * @Put("/unavailable_vehicles/{id}") + * @Transaction({ + * @Request({"id": 1, "vehicle_id": 1, "start_date": 2016-08-09, "end_date": "2016-09-09"}), + * @Response(200, body={"success": "Record has been updated."}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {}, "status_code": 422}) + * }) + */ + public function update(Request $request, $id) + { + $user = $this->auth->user(); + $unavailable_vehicle_data = $request->only('id', 'start_date', 'end_date'); + $unavailable_vehicle = false; + if ($request->has('id')) { + $unavailable_vehicle = UnavailableVehicle::with(['vehicle'])->where('is_dummy', 2)->filterByMyVehicle($user->id)->find($id); + $unavailable_vehicle = ($request->id != $id) ? false : $unavailable_vehicle; + } + if (!$unavailable_vehicle || !$user) { + return $this->response->errorNotFound("Invalid Request"); + } + if ($request->start_date > $request->end_date) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Start date should be less than end date'); + } + if (!is_null($request['start_date'])) { + $unavailable_vehicle_data['start_date'] = date("Y-m-d H:i:s", strtotime($request['start_date'])); + } + if (!is_null($request['end_date'])) { + $unavailable_vehicle_data['end_date'] = date("Y-m-d H:i:s", strtotime($request['end_date'])); + } + //check whether the given date already in list + $unavailable_vehicle_check = UnavailableVehicle::with(['vehicle'])->where('vehicle_id', $unavailable_vehicle->vehicle_id) + ->where('id', '!=', [$id]) + ->where(function ($query) use ($unavailable_vehicle_data) { + $query->whereBetween('start_date', [$unavailable_vehicle_data['start_date'], $unavailable_vehicle_data['end_date']]) + ->orWhereBetween('end_date', [$unavailable_vehicle_data['start_date'], $unavailable_vehicle_data['end_date']]) + ->orwhere(function ($query) use ($unavailable_vehicle_data) { + $query->where('start_date', '>', $unavailable_vehicle_data['start_date']) + ->where('end_date', '<', $unavailable_vehicle_data['start_date']); + })->orwhere(function ($query) use ($unavailable_vehicle_data) { + $query->where('start_date', '<', $unavailable_vehicle_data['end_date']) + ->where('end_date', '>', $unavailable_vehicle_data['end_date']); + }); + })->first(); + if ($unavailable_vehicle_check) { + if ($unavailable_vehicle_check->is_dummy == 2) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Maintenance date already updated. Please, try again some other date.'); + } else if ($unavailable_vehicle_check->is_dummy == 0) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Vehicle booked that day. Please, try again some other date.'); + } + } else { + $unavailable_vehicle = UnavailableVehicle::with(['vehicle'])->where('is_dummy', 2)->filterByMyVehicle($user->id)->find($id); + } + $validator = Validator::make($unavailable_vehicle_data, UnavailableVehicle::GetValidationRule(), UnavailableVehicle::GetValidationMessage()); + if ($validator->passes()) { + try { + $unavailable_vehicle->update($unavailable_vehicle_data); + return response()->json(['Success' => 'Maintenance date has been updated', 'vehicle_id' => $unavailable_vehicle->vehicle_id], 200); + } catch (\Exception $e) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Maintenance date could not be updated. Please, try again.', array($e->getMessage())); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Maintenance date could not be updated. Please, try again.', $validator->errors()); + } + } + + /** + * Delete the specified unavailable vehicle. + * Delete the unavailable vehicle with a `id`. + * @Delete("/unavailable_vehicles/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"success": "Record Deleted."}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function destroy($id) + { + $user = $this->auth->user(); + $unavailable_vehicle = UnavailableVehicle::with(['vehicle'])->where('is_dummy', 2)->filterByMyVehicle($user->id)->find($id); + if (!$unavailable_vehicle) { + return $this->response->errorNotFound("Invalid Request"); + } else { + $unavailable_vehicle->delete(); + } + return response()->json(['Success' => 'Maintenance date deleted'], 200); + } + +} diff --git a/app/Plugins/Vehicles/Controllers/VehicleCompaniesController.php b/app/Plugins/Vehicles/Controllers/VehicleCompaniesController.php new file mode 100644 index 0000000..a5bfe26 --- /dev/null +++ b/app/Plugins/Vehicles/Controllers/VehicleCompaniesController.php @@ -0,0 +1,167 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Vehicles\Controllers; + + +use Illuminate\Http\Request; +use App\Http\Requests; +use App\Http\Controllers\Controller; +use Plugins\Vehicles\Model\VehicleCompany; +use JWTAuth; +use Validator; +use Plugins\Vehicles\Transformers\VehicleCompanyTransformer; +use EasySlug\EasySlug\EasySlugFacade as EasySlug; + + +/** + * Class VehicleCompaniesController + * @package Plugins\Vehicles\Controllers + */ +class VehicleCompaniesController extends Controller +{ + + public function __construct() + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth'); + } + + /** + * Show all vehicle companies. + * Get a JSON representation of all the Vehicle Companies. + * + * @Get("/vehicle_companies?filter={filter}&sort={sort}&sortby={sortby}&q={q}") + * @Parameters({ + * @Parameter("filter", type="integer", required=false, description="Filter the Vehicle Companies list by status.", default=null), + * @Parameter("sort", type="string", required=false, description="Sort the Vehicle Companies list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort Vehicle Companies by Ascending / Descending Order.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1) + * }) + */ + public function index(Request $request) + { + $vehicle_company_count = config('constants.ConstPageLimit'); + if ($request->has('type') && $request->type == 'list') { + $vehicle_company_count = VehicleCompany::count(); + } + $vehicle_companies = VehicleCompany::with('user')->filterByRequest($request)->paginate($vehicle_company_count); + return $this->response->paginator($vehicle_companies, (new VehicleCompanyTransformer)->setDefaultIncludes(['user'])); + } + + /** + * Store a new vehicle company. + * @Post("/vehicle_companies") + * @Transaction({ + * @Request({}), + * @Response(200, body={"success": "Record has been added."}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {"amount": {}}, "status_code": 422}) + * }) + */ + public function store(Request $request) + { + $vehicle_company_data = $request->only('name', 'address', 'latitude', 'longitude', 'phone', 'fax', 'mobile', 'email'); + $vehicle_company_data['slug'] = EasySlug::generateUniqueSlug($request->name, 'vehicle_companies'); + $user = $this->auth->user(); + if (!$user) { + return $this->response->errorNotFound("Invalid Request"); + } + $validation_rules = VehicleCompany::GetValidationRule(); + $vehicle_company_data['user_id'] = $user->id; + $vehicle_company = VehicleCompany::where('user_id', $user->id)->first(); + if (!is_null($vehicle_company) && $vehicle_company->user_id == $vehicle_company_data['user_id']) { + $validation_rules['user_id'] = 'required'; + } + $validator = Validator::make($vehicle_company_data, $validation_rules, VehicleCompany::GetValidationMessage()); + if ($validator->passes()) { + try { + if($vehicle_company){ + $vehicle_company->update($vehicle_company_data); + return $this->response->item($vehicle_company, (new VehicleCompanyTransformer)); + }else{ + $vehicle_company_data['is_active'] = (config('vehicle.company_auto_approve')) ? 1 : 0; + VehicleCompany::create($vehicle_company_data); + return $this->response->item($vehicle_company, (new VehicleCompanyTransformer)); + } + } catch (\Exception $e) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Vehicle company could not be added. Please, try again.', array($e->getMessage())); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Vehicle company could not be added. Please, try again.', $validator->errors()); + } + } + + /** + * Edit the specified vehicle_company. + * Edit the vehicle_company with a `id`. + * @Get("/vehicle_companies/{id}/edit") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"id": 1}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function edit() + { + $user = $this->auth->user(); + $vehicle_company = VehicleCompany::where('user_id', $user->id)->first(); + if (!$user || !$vehicle_company || $user->id != $vehicle_company->user_id) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($vehicle_company, (new VehicleCompanyTransformer)); + } + + /** + * Delete the specified Vehicle Company. + * Delete the Vehicle Company with a `id`. + * @Delete("/vehicle_companies/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"success": "Record Deleted."}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function destroy($id) + { + $vehicle_company = VehicleCompany::find($id); + $user = $this->auth->user(); + if (!$user || !$vehicle_company || $user->id != $vehicle_company->user_id) { + return $this->response->errorNotFound("Invalid Request"); + } else { + $vehicle_company->delete(); + } + return response()->json(['Success' => 'Vehicle company deleted'], 200); + } + + /** + * Show the specified Vehicle Company. + * Show the Vehicle Company with a `id`. + * @Get("/vehicle_companies/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"id": 1, "amount": 1000, "user_id": 1, "name": "house for rent", "booking_type_id": 1, "description": "This house is for rent", "User": {}}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function show() + { + $user = $this->auth->user(); + $vehicle_company = VehicleCompany::where('user_id', $user->id)->first(); + if (!$user || !$vehicle_company || $user->id != $vehicle_company->user_id) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($vehicle_company, (new VehicleCompanyTransformer)); + } +} diff --git a/app/Plugins/Vehicles/Controllers/VehicleMakesController.php b/app/Plugins/Vehicles/Controllers/VehicleMakesController.php new file mode 100644 index 0000000..72705da --- /dev/null +++ b/app/Plugins/Vehicles/Controllers/VehicleMakesController.php @@ -0,0 +1,61 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Vehicles\Controllers; + +use Illuminate\Http\Request; +use App\Http\Requests; +use App\Http\Controllers\Controller; +use Plugins\Vehicles\Model\VehicleMake; +use JWTAuth; +use Validator; +use Plugins\Vehicles\Transformers\VehicleMakeTransformer; + +/** + * Class VehicleMakesController + * @package Plugins\Vehicles\Controllers + */ +class VehicleMakesController extends Controller +{ + + public function __construct() + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth'); + } + + /** + * Show all vehicle makes. + * Get a JSON representation of all the vehicle makes. + * + * @Get("/vehicle_makes?filter={filter}&sort={sort}&sortby={sortby}&q={q}") + * @Parameters({ + * @Parameter("filter", type="integer", required=false, description="Filter the vehicle makes list by status.", default=null), + * @Parameter("sort", type="string", required=false, description="Sort the vehicle makes list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort vehicle makes by Ascending / Descending Order.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1) + * }) + */ + public function index(Request $request) + { + $vehicle_make_count = config('constants.ConstPageLimit'); + if ($request->has('type') && $request->type == 'list') { + $vehicle_make_count = VehicleMake::count(); + } + $vehicle_makes = VehicleMake::filterByRequest($request)->paginate($vehicle_make_count); + return $this->response->paginator($vehicle_makes, new VehicleMakeTransformer); + } + +} diff --git a/app/Plugins/Vehicles/Controllers/VehicleModelsController.php b/app/Plugins/Vehicles/Controllers/VehicleModelsController.php new file mode 100644 index 0000000..0ea517a --- /dev/null +++ b/app/Plugins/Vehicles/Controllers/VehicleModelsController.php @@ -0,0 +1,62 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Vehicles\Controllers; + + +use Illuminate\Http\Request; +use App\Http\Requests; +use App\Http\Controllers\Controller; +use Plugins\Vehicles\Model\VehicleModel; +use JWTAuth; +use Validator; +use Plugins\Vehicles\Transformers\VehicleModelTransformer; + +/** + * Class VehicleModelsController + * @package Plugins\Vehicles\Controllers + */ +class VehicleModelsController extends Controller +{ + + public function __construct() + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth'); + } + + /** + * Show all vehicle models. + * Get a JSON representation of all the vehicle models. + * + * @Get("/vehicle_models?filter={filter}&sort={sort}&sortby={sortby}&q={q}") + * @Parameters({ + * @Parameter("filter", type="integer", required=false, description="Filter the vehicle models list by status.", default=null), + * @Parameter("sort", type="string", required=false, description="Sort the vehicle models list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort vehicle models by Ascending / Descending Order.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1) + * }) + */ + public function index(Request $request) + { + $vehicle_model_count = config('constants.ConstPageLimit'); + if ($request->has('type') && $request->type == 'list') { + $vehicle_model_count = VehicleModel::count(); + } + $vehicle_models = VehicleModel::with('vehicle_make')->filterByRequest($request)->paginate($vehicle_model_count); + return $this->response->paginator($vehicle_models, (new VehicleModelTransformer)->setDefaultIncludes(['vehicle_make'])); + } + +} diff --git a/app/Plugins/Vehicles/Controllers/VehicleSpecialPricesController.php b/app/Plugins/Vehicles/Controllers/VehicleSpecialPricesController.php new file mode 100644 index 0000000..5ed1688 --- /dev/null +++ b/app/Plugins/Vehicles/Controllers/VehicleSpecialPricesController.php @@ -0,0 +1,96 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Vehicles\Controllers; + +use Illuminate\Http\Request; +use App\Http\Controllers\Controller; +use Plugins\Vehicles\Model\VehicleSpecialPrice; +use JWTAuth; +use Validator; +use Plugins\Vehicles\Transformers\VehicleSpecialPriceTransformer; + +/** + * VehiclePrices resource representation. + * @Resource("VehiclePrices") + */ +class VehicleSpecialPricesController extends Controller +{ + /** + * VehiclePricesController constructor. + */ + public function __construct() + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth'); + } + + /** + * Show all prices + * Get a JSON representation of all the prices. + * + * @Get("/vehicle_special_prices?sort={sort}&sortby={sortby}&page={page}&q={q}") + * @Parameters({ + * @Parameter("sort", type="string", required=false, description="Sort the prices list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort prices by Ascending / Descending Order.", default=null), + * @Parameter("q", type="string", required=false, description="Search VehiclePrices.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1) + * }) + */ + public function index(Request $request) + { + $vehicle_special_prices = VehicleSpecialPrice::with('vehicle_type')->filterByRequest($request)->paginate(config('constants.ConstPageLimit')); + return $this->response->paginator($vehicle_special_prices, (new VehicleSpecialPriceTransformer)->setDefaultIncludes(array('vehicle_type'))); + } + + /** + * Edit the specified vehicle_special_price. + * Edit the vehicle_special_price with a `id`. + * @Get("/vehicle_special_prices/{id}/edit") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body= {"id": 1, "vehicle_special_id": 1, "price_id": 1, "discount_type_id": 1, "duration_type_id": 1, "rate": 200, "max_allowed_amount": 1000, "vehicle_type": {}, "vehicle_price": {}, "duration_type": {}, "discount_type": {}}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function edit($id) + { + $vehicle_special_price = VehicleSpecialPrice::with('vehicle_type')->find($id); + if (!$vehicle_special_price) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($vehicle_special_price, (new VehicleSpecialPriceTransformer)->setDefaultIncludes(array('vehicle_type'))); + } + + /** + * Edit the specified vehicle_special_price. + * Edit the vehicle_special_price with a `id`. + * @Get("/vehicle_special_prices/{id}/edit") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body= {"id": 1, "vehicle_type_id": 1, "minimum_no_of_day": 1, "maximum_no_of_day": 1, "discount_percentage": 1, "is_active": 1, "vehicle_type": {}}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function show($id) + { + $vehicle_special_price = VehicleSpecialPrice::with('vehicle_type')->find($id); + if (!$vehicle_special_price) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($vehicle_special_price, (new VehicleSpecialPriceTransformer)->setDefaultIncludes(array('vehicle_type'))); + } + +} diff --git a/app/Plugins/Vehicles/Controllers/VehicleTypePricesController.php b/app/Plugins/Vehicles/Controllers/VehicleTypePricesController.php new file mode 100644 index 0000000..f0c5f8e --- /dev/null +++ b/app/Plugins/Vehicles/Controllers/VehicleTypePricesController.php @@ -0,0 +1,96 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Vehicles\Controllers; + +use Illuminate\Http\Request; +use App\Http\Controllers\Controller; +use Plugins\Vehicles\Model\VehicleTypePrice; +use JWTAuth; +use Validator; +use Plugins\Vehicles\Transformers\VehicleTypePriceTransformer; + +/** + * VehiclePrices resource representation. + * @Resource("VehiclePrices") + */ +class VehicleTypePricesController extends Controller +{ + /** + * VehiclePricesController constructor. + */ + public function __construct() + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth'); + } + + /** + * Show all prices + * Get a JSON representation of all the prices. + * + * @Get("/vehicle_type_prices?sort={sort}&sortby={sortby}&page={page}&q={q}") + * @Parameters({ + * @Parameter("sort", type="string", required=false, description="Sort the prices list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort prices by Ascending / Descending Order.", default=null), + * @Parameter("q", type="string", required=false, description="Search VehiclePrices.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1) + * }) + */ + public function index(Request $request) + { + $vehicle_type_prices = VehicleTypePrice::with('vehicle_type')->filterByRequest($request)->paginate(config('constants.ConstPageLimit')); + return $this->response->paginator($vehicle_type_prices, (new VehicleTypePriceTransformer)->setDefaultIncludes(array('vehicle_type'))); + } + + /** + * Edit the specified vehicle_type_price. + * Edit the vehicle_type_price with a `id`. + * @Get("/vehicle_type_prices/{id}/edit") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body= {"id": 1, "vehicle_type_id": 1, "price_id": 1, "discount_type_id": 1, "duration_type_id": 1, "rate": 200, "max_allowed_amount": 1000, "vehicle_type": {}, "vehicle_price": {}, "duration_type": {}, "discount_type": {}}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function edit($id) + { + $vehicle_type_price = VehicleTypePrice::with('vehicle_type')->find($id); + if (!$vehicle_type_price) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($vehicle_type_price, (new VehicleTypePriceTransformer)->setDefaultIncludes(array('vehicle_type'))); + } + + /** + * Edit the specified vehicle_type_price. + * Edit the vehicle_type_price with a `id`. + * @Get("/vehicle_type_prices/{id}/edit") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body= {"id": 1, "vehicle_type_id": 1, "minimum_no_of_day": 1, "maximum_no_of_day": 1, "discount_percentage": 1, "is_active": 1, "vehicle_type": {}}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function show($id) + { + $vehicle_type_price = VehicleTypePrice::with('vehicle_type')->find($id); + if (!$vehicle_type_price) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($vehicle_type_price, (new VehicleTypePriceTransformer)->setDefaultIncludes(array('vehicle_type'))); + } + +} diff --git a/app/Plugins/Vehicles/Controllers/VehicleTypesController.php b/app/Plugins/Vehicles/Controllers/VehicleTypesController.php new file mode 100644 index 0000000..a7adf36 --- /dev/null +++ b/app/Plugins/Vehicles/Controllers/VehicleTypesController.php @@ -0,0 +1,79 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Vehicles\Controllers; + + +use Illuminate\Http\Request; +use App\Http\Requests; +use App\Http\Controllers\Controller; +use Plugins\Vehicles\Model\VehicleType; +use JWTAuth; +use Validator; +use Plugins\Vehicles\Transformers\VehicleTypeTransformer; + +/** + * Class VehicleTypesController + * @package Plugins\Vehicles\Controllers + */ +class VehicleTypesController extends Controller +{ + + /** + * Show all vehicle types. + * Get a JSON representation of all the vehicle types. + * + * @Get("/vehicle_types?filter={filter}&sort={sort}&sortby={sortby}&q={q}") + * @Parameters({ + * @Parameter("filter", type="integer", required=false, description="Filter the vehicle types list by status.", default=null), + * @Parameter("sort", type="string", required=false, description="Sort the vehicle types list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort vehicle types by Ascending / Descending Order.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1) + * }) + */ + public function index(Request $request) + { + $vehicle_type_count = config('constants.ConstPageLimit'); + if ($request->has('type') && $request->type == 'list') { + $vehicle_type_count = VehicleType::count(); + } + $vehicle_types = VehicleType::filterByRequest($request)->paginate($vehicle_type_count); + return $this->response->paginator($vehicle_types, new VehicleTypeTransformer); + } + + /** + * Show the specified vehicle. + * Show the vehicle_types with a `id`. + * @Get("/vehicle_types/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"id": 1}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function show($id) + { + $enabled_includes = array(); + (isPluginEnabled('VehicleExtraAccessories')) ? $enabled_includes[] = 'vehicle_type_extra_accessory' : ''; + (isPluginEnabled('VehicleInsurances')) ? $enabled_includes[] = 'vehicle_type_insurance' : ''; + (isPluginEnabled('VehicleFuelOptions')) ? $enabled_includes[] = 'vehicle_type_fuel_option' : ''; + $vehicle_type = VehicleType::with($enabled_includes)->find($id); + if (!$vehicle_type) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($vehicle_type, (new VehicleTypeTransformer)->setDefaultIncludes($enabled_includes)); + } + +} diff --git a/app/Plugins/Vehicles/Controllers/VehiclesController.php b/app/Plugins/Vehicles/Controllers/VehiclesController.php new file mode 100644 index 0000000..1cfcb5c --- /dev/null +++ b/app/Plugins/Vehicles/Controllers/VehiclesController.php @@ -0,0 +1,571 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Vehicles\Controllers; + + +use Carbon; +use Illuminate\Http\Request; +use App\Http\Requests; +use App\Http\Controllers\Controller; +use Plugins\Vehicles\Model\Vehicle; +use Plugins\Vehicles\Model\VehicleMake; +use Plugins\Vehicles\Model\VehicleModel; +use JWTAuth; +use Validator; +use Plugins\Vehicles\Transformers\VehicleTransformer; +use Plugins\Vehicles\Services\VehicleService; +use Plugins\Vehicles\Services\VehicleCompanyService; +use Plugins\Vehicles\Services\VehicleMakeService; +use Plugins\Vehicles\Services\VehicleModelService; +use Plugins\Vehicles\Services\VehicleTypeService; +use Plugins\Vehicles\Services\CounterLocationService; +use Plugins\Vehicles\Services\FuelTypeService; +use EasySlug\EasySlug\EasySlugFacade as EasySlug; +use File; +use Image; +use App\Attachment; +use App\User; + +/** + * Class VehiclesController + * @package Plugins\Vehicles\Controllers + */ +class VehiclesController extends Controller +{ + /** + * @var + */ + protected $vehicleService; + + /** + * @var $vehicleCompanyService + */ + protected $vehicleCompanyService; + /** + * @var $vehicleMakeService + */ + protected $vehicleMakeService; + /** + * @var $vehicleModelService + */ + protected $vehicleModelService; + /** + * @var $vehicleTypeService + */ + protected $vehicleTypeService; + /** + * @var $counterLocationService + */ + protected $counterLocationService; + + /** + * @var $fuelTypeService + */ + protected $fuelTypeService; + + /** + * VehiclesController constructor. + */ + public function __construct() + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth', ['except' => ['search', 'getVehicleRelatedFilters', 'show']]); + $this->setVehicleService(); + $this->setVehicleCompanyService(); + $this->setVehicleMakeService(); + $this->setVehicleModelService(); + $this->setVehicleTypeService(); + $this->setCounterLocationService(); + $this->setFuelTypeService(); + } + + /** + * setVehicleService + */ + public function setVehicleService() + { + $this->vehicleService = new VehicleService(); + } + + public function setVehicleCompanyService() + { + $this->vehicleCompanyService = new VehicleCompanyService(); + } + + public function setVehicleMakeService() + { + $this->vehicleMakeService = new VehicleMakeService(); + } + + public function setVehicleModelService() + { + $this->vehicleModelService = new VehicleModelService(); + } + + public function setVehicleTypeService() + { + $this->vehicleTypeService = new VehicleTypeService(); + } + + public function setCounterLocationService() + { + $this->counterLocationService = new CounterLocationService(); + } + + public function setFuelTypeService() + { + $this->fuelTypeService = new FuelTypeService(); + } + + /** + * Show all vehicles. + * Get a JSON representation of all the vehicles. + * + * @Get("/vehicles?filter={filter}&sort={sort}&sortby={sortby}&q={q}") + * @Parameters({ + * @Parameter("filter", type="integer", required=false, description="Filter the vehicles list by status.", default=null), + * @Parameter("sort", type="string", required=false, description="Sort the vehicles list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort vehicles by Ascending / Descending Order.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1) + * }) + */ + public function search(Request $request) + { + if($request->has('start_date') && $request->has('end_date')) { + $current_date = strtotime(Carbon::now()->toDateTimeString()); + $request->start_date = date("Y-m-d H:i:s", strtotime($request->start_date)); + $request->end_date = date("Y-m-d H:i:s", strtotime($request->end_date)); + $start_date = strtotime($request->start_date); + $end_date = strtotime($request->end_date); + if ($start_date <= $current_date) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Start Date should be greater than current date'); + } + if ($end_date < $start_date) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('End Date should be greater than start date'); + } + } + $enabled_includes = array('vehicle_type', 'fuel_type', 'counter_location', 'vehicle_company', 'vehicle_make', 'vehicle_model', 'attachments', 'user'); + $vehicles = Vehicle::with($enabled_includes)->filterByRequest($request)->filterActiveVehicle($request)->paginate(config('constants.ConstPageLimit')); + if($request->has('start_date') && $request->has('end_date')) { + $vehicles = $this->vehicleService->getDiscountRate($vehicles, $request->start_date, $request->end_date); + $request_data = $request->only('start_date', 'end_date', 'pickup_location_id', 'drop_location_id', 'price_min', 'price_max', 'sort', 'sortby', 'mileage_min', 'mileage_max', 'seat_min', 'seat_max', 'vehicle_type', 'is_manual_transmission', 'fuel_type', 'ac', 'non_ac', 'auto_transmission', 'airbag', 'non_airbag'); + $res = $this->response->paginator($vehicles, (new VehicleTransformer)->setDefaultIncludes($enabled_includes)); + $res->addMeta('request', $request_data); + $res->addMeta('booking_details', $vehicles->booking_details); + } else { + $request_data = $request->only('price_min', 'price_max', 'sort', 'sortby', 'mileage_min', 'mileage_max', 'seat_min', 'seat_max', 'vehicle_type', 'is_manual_transmission', 'fuel_type', 'ac', 'non_ac', 'auto_transmission', 'airbag', 'non_airbag'); + $res = $this->response->paginator($vehicles, (new VehicleTransformer)->setDefaultIncludes($enabled_includes)); + $res->addMeta('request', $request_data); + } + return $res; + } + + /** + * Show own all vehicles. + * Get a JSON representation of own all the vehicles. + * + * @Get("/vehicles/me?filter={filter}&sort={sort}&sortby={sortby}&q={q}") + * @Parameters({ + * @Parameter("filter", type="integer", required=false, description="Filter the vehicles list by status.", default=null), + * @Parameter("sort", type="string", required=false, description="Sort the vehicles list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort vehicles by Ascending / Descending Order.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1) + * }) + */ + public function index(Request $request) + { + $user = $this->auth->user(); + $enabled_includes = array('vehicle_type', 'fuel_type', 'counter_location', 'vehicle_company', 'vehicle_make', 'vehicle_model', 'attachments'); + $vehicles = Vehicle::with($enabled_includes)->filterByRequest($request)->filterByMyVehicle($request, $user->id)->paginate(config('constants.ConstPageLimit')); + return $this->response->paginator($vehicles, (new VehicleTransformer)->setDefaultIncludes($enabled_includes)); + } + + /** + * Store a new vehicle. + * Store a new vehicle with a 'amount', 'user_id', 'name', 'booking_type_id', 'description'. + * @Post("/vehicles") + * @Transaction({ + * @Request({"amount": 1000, "user_id": 1, "name": "house for rent", "booking_type_id": 1, "description": "This house is for rent"}), + * @Response(200, body={"success": "Record has been added."}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {"amount": {}}, "status_code": 422}) + * }) + */ + public function store(Request $request) + { + $vehicle_data = $request->only('vehicle_make_id', 'vehicle_model_id', 'vehicle_type_id', 'pickup_counter_locations', 'drop_counter_locations', 'driven_kilometer', 'vehicle_no', 'no_of_seats', 'no_of_doors', 'no_of_gears', 'is_manual_transmission', 'no_small_bags', 'no_large_bags', 'is_ac', 'minimum_age_of_driver', 'mileage', 'is_km', 'is_airbag', 'no_of_airbags', 'is_abs', 'per_hour_amount', 'per_day_amount', 'fuel_type_id', 'feedback_count'); + $user = $this->auth->user(); + $user = User::with('vehicle_company')->where('id', $user->id)->first(); + if (!$user || !$user->vehicle_company) { + return $this->response->errorNotFound("Invalid Request"); + } + $vehicle_data['is_active'] = (config('vehicle.auto_approve')) ? true : false; + $vehicle_data['is_paid'] = (config('vehicle.listing_fee') == 0) ? true : false; + $vehicle_data['user_id'] = $user->id; + $vehicle_data['vehicle_company_id'] = $user->vehicle_company->id; + $vehicle_make = VehicleMake::where('id', $request->vehicle_make_id)->first(); + $vehicle_model = VehicleModel::where('id', $request->vehicle_model_id)->first(); + $vehicle_data['name'] = $vehicle_make->name . ':' . $vehicle_model->name; + $vehicle_data['slug'] = EasySlug::generateUniqueSlug($vehicle_data['name'], 'vehicles'); + $validator = Validator::make($vehicle_data, Vehicle::GetValidationRule(), Vehicle::GetValidationMessage()); + if ($validator->passes() && ($request->hasFile('file') && $request->file('file')->isValid())) { + try { + $vehicle = Vehicle::create($vehicle_data); + if (!empty($vehicle->id)) { + $vehicle_data['name'] = $vehicle_make->name . ':' . $vehicle_model->name.' #'.$vehicle->id; + $vehicle_data['slug'] = EasySlug::generateUniqueSlug($vehicle_data['name'], 'vehicles'); + $vehicle->update($vehicle_data); + // afterSave count updatae & dummy record put + $this->vehicleService->afterSave($vehicle); + if (!empty($request->pickup_counter_locations) || !empty($request->drop_counter_locations)) { + $common_loctions = array_intersect($request->pickup_counter_locations, $request->drop_counter_locations); + $diff_in_pickup = array_diff($request->pickup_counter_locations, $request->drop_counter_locations); + $diff_in_drop = array_diff($request->drop_counter_locations, $request->pickup_counter_locations); + if ($common_loctions) { + foreach ($common_loctions as $key => $value) { + $vehicle->counter_location()->attach([$value => ['is_pickup' => 1, 'is_drop' => 1]]); + } + } + if ($diff_in_pickup) { + foreach ($diff_in_pickup as $key => $value) { + $vehicle->counter_location()->attach([$value => ['is_pickup' => 1, 'is_drop' => 0]]); + } + } + if ($diff_in_drop) { + foreach ($diff_in_drop as $key => $value) { + $vehicle->counter_location()->attach([$value => ['is_pickup' => 0, 'is_drop' => 1]]); + } + } + } + if ($request->hasFile('file')) { + $path = storage_path('app/Vehicle/' . $vehicle->id . '/'); + if (!File::isDirectory($path)) { + File::makeDirectory($path, 0777, true); + } + $img = Image::make($_FILES['file']['tmp_name']); + $path = storage_path('app/Vehicle/' . $vehicle->id . '/' . $_FILES['file']['name']); + if ($img->save($path)) { + $attachment = array(); + $attachment['filename'] = $_FILES['file']['name']; + $attachment['dir'] = 'app/Vehicle/' . $vehicle->id . '/'; + $attachment['mimetype'] = $request->file('file')->getClientMimeType(); + $attachment['filesize'] = $request->file('file')->getClientSize(); + $att = Attachment::create($attachment); + $curuser = Vehicle::with(['attachments'])->where('id', '=', $vehicle->id)->first(); + $curuser->attachments()->save($att); + } + } + } + if ($vehicle) { + return response()->json(['Success' => 'Vehicle has been added', 'id' => $vehicle->id], 200); + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Vehicle could not be added. Please, try again.'); + } + } catch (\Exception $e) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Vehicle could not be added. Please, try again.', + array($e->getMessage())); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Vehicle could not be added. Please, try again.', $validator->errors()); + } + } + + /** + * Edit the specified vehicle. + * Edit the vehicle with a `id`. + * @Get("/vehicles/{id}/edit") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"id": 1}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function edit($id) + { + $enabled_includes = array('counter_location', 'vehicle_make', 'vehicle_model', 'vehicle_type', 'vehicle_company', 'fuel_type', 'attachments'); + $vehicle = Vehicle::with($enabled_includes)->find($id); + if (!$vehicle) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($vehicle, (new VehicleTransformer)->setDefaultIncludes($enabled_includes)); + } + + /** + * Update the specified vehicle. + * Update the vehicle with a `id`. + * @Put("/vehicles/{id}") + * @Transaction({ + * @Response(200, body={"success": "Record has been updated."}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {}, "status_code": 422}) + * }) + */ + public function update(Request $request, $id) + { + $user = $this->auth->user(); + $vehicle_data = $request->only('id', 'vehicle_make_id', 'vehicle_model_id', 'vehicle_type_id', 'driven_kilometer', 'vehicle_no', 'no_of_seats', 'no_of_doors', 'no_of_gears', 'is_manual_transmission', 'no_small_bags', 'no_large_bags', 'is_ac', 'minimum_age_of_driver', 'mileage', 'is_km', 'is_airbag', 'no_of_airbags', 'is_abs', 'per_hour_amount', 'per_day_amount', 'fuel_type_id', 'feedback_count'); + $vehicle = false; + $valid_user = false; + if ($request->has('id')) { + $vehicle = Vehicle::find($id); + $vehicle = ($request->id != $id) ? false : $vehicle; + $valid_user = ($vehicle->user_id != $user->id) ? false : true; + } + $validator = Validator::make($vehicle_data, Vehicle::GetValidationRule(), Vehicle::GetValidationMessage()); + if ($validator->passes() && $vehicle && $valid_user && (($request->hasFile('file') && $request->file('file')->isValid()) || (!$request->hasFile('file')))) { + try { + $user = User::with('vehicle_company')->where('id', $user->id)->first(); + $vehicle_data['user_id'] = $user->id; + $vehicle_data['vehicle_company_id'] = $user->vehicle_company->id; + $vehicle_make = VehicleMake::where('id', $request->vehicle_make_id)->first(); + $vehicle_model = VehicleModel::where('id', $request->vehicle_model_id)->first(); + $vehicle_data['name'] = $vehicle_make->name . ':' . $vehicle_model->name. '#'.$vehicle->id; + $vehicle_data['slug'] = EasySlug::generateUniqueSlug($vehicle_data['name'], 'vehicles'); + $vehicle->update($vehicle_data); + // afterSave count updatae & dummy record put + $this->vehicleService->afterSave($vehicle); + if (!empty($request->pickup_counter_locations) || !empty($request->drop_counter_locations)) { + $common_loctions = array_intersect($request->pickup_counter_locations, $request->drop_counter_locations); + $diff_in_pickup = array_diff($request->pickup_counter_locations, $request->drop_counter_locations); + $diff_in_drop = array_diff($request->drop_counter_locations, $request->pickup_counter_locations); + $vehicle->counter_location()->detach(); + if ($common_loctions) { + foreach ($common_loctions as $key => $value) { + $vehicle->counter_location()->attach([$value => ['is_pickup' => 1, 'is_drop' => 1]]); + } + } + if ($diff_in_pickup) { + foreach ($diff_in_pickup as $key => $value) { + $vehicle->counter_location()->attach([$value => ['is_pickup' => 1, 'is_drop' => 0]]); + } + } + if ($diff_in_drop) { + foreach ($diff_in_drop as $key => $value) { + $vehicle->counter_location()->attach([$value => ['is_pickup' => 0, 'is_drop' => 1]]); + } + } + } + if ($request->hasFile('file')) { + $path = storage_path('app/Vehicle/' . $vehicle->id . '/'); + if (!File::isDirectory($path)) { + File::makeDirectory($path, 0777, true); + } + $img = Image::make($_FILES['file']['tmp_name']); + $path = storage_path('app/Vehicle/' . $vehicle->id . '/' . $_FILES['file']['name']); + if ($img->save($path)) { + $curVehicle = Vehicle::with(['attachments'])->where('id', '=', $vehicle->id)->first(); + $attachment = array(); + $attachment['filename'] = $_FILES['file']['name']; + $attachment['dir'] = 'app/Vehicle/' . $vehicle->id . '/'; + $attachment['mimetype'] = $request->file('file')->getClientMimeType(); + $attachment['filesize'] = $request->file('file')->getClientSize(); + if ($curVehicle->attachments) { + $curVehicle->attachments()->update($attachment); + } else { + $att = Attachment::create($attachment); + $curVehicle = Vehicle::with(['attachments'])->where('id', '=', $vehicle->id)->first(); + $curVehicle->attachments()->save($att); + } + } + } + return response()->json(['Success' => 'Vehicle has been updated'], 200); + } catch (\Exception $e) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Vehicle could not be updated. Please, try again.', + array($e->getMessage())); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Vehicle could not be updated. Please, try again.', $validator->errors()); + } + } + + /** + * Delete the specified vehicle. + * Delete the vehicle with a `id`. + * @Delete("/vehicles/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"success": "Record Deleted."}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function destroy($id) + { + $vehicle = Vehicle::find($id); + if (!$vehicle) { + return $this->response->errorNotFound("Invalid Request"); + } else { + $vehicle->delete(); + } + return response()->json(['Success' => 'Vehicle deleted'], 200); + } + + /** + * Show the specified vehicle. + * Show the vehicle with a `id`. + * @Get("/vehicles/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"id": 1}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function show($id) + { + $enabled_includes = array('counter_location', 'vehicle_make', 'vehicle_model', 'vehicle_type', 'vehicle_company', 'fuel_type', 'attachments', 'user'); + $vehicle = Vehicle::with($enabled_includes)->find($id); + if (!$vehicle) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($vehicle, (new VehicleTransformer)->setDefaultIncludes($enabled_includes)); + } + + public function getVehicleRelatedDetail() + { + $vehicle_company_list = $this->vehicleCompanyService->getVehicleCompanyList(); + $vehicle_make_list = $this->vehicleMakeService->getVehicleMakeList(); + $vehicle_model_list = $this->vehicleModelService->getVehicleModelList(); + $vehicle_type_list = $this->vehicleTypeService->getVehicleTypeList(); + $counter_location_list = $this->counterLocationService->getCounterLocationList(); + $fuel_type_list = $this->fuelTypeService->getFuelTypeList(); + $settings = array(); + $settings['seats'] = config('vehicle.no_of_seats'); + $settings['doors'] = config('vehicle.no_of_doors'); + $settings['gears'] = config('vehicle.no_of_gears'); + $settings['small_bags'] = config('vehicle.no_small_bags'); + $settings['large_bags'] = config('vehicle.no_large_bags'); + $settings['airbags'] = config('vehicle.no_of_airbags'); + return response()->json(compact('vehicle_company_list', 'vehicle_make_list', 'vehicle_model_list', 'vehicle_type_list', 'counter_location_list', 'fuel_type_list', 'settings')); + } + + public function getVehicleRelatedFilters() + { + $vehicle_company_list = $this->vehicleCompanyService->getVehicleCompanyList(); + $vehicle_type_list = $this->vehicleTypeService->getVehicleTypeList(); + $vehicle_type_price = $this->vehicleTypeService->getVehicleTypePriceFilters(); + $counter_location_list = $this->counterLocationService->getCounterLocationList(); + $fuel_type_list = $this->fuelTypeService->getFuelTypeList(); + $settings = array(); + $settings['seats'] = config('vehicle.no_of_seats'); + $settings['doors'] = config('vehicle.no_of_doors'); + $settings['gears'] = config('vehicle.no_of_gears'); + $settings['small_bags'] = config('vehicle.no_small_bags'); + $settings['large_bags'] = config('vehicle.no_large_bags'); + $settings['airbags'] = config('vehicle.no_of_airbags'); + return response()->json(compact('vehicle_company_list', 'vehicle_type_list', 'counter_location_list', 'fuel_type_list', 'settings', 'vehicle_type_price')); + } + + /** + * @param Request $request + * @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response + */ + public function payNow(Request $request) + { + $user = $this->auth->user(); + $listing_fee = config('vehicle.listing_fee'); + if ($request->has('vehicle_id')) { + $vehicle = Vehicle::where('id', $request->vehicle_id)->first(); + if ($vehicle->is_paid == 1) { + return response()->json(['Success' => 'Already you have paid listing fee'], 200); + } else if ($listing_fee == 0) { + $vehicle->update(['is_paid' => 1]); + return response()->json(['Success' => 'No vehicle listing fee'], 200); + } + } else { + return $this->response->errorNotFound("Invalid Request"); + } + if ($request->has('gateway_id') && ((isPluginEnabled('Paypal') && $request->gateway_id == config('constants.ConstPaymentGateways.PayPal')) || (isPluginEnabled('Sudopays') && $request->gateway_id == config('constants.ConstPaymentGateways.SudoPay')) || ($request->gateway_id == config('constants.ConstPaymentGateways.Wallet')))) { + $data['amount'] = $listing_fee; + if ($request->gateway_id == config('constants.ConstPaymentGateways.PayPal')) { + $paypalLogService = new \Plugins\Paypal\Services\PaypalTransactionLogService(); + $paypalService = new \Plugins\Paypal\Services\PayPalService(); + $vehicle = Vehicle::with('paypal_transaction_log')->where('id', $request->vehicle_id)->first(); + if (!$vehicle) { + return $this->response->errorNotFound("Invalid Request"); + } + // Already user have try and not paid case + if (!is_null($vehicle->paypal_transaction_log)) { + $paypalLogService->updateLogById($data, $vehicle->paypal_transaction_log->id); + $paypal_transaction = $vehicle->paypal_transaction_log; + } else { + $paypal_transaction = $paypalLogService->log($data); + $vehicle = Vehicle::with('paypal_transaction_log')->where('id', $request->vehicle_id)->first(); + $vehicle->paypal_transaction_log()->save($paypal_transaction); + } + $response = $paypalService->createPayment($paypal_transaction->id, config('constants.ConstPaypalGatewaysProcess.sale')); + return response()->json(['url' => $response], 200); + } elseif ($request->gateway_id == config('constants.ConstPaymentGateways.SudoPay')) { + $sudopay_data = array('address', 'city', 'country', 'email', 'gateway_id', 'payment_id', 'phone', 'state', 'zip_code'); + if ($request->has('credit_card_code')) { + $sudopay_data = array_merge($sudopay_data, array('credit_card_code', 'credit_card_expire', 'credit_card_name_on_card', 'credit_card_number')); + } + if ($request->has('payment_note')) { + $sudopay_data = array_merge($sudopay_data, array('payment_note')); + } + $sudopay_data = $request->only($sudopay_data); + $log_data['amount'] = $listing_fee; + $log_data['gateway_id'] = $request['payment_id']; + $this->logtService = new \Plugins\Sudopays\Services\SudopayTransactionLogService(); + $this->paymentService = new \Plugins\Sudopays\Services\SudopayService(); + $cur_vehicle = Vehicle::with(['sudopay_transaction_logs'])->where('id', '=', $request->vehicle_id)->first(); + if (is_null(!$cur_vehicle)) { + return $this->response->errorNotFound("Invalid Request"); + } + // Already user have try and not paid case + if (!is_null($cur_vehicle->sudopay_transaction_logs)) { + $this->logtService->updateLogById($log_data, $cur_vehicle->sudopay_transaction_logs->id); + $cur_transaction = $cur_vehicle->sudopay_transaction_logs; + } else { + $cur_transaction = $this->logtService->log($log_data); + $cur_vehicle_rental = Vehicle::with('sudopay_transaction_logs')->where('id', $request->vehicle_id)->first(); + $cur_vehicle_rental->sudopay_transaction_logs()->save($cur_transaction); + } + $response = $this->paymentService->createPayment($cur_transaction->id, $sudopay_data); + if (!empty($response['gateway_callback_url'])) { + return response()->json(['url' => $response['gateway_callback_url']], 200); + } + if (!empty($response['pending'])) { + return response()->json(['Success' => 'Once payment is received, it will be processed'], 200); + } elseif (!empty($response['success'])) { + return response()->json(['Success' => 'Vehicle listing fee paid successfully'], 200); + } elseif (!empty($response['error'])) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Payment gateway could not be set. Please, try again.'); + } + } elseif ($request->gateway_id == config('constants.ConstPaymentGateways.Wallet')) { + $walletLogService = new \App\Services\WalletTransactionLogService(); + $walletService = new \App\Services\WalletService(); + $wallet_vehicle = Vehicle::with('wallet_transaction_log')->where('id', $request->vehicle_id)->first(); + if (!$wallet_vehicle) { + return $this->response->errorNotFound("Invalid Request"); + } + $data['amount'] = $listing_fee; + // Already user have try and not paid case + if (is_null($wallet_vehicle->wallet_transaction_log)) { + $wallet_log = $walletLogService->log($data); + $wallet_vehicle = Vehicle::with('wallet_transaction_log')->where('id', $request->vehicle_id)->first(); + $wallet_vehicle->wallet_transaction_log()->save($wallet_log); + } else { + $walletLogService->updateLogById($data, $wallet_vehicle->wallet_transaction_log->id); + $wallet_log = $wallet_vehicle->wallet_transaction_log; + } + $response = $walletService->createPayment($wallet_log->id); + if ($response) { + $walletService->executePayment($wallet_vehicle, 'MorphVehicle', $wallet_log->id); + return response()->json(['data' => 'wallet'], 200); + } + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Payment gateway could not be set. Please, try again.'); + } + } +} diff --git a/app/Plugins/Vehicles/Model/CounterLocation.php b/app/Plugins/Vehicles/Model/CounterLocation.php new file mode 100644 index 0000000..59f740e --- /dev/null +++ b/app/Plugins/Vehicles/Model/CounterLocation.php @@ -0,0 +1,94 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Vehicles\Model; + +use Illuminate\Http\Request; +use Illuminate\Database\Eloquent\Model; + +/** + * Class CounterLocation + * @package Plugins\Vehicles\Model + */ +class CounterLocation extends Model +{ + /** + * @var string + */ + protected $table = "counter_locations"; + /** + * The attributes that are mass assignable. + * @var array + */ + protected $fillable = [ + 'address', 'latitude', 'longitude', 'fax', 'phone', 'mobile', 'email' + ]; + + /** + * @return mixed + */ + public function vehicle() + { + return $this->belongsToMany(Vehicle::class); + } + + /** + * @param $query + * @param Request $request + * @return mixed + */ + public function scopeFilterByRequest($query, Request $request) + { + $query->orderBy($request->input('sort', 'id'), $request->input('sortby', 'desc')); + if ($request->has('q')) { + $query->where('address', 'LIKE', '%' . $request->input('q') . '%') + ->orWhere('mobile', 'LIKE', '%' . $request->input('q') . '%') + ->orWhere('email', 'LIKE', '%' . $request->input('q') . '%'); + } + if ($request->has('vehicle_id')) { + $query->whereHas('vehicle', function ($q) use ($request) { + $q->where('vehicle_id', $request->input('vehicle_id')); + }); + } + return $query; + } + + /** + * @return array + */ + public function scopeGetValidationRule() + { + return [ + 'address' => 'required|min:5|unique:counter_locations', + 'mobile' => 'required', + 'email' => 'required|email' + ]; + } + + /** + * @return array + */ + public function scopeGetValidationMessage() + { + return [ + 'address.required' => 'Required', + 'address.min' => 'address - minimum length is 5!', + 'address.unique' => 'address - already exists!', + 'mobile.required' => 'Required', + 'email.required' => 'Required', + 'email.email' => 'Enter valid e-mail address!' + ]; + } +} \ No newline at end of file diff --git a/app/Plugins/Vehicles/Model/FuelType.php b/app/Plugins/Vehicles/Model/FuelType.php new file mode 100644 index 0000000..27f4792 --- /dev/null +++ b/app/Plugins/Vehicles/Model/FuelType.php @@ -0,0 +1,47 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Vehicles\Model; + +use Illuminate\Http\Request; +use Illuminate\Database\Eloquent\Model; + + +/** + * Class FuelType + * @package Plugins\Vehicles\Model + */ +class FuelType extends Model +{ + /** + * @var string + */ + protected $table = "fuel_types"; + /** + * The attributes that are mass assignable. + * @var array + */ + protected $fillable = [ + 'name' + ]; + + /** + * @return \Illuminate\Database\Eloquent\Relations\HasMany + */ + public function vehicle() + { + return $this->hasMany(Vehicle::class); + } +} diff --git a/app/Plugins/Vehicles/Model/UnavailableVehicle.php b/app/Plugins/Vehicles/Model/UnavailableVehicle.php new file mode 100644 index 0000000..0ec2480 --- /dev/null +++ b/app/Plugins/Vehicles/Model/UnavailableVehicle.php @@ -0,0 +1,113 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Vehicles\Model; + +use Illuminate\Http\Request; +use Illuminate\Database\Eloquent\Model; +use Plugins\Vehicles\Model\Vehicle; + +/** + * Class VehicleCompany + * @package Plugins\Vehicles\Model + */ +class UnavailableVehicle extends Model +{ + /** + * @var string + */ + protected $table = "unavailable_vehicles"; + + /** + * The attributes that are mass assignable. + * @var array + */ + protected $fillable = [ + 'item_user_id', 'vehicle_id', 'start_date', 'end_date', 'is_dummy' + ]; + + /** + * @return mixed + */ + public function vehicle() + { + return $this->belongsTo(Vehicle::class, 'vehicle_id'); + } + + public function scopeFilterByMyVehicle($query, $user_id = null) + { + if (!is_null($user_id)) { + $query->WhereHas('vehicle', function ($query) use ($user_id) { + $query->where('user_id', $user_id); + }); + } + } + + public function scopeFilterByRequest($query, Request $request) + { + $query->orderBy($request->input('sort', 'id'), $request->input('sortby', 'desc')); + // maintance record only + $query->where('is_dummy', 2); + // query to filter pickup counter location id + if ($request->has('vehicle_id')) { + $query->where('vehicle_id', $request->vehicle_id); + } + if ($request->has('q')) { + $query->whereHas('vehicle', function ($q) use ($request) { + $q->where('name', 'like', '%' . $request->input('q') . '%'); + }); + } + if($request->has('start_date') && $request->has('end_date')) { + $query->whereBetween('start_date', array($request->start_date, $request->end_date)); + $query->orWhereBetween('end_date', array($request->start_date, $request->end_date)); + }else if($request->has('start_date')){ + $query->where('start_date','>=', $request->start_date); + }else if($request->has('end_date')){ + $query->where('end_date', '<=', $request->end_date); + } + + return $query; + } + + /** + * @return array + */ + public function scopeGetValidationRule() + { + return [ + 'vehicle_id' => 'sometimes|required|integer|exists:vehicles,id', + 'start_date' => 'required|date|date_format:Y-m-d H:i:s', + 'end_date' => 'required|date|date_format:Y-m-d H:i:s', + ]; + } + + /** + * @return array + */ + public function scopeGetValidationMessage() + { + return [ + 'vehicle_id.required' => 'Required', + 'vehicle_id.integer' => 'vehicle_id must be a number', + 'vehicle_id.exists' => 'Invalid vehicle id', + 'start_date.required' => 'Required', + 'start_date.date' => 'Start date should be a date!', + 'start_date.date_format' => 'Date should be in Y-m-d H:i:s format', + 'end_date.required' => 'Required', + 'end_date.date' => 'End date should be a date!', + 'end_date.date_format' => 'Date should be in Y-m-d H:i:s format' + ]; + } +} diff --git a/app/Plugins/Vehicles/Model/Vehicle.php b/app/Plugins/Vehicles/Model/Vehicle.php new file mode 100644 index 0000000..d163179 --- /dev/null +++ b/app/Plugins/Vehicles/Model/Vehicle.php @@ -0,0 +1,411 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Vehicles\Model; + +use Illuminate\Http\Request; +use Illuminate\Database\Eloquent\Model; +use App\User; + +/** + * Class Vehicle + * @package Plugins\Vehicles\Model + */ +class Vehicle extends Model +{ + /** + * @var string + */ + protected $table = "vehicles"; + /** + * The attributes that are mass assignable. + * @var array + */ + protected $fillable = [ + 'name', 'slug', 'user_id', 'vehicle_company_id', 'vehicle_make_id', 'vehicle_model_id', 'vehicle_type_id', 'driven_kilometer', 'vehicle_no', 'no_of_seats', 'no_of_doors', 'no_of_gears', 'is_manual_transmission', 'no_small_bags', 'no_large_bags', 'is_ac', 'minimum_age_of_driver', 'mileage', 'is_km', 'is_airbag', 'no_of_airbags', 'is_abs', 'per_hour_amount', 'per_day_amount', 'fuel_type_id', 'vehicle_rental_count', 'feedback_count', 'is_active', 'feedback_rating' + ]; + + /** + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function user() + { + return $this->belongsTo(User::class); + } + + /** + * Get all of the vehicle's bookings . + */ + public function vehicle_rentals() + { + return $this->morphMany(\Plugins\VehicleRentals\Model\VehicleRental::class, 'item_userable'); + } + + /** + * @return mixed + */ + public function vehicle_make() + { + return $this->belongsTo(VehicleMake::class); + } + + /** + * @return mixed + */ + public function vehicle_model() + { + return $this->belongsTo(VehicleModel::class); + } + + + /** + * @return mixed + */ + public function vehicle_type() + { + return $this->belongsTo(VehicleType::class); + } + + /** + * @return mixed + */ + public function vehicle_company() + { + return $this->belongsTo(VehicleCompany::class); + } + + /** + * @return mixed + */ + public function fuel_type() + { + return $this->belongsTo(FuelType::class, 'fuel_type_id'); + } + + /** + * @return mixed + */ + public function unavailable_vehicle() + { + return $this->hasMany(UnavailableVehicle::class); + } + + /** + * @return mixed + */ + public function counter_location() + { + return $this->belongsToMany(CounterLocation::class) + ->withPivot('is_pickup', 'is_drop') + ->withTimestamps(); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\MorphMany + */ + public function vehicle_coupons() + { + return $this->morphMany(\Plugins\VehicleCoupons\Model\VehicleCoupon::class, 'couponable'); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\MorphOne + */ + public function attachments() + { + return $this->morphOne(\App\Attachment::class, 'attachmentable'); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\MorphOne + */ + public function paypal_transaction_log() + { + return $this->morphOne(\Plugins\Paypal\Model\PaypalTransactionLog::class, 'paypal_transaction_logable'); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\MorphOne + */ + public function wallet_transaction_log() + { + return $this->morphOne(\App\WalletTransactionLog::class, 'wallet_transaction_logable'); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\MorphOne + */ + public function sudopay_transaction_logs() + { + return $this->morphOne(\Plugins\Sudopays\Model\SudopayTransactionLog::class, 'sudopay_transaction_logable'); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\MorphOne + */ + public function transactions() + { + return $this->morphOne(\App\Transaction::class, 'transactionable'); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\MorphMany + */ + public function vehicle_feedback() + { + return $this->morphMany(\Plugins\VehicleFeedbacks\Model\VehicleFeedback::class, 'feedbackable'); + } + + /** + * @param $query + * @param Request $request + * @param null $user_id + */ + public function scopeFilterByMyVehicle($query, Request $request, $user_id = null) + { + if (!is_null($user_id)) { + $query->where('user_id', '=', $user_id); + } + } + + /** + * @param $query + * @param Request $request + */ + public function scopeFilterActiveVehicle($query, Request $request) + { + $query->where('is_active', 1); + $query->where('is_paid', 1); + } + + /** + * @param $query + * @param Request $request + * @return mixed + */ + public function scopeFilterByRequest($query, Request $request) + { + $field = ''; + // query to filter pickup counter location id + if ($request->has('pickup_location_id')) { + $query->WhereHas('counter_location', function ($query) use ($request) { + $query->where('counter_location_id', $request->pickup_location_id) + ->where('is_pickup', '=', 1); + }); + + } + // query to filter drop counter location id + if ($request->has('drop_location_id')) { + $query->WhereHas('counter_location', function ($query) use ($request) { + $query->where('counter_location_id', $request->drop_location_id) + ->where('is_drop', '=', 1); + }); + } + // query to filter vehicle company id + if ($request->has('vehicle_company_id')) { + $query->where('vehicle_company_id', $request->vehicle_company_id); + } + // query to filter vehicle model id + if ($request->has('vehicle_model_id')) { + $query->where('vehicle_model_id', $request->vehicle_model_id); + } + // query to filter vehicle make id + if ($request->has('vehicle_make_id')) { + $query->where('vehicle_make_id', $request->vehicle_make_id); + } + // query to filter vehicle type id + if ($request->has('vehicle_type_id')) { + $query->where('vehicle_type_id', $request->vehicle_type_id); + } + + // query to remove already booked vehicles + if ($request->has('start_date') && $request->has('end_date')) { + $data = UnavailableVehicle::where(function ($query) use ($request) { + $query->whereBetween('start_date', [$request->start_date, $request->end_date]) + ->orWhereBetween('end_date', [$request->start_date, $request->end_date]) + ->orwhere(function ($query) use ($request) { + $query->where('start_date', '>', $request->start_date) + ->where('end_date', '<', $request->start_date); + })->orwhere(function ($query) use ($request) { + $query->where('start_date', '<', $request->end_date) + ->where('end_date', '>', $request->end_date); + }); + }) + ->where('is_dummy', '!=', 1) + ->groupBy('vehicle_id') + ->lists('vehicle_id'); + $query->whereHas('unavailable_vehicle', function ($query) use ($data) { + $query->whereNotIN('vehicle_id', $data->toArray()); + }); + $hourdiff = round((strtotime($request->end_date) - strtotime($request->start_date)) / 3600, 1); + $field = 'per_hour_amount'; + if ($hourdiff >= 24) { + $field = 'per_day_amount'; + } + } + //Price filter if no start and end date + if ($request->has('price_type') && $request->price_type == 'day') { + $field = 'per_day_amount'; + } + if ($request->has('price_type') && $request->price_type == 'hour') { + $field = 'per_hour_amount'; + } + // query to filter price min value + if ($request->has('price_min') && !empty($field)) { + $query->where($field, '>=', $request->price_min); + } + // query to filter price max value + if ($request->has('price_max') && !empty($field)) { + $query->where($field, '<=', $request->price_max); + } + // sorting conditions + if ($request->has('sort') && $request->sort == 'price') { + if($request->has('sort_by_price') && $request->sort_by_price == 'day') { + $field = 'per_day_amount'; + } + if($request->has('sort_by_price') && $request->sort_by_price == 'hour') { + $field = 'per_hour_amount'; + } + $query->orderBy($field, $request->input('sortby', 'desc')); + } else if ($request->has('sort') && $request->sort == 'rating') { + $query->orderBy('feedback_rating', $request->input('sortby', 'desc')); + } else { + $query->orderBy($request->input('sort', 'id'), $request->input('sortby', 'desc')); + } + // query to filter Vehicle type id + if ($request->has('mileage_min')) { + $query->where('mileage', '>=', $request->mileage_min); + } + // query to filter price max value + if ($request->has('mileage_max')) { + $query->where('mileage', '<=', $request->mileage_max); + } + // query to filter Vehicle type id + if ($request->has('seat_min')) { + $query->where('no_of_seats', '>=', $request->seat_min); + } + // query to filter price max value + if ($request->has('seat_max')) { + $query->where('no_of_seats', '<=', $request->seat_max); + } + // query to filter Vehicle type id + if ($request->has('vehicle_type') && !empty($request->vehicle_type)) { + $query->whereIn('vehicle_type_id', $request->vehicle_type); + } + // query to filter fuel type id + if ($request->has('fuel_type') && !empty($request->fuel_type)) { + $query->whereIn('fuel_type_id', $request->fuel_type); + } + + if ($request->has('ac') && $request->ac == 1 && $request->has('non_ac') && $request->non_ac == 0) { + $query->where('is_ac', '=', 1); + } else if ($request->has('ac') && $request->ac == 0 && $request->has('non_ac') && $request->non_ac == 1) { + $query->where('is_ac', '=', 0); + } else if (!$request->has('ac') && $request->has('non_ac') && $request->non_ac == 1) { + $query->where('is_ac', '=', 0); + } else if ($request->has('ac') && $request->ac == 1 && !$request->has('non_ac')) { + $query->where('is_ac', '=', 1); + } + + // query to filter transmission + if ($request->has('manual_transmission') && $request->manual_transmission == 1 && $request->has('auto_transmission') && $request->auto_transmission == 0) { + $query->where('is_manual_transmission', '=', 1); + } else if ($request->has('manual_transmission') && $request->manual_transmission == 0 && $request->has('auto_transmission') && $request->auto_transmission == 1) { + $query->where('is_manual_transmission', '=', 0); + } else if (!$request->has('manual_transmission') && $request->has('auto_transmission') && $request->auto_transmission == 1) { + $query->where('is_manual_transmission', '=', 0); + } else if ($request->has('manual_transmission') && $request->manual_transmission == 1 && !$request->has('auto_transmission')) { + $query->where('is_manual_transmission', '=', 1); + } + + // query to filter Airbag type + if ($request->has('airbag') && $request->airbag == 1) { + $query->where('is_airbag', '=', 1); + } + + if ($request->has('filter')) { + $filter = false; + if ($request->filter == 'active') { + $filter = true; + } + $query->where('is_active', '=', $filter); + } + if ($request->has('q')) { + //Search vehicle tables + $query->where('vehicles.name', 'LIKE', '%' . $request->input('q') . '%'); + $query->orWhere('vehicles.per_day_amount', 'LIKE', '%' . $request->input('q') . '%'); + $query->orWhere('vehicles.per_hour_amount', 'LIKE', '%' . $request->input('q') . '%'); + $query->orWhere('vehicles.feedback_count', 'LIKE', '%' . $request->input('q') . '%'); + //Search vehicle relation tables + $query->orWhereHas('vehicle_company', function ($q) use ($request) { + $q->where('name', 'like', '%' . $request->input('q') . '%'); + }); + $query->orWhereHas('vehicle_make', function ($q) use ($request) { + $q->where('name', 'like', '%' . $request->input('q') . '%'); + }); + $query->orWhereHas('vehicle_model', function ($q) use ($request) { + $q->where('name', 'like', '%' . $request->input('q') . '%'); + }); + $query->orWhereHas('vehicle_type', function ($q) use ($request) { + $q->where('name', 'like', '%' . $request->input('q') . '%'); + }); + } + + return $query; + } + + /** + * @return array + */ + public function scopeGetValidationRule() + { + return [ + 'vehicle_company_id' => 'sometimes|required|integer|exists:vehicle_companies,id', + 'vehicle_make_id' => 'required|integer|exists:vehicle_makes,id', + 'vehicle_model_id' => 'required|integer|exists:vehicle_models,id', + 'vehicle_type_id' => 'required|integer|exists:vehicle_types,id', + 'vehicle_no' => 'required', + 'per_hour_amount' => 'numeric', + 'per_day_amount' => 'required|numeric', + 'is_active' => 'sometimes|required|boolean', + ]; + } + + public function scopeGetValidationMessage() + { + return [ + 'vehicle_company_id.required' => 'Required', + 'vehicle_company_id.integer' => 'vehicle_company_id - should be a number!', + 'vehicle_company_id.exists' => 'Invalid vehicle company id', + 'vehicle_make_id.required' => 'Required', + 'vehicle_make_id.integer' => 'vehicle_make_id - should be a number!', + 'vehicle_make_id.exists' => 'Invalid vehicle make id', + 'vehicle_model_id.required' => 'Required', + 'vehicle_model_id.integer' => 'vehicle_model_id - should be a number!', + 'vehicle_model_id.exists' => 'Invalid vehicle model id', + 'vehicle_type_id.required' => 'Required', + 'vehicle_type_id.integer' => 'vehicle_type_id - should be a number!', + 'vehicle_type_id.exists' => 'Invalid vehicle type id', + 'vehicle_no.required' => 'Required', + 'per_hour_amount.numeric' => 'Per hour amount must be a number', + 'per_day_amount.required' => 'Required', + 'per_day_amount.numeric' => 'Per day amount must be a number', + 'is_paid.required' => 'Required', + 'is_paid.boolean' => 'is_paid must be a boolean', + 'is_active.required' => 'Required', + 'is_active.boolean' => 'is_active - should be a boolean!', + ]; + } +} diff --git a/app/Plugins/Vehicles/Model/VehicleCompany.php b/app/Plugins/Vehicles/Model/VehicleCompany.php new file mode 100644 index 0000000..18b0c57 --- /dev/null +++ b/app/Plugins/Vehicles/Model/VehicleCompany.php @@ -0,0 +1,127 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Vehicles\Model; + +use Illuminate\Http\Request; +use Illuminate\Database\Eloquent\Model; +use App\User; + +/** + * Class VehicleCompany + * @package Plugins\Vehicles\Model + */ +class VehicleCompany extends Model +{ + /** + * @var string + */ + protected $table = "vehicle_companies"; + /** + * The attributes that are mass assignable. + * @var array + */ + protected $fillable = [ + 'user_id', 'name', 'address', 'latitude', 'longitude', 'fax', 'phone', 'mobile', 'email', 'is_active', 'vehicle_count' + ]; + + /** + * @return mixed + */ + public function vehicle() + { + return $this->hasMany(Vehicle::class); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function user() + { + return $this->belongsTo(User::class); + } + + /** + * @param $query + * @param Request $request + * @param string $status + * @return mixed + */ + public function scopeFilterByRequest($query, Request $request, $status = '') + { + + if ($request->has('sort') && $request->sort == 'status') { + $query->orderBy('is_active', $request->input('sortby', 'desc')); + } else { + $query->orderBy($request->input('sort', 'id'), $request->input('sortby', 'desc')); + } + if ($request->has('filter')) { + $filter = 0; + if ($request->input('filter') == 'active') { + $filter = 1; + } + if ($request->input('filter') == 'rejected') { + $filter = 2; + } + $query->where('is_active', '=', $filter); + } + if($request->has('is_active')) { + $query->where('is_active', $request->input('is_active')); + } + if($request->has('user_id')) { + $query->where('user_id', $request->input('user_id')); + } + if ($request->has('q')) { + $query->whereHas('user', function ($q) use ($request) { + $q->where('username', 'LIKE', '%' . $request->input('q') . '%'); + }); + $query->orwhere('name', 'LIKE', '%' . $request->input('q') . '%') + ->orWhere('address', 'LIKE', '%' . $request->input('q') . '%') + ->orWhere('mobile', 'LIKE', '%' . $request->input('q') . '%') + ->orWhere('email', 'LIKE', '%' . $request->input('q') . '%'); + } + return $query; + } + + /** + * @return array + */ + public function scopeGetValidationRule() + { + return [ + 'user_id' => 'required|unique:vehicle_companies', + 'name' => 'required|min:2', + 'address' => 'required|min:5', + 'mobile' => 'required', + 'email' => 'required|email' + ]; + } + + public function scopeGetValidationMessage() + { + return [ + 'user_id.required' => 'Required', + 'user_id.unique' => 'User - already added company', + 'name.required' => 'Required', + 'name.min' => 'Name - minimum length is 2!', + 'address.required' => 'Required', + 'address.min' => 'address - minimum length is 5!', + 'mobile.required' => 'Required', + 'email.required' => 'Required', + 'email.email' => 'Enter valid e-mail address!', + ]; + } + +} diff --git a/app/Plugins/Vehicles/Model/VehicleMake.php b/app/Plugins/Vehicles/Model/VehicleMake.php new file mode 100644 index 0000000..41da11c --- /dev/null +++ b/app/Plugins/Vehicles/Model/VehicleMake.php @@ -0,0 +1,92 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Vehicles\Model; + +use Illuminate\Http\Request; +use Illuminate\Database\Eloquent\Model; + +/** + * Class VehicleMake + * @package Plugins\Vehicles\Model + */ +class VehicleMake extends Model +{ + /** + * @var string + */ + protected $table = "vehicle_makes"; + /** + * The attributes that are mass assignable. + * @var array + */ + protected $fillable = [ + 'name', 'slug', 'is_active', 'vehicle_count', 'vehicle_model_count' + ]; + + /** + * @return mixed + */ + public function vehicle_model() + { + return $this->hasMany(VehicleModel::class); + } + + /** + * @return mixed + */ + public function vehicle() + { + return $this->hasMany(Vehicle::class); + } + + public function scopeFilterByRequest($query, Request $request) + { + $query->orderBy($request->input('sort', 'id'), $request->input('sortby', 'desc')); + if ($request->has('filter')) { + $filter = false; + if ($request->input('filter') == 'active') { + $filter = true; + } + $query->where('is_active', '=', $filter); + } + if ($request->has('q')) { + $query->where('name', 'LIKE', '%' . $request->input('q') . '%'); + } + return $query; + } + + /** + * @return array + */ + public function scopeGetValidationRule() + { + return [ + 'name' => 'required|min:2', + 'is_active' => 'required|boolean' + ]; + } + + public function scopeGetValidationMessage() + { + return [ + 'name.required' => 'Required', + 'name.min' => 'Name - minimum length is 2!', + 'is_active.required' => 'Required', + 'is_active.boolean' => 'is_active must be a boolean' + ]; + } + +} diff --git a/app/Plugins/Vehicles/Model/VehicleModel.php b/app/Plugins/Vehicles/Model/VehicleModel.php new file mode 100644 index 0000000..2dd138b --- /dev/null +++ b/app/Plugins/Vehicles/Model/VehicleModel.php @@ -0,0 +1,110 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Vehicles\Model; + +use Illuminate\Http\Request; +use Illuminate\Database\Eloquent\Model; + + +/** + * Class VehicleModel + * @package Plugins\Vehicles\Model + */ +class VehicleModel extends Model +{ + /** + * @var string + */ + protected $table = "vehicle_models"; + /** + * The attributes that are mass assignable. + * @var array + */ + protected $fillable = [ + 'name', 'slug', 'vehicle_make_id', 'is_active', 'vehicle_count' + ]; + + /** + * @return mixed + */ + public function vehicle_make() + { + return $this->belongsTo(VehicleMake::class); + } + + /** + * @return mixed + */ + public function vehicle() + { + return $this->hasMany(Vehicle::class); + } + + /** + * @param $query + * @param Request $request + * @return mixed + */ + public function scopeFilterByRequest($query, Request $request) + { + $query->orderBy($request->input('sort', 'id'), $request->input('sortby', 'desc')); + if ($request->has('filter')) { + $filter = false; + if ($request->input('filter') == 'active') { + $filter = true; + } + $query->where('is_active', '=', $filter); + } + if($request->has('vehicle_make_id')) { + $query->where('vehicle_make_id', $request->input('vehicle_make_id')); + } + if ($request->has('q')) { + $query->whereHas('vehicle_make', function ($q) use ($request) { + $q->where('name', 'LIKE', '%' . $request->input('q') . '%'); + }); + $query->orwhere('vehicle_models.name', 'LIKE', '%' . $request->input('q') . '%'); + } + return $query; + } + + /** + * @return array + */ + public function scopeGetValidationRule() + { + return [ + 'name' => 'required|min:2', + 'vehicle_make_id' => 'required|integer|exists:vehicle_makes,id', + 'is_active' => 'required|boolean' + ]; + } + + /** + * @return array + */ + public function scopeGetValidationMessage() + { + return [ + 'name.required' => 'Required', + 'name.min' => 'Name - minimum length is 2!', + 'vehicle_make_id.required' => 'Required', + 'vehicle_make_id.integer' => 'vehicle_make_id must be a number', + 'vehicle_make_id.exists' => 'Invalid vehicle make id', + 'is_active.required' => 'Required', + 'is_active.boolean' => 'is_active must be a boolean', + ]; + } +} diff --git a/app/Plugins/Vehicles/Model/VehicleSpecialPrice.php b/app/Plugins/Vehicles/Model/VehicleSpecialPrice.php new file mode 100644 index 0000000..0d97e91 --- /dev/null +++ b/app/Plugins/Vehicles/Model/VehicleSpecialPrice.php @@ -0,0 +1,111 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Vehicles\Model; + +use Illuminate\Http\Request; +use Illuminate\Database\Eloquent\Model; + + +/** + * Class VehicleSpecialPrice + * @package Plugins\Vehicles\Model + */ +class VehicleSpecialPrice extends Model +{ + /** + * @var string + */ + protected $table = "vehicle_special_prices"; + /** + * The attributes that are mass assignable. + * @var array + */ + protected $fillable = [ + 'start_date', 'end_date', 'vehicle_type_id', 'discount_percentage', 'is_active' + ]; + + /** + * @return mixed + */ + public function vehicle_type() + { + return $this->belongsTo(VehicleType::class); + } + + /** + * @param $query + * @param Request $request + * @return mixed + */ + public function scopeFilterByRequest($query, Request $request) + { + $query->orderBy($request->input('sort', 'id'), $request->input('sortby', 'desc')); + if ($request->has('filter')) { + $filter = false; + if ($request->input('filter') == 'active') { + $filter = true; + } + $query->where('is_active', '=', $filter); + } + if ($request->has('vehicle_type_id')) { + $query->where('vehicle_type_id', $request->input('vehicle_type_id')); + } + if ($request->has('start_date')) { + $query->where('start_date', '>=', $request->input('start_date')); + } + if ($request->has('end_date')) { + $query->where('end_date', '<=', $request->input('end_date')); + } + return $query; + } + + /** + * @return array + */ + public function scopeGetValidationRule() + { + return [ + 'start_date' => 'required|date|date_format:Y-m-d H:i:s', + 'end_date' => 'required|date|date_format:Y-m-d H:i:s', + 'vehicle_type_id' => 'required|integer|exists:vehicle_types,id', + 'discount_percentage' => 'required|numeric', + 'is_active' => 'required|boolean' + ]; + } + + /** + * @return array + */ + public function scopeGetValidationMessage() + { + return [ + 'start_date.required' => 'Required', + 'start_date.date' => 'Start date should be a date!', + 'start_date.date_format' => 'Date should be in Y-m-d H:i:s format', + 'end_date.required' => 'Required', + 'end_date.date' => 'End date should be a date!', + 'end_date.date_format' => 'Date should be in Y-m-d H:i:s format', + 'vehicle_type_id.required' => 'Required', + 'vehicle_type_id.integer' => 'Vehicle type id must be a number!', + 'vehicle_type_id.exists' => 'Invalid vehicle type id', + 'discount_percentage.required' => 'Required', + 'discount_percentage.numeric' => 'Discount percentage must be numeric', + 'is_active.required' => 'Required', + 'is_active.boolean' => 'Possible values to be entered is 0 or 1' + ]; + } + +} diff --git a/app/Plugins/Vehicles/Model/VehicleType.php b/app/Plugins/Vehicles/Model/VehicleType.php new file mode 100644 index 0000000..18593d3 --- /dev/null +++ b/app/Plugins/Vehicles/Model/VehicleType.php @@ -0,0 +1,180 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Vehicles\Model; + +use App\DurationType; +use Illuminate\Http\Request; +use Illuminate\Database\Eloquent\Model; + +/** + * Class VehicleType + * @package Plugins\Vehicles\Model + */ +class VehicleType extends Model +{ + /** + * @var string + */ + protected $table = "vehicle_types"; + /** + * The attributes that are mass assignable. + * @var array + */ + protected $fillable = [ + 'name', 'slug', 'minimum_hour_price', 'maximum_hour_price', 'minimum_day_price', 'maximum_day_price', 'drop_location_differ_unit_price', 'drop_location_differ_additional_fee', 'deposit_amount', 'is_active', 'vehicle_count', 'late_checkout_addtional_fee', 'duration_type_id' + ]; + + /** + * @return mixed + */ + public function vehicle() + { + return $this->hasMany(Vehicle::class); + } + + /** + * @return mixed + */ + public function vehicle_type_price() + { + return $this->hasMany(VehicleTypePrice::class); + } + + /** + * @return mixed + */ + public function vehicle_special_price() + { + return $this->hasMany(VehicleSpecialPrice::class); + } + + /** + * @return mixed + */ + public function vehicle_type_surcharge() + { + return $this->hasMany(\Plugins\VehicleSurcharges\Model\VehicleTypeSurcharge::class); + } + + /** + * @return mixed + */ + public function vehicle_type_tax() + { + return $this->hasMany(\Plugins\VehicleTaxes\Model\VehicleTypeTax::class); + } + + /** + * @return mixed + */ + public function vehicle_type_extra_accessory() + { + return $this->hasMany(\Plugins\VehicleExtraAccessories\Model\VehicleTypeExtraAccessory::class); + } + + /** + * @return mixed + */ + public function vehicle_type_insurance() + { + return $this->hasMany(\Plugins\VehicleInsurances\Model\VehicleTypeInsurance::class); + } + + /** + * @return mixed + */ + public function vehicle_type_fuel_option() + { + return $this->hasMany(\Plugins\VehicleFuelOptions\Model\VehicleTypeFuelOption::class); + } + + /** + * @return mixed + */ + public function duration_type() + { + return $this->belongsTo(DurationType::class); + } + /** + * @param $query + * @param Request $request + */ + public function scopeFilterByActiveRecord($query, Request $request) + { + $query->where('is_active', '=', 1); + } + /** + * @param $query + * @param Request $request + * @return mixed + */ + public function scopeFilterByRequest($query, Request $request) + { + $query->orderBy($request->input('sort', 'id'), $request->input('sortby', 'desc')); + if ($request->has('filter')) { + $filter = false; + if ($request->input('filter') == 'active') { + $filter = true; + } + $query->where('is_active', '=', $filter); + } + if ($request->has('q')) { + $query->where('name', 'LIKE', '%' . $request->input('q') . '%'); + } + if ($request->has('type') && $request->type == 'vehicle_count') { + $query->where('vehicle_count', '>', 0); + } + return $query; + } + + /** + * @return array + */ + public function scopeGetValidationRule() + { + return [ + 'name' => 'required|min:2', + 'minimum_hour_price' => 'numeric', + 'maximum_hour_price' => 'numeric', + 'minimum_day_price' => 'numeric', + 'maximum_day_price' => 'numeric', + 'drop_location_differ_unit_price' => 'numeric', + 'drop_location_differ_additional_fee' => 'numeric', + 'deposit_amount' => 'numeric', + 'is_active' => 'required|boolean', + ]; + } + + /** + * @return array + */ + public function scopeGetValidationMessage() + { + return [ + 'name.required' => 'Required', + 'name.min' => 'Name - minimum length is 2!', + 'minimum_hour_price.numeric' => 'minimum hour price must be a number', + 'maximum_hour_price.numeric' => 'maximum_hour_price must be a number', + 'minimum_day_price.numeric' => 'minimum_day_price must be a number', + 'maximum_day_price.numeric' => 'maximum_day_price must be a number', + 'drop_location_differ_unit_price.numeric' => 'drop_location_differ_unit_price must be a number', + 'drop_location_differ_additional_fee.numeric' => 'drop_location_differ_additional_fee must be a number', + 'deposit_amount.numeric' => 'deposit_amount must be a number', + 'is_active.required' => 'Required', + 'is_active.boolean' => 'boolean', + ]; + } +} diff --git a/app/Plugins/Vehicles/Model/VehicleTypePrice.php b/app/Plugins/Vehicles/Model/VehicleTypePrice.php new file mode 100644 index 0000000..0e64a00 --- /dev/null +++ b/app/Plugins/Vehicles/Model/VehicleTypePrice.php @@ -0,0 +1,108 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Vehicles\Model; + +use Illuminate\Http\Request; +use Illuminate\Database\Eloquent\Model; + + +/** + * Class VehicleTypePrice + * @package Plugins\Vehicles\Model + */ +class VehicleTypePrice extends Model +{ + /** + * @var string + */ + protected $table = "vehicle_type_prices"; + /** + * The attributes that are mass assignable. + * @var array + */ + protected $fillable = [ + 'vehicle_type_id', 'minimum_no_of_day', 'maximum_no_of_day', 'discount_percentage', 'is_active' + ]; + + /** + * @return mixed + */ + public function vehicle_type() + { + return $this->belongsTo(VehicleType::class); + } + + /** + * @param $query + * @param Request $request + * @return mixed + */ + public function scopeFilterByRequest($query, Request $request) + { + $query->orderBy($request->input('sort', 'id'), $request->input('sortby', 'desc')); + if ($request->has('filter')) { + $filter = false; + if ($request->input('filter') == 'active') { + $filter = true; + } + $query->where('is_active', '=', $filter); + } + if($request->has('vehicle_type_id')) { + $query->where('vehicle_type_id', $request->input('vehicle_type_id')); + } + if ($request->has('q')) { + $query->whereHas('vehicle_type', function ($q) use ($request) { + $q->where('name', 'like', '%' . $request->input('q') . '%'); + }); + } + return $query; + } + + /** + * @return array + */ + public function scopeGetValidationRule() + { + return [ + 'vehicle_type_id' => 'required|integer|exists:vehicle_types,id', + 'minimum_no_of_day' => 'required|integer', + 'maximum_no_of_day' => 'required|integer', + 'discount_percentage' => 'required|numeric', + 'is_active' => 'required|boolean' + ]; + } + + /** + * @return array + */ + public function scopeGetValidationMessage() + { + return [ + 'vehicle_type_id.required' => 'Required', + 'vehicle_type_id.integer' => 'Vehicle Type Id must be integer', + 'vehicle_type_id.exists' => 'Invalid vehicle type id', + 'minimum_no_of_day.required' => 'Required', + 'minimum_no_of_day.integer' => 'Minimum number of days must be integer', + 'maximum_no_of_day.required' => 'Required', + 'maximum_no_of_day.integer' => 'Maximum number of day must be integer', + 'discount_percentage.required' => 'Required', + 'discount_percentage.numeric' => 'Discount percentage must be numeric', + 'is_active.required' => 'Required', + 'is_active.boolean' => 'Possible values to be entered is 0 or 1' + ]; + } + +} diff --git a/app/Plugins/Vehicles/Providers/VehicleServiceProvider.php b/app/Plugins/Vehicles/Providers/VehicleServiceProvider.php new file mode 100644 index 0000000..4666f88 --- /dev/null +++ b/app/Plugins/Vehicles/Providers/VehicleServiceProvider.php @@ -0,0 +1,61 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Vehicles\Providers; + +use Illuminate\Support\ServiceProvider; + +class VehicleServiceProvider extends ServiceProvider +{ + /** + * Register any application services. + * + * @return void + */ + public function register() + { + include __DIR__ . '/../routes.php'; + $this->app->make('Plugins\Vehicles\Controllers\Admin\AdminVehicleMakesController'); + $this->app->make('Plugins\Vehicles\Controllers\Admin\AdminVehicleTypesController'); + $this->app->make('Plugins\Vehicles\Controllers\Admin\AdminVehicleCompaniesController'); + $this->app->make('Plugins\Vehicles\Controllers\Admin\AdminVehicleModelsController'); + $this->app->make('Plugins\Vehicles\Controllers\Admin\AdminCounterLocationsController'); + $this->app->make('Plugins\Vehicles\Controllers\Admin\AdminVehiclesController'); + $this->app->make('Plugins\Vehicles\Controllers\Admin\AdminVehicleSpecialPricesController'); + $this->app->make('Plugins\Vehicles\Controllers\Admin\AdminVehicleTypePricesController'); + $this->app->make('Plugins\Vehicles\Controllers\Admin\AdminFuelTypesController'); + $this->app->make('Plugins\Vehicles\Controllers\Admin\AdminUnavailableVehiclesController'); + $this->app->make('Plugins\Vehicles\Controllers\VehiclesController'); + $this->app->make('Plugins\Vehicles\Controllers\VehicleSpecialPricesController'); + $this->app->make('Plugins\Vehicles\Controllers\VehicleTypePricesController'); + $this->app->make('Plugins\Vehicles\Controllers\VehicleCompaniesController'); + $this->app->make('Plugins\Vehicles\Controllers\VehicleMakesController'); + $this->app->make('Plugins\Vehicles\Controllers\VehicleModelsController'); + $this->app->make('Plugins\Vehicles\Controllers\VehicleTypesController'); + $this->app->make('Plugins\Vehicles\Controllers\CounterLocationsController'); + $this->app->make('Plugins\Vehicles\Controllers\FuelTypesController'); + $this->app->make('Plugins\Vehicles\Controllers\UnavailableVehiclesController'); + } + + /** + * Bootstrap the application services. + * + * @return void + */ + public function boot() + { + + } +} diff --git a/app/Plugins/Vehicles/Services/CounterLocationService.php b/app/Plugins/Vehicles/Services/CounterLocationService.php new file mode 100644 index 0000000..61930c7 --- /dev/null +++ b/app/Plugins/Vehicles/Services/CounterLocationService.php @@ -0,0 +1,64 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Vehicles\Services; + +use Plugins\Vehicles\Model\CounterLocation; +use Plugins\Vehicles\Model\CounterLocationVehicle; +use Plugins\Vehicles\Model\Vehicle; + +class CounterLocationService +{ + /** + * CounterLocationService constructor. + */ + public function __construct() + { + } + + /** + * @return mixed + */ + public function getCounterLocationList() + { + $counter_location_list = CounterLocation::lists('id', 'address'); + return $counter_location_list; + } + + public function getVehicleCounterLocation($vehicle_id) + { + $vehicle_locations = Vehicle::with(array('counter_location'))->where('id', '=', $vehicle_id)->first(); + $vehicle_counter_locations = array(); + $i = 0; + + foreach ($vehicle_locations->counter_location as $counter_location) { + if ($counter_location->pivot->is_pickup == 1) { + $vehicle_counter_locations['pickup'][$i]['id'] = $counter_location->id; + $vehicle_counter_locations['pickup'][$i]['address'] = $counter_location->address; + $vehicle_counter_locations['pickup'][$i]['latitude'] = $counter_location->latitude; + $vehicle_counter_locations['pickup'][$i]['longitude'] = $counter_location->longitude; + } + if ($counter_location->pivot->is_drop == 1) { + $vehicle_counter_locations['drop'][$i]['id'] = $counter_location->id; + $vehicle_counter_locations['drop'][$i]['address'] = $counter_location->address; + $vehicle_counter_locations['drop'][$i]['latitude'] = $counter_location->latitude; + $vehicle_counter_locations['drop'][$i]['longitude'] = $counter_location->longitude; + } + $i++; + } + return $vehicle_counter_locations; + + } +} diff --git a/app/Plugins/Vehicles/Services/FuelTypeService.php b/app/Plugins/Vehicles/Services/FuelTypeService.php new file mode 100644 index 0000000..c4669af --- /dev/null +++ b/app/Plugins/Vehicles/Services/FuelTypeService.php @@ -0,0 +1,40 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Vehicles\Services; + +use Plugins\Vehicles\Model\FuelType; + +class FuelTypeService +{ + /** + * FuelTypeService constructor. + */ + public function __construct() + { + } + + /** + * @return mixed + */ + public function getFuelTypeList() + { + $feul_type_list = FuelType::lists('id', 'name'); + foreach($feul_type_list as $value=>$key) { + $feul_type_list[$value] = (integer)$key; + } + return $feul_type_list; + } +} diff --git a/app/Plugins/Vehicles/Services/UnavailableVehicleService.php b/app/Plugins/Vehicles/Services/UnavailableVehicleService.php new file mode 100644 index 0000000..922fc5e --- /dev/null +++ b/app/Plugins/Vehicles/Services/UnavailableVehicleService.php @@ -0,0 +1,65 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Vehicles\Services; + +use Plugins\Vehicles\Model\UnavailableVehicle; + +class UnavailableVehicleService +{ + /** + * UnavailableVehicleService constructor. + */ + public function __construct() + { + } + + /** + * Clear unavailable vehicle by id + * @param $id + */ + public function clearUnavaialablelist($item_user_id) + { + $unavailable_vehicle = UnavailableVehicle::where('item_user_id',$item_user_id)->first(); + if(!$unavailable_vehicle){ + return $this->response->errorNotFound("Invalid Request"); + } else { + $unavailable_vehicle->delete(); + } + } + + /** + * check the booking is available before payment + * @param $vehicle_rental + */ + public function checkBookingAvailability($vehicle_rental){ + $start_date = $vehicle_rental->item_booking_start_date; + $end_date = $vehicle_rental->item_booking_end_date; + $unavailable_vehicle = UnavailableVehicle::where('vehicle_id', $vehicle_rental->item_userable_id) + ->where(function ($query) use ($start_date, $end_date) { + $query->whereBetween('start_date', [$start_date, $end_date]) + ->orWhereBetween('end_date', [$start_date, $end_date]) + ->orwhere(function ($query) use ($start_date, $end_date) { + $query->where('start_date', '>', $start_date) + ->where('end_date', '<', $start_date); + })->orwhere(function ($query) use ($start_date, $end_date) { + $query->where('start_date', '<', $end_date) + ->where('end_date', '>', $end_date); + }); + }) + ->where('is_dummy', '!=', 1)->first(); + return $unavailable_vehicle; + } +} diff --git a/app/Plugins/Vehicles/Services/VehicleCompanyService.php b/app/Plugins/Vehicles/Services/VehicleCompanyService.php new file mode 100644 index 0000000..4961d5e --- /dev/null +++ b/app/Plugins/Vehicles/Services/VehicleCompanyService.php @@ -0,0 +1,40 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Vehicles\Services; + +use Plugins\Vehicles\Model\VehicleCompany; + +class VehicleCompanyService +{ + /** + * VehicleCompanyService constructor. + */ + public function __construct() + { + } + + /** + * @return mixed + */ + public function getVehicleCompanyList() + { + $vehicle_company_list = VehicleCompany::where('is_active', true)->lists('id', 'name'); + foreach($vehicle_company_list as $value=>$key) { + $vehicle_company_list[$value] = (integer)$key; + } + return $vehicle_company_list; + } +} diff --git a/app/Plugins/Vehicles/Services/VehicleMakeService.php b/app/Plugins/Vehicles/Services/VehicleMakeService.php new file mode 100644 index 0000000..958d3d4 --- /dev/null +++ b/app/Plugins/Vehicles/Services/VehicleMakeService.php @@ -0,0 +1,40 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Vehicles\Services; + +use Plugins\Vehicles\Model\VehicleMake; + +class VehicleMakeService +{ + /** + * VehicleMakeService constructor. + */ + public function __construct() + { + } + + /** + * @return mixed + */ + public function getVehicleMakeList() + { + $vehicle_make_list = VehicleMake::where('is_active', true)->lists('id', 'name'); + foreach($vehicle_make_list as $value=>$key) { + $vehicle_make_list[$value] = (integer)$key; + } + return $vehicle_make_list; + } +} diff --git a/app/Plugins/Vehicles/Services/VehicleModelService.php b/app/Plugins/Vehicles/Services/VehicleModelService.php new file mode 100644 index 0000000..4878836 --- /dev/null +++ b/app/Plugins/Vehicles/Services/VehicleModelService.php @@ -0,0 +1,53 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Vehicles\Services; + +use Plugins\Vehicles\Model\VehicleModel; +use Plugins\Vehicles\Model\VehicleMake; + +class VehicleModelService +{ + /** + * VehicleModelService constructor. + */ + public function __construct() + { + } + + /** + * @return mixed + */ + public function getVehicleModelList() + { + $vehicle_model_list = VehicleModel::where('is_active', true)->lists('id', 'name'); + return $vehicle_model_list; + } + + public function afterSave($vehicle_model, $vehicle_model_old = false){ + // vehicle_model_count update to VehicleMake + if($vehicle_model){ + $model_count = VehicleModel::where('is_active', 1)->where('vehicle_make_id', $vehicle_model->vehicle_make_id)->count(); + VehicleMake::where('id', '=', $vehicle_model->vehicle_make_id)->update(['vehicle_model_count' => $model_count]); + } + if($vehicle_model_old){ + if($vehicle_model_old->vehicle_make_id != $vehicle_model->vehicle_make_id){ + $model_count = VehicleModel::where('is_active', 1)->where('vehicle_make_id', $vehicle_model_old->vehicle_make_id)->count(); + VehicleMake::where('id', '=', $vehicle_model_old->vehicle_make_id)->update(['vehicle_model_count' => $model_count]); + } + + } + } +} diff --git a/app/Plugins/Vehicles/Services/VehicleService.php b/app/Plugins/Vehicles/Services/VehicleService.php new file mode 100644 index 0000000..1160d4c --- /dev/null +++ b/app/Plugins/Vehicles/Services/VehicleService.php @@ -0,0 +1,406 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Vehicles\Services; + + +use App\User; +use Plugins\Vehicles\Model\UnavailableVehicle; +use Plugins\Vehicles\Model\Vehicle; +use Plugins\Vehicles\Model\CounterLocation; +use Plugins\Vehicles\Services\VehicleSpecialPriceService; +use Plugins\Vehicles\Services\VehicleTypePriceService; +use Plugins\Vehicles\Model\VehicleType; +use Plugins\Vehicles\Model\VehicleMake; +use Plugins\Vehicles\Model\VehicleModel; +use Plugins\Vehicles\Model\VehicleCompany; +use App\Services\TransactionService; +use Carbon; +use DB; + +class VehicleService +{ + /** + * @var vehicleSpecialPriceService + */ + protected $vehicleSpecialPriceService; + + /** + * @var vehicleTypePriceService + */ + protected $vehicleTypePriceService; + + /** + * VehicleService constructor. + */ + public function __construct() + { + $this->setTransactionService(); + $this->setVehicleSpecialPriceService(); + $this->setVehicleTypePriceService(); + } + + public function setTransactionService() + { + $this->transactionService = new TransactionService(); + } + + public function setVehicleSpecialPriceService() + { + $this->vehicleSpecialPriceService = new VehicleSpecialPriceService(); + } + + public function setVehicleTypePriceService() + { + $this->vehicleTypePriceService = new VehicleTypePriceService(); + } + + /** + * get last registered record for admin dashboard + * @param $request + * @return User created_at + */ + public function getLastAddVehicle() + { + $item_details = Vehicle::select('created_at')->where('is_active', 1)->orderBy('created_at', 'desc')->first(); + return ($item_details) ? $item_details->created_at->diffForHumans() : '-'; + } + + /** + * @param $request + * @param string $type + * @return mixed + */ + public function getVehicleCount($request, $type = 'filter') + { + if ($type == 'filter') { + $check_date = $this->getDateFilter($request); + $check_date = Carbon::parse($check_date)->format('Y-m-d'); + $vehicle_count = Vehicle::where('created_at', '>=', $check_date) + ->count(); + } else { + $vehicle_count = Vehicle::count(); + } + return $vehicle_count; + } + + /** + * get the date filter + * @return $check_date + */ + public function getDateFilter($request) + { + $check_date = Carbon::now()->subDays(7); + if ($request->has('filter')) { + if ($request->filter == 'lastDays') { + $check_date = Carbon::now()->subDays(7); + } else if ($request->filter == 'lastWeeks') { + $check_date = Carbon::now()->subWeeks(4); + } else if ($request->filter == 'lastMonths') { + $check_date = Carbon::now()->subMonths(3); + } else if ($request->filter == 'lastYears') { + $check_date = Carbon::now()->subYears(3); + } + } + return $check_date; + } + + /** + * @param $location1 + * @param $location2 + * @param $vehicle_type_id + * @return float + */ + public function processDifferLocationDropAmount($location1, $location2, $vehicle_type_id) + { + $unit = config('vehicle.unit'); + $lat = array(); + $lon = array(); + $diff_location_drop_details = array(); + $counter_locations = CounterLocation::whereIn('id', array($location1, $location2))->get(); + if (!empty($counter_locations)) { + foreach ($counter_locations as $counter_location) { + $lat[] = $counter_location->latitude; + $lon[] = $counter_location->longitude; + } + $theta = $lon[0] - $lon[1]; + $dist = sin(deg2rad($lat[0])) * sin(deg2rad($lat[1])) + cos(deg2rad($lat[0])) * cos(deg2rad($lat[1])) * cos(deg2rad($theta)); + $dist = acos($dist); + $dist = rad2deg($dist); + $miles = $dist * 60 * 1.1515; + $unit = strtoupper($unit); + if ($unit == "KM") { + $miles = $miles * 1.609344; + } + $diff_location_drop_details['total_distance'] = ceil($miles); + $vehicle_type = VehicleType::where('id', $vehicle_type_id)->first(); + $diff_location_drop_amount = ceil($miles) * $vehicle_type->drop_location_differ_unit_price; + if (!empty($vehicle_type->drop_location_differ_additional_fee)) { + $diff_location_drop_details['drop_location_differ_additional_fee'] = $vehicle_type->drop_location_differ_additional_fee; + } + $diff_location_drop_details['diff_location_drop_amount'] = $diff_location_drop_amount; + $diff_location_drop_details['distance_unit'] = $unit; + return $diff_location_drop_details; + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Given Counter locations not available. Please, try again.'); + } + } + + /** + * @param $vehicles + * @param $start_date + * @param $end_date + * @return mixed + */ + public function getDiscountRate($vehicles, $start_date, $end_date) + { + $total_trip_amount_details = array(); + foreach ($vehicles as $vehicle) { + $special_price_percent = 0; + // calculate total trip amount + $total_trip_amount_details = $this->calculateBookingAmount($start_date, $end_date, $vehicle); + $vehicle->booking_amount = $total_trip_amount_details['booking_amount']; + // set vehicle type prices + if (!is_null($vehicle->vehicle_type) && !is_null($vehicle->vehicle_type->vehicle_special_price)) { + foreach ($vehicle->vehicle_type->vehicle_special_price as $special_price) { + if ($special_price->discount_percentage > $special_price_percent && strtotime($start_date) >= strtotime($special_price->start_date) && strtotime($end_date) <= strtotime($special_price->end_date)) { + $special_price_percent = $special_price->discount_percentage; + } + } + } + // set vehicle type prices + if (!is_null($vehicle->vehicle_type) && !is_null($vehicle->vehicle_type->vehicle_type_price)) { + foreach ($vehicle->vehicle_type->vehicle_type_price as $type_price) { + if ($type_price->discount_percentage > $special_price_percent && $total_trip_amount_details['total_days'] >= $type_price->minimum_no_of_day && $total_trip_amount_details['total_days'] <= $type_price->maximum_no_of_day) { + $special_price_percent = $type_price->discount_percentage; + } + } + } + + if ($special_price_percent > 0) { + $vehicle->max_discount_percent = $special_price_percent; + } + } + unset($total_trip_amount_details['booking_amount']); + $vehicles->booking_details = $total_trip_amount_details; + return $vehicles; + } + + /** + * @param $vehicle_id + * @param bool $item_user_id + * @param bool $start_date + * @param bool $end_date + * @param int $is_dummy + */ + public function addVehicleSearchRecord($vehicle_id, $item_user_id = false, $start_date = false, $end_date = false, $is_dummy = 0) + { + $vehicle = false; + $search_insert_data['vehicle_id'] = $vehicle_id; + if ($item_user_id) + $search_insert_data['item_user_id'] = $item_user_id; + $search_insert_data['is_dummy'] = $is_dummy; + if ($start_date) { + $search_insert_data['start_date'] = $start_date; + } + if ($end_date) { + $search_insert_data['end_date'] = $end_date; + if ($item_user_id && config('vehicle_rental.late_checkout_grace_time') > 0) { + $grace_time_added_end_date = Carbon::createFromTimeStamp(strtotime($end_date))->addHours(config('vehicle_rental.late_checkout_grace_time')); + $search_insert_data['end_date'] = $grace_time_added_end_date->toDateTimeString(); + } + } + if ($is_dummy && !$item_user_id) { + $vehicle = UnavailableVehicle::where('vehicle_id', $vehicle_id)->where('is_dummy', $is_dummy)->first(); + } else { + $vehicle = UnavailableVehicle::where('vehicle_id', $vehicle_id)->where('is_dummy', $is_dummy)->where('item_user_id', $item_user_id)->first(); + } + if (!$vehicle) { + UnavailableVehicle::create($search_insert_data); + } + } + + /** + * @param $start_date + * @param $end_date + * @param $vehicle + * @return array + */ + public function calculateBookingAmount($start_date, $end_date, $vehicle) + { + $booking_calculated_details = array(); + $date_diff = $this->getDateDiff($start_date, $end_date); + $booking_calculated_details['total_days'] = $date_diff['total_days']; + $booking_calculated_details['total_hours'] = $date_diff['total_hours']; + $day_amount = 0; + $hour_amount = 0; + $booking_calculated_details['is_day_price'] = 0; + if ($booking_calculated_details['total_days'] > 0) { + $day_amount = $booking_calculated_details['total_days'] * $vehicle->per_day_amount; + $booking_calculated_details['is_day_price'] = 1; + } + if ($booking_calculated_details['total_hours'] > 0) { + if (!empty($vehicle->per_hour_amount)) { + $hour_amount = $booking_calculated_details['total_hours'] * $vehicle->per_hour_amount; + } else { + $hour_amount = $vehicle->per_day_amount; + } + } + $booking_calculated_details['booking_amount'] = $day_amount + $hour_amount; + $booking_calculated_details['special_price_discount_amount'] = $this->vehicleSpecialPriceService->processSpecialPriceAmount($vehicle->vehicle_type_id, $booking_calculated_details['booking_amount'], $start_date, $end_date); + $booking_calculated_details['type_price_discount_amount'] = $this->vehicleTypePriceService->processTypePriceAmount($vehicle->vehicle_type_id, $booking_calculated_details['booking_amount'], $date_diff); + return $booking_calculated_details; + } + + public function updateTotalAmount($vehicle_rental) + { + $differ_drop_additional_fee = 0; + if ($vehicle_rental->drop_location_differ_charges > 0) { + $differ_drop_additional_fee = $vehicle_rental->item_userable->vehicle_type->drop_location_differ_additional_fee; + } + $vehicle_rental_data['total_amount'] = ($vehicle_rental->booking_amount + $vehicle_rental->tax_amount + $vehicle_rental->surcharge_amount + $vehicle_rental->drop_location_differ_charges + $vehicle_rental->additional_fee + $vehicle_rental->insurance_amount + $vehicle_rental->extra_accessory_amount + $vehicle_rental->fuel_option_amount + $vehicle_rental->deposit_amount + $vehicle_rental->cancellation_deduct_amount + $vehicle_rental->paid_manual_amount + $differ_drop_additional_fee) - ($vehicle_rental->special_discount_amount + $vehicle_rental->type_discount_amount + $vehicle_rental->coupon_discount_amount); + $vehicle_rental_data['admin_commission_amount'] = $vehicle_rental_data['total_amount'] * (config('vehicle_rental.admin_commission_amount') / 100); + if ($vehicle_rental->paid_deposit_amount > 0) { + $vehicle_rental_data['booker_amount'] = $vehicle_rental->deposit_amount - $vehicle_rental->paid_deposit_amount; + } + $vehicle_rental_data['host_service_amount'] = ($vehicle_rental_data['total_amount'] + $vehicle_rental->paid_deposit_amount) - ($vehicle_rental_data['admin_commission_amount'] + $vehicle_rental->deposit_amount); + $vehicle_rental->update($vehicle_rental_data); + return $vehicle_rental; + } + + public function getDateDiff($start_date, $end_date) + { + $date_diff = array(); + $hour_diff = round((strtotime($end_date) - strtotime($start_date)) / 3600, 1); + $hour_diff = ceil($hour_diff); + $date_diff['total_days'] = floor($hour_diff / 24); + $date_diff['total_hours'] = ceil($hour_diff % 24); + return $date_diff; + } + + /** + * @param $vehicle + */ + public function afterSave($vehicle) + { + // unavailable vehicle dummy record put changes + $this->addVehicleSearchRecord($vehicle->id, false, false, false, 1); + // vehicle count update to realted table + $this->updateVehicleCount($vehicle->vehicle_make_id, $vehicle->vehicle_model_id, $vehicle->vehicle_type_id, $vehicle->vehicle_company_id); + } + + /** + * Update Vehicle count in related table + * @param $make_id + * @param $model_id + * @param $type_id + * @param $company_id + */ + public function updateVehicleCount($make_id, $model_id, $type_id, $company_id) + { + if ($make_id) { + $make_count = Vehicle::where('is_active', 1)->where('vehicle_make_id', $make_id)->count(); + VehicleMake::where('id', '=', $make_id)->update(['vehicle_count' => $make_count]); + } + if ($model_id) { + $vehicle_model_count = Vehicle::where('is_active', 1)->where('vehicle_model_id', $model_id)->count(); + VehicleModel::where('id', '=', $model_id)->update(['vehicle_count' => $vehicle_model_count]); + } + if ($type_id) { + $type_count = Vehicle::where('is_active', 1)->where('vehicle_type_id', $type_id)->count(); + VehicleType::where('id', '=', $type_id)->update(['vehicle_count' => $type_count]); + } + if ($company_id) { + $company_count = Vehicle::where('is_active', 1)->where('vehicle_company_id', $company_id)->count(); + VehicleCompany::where('id', '=', $company_id)->update(['vehicle_count' => $company_count]); + } + } + + /** + * @param $vehicleId + * @param $transaction_fee + * @return bool + */ + public function processVehicleLisitngFee($vehicleId, $gateway_id, $transaction_fee) + { + $vehicle = Vehicle::with('user')->where('id', $vehicleId)->first(); + if (empty($vehicle)) { + return $this->response->errorNotFound("Invalid Request"); + } + if (!$vehicle['is_paid']) { + $this->transactionService->log($vehicle->user->id, config('constants.ConstUserIds.Admin'), config('constants.ConstTransactionTypes.VehicleListingFee'), config('vehicle.listing_fee'), $vehicle->id, 'Vehicles', $gateway_id, $transaction_fee, "Vehicle listing Fee"); + $vehicle->is_paid = true; + $vehicle->save(); + return true; + } else { + return true; + } + } + + public function updateFeedbackDetails($vehicle, $average_rating) + { + + $vehicle->feedback_count = \Plugins\VehicleFeedbacks\Model\VehicleFeedback::where('feedbackable_id', $vehicle->id)->count(); + // update average rating + $vehicle->feedback_rating = $average_rating; + $vehicle->save(); + } + + public function processCheckoutLateFee($vehicle_rental, $claim_request_amount) + { + $late_fee_details = array(); + $late_fee_details['late_checkout_days_fee'] = $late_fee_details['late_checkout_hours_fee'] = $late_fee_details['late_checkout_hours'] = $late_fee_details['revised_late_hours_from_gracetime'] = $late_fee_details['late_checkout_days'] = 0; + $late_fee_details['grace_time'] = config('vehicle_rental.late_checkout_grace_time'); + $checkout_time = Carbon::now()->toDateTimeString(); + $late_fee_details['current_date'] = $checkout_time; + $checkout_late_date_diff = $this->getDateDiff($vehicle_rental->item_booking_end_date, $checkout_time); + $late_fee_details['total_late_hours'] = ($checkout_late_date_diff['total_days'] * 24) + $checkout_late_date_diff['total_hours']; + if ($checkout_late_date_diff['total_days']) { + $late_fee_details['late_checkout_days'] = $checkout_late_date_diff['total_days']; + $late_fee_details['late_checkout_days_fee'] = $late_fee_details['late_checkout_days'] * $vehicle_rental->item_userable->per_day_amount; + } + if ($checkout_late_date_diff['total_hours']) { + $late_fee_details['late_checkout_hours'] = $checkout_late_date_diff['total_hours']; + if ($vehicle_rental->item_userable->per_hour_amount) { + if ($late_fee_details['grace_time'] < $late_fee_details['late_checkout_hours']) { + $late_fee_details['revised_late_hours_from_gracetime'] = $late_fee_details['late_checkout_hours'] - $late_fee_details['grace_time']; + } + $late_fee_details['late_checkout_hours_fee'] = $late_fee_details['revised_late_hours_from_gracetime'] * $vehicle_rental->item_userable->per_hour_amount; + } else { + $late_fee_details['late_checkout_hours_fee'] = $vehicle_rental->item_userable->per_day_amount; + } + } + $late_fee_details['vehicle_type_late_checkout_fee'] = $vehicle_rental->item_userable->vehicle_type->late_checkout_addtional_fee; + $late_fee_details['late_checkout_total_fee'] = $late_fee_details['late_checkout_days_fee'] + $late_fee_details['late_checkout_hours_fee'] + $late_fee_details['vehicle_type_late_checkout_fee']; + if ($late_fee_details['grace_time'] > $late_fee_details['late_checkout_hours']) { + $late_fee_details['late_checkout_total_fee'] = 0; + } + // calculate manual payment + $late_fee_details['paid_deposit_amount'] = 0; + $late_fee_details['paid_manual_amount'] = 0; + if ($claim_request_amount > 0 || $late_fee_details['late_checkout_total_fee'] > 0) { + $booker_manual_payable = $claim_request_amount + $late_fee_details['late_checkout_total_fee']; + if ($booker_manual_payable >= $vehicle_rental->deposit_amount) { + $late_fee_details['paid_deposit_amount'] = $vehicle_rental->deposit_amount; + $late_fee_details['paid_manual_amount'] = $booker_manual_payable - $vehicle_rental->deposit_amount; + } else if ($vehicle_rental->deposit_amount > $booker_manual_payable) { + $late_fee_details['paid_deposit_amount'] = $booker_manual_payable; + $late_fee_details['paid_manual_amount'] = 0; + } + } + return $late_fee_details; + } + +} diff --git a/app/Plugins/Vehicles/Services/VehicleSpecialPriceService.php b/app/Plugins/Vehicles/Services/VehicleSpecialPriceService.php new file mode 100644 index 0000000..466825b --- /dev/null +++ b/app/Plugins/Vehicles/Services/VehicleSpecialPriceService.php @@ -0,0 +1,58 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Vehicles\Services; + +use Plugins\Vehicles\Model\VehicleSpecialPrice; + +class VehicleSpecialPriceService +{ + /** + * VehicleSpecialPriceService constructor. + */ + public function __construct() + { + } + + /** + * @return mixed + */ + public function getVehicleSpecialPriceList() + { + $vehicle_special_price_list = VehicleSpecialPrice::where('is_active', true)->lists('id', 'vehicle_type_id', 'start_date', 'end_date', 'discount_percentage'); + return $vehicle_special_price_list; + } + + /** + * @param $vehicle_type_id + * @param $booking_amount + * @param $vehicle_rental_start_date + * @param $vehicle_rental_end_date + * @return float|int + */ + public function processSpecialPriceAmount($vehicle_type_id, $booking_amount, $vehicle_rental_start_date, $vehicle_rental_end_date) + { + $special_price_amount = 0; + $vehicle_special_price = VehicleSpecialPrice::where('vehicle_type_id', $vehicle_type_id) + ->where('start_date', '<=', $vehicle_rental_start_date) + ->where('end_date', '>=', $vehicle_rental_end_date) + ->where('is_active', 1) + ->orderBy('discount_percentage', 'desc')->first(); + if (!empty($vehicle_special_price)) { + $special_price_amount = $booking_amount * $vehicle_special_price->discount_percentage / 100; + } + return $special_price_amount; + } +} diff --git a/app/Plugins/Vehicles/Services/VehicleTypePriceService.php b/app/Plugins/Vehicles/Services/VehicleTypePriceService.php new file mode 100644 index 0000000..90297e2 --- /dev/null +++ b/app/Plugins/Vehicles/Services/VehicleTypePriceService.php @@ -0,0 +1,60 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Vehicles\Services; + +use Plugins\Vehicles\Model\VehicleTypePrice; + +class VehicleTypePriceService +{ + /** + * VehicleTypePriceService constructor. + */ + public function __construct() + { + } + + /** + * @return mixed + */ + public function getVehicleTypePriceList() + { + $vehicle_type_price_list = VehicleTypePrice::where('is_active', true)->lists('id', 'vehicle_type_id', 'minimum_no_of_day', 'maximum_no_of_day', 'discount_percentage'); + return $vehicle_type_price_list; + } + + /** + * @param $vehicle_type_id + * @param $booking_amount + * @param $date_diff + * @return float|int + */ + public function processTypePriceAmount($vehicle_type_id, $booking_amount, $date_diff) + { + $vehicle_type_price_amount = 0; + if ($date_diff['total_hours']) { + $date_diff['total_days'] = $date_diff['total_days'] + 1; + } + $vehicle_type_price = VehicleTypePrice::where('vehicle_type_id', $vehicle_type_id) + ->where('minimum_no_of_day', '<=', $date_diff['total_days']) + ->where('maximum_no_of_day', '>=', $date_diff['total_days']) + ->where('is_active', 1) + ->orderBy('discount_percentage', 'desc')->first(); + if (!empty($vehicle_type_price)) { + $vehicle_type_price_amount = $booking_amount * $vehicle_type_price->discount_percentage / 100; + } + return $vehicle_type_price_amount; + } +} diff --git a/app/Plugins/Vehicles/Services/VehicleTypeService.php b/app/Plugins/Vehicles/Services/VehicleTypeService.php new file mode 100644 index 0000000..82278a8 --- /dev/null +++ b/app/Plugins/Vehicles/Services/VehicleTypeService.php @@ -0,0 +1,56 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Vehicles\Services; + +use Plugins\Vehicles\Model\VehicleType; + +class VehicleTypeService +{ + /** + * VehicleTypeService constructor. + */ + public function __construct() + { + } + + /** + * @return mixed + */ + public function getVehicleTypeList() + { + $vehicle_type_list = VehicleType::where('is_active', true)->lists('id', 'name'); + foreach($vehicle_type_list as $value=>$key) { + $vehicle_type_list[$value] = (integer)$key; + } + return $vehicle_type_list; + } + + /** + * @return mixed + */ + public function getVehicleTypePriceFilters() + { + $vehicle_types = VehicleType::where('is_active', true)->get(); + $vehicle_type_filters = array(); + if ($vehicle_types) { + $vehicle_type_filters['max_day_price'] = collect($vehicle_types)->max('maximum_day_price'); + $vehicle_type_filters['min_day_price'] = collect($vehicle_types)->min('minimum_day_price'); + $vehicle_type_filters['max_hour_price'] = collect($vehicle_types)->max('maximum_hour_price'); + $vehicle_type_filters['min_hour_price'] = collect($vehicle_types)->min('minimum_hour_price'); + } + return $vehicle_type_filters; + } +} diff --git a/app/Plugins/Vehicles/Transformers/AdminCounterLocationTransformer.php b/app/Plugins/Vehicles/Transformers/AdminCounterLocationTransformer.php new file mode 100644 index 0000000..f950023 --- /dev/null +++ b/app/Plugins/Vehicles/Transformers/AdminCounterLocationTransformer.php @@ -0,0 +1,40 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Vehicles\Transformers; + +use League\Fractal; +use Plugins\Vehicles\Model\CounterLocation; + + +/** + * Class AdminCounterLocationTransformer + * @package Plugins\Vehicles\Transformers + */ +class AdminCounterLocationTransformer extends Fractal\TransformerAbstract +{ + + /** + * @param CounterLocation $counter_location + * @return array + */ + public function transform(CounterLocation $counter_location) + { + $output = array_only($counter_location->toArray(), ['id', 'created_at', 'address', 'latitude', 'longitude', 'phone', 'mobile', 'fax', 'email']); + return $output; + } + + +} diff --git a/app/Plugins/Vehicles/Transformers/AdminFuelTypeTransformer.php b/app/Plugins/Vehicles/Transformers/AdminFuelTypeTransformer.php new file mode 100644 index 0000000..3fc0cb5 --- /dev/null +++ b/app/Plugins/Vehicles/Transformers/AdminFuelTypeTransformer.php @@ -0,0 +1,39 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Vehicles\Transformers; + +use League\Fractal; +use Plugins\Vehicles\Model\FuelType; + + +/** + * Class AdminFuelTypeTransformer + * @package Plugins\Vehicles\Transformers + */ +class AdminFuelTypeTransformer extends Fractal\TransformerAbstract +{ + + /** + * @param FuelType $fuel_type + * @return array + */ + public function transform(FuelType $fuel_type) + { + $output = array_only($fuel_type->toArray(), ['id', 'name']); + return $output; + } + +} diff --git a/app/Plugins/Vehicles/Transformers/AdminVehicleCompanyTransformer.php b/app/Plugins/Vehicles/Transformers/AdminVehicleCompanyTransformer.php new file mode 100644 index 0000000..f78ec28 --- /dev/null +++ b/app/Plugins/Vehicles/Transformers/AdminVehicleCompanyTransformer.php @@ -0,0 +1,66 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Vehicles\Transformers; + +use League\Fractal; +use Plugins\Vehicles\Model\VehicleCompany; +use App\Transformers\UserSimpleTransformer; + + +/** + * Class AdminVehicleCompanyTransformer + * @package Plugins\Vehicles\Transformers + */ +class AdminVehicleCompanyTransformer extends Fractal\TransformerAbstract +{ + /** + * @var array + */ + protected $availableIncludes = [ + 'User' + ]; + + /** + * @param VehicleCompany $vehicle_company + * @return array + */ + public function transform(VehicleCompany $vehicle_company) + { + $output = array_only($vehicle_company->toArray(), ['id', 'created_at', 'user_id', 'name', 'address', 'latitude', 'longitude', 'phone', 'mobile', 'fax', 'email', 'vehicle_count', 'is_active']); + $output['user_id'] = (integer)$output['user_id']; + if ($output['is_active'] == 1) { + $output['status'] = "Active"; + } else if ($output['is_active'] == 0) { + $output['status'] = "Deactive"; + } else if ($output['is_active'] == 2) { + $output['status'] = "Rejected"; + } + return $output; + } + + /** + * @param VehicleCompany $vehicle_company + * @return Fractal\Resource\Item|null + */ + public function includeUser(VehicleCompany $vehicle_company) + { + if ($vehicle_company->user) { + return $this->item($vehicle_company->user, new UserSimpleTransformer()); + } else { + return null; + } + } +} diff --git a/app/Plugins/Vehicles/Transformers/AdminVehicleMakeTransformer.php b/app/Plugins/Vehicles/Transformers/AdminVehicleMakeTransformer.php new file mode 100644 index 0000000..d472d3d --- /dev/null +++ b/app/Plugins/Vehicles/Transformers/AdminVehicleMakeTransformer.php @@ -0,0 +1,41 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Vehicles\Transformers; + +use League\Fractal; +use Plugins\Vehicles\Model\VehicleMake; + + +/** + * Class AdminVehicleMakeTransformer + * @package Plugins\Vehicles\Transformers + */ +class AdminVehicleMakeTransformer extends Fractal\TransformerAbstract +{ + + /** + * @param VehicleMake $vehicle_make + * @return array + */ + public function transform(VehicleMake $vehicle_make) + { + $output = array_only($vehicle_make->toArray(), ['id', 'created_at', 'name', 'slug', 'vehicle_count', 'vehicle_model_count', 'is_active']); + $output['is_active'] = ($output['is_active'] == 1) ? true : false; + return $output; + } + + +} diff --git a/app/Plugins/Vehicles/Transformers/AdminVehicleModelTransformer.php b/app/Plugins/Vehicles/Transformers/AdminVehicleModelTransformer.php new file mode 100644 index 0000000..a6eaa4d --- /dev/null +++ b/app/Plugins/Vehicles/Transformers/AdminVehicleModelTransformer.php @@ -0,0 +1,59 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Vehicles\Transformers; + +use League\Fractal; +use Plugins\Vehicles\Model\VehicleModel; +use Plugins\Vehicles\Transformers\AdminVehicleMakeTransformer; + + +/** + * Class AdminVehicleModelTransformer + * @package Plugins\Vehicles\Transformers + */ +class AdminVehicleModelTransformer extends Fractal\TransformerAbstract +{ + /** + * @var array + */ + protected $availableIncludes = [ + 'VehicleMake' + ]; + + /** + * @param VehicleModel $vehicle_model + * @return array + */ + public function transform(VehicleModel $vehicle_model) + { + $output = array_only($vehicle_model->toArray(), ['id', 'created_at', 'name', 'slug', 'vehicle_make_id', 'vehicle_count', 'is_active']); + $output['is_active'] = ($output['is_active'] == 1) ? true : false; + return $output; + } + + /** + * @param VehicleModel $vehicle_model + * @return Fractal\Resource\Item|null + */ + public function includeVehicleMake(VehicleModel $vehicle_model) + { + if ($vehicle_model->vehicle_make) { + return $this->item($vehicle_model->vehicle_make, new AdminVehicleMakeTransformer()); + } else { + return null; + } + } +} diff --git a/app/Plugins/Vehicles/Transformers/AdminVehicleSpecialPriceTransformer.php b/app/Plugins/Vehicles/Transformers/AdminVehicleSpecialPriceTransformer.php new file mode 100644 index 0000000..f56963c --- /dev/null +++ b/app/Plugins/Vehicles/Transformers/AdminVehicleSpecialPriceTransformer.php @@ -0,0 +1,63 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Vehicles\Transformers; + +use League\Fractal; +use Plugins\Vehicles\Model\VehicleSpecialPrice; + + + +/** + * Class AdminVehicleSpecialPriceTransformer + * @package Plugins\Vehicles\Transformers + */ +class AdminVehicleSpecialPriceTransformer extends Fractal\TransformerAbstract +{ + + /** + * List of resources possible to include + * + * @var array + */ + protected $availableIncludes = [ + 'VehicleType' + ]; + + /** + * @param VehicleSpecialPrice $vehicle_special_price + * @return array + */ + public function transform(VehicleSpecialPrice $vehicle_special_price) + { + $output = array_only($vehicle_special_price->toArray(), ['id', 'created_at', 'start_date', 'end_date', 'vehicle_type_id', 'discount_percentage', 'is_active']); + $output['is_active'] = ($output['is_active'] == 1) ? true : false; + return $output; + } + + /** + * @param VehicleTypePrice $vehicle_type_price + * @return Fractal\Resource\Item|null + */ + public function includeVehicleType(VehicleSpecialPrice $vehicle_special_price) + { + if ($vehicle_special_price->vehicle_type) { + return $this->item($vehicle_special_price->vehicle_type, new AdminVehicleTypeTransformer()); + } else { + return null; + } + + } +} diff --git a/app/Plugins/Vehicles/Transformers/AdminVehicleTransformer.php b/app/Plugins/Vehicles/Transformers/AdminVehicleTransformer.php new file mode 100644 index 0000000..5bd55da --- /dev/null +++ b/app/Plugins/Vehicles/Transformers/AdminVehicleTransformer.php @@ -0,0 +1,192 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Vehicles\Transformers; + +use League\Fractal; +use Plugins\Vehicles\Model\Vehicle; +use App\Transformers\AttachmentTransformer; +use App\Transformers\UserSimpleTransformer; +use App\Attachment; + + +/** + * Class AdminVehicleTransformer + * @package Plugins\Vehicles\Transformers + */ +class AdminVehicleTransformer extends Fractal\TransformerAbstract +{ + /** + * @var array + */ + protected $availableIncludes = [ + 'CounterLocation', 'VehicleMake', 'VehicleModel', 'VehicleType', 'VehicleCompany', 'FuelType', 'Attachments', 'User' + ]; + + /** + * @param Vehicle $vehicle + * @return array + */ + public function transform(Vehicle $vehicle) + { + $output = array_only($vehicle->toArray(), ['id', 'created_at', 'name', 'slug', 'user_id', 'vehicle_company_id', 'vehicle_make_id', 'vehicle_model_id', 'vehicle_type_id', 'driven_kilometer', 'vehicle_no', 'no_of_seats', 'no_of_doors', 'no_of_gears', 'is_manual_transmission', 'no_small_bags', 'no_large_bags', 'is_ac', 'minimum_age_of_driver', 'mileage', 'is_km', 'is_airbag', 'no_of_airbags', 'is_abs', 'per_hour_amount', 'per_day_amount', 'fuel_type_id', 'vehicle_rental_count', 'feedback_count', 'feedback_rating', 'is_paid', 'is_active']); + $output['id'] = (integer)$output['id']; + $output['user_id'] = (integer)$output['user_id']; + $output['vehicle_company_id'] = (integer)$output['vehicle_company_id']; + $output['vehicle_make_id'] = (integer)$output['vehicle_make_id']; + $output['vehicle_model_id'] = (integer)$output['vehicle_model_id']; + $output['vehicle_type_id'] = (integer)$output['vehicle_type_id']; + $output['fuel_type_id'] = (integer)$output['fuel_type_id']; + $output['is_paid'] = ($output['is_paid'] == 1) ? true : false; + $output['is_active'] = ($output['is_active'] == 1) ? true : false; + $output['is_ac'] = ($output['is_ac'] == 1) ? 1 : 0; + $output['is_km'] = ($output['is_km'] == 1) ? 1 : 0; + $output['is_airbag'] = ($output['is_airbag'] == 1) ? 1 : 0; + $output['is_abs'] = ($output['is_abs'] == 1) ? 1 : 0; + $output['is_manual_transmission'] = ($output['is_manual_transmission'] == 1) ? 1 : 0; + if(is_null($vehicle->feedback_count)){ + $output['feedback_count'] = 0; + } + if(is_null($vehicle->vehicle_rental_count)){ + $output['vehicle_rental_count'] = 0; + } + $pick_up_location = $drop_up_location = array(); + foreach ($vehicle->counter_location as $location) { + if ($location->pivot->is_drop) { + $drop_up_location[] = array_only($location->toArray(), ['id', 'address', 'latitude', 'longitude']); + } + if ($location->pivot->is_pickup) { + $pick_up_location[] = array_only($location->toArray(), ['id', 'address', 'latitude', 'longitude']); + } + } + $output['per_day_amount'] = (double)$output['per_day_amount']; + $output['per_hour_amount'] = (double)$output['per_hour_amount']; + $output['pickup_locations'] = $pick_up_location; + $output['drop_locations'] = $drop_up_location; + return $output; + } + + /** + * @param Vehicle $vehicle + * @return Fractal\Resource\Item|null + */ + public function includeVehicleMake(Vehicle $vehicle) + { + if ($vehicle->vehicle_make) { + return $this->item($vehicle->vehicle_make, new AdminVehicleMakeTransformer()); + } else { + return null; + } + } + + /** + * @param Vehicle $vehicle + * @return Fractal\Resource\Item|null + */ + public function includeVehicleModel(Vehicle $vehicle) + { + if ($vehicle->vehicle_model) { + return $this->item($vehicle->vehicle_model, new AdminVehicleModelTransformer()); + } else { + return null; + } + } + + /** + * @param Vehicle $vehicle + * @return Fractal\Resource\Item|null + */ + public function includeVehicleType(Vehicle $vehicle) + { + if ($vehicle->vehicle_type) { + $enabled_includes = array(); + (isPluginEnabled('VehicleExtraAccessories')) ? $enabled_includes[] = 'vehicle_type_extra_accessory' : ''; + (isPluginEnabled('VehicleInsurances')) ? $enabled_includes[] = 'vehicle_type_insurance' : ''; + (isPluginEnabled('VehicleFuelOptions')) ? $enabled_includes[] = 'vehicle_type_fuel_option' : ''; + (isPluginEnabled('VehicleSurcharges')) ? $enabled_includes[] = 'vehicle_type_surcharge' : ''; + (isPluginEnabled('VehicleTaxes')) ? $enabled_includes[] = 'vehicle_type_tax' : ''; + return $this->item($vehicle->vehicle_type, (new AdminVehicleTypeTransformer())->setDefaultIncludes($enabled_includes)); + } else { + return null; + } + } + + /** + * @param Vehicle $vehicle + * @return Fractal\Resource\Item|null + */ + public function includeVehicleCompany(Vehicle $vehicle) + { + if ($vehicle->vehicle_company) { + return $this->item($vehicle->vehicle_company, new AdminVehicleCompanyTransformer()); + } else { + return null; + } + } + + /** + * @param Vehicle $vehicle + * @return Fractal\Resource\Item|null + */ + public function includeFuelType(Vehicle $vehicle) + { + if ($vehicle->fuel_type) { + return $this->item($vehicle->fuel_type, new AdminFuelTypeTransformer()); + } else { + return null; + } + } + + /** + * @param Vehicle $vehicle + * @return Fractal\Resource\Item|null + */ + public function includeCounterLocation(Vehicle $vehicle) + { + if ($vehicle->counter_location) { + return $this->collection($vehicle->counter_location, new AdminCounterLocationTransformer()); + } else { + return null; + } + } + + /** + * @param Vehicle $vehicle + * @return Fractal\Resource\Item|null + */ + public function includeUser(Vehicle $vehicle) + { + if ($vehicle->user) { + return $this->item($vehicle->user, new UserSimpleTransformer()); + } else { + return null; + } + } + + /** + * @param Vehicle $vehicle + * @return mixed + */ + public function includeAttachments(Vehicle $vehicle) + { + if ($vehicle->attachments) { + return $this->item($vehicle->attachments, new AttachmentTransformer()); + } else { + $vehicle->attachments = Attachment::where('id', '=', config('constants.ConstAttachment.VehicleAvatar'))->first(); + $vehicle->attachments->attachmentable_id = $vehicle->id; + return $this->item($vehicle->attachments, new AttachmentTransformer()); + } + } +} diff --git a/app/Plugins/Vehicles/Transformers/AdminVehicleTypePriceTransformer.php b/app/Plugins/Vehicles/Transformers/AdminVehicleTypePriceTransformer.php new file mode 100644 index 0000000..790473c --- /dev/null +++ b/app/Plugins/Vehicles/Transformers/AdminVehicleTypePriceTransformer.php @@ -0,0 +1,61 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Vehicles\Transformers; + +use League\Fractal; +use Plugins\Vehicles\Model\VehicleTypePrice; + +/** + * Class AdminVehicleTypePriceTransformer + * @package Plugins\Vehicles\Transformers + */ +class AdminVehicleTypePriceTransformer extends Fractal\TransformerAbstract +{ + /** + * List of resources possible to include + * + * @var array + */ + protected $availableIncludes = [ + 'VehicleType' + ]; + + /** + * @param VehicleTypePrice $vehicle_type_price + * @return array + */ + public function transform(VehicleTypePrice $vehicle_type_price) + { + $output = array_only($vehicle_type_price->toArray(), ['id', 'created_at', 'vehicle_type_id', 'minimum_no_of_day', 'maximum_no_of_day', 'discount_percentage', 'is_active']); + $output['is_active'] = ($output['is_active'] == 1) ? true : false; + return $output; + } + + + /** + * @param VehicleTypePrice $vehicle_type_price + * @return Fractal\Resource\Item|null + */ + public function includeVehicleType(VehicleTypePrice $vehicle_type_price) + { + if ($vehicle_type_price->vehicle_type) { + return $this->item($vehicle_type_price->vehicle_type, new AdminVehicleTypeTransformer()); + } else { + return null; + } + + } +} \ No newline at end of file diff --git a/app/Plugins/Vehicles/Transformers/AdminVehicleTypeTransformer.php b/app/Plugins/Vehicles/Transformers/AdminVehicleTypeTransformer.php new file mode 100644 index 0000000..f626d0b --- /dev/null +++ b/app/Plugins/Vehicles/Transformers/AdminVehicleTypeTransformer.php @@ -0,0 +1,114 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Vehicles\Transformers; + +use League\Fractal; +use Plugins\Vehicles\Model\VehicleType; + + +/** + * Class AdminVehicleTypeTransformer + * @package Plugins\Vehicles\Transformers + */ +class AdminVehicleTypeTransformer extends Fractal\TransformerAbstract +{ + + /** + * List of resources possible to include + * @var array + */ + protected $availableIncludes = [ + 'VehicleTypeExtraAccessory', 'VehicleTypeFuelOption', 'VehicleTypeInsurance', 'VehicleTypeSurcharge', 'VehicleTypeTax' + ]; + + /** + * @param VehicleType $vehicle_type + * @return array + */ + public function transform(VehicleType $vehicle_type) + { + $output = array_only($vehicle_type->toArray(), ['id', 'created_at', 'name', 'slug', 'minimum_hour_price', 'maximum_hour_price', 'minimum_day_price', 'maximum_day_price', 'drop_location_differ_unit_price', 'drop_location_differ_additional_fee', 'deposit_amount', 'vehicle_count', 'is_active']); + $output['is_active'] = ($output['is_active'] == 1) ? true : false; + return $output; + } + + /** + * @param VehicleType $vehicle_type + * @return Fractal\Resource\Item|null + */ + public function includeVehicleTypeExtraAccessory(VehicleType $vehicle_type) + { + if (!empty($vehicle_type->vehicle_type_extra_accessory)) { + return $this->collection($vehicle_type->vehicle_type_extra_accessory, (new \Plugins\VehicleExtraAccessories\Transformers\VehicleTypeExtraAccessoryTransformer())->setDefaultIncludes(['vehicle_extra_accessory'])); + } else { + return null; + } + + } + + public function includeVehicleTypeFuelOption(VehicleType $vehicle_type) + { + if (!empty($vehicle_type->vehicle_type_fuel_option)) { + return $this->collection($vehicle_type->vehicle_type_fuel_option, (new \Plugins\VehicleFuelOptions\Transformers\VehicleTypeFuelOptionTransformer())->setDefaultIncludes(['vehicle_fuel_option'])); + } else { + return null; + } + + } + + /** + * @param VehicleType $vehicle_type + * @return Fractal\Resource\Collection|null + */ + public function includeVehicleTypeInsurance(VehicleType $vehicle_type) + { + if (!empty($vehicle_type->vehicle_type_insurance)) { + return $this->collection($vehicle_type->vehicle_type_insurance, (new \Plugins\VehicleInsurances\Transformers\VehicleTypeInsuranceTransformer())->setDefaultIncludes(['vehicle_insurance'])); + } else { + return null; + } + + } + + /** + * @param VehicleType $vehicle_type + * @return Fractal\Resource\Collection|null + */ + public function includeVehicleTypeSurcharge(VehicleType $vehicle_type) + { + if (!empty($vehicle_type->vehicle_type_surcharge)) { + return $this->collection($vehicle_type->vehicle_type_surcharge, (new \Plugins\VehicleSurcharges\Transformers\VehicleTypeSurchargeTransformer())->setDefaultIncludes(['vehicle_surcharge'])); + } else { + return null; + } + + } + + /** + * @param VehicleType $vehicle_type + * @return Fractal\Resource\Collection|null + */ + public function includeVehicleTypeTax(VehicleType $vehicle_type) + { + if (!empty($vehicle_type->vehicle_type_tax)) { + return $this->collection($vehicle_type->vehicle_type_tax, (new \Plugins\VehicleTaxes\Transformers\VehicleTypeTaxTransformer())->setDefaultIncludes(['vehicle_tax'])); + } else { + return null; + } + + } + +} diff --git a/app/Plugins/Vehicles/Transformers/CounterLocationTransformer.php b/app/Plugins/Vehicles/Transformers/CounterLocationTransformer.php new file mode 100644 index 0000000..466db37 --- /dev/null +++ b/app/Plugins/Vehicles/Transformers/CounterLocationTransformer.php @@ -0,0 +1,40 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Vehicles\Transformers; + +use League\Fractal; +use Plugins\Vehicles\Model\CounterLocation; + + +/** + * Class CounterLocationTransformer + * @package Plugins\Vehicles\Transformers + */ +class CounterLocationTransformer extends Fractal\TransformerAbstract +{ + + /** + * @param CounterLocation $counter_location + * @return array + */ + public function transform(CounterLocation $counter_location) + { + $output = array_only($counter_location->toArray(), ['id', 'address']); + return $output; + } + + +} diff --git a/app/Plugins/Vehicles/Transformers/FuelTypeTransformer.php b/app/Plugins/Vehicles/Transformers/FuelTypeTransformer.php new file mode 100644 index 0000000..e9efd53 --- /dev/null +++ b/app/Plugins/Vehicles/Transformers/FuelTypeTransformer.php @@ -0,0 +1,39 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Vehicles\Transformers; + +use League\Fractal; +use Plugins\Vehicles\Model\FuelType; + + +/** + * Class FuelTypeTransformer + * @package Plugins\Vehicles\Transformers + */ +class FuelTypeTransformer extends Fractal\TransformerAbstract +{ + + /** + * @param FuelType $fuel_type + * @return array + */ + public function transform(FuelType $fuel_type) + { + $output = array_only($fuel_type->toArray(), ['id', 'name']); + return $output; + } + +} diff --git a/app/Plugins/Vehicles/Transformers/UnavailableVehicleTransformer.php b/app/Plugins/Vehicles/Transformers/UnavailableVehicleTransformer.php new file mode 100644 index 0000000..7878130 --- /dev/null +++ b/app/Plugins/Vehicles/Transformers/UnavailableVehicleTransformer.php @@ -0,0 +1,58 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Vehicles\Transformers; + +use League\Fractal; +use Plugins\Vehicles\Model\UnavailableVehicle; +use Plugins\Vehicles\Transformers\VehicleTransformer; +use Carbon; + +/** + * Class UnavailableVehicleTransformer + * @package Plugins\Vehicles\Transformers + */ +class UnavailableVehicleTransformer extends Fractal\TransformerAbstract +{ + /** + * @var array + */ + protected $availableIncludes = [ + 'Vehicle' + ]; + + /** + * @param UnavailableVehicle $unavailable_vehicle + * @return array + */ + public function transform(UnavailableVehicle $unavailable_vehicle) + { + $output = array_only($unavailable_vehicle->toArray(), ['id', 'item_user_id', 'vehicle_id', 'start_date', 'end_date', 'is_dummy']); + return $output; + } + + /** + * @param UnavailableVehicle $unavailable_vehicle + * @return Fractal\Resource\Item|null + */ + public function includeVehicle(UnavailableVehicle $unavailable_vehicle) + { + if ($unavailable_vehicle->vehicle) { + return $this->item($unavailable_vehicle->vehicle, new VehicleTransformer()); + } else { + return null; + } + } +} diff --git a/app/Plugins/Vehicles/Transformers/VehicleCompanyTransformer.php b/app/Plugins/Vehicles/Transformers/VehicleCompanyTransformer.php new file mode 100644 index 0000000..922241b --- /dev/null +++ b/app/Plugins/Vehicles/Transformers/VehicleCompanyTransformer.php @@ -0,0 +1,58 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Vehicles\Transformers; + +use League\Fractal; +use Plugins\Vehicles\Model\VehicleCompany; +use App\Transformers\UserSimpleTransformer; + + +/** + * Class VehicleCompanyTransformer + * @package Plugins\Vehicles\Transformers + */ +class VehicleCompanyTransformer extends Fractal\TransformerAbstract +{ + /** + * @var array + */ + protected $availableIncludes = [ + 'User' + ]; + + /** + * @param VehicleCompany $vehicle_company + * @return array + */ + public function transform(VehicleCompany $vehicle_company) + { + $output = array_only($vehicle_company->toArray(), ['id', 'user_id', 'name', 'address', 'latitude', 'longitude', 'phone', 'mobile', 'fax', 'email', 'vehicle_count', 'is_active']); + return $output; + } + + /** + * @param VehicleCompany $vehicle_company + * @return Fractal\Resource\Item|null + */ + public function includeUser(VehicleCompany $vehicle_company) + { + if ($vehicle_company->user) { + return $this->item($vehicle_company->user, new UserSimpleTransformer()); + } else { + return null; + } + } +} diff --git a/app/Plugins/Vehicles/Transformers/VehicleMakeTransformer.php b/app/Plugins/Vehicles/Transformers/VehicleMakeTransformer.php new file mode 100644 index 0000000..983ff87 --- /dev/null +++ b/app/Plugins/Vehicles/Transformers/VehicleMakeTransformer.php @@ -0,0 +1,40 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Vehicles\Transformers; + +use League\Fractal; +use Plugins\Vehicles\Model\VehicleMake; + + +/** + * Class VehicleMakeTransformer + * @package Plugins\Vehicles\Transformers + */ +class VehicleMakeTransformer extends Fractal\TransformerAbstract +{ + + /** + * @param VehicleMake $vehicle_make + * @return array + */ + public function transform(VehicleMake $vehicle_make) + { + $output = array_only($vehicle_make->toArray(), ['id', 'name']); + return $output; + } + + +} diff --git a/app/Plugins/Vehicles/Transformers/VehicleModelTransformer.php b/app/Plugins/Vehicles/Transformers/VehicleModelTransformer.php new file mode 100644 index 0000000..77a71f7 --- /dev/null +++ b/app/Plugins/Vehicles/Transformers/VehicleModelTransformer.php @@ -0,0 +1,57 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Vehicles\Transformers; + +use League\Fractal; +use Plugins\Vehicles\Model\VehicleModel; +use Plugins\Vehicles\Transformers\VehicleMakeTransformer; + +/** + * Class VehicleModelTransformer + * @package Plugins\Vehicles\Transformers + */ +class VehicleModelTransformer extends Fractal\TransformerAbstract +{ + /** + * @var array + */ + protected $availableIncludes = [ + 'VehicleMake' + ]; + + /** + * @param VehicleModel $vehicle_model + * @return array + */ + public function transform(VehicleModel $vehicle_model) + { + $output = array_only($vehicle_model->toArray(), ['id', 'name']); + return $output; + } + + /** + * @param VehicleModel $vehicle_model + * @return Fractal\Resource\Item|null + */ + public function includeVehicleMake(VehicleModel $vehicle_model) + { + if ($vehicle_model->vehicle_make) { + return $this->item($vehicle_model->vehicle_make, new AdminVehicleMakeTransformer()); + } else { + return null; + } + } +} diff --git a/app/Plugins/Vehicles/Transformers/VehicleSimpleTransformer.php b/app/Plugins/Vehicles/Transformers/VehicleSimpleTransformer.php new file mode 100644 index 0000000..725bfaa --- /dev/null +++ b/app/Plugins/Vehicles/Transformers/VehicleSimpleTransformer.php @@ -0,0 +1,38 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Vehicles\Transformers; + +use League\Fractal; +use Plugins\Vehicles\Model\Vehicle; + + +/** + * Class VehicleSimpleTransformer + * @package Plugins\Vehicles\Transformers + */ +class VehicleSimpleTransformer extends Fractal\TransformerAbstract +{ + /** + * @param Vehicle $vehicle + * @return array + */ + public function transform(Vehicle $vehicle) + { + $output = array_only($vehicle->toArray(), ['id', 'name']); + return $output; + } + +} diff --git a/app/Plugins/Vehicles/Transformers/VehicleSpecialPriceTransformer.php b/app/Plugins/Vehicles/Transformers/VehicleSpecialPriceTransformer.php new file mode 100644 index 0000000..9e5906f --- /dev/null +++ b/app/Plugins/Vehicles/Transformers/VehicleSpecialPriceTransformer.php @@ -0,0 +1,63 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Vehicles\Transformers; + +use League\Fractal; +use Plugins\Vehicles\Model\VehicleSpecialPrice; + + + +/** + * Class VehicleSpecialPriceTransformer + * @package Plugins\Vehicles\Transformers + */ +class VehicleSpecialPriceTransformer extends Fractal\TransformerAbstract +{ + + /** + * List of resources possible to include + * + * @var array + */ + protected $availableIncludes = [ + 'VehicleType' + ]; + + /** + * @param VehicleSpecialPrice $vehicle_special_price + * @return array + */ + public function transform(VehicleSpecialPrice $vehicle_special_price) + { + $output = array_only($vehicle_special_price->toArray(), ['id', 'created_at', 'start_date', 'end_date', 'vehicle_type_id', 'discount_percentage', 'is_active']); + $output['is_active'] = ($output['is_active'] == 1) ? true : false; + return $output; + } + + /** + * @param VehicleTypePrice $vehicle_type_price + * @return Fractal\Resource\Item|null + */ + public function includeVehicleType(VehicleSpecialPrice $vehicle_special_price) + { + if ($vehicle_special_price->vehicle_type) { + return $this->item($vehicle_special_price->vehicle_type, new VehicleTypeTransformer()); + } else { + return null; + } + + } +} diff --git a/app/Plugins/Vehicles/Transformers/VehicleTransformer.php b/app/Plugins/Vehicles/Transformers/VehicleTransformer.php new file mode 100644 index 0000000..4c93f40 --- /dev/null +++ b/app/Plugins/Vehicles/Transformers/VehicleTransformer.php @@ -0,0 +1,226 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Vehicles\Transformers; + +use League\Fractal; +use Plugins\Vehicles\Model\Vehicle; +use App\Transformers\AttachmentTransformer; +use App\Attachment; +use App\Transformers\UserSimpleTransformer; +use App\User; + + +/** + * Class VehicleTransformer + * @package Plugins\Vehicles\Transformers + */ +class VehicleTransformer extends Fractal\TransformerAbstract +{ + /** + * List of resources possible to include + * + * @var array + */ + protected $availableIncludes = [ + 'VehicleType', 'FuelType', 'CounterLocation', 'VehicleCompany', 'VehicleMake', 'VehicleModel', 'Attachments', 'User' + ]; + + /** + * @param Vehicle $vehicle + * @return array + */ + public function transform(Vehicle $vehicle) + { + $output = array_only($vehicle->toArray(), ['id', 'created_at', 'name', 'slug', 'user_id', 'vehicle_company_id', 'vehicle_make_id', 'vehicle_model_id', 'vehicle_type_id', 'driven_kilometer', 'vehicle_no', 'no_of_seats', 'no_of_doors', 'no_of_gears', 'is_manual_transmission', 'no_small_bags', 'no_large_bags', 'is_ac', 'minimum_age_of_driver', 'mileage', 'is_km', 'is_airbag', 'no_of_airbags', 'is_abs', 'per_hour_amount', 'per_day_amount', 'fuel_type_id', 'feedback_count', 'feedback_rating', 'is_paid', 'is_active']); + $output['id'] = (integer)$output['id']; + $output['user_id'] = (integer)$output['user_id']; + $output['vehicle_company_id'] = (integer)$output['vehicle_company_id']; + $output['vehicle_make_id'] = (integer)$output['vehicle_make_id']; + $output['vehicle_model_id'] = (integer)$output['vehicle_model_id']; + $output['vehicle_type_id'] = (integer)$output['vehicle_type_id']; + $output['fuel_type_id'] = (integer)$output['fuel_type_id']; + $output['is_paid'] = ($output['is_paid'] == 1) ? true : false; + $output['is_active'] = ($output['is_active'] == 1) ? true : false; + $output['is_ac'] = ($output['is_ac'] == 1) ? 1 : 0; + $output['is_km'] = ($output['is_km'] == 1) ? 1 : 0; + $output['is_airbag'] = ($output['is_airbag'] == 1) ? 1 : 0; + $output['is_abs'] = ($output['is_abs'] == 1) ? 1 : 0; + $output['is_manual_transmission'] = ($output['is_manual_transmission'] == 1) ? 1 : 0; + if(is_null($vehicle->feedback_count)){ + $output['feedback_count'] = 0; + } + if(is_null($vehicle->vehicle_rental_count)){ + $output['vehicle_rental_count'] = 0; + } + if (!is_null($vehicle->booking_amount)) { + $output['booking_amount'] = $vehicle->booking_amount; + } + if (!is_null($vehicle->max_discount_percent)) { + $output['max_discount_percent'] = (integer)$vehicle->max_discount_percent; + } + if (!is_null($vehicle->price_details)) { + $output['price_details'] = $vehicle->price_details; + } + $pick_up_location = $drop_up_location = array(); + foreach($vehicle->counter_location as $location){ + if($location->pivot->is_drop){ + $drop_up_location[] = array_only($location->toArray(), ['id', 'address', 'latitude', 'longitude']); + } + if($location->pivot->is_pickup){ + $pick_up_location[] = array_only($location->toArray(), ['id', 'address', 'latitude', 'longitude']); + } + } + $output['per_day_amount'] = (double)$output['per_day_amount']; + $output['per_hour_amount'] = (double)$output['per_hour_amount']; + $output['pickup_locations'] = $pick_up_location; + $output['drop_locations'] = $drop_up_location; + return $output; + } + + /** + * @param Vehicle $vehicle + * @return Fractal\Resource\Item|null + */ + public function includeVehicleType(Vehicle $vehicle) + { + if ($vehicle->vehicle_type) { + $enabled_includes = array(); + (isPluginEnabled('VehicleExtraAccessories')) ? $enabled_includes[] = 'vehicle_type_extra_accessory' : ''; + (isPluginEnabled('VehicleInsurances')) ? $enabled_includes[] = 'vehicle_type_insurance' : ''; + (isPluginEnabled('VehicleFuelOptions')) ? $enabled_includes[] = 'vehicle_type_fuel_option' : ''; + (isPluginEnabled('VehicleSurcharges')) ? $enabled_includes[] = 'vehicle_type_surcharge' : ''; + (isPluginEnabled('VehicleTaxes')) ? $enabled_includes[] = 'vehicle_type_tax' : ''; + return $this->item($vehicle->vehicle_type, (new VehicleTypeTransformer())->setDefaultIncludes($enabled_includes)); + } else { + return null; + } + + } + + /** + * @param Vehicle $vehicle + * @return Fractal\Resource\Item|null + */ + public function includeFuelType(Vehicle $vehicle) + { + if ($vehicle->fuel_type) { + return $this->item($vehicle->fuel_type, new FuelTypeTransformer()); + } else { + return null; + } + + } + + /** + * @param Vehicle $vehicle + * @return Fractal\Resource\Item|null + */ + public function includeCounterLocation(Vehicle $vehicle) + { + if ($vehicle->counter_location) { + return $this->collection($vehicle->counter_location, new CounterLocationTransformer()); + } else { + return null; + } + + } + + /** + * @param Vehicle $vehicle + * @return Fractal\Resource\Item|null + */ + public function includeVehicleCompany(Vehicle $vehicle) + { + if ($vehicle->vehicle_company) { + return $this->item($vehicle->vehicle_company, new VehicleCompanyTransformer()); + } else { + return null; + } + + } + + /** + * @param Vehicle $vehicle + * @return Fractal\Resource\Item|null + */ + public function includeVehicleMake(Vehicle $vehicle) + { + if ($vehicle->vehicle_make) { + return $this->item($vehicle->vehicle_make, new VehicleMakeTransformer()); + } else { + return null; + } + + } + + /** + * @param Vehicle $vehicle + * @return Fractal\Resource\Item|null + */ + public function includeVehicleModel(Vehicle $vehicle) + { + if ($vehicle->vehicle_model) { + return $this->item($vehicle->vehicle_model, new VehicleModelTransformer()); + } else { + return null; + } + + } + + /** + * @param Vehicle $vehicle + * @return Fractal\Resource\Item|null + */ + public function includeUserModel(Vehicle $vehicle) + { + if ($vehicle->user) { + return $this->item($vehicle->user, new UserTransformer()); + } else { + return null; + } + + } + + /** + * @param Vehicle $vehicle + * @return mixed + */ + public function includeAttachments(Vehicle $vehicle) + { + if ($vehicle->attachments) { + return $this->item($vehicle->attachments, new AttachmentTransformer()); + } else { + $vehicle->attachments = Attachment::where('id', '=', config('constants.ConstAttachment.VehicleAvatar'))->first(); + $vehicle->attachments->attachmentable_id = $vehicle->id; + return $this->item($vehicle->attachments, new AttachmentTransformer()); + } + } + + /** + * @param Vehicle $vehicle + * @return Fractal\Resource\Item|null + */ + public function includeUser(Vehicle $vehicle) + { + if ($vehicle->user) { + return $this->item($vehicle->user, new UserSimpleTransformer()); + } else { + return null; + } + + } + +} diff --git a/app/Plugins/Vehicles/Transformers/VehicleTypePriceTransformer.php b/app/Plugins/Vehicles/Transformers/VehicleTypePriceTransformer.php new file mode 100644 index 0000000..a997144 --- /dev/null +++ b/app/Plugins/Vehicles/Transformers/VehicleTypePriceTransformer.php @@ -0,0 +1,61 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Vehicles\Transformers; + +use League\Fractal; +use Plugins\Vehicles\Model\VehicleTypePrice; + +/** + * Class VehicleTypePriceTransformer + * @package Plugins\Vehicles\Transformers + */ +class VehicleTypePriceTransformer extends Fractal\TransformerAbstract +{ + /** + * List of resources possible to include + * + * @var array + */ + protected $availableIncludes = [ + 'VehicleType' + ]; + + /** + * @param VehicleTypePrice $vehicle_type_price + * @return array + */ + public function transform(VehicleTypePrice $vehicle_type_price) + { + $output = array_only($vehicle_type_price->toArray(), ['id', 'created_at', 'vehicle_type_id', 'minimum_no_of_day', 'maximum_no_of_day', 'discount_percentage', 'is_active']); + $output['is_active'] = ($output['is_active'] == 1) ? true : false; + return $output; + } + + + /** + * @param VehicleTypePrice $vehicle_type_price + * @return Fractal\Resource\Item|null + */ + public function includeVehicleType(VehicleTypePrice $vehicle_type_price) + { + if ($vehicle_type_price->vehicle_type) { + return $this->item($vehicle_type_price->vehicle_type, new AdminVehicleTypeTransformer()); + } else { + return null; + } + + } +} \ No newline at end of file diff --git a/app/Plugins/Vehicles/Transformers/VehicleTypeSimpleTransformer.php b/app/Plugins/Vehicles/Transformers/VehicleTypeSimpleTransformer.php new file mode 100644 index 0000000..c04b237 --- /dev/null +++ b/app/Plugins/Vehicles/Transformers/VehicleTypeSimpleTransformer.php @@ -0,0 +1,38 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Vehicles\Transformers; + +use League\Fractal; +use Plugins\Vehicles\Model\VehicleType; + + +/** + * Class VehiclTypeSimpleTransformer + * @package Plugins\Vehicles\Transformers + */ +class VehicleTypeSimpleTransformer extends Fractal\TransformerAbstract +{ + /** + * @param Vehicle $vehicle + * @return array + */ + public function transform(VehicleType $vehicle_type) + { + $output = array_only($vehicle_type->toArray(), ['id', 'name']); + return $output; + } + +} diff --git a/app/Plugins/Vehicles/Transformers/VehicleTypeTransformer.php b/app/Plugins/Vehicles/Transformers/VehicleTypeTransformer.php new file mode 100644 index 0000000..2a049d2 --- /dev/null +++ b/app/Plugins/Vehicles/Transformers/VehicleTypeTransformer.php @@ -0,0 +1,136 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Vehicles\Transformers; + +use League\Fractal; +use Plugins\Vehicles\Model\VehicleType; + + +/** + * Class VehicleTypeTransformer + * @package Plugins\Vehicles\Transformers + */ +class VehicleTypeTransformer extends Fractal\TransformerAbstract +{ + + /** + * List of resources possible to include + * @var array + */ + protected $availableIncludes = [ + 'VehicleTypePrice', 'VehicleSpecialPrice', 'VehicleTypeExtraAccessory', 'VehicleTypeFuelOption', 'VehicleTypeInsurance', 'VehicleTypeSurcharge', 'VehicleTypeTax' + ]; + + /** + * @param VehicleType $vehicle_type + * @return array + */ + public function transform(VehicleType $vehicle_type) + { + $output = array_only($vehicle_type->toArray(), ['id', 'name', 'minimum_hour_price', 'maximum_hour_price', 'minimum_day_price', 'maximum_day_price', 'drop_location_differ_unit_price', 'drop_location_differ_additional_fee', 'deposit_amount', 'vehicle_count']); + return $output; + } + + /** + * @param VehicleType $vehicle_type + * @return Fractal\Resource\Item|null + */ + public function includeVehicleTypePrice(VehicleType $vehicle_type) + { + if ($vehicle_type->vehicle_type_price) { + return $this->collection($vehicle_type->vehicle_type_price, new VehicleTypePriceTransformer()); + } else { + return null; + } + + } + + /** + * @param VehicleType $vehicle_type + * @return Fractal\Resource\Item|null + */ + public function includeVehicleTypeExtraAccessory(VehicleType $vehicle_type) + { + if (!empty($vehicle_type->vehicle_type_extra_accessory)) { + return $this->collection($vehicle_type->vehicle_type_extra_accessory, (new \Plugins\VehicleExtraAccessories\Transformers\VehicleTypeExtraAccessoryTransformer())->setDefaultIncludes(['vehicle_extra_accessory'])); + } else { + return null; + } + + } + + public function includeVehicleTypeFuelOption(VehicleType $vehicle_type) + { + if (!empty($vehicle_type->vehicle_type_fuel_option)) { + return $this->collection($vehicle_type->vehicle_type_fuel_option, (new \Plugins\VehicleFuelOptions\Transformers\VehicleTypeFuelOptionTransformer())->setDefaultIncludes(['vehicle_fuel_option'])); + } else { + return null; + } + + } + + public function includeVehicleTypeInsurance(VehicleType $vehicle_type) + { + if (!empty($vehicle_type->vehicle_type_insurance)) { + return $this->collection($vehicle_type->vehicle_type_insurance, (new \Plugins\VehicleInsurances\Transformers\VehicleTypeInsuranceTransformer())->setDefaultIncludes(['vehicle_insurance'])); + } else { + return null; + } + + } + + /** + * @param VehicleType $vehicle_type + * @return Fractal\Resource\Item|null + */ + public function includeVehicleSpecialPrice(VehicleType $vehicle_type) + { + if ($vehicle_type->vehicle_special_price) { + return $this->collection($vehicle_type->vehicle_special_price, new VehicleSpecialPriceTransformer()); + } else { + return null; + } + + } + /** + * @param VehicleType $vehicle_type + * @return Fractal\Resource\Collection|null + */ + public function includeVehicleTypeSurcharge(VehicleType $vehicle_type) + { + if (!empty($vehicle_type->vehicle_type_surcharge)) { + return $this->collection($vehicle_type->vehicle_type_surcharge, (new \Plugins\VehicleSurcharges\Transformers\VehicleTypeSurchargeTransformer())->setDefaultIncludes(['vehicle_surcharge'])); + } else { + return null; + } + + } + + /** + * @param VehicleType $vehicle_type + * @return Fractal\Resource\Collection|null + */ + public function includeVehicleTypeTax(VehicleType $vehicle_type) + { + if (!empty($vehicle_type->vehicle_type_tax)) { + return $this->collection($vehicle_type->vehicle_type_tax, (new \Plugins\VehicleTaxes\Transformers\VehicleTypeTaxTransformer())->setDefaultIncludes(['vehicle_tax'])); + } else { + return null; + } + + } + +} diff --git a/app/Plugins/Vehicles/plugin.json b/app/Plugins/Vehicles/plugin.json new file mode 100644 index 0000000..99a0a11 --- /dev/null +++ b/app/Plugins/Vehicles/plugin.json @@ -0,0 +1,9 @@ +{ + "name": "Vehicles", + "class": "fa fa-2x fa-taxi", + "description": "By enabling this plugin, user can work with vehicle related functionalities.", + "dependencies": "", + "module_id": "", + "module_hash": "", + "display_order": "9" +} diff --git a/app/Plugins/Vehicles/routes.php b/app/Plugins/Vehicles/routes.php new file mode 100644 index 0000000..134a1d9 --- /dev/null +++ b/app/Plugins/Vehicles/routes.php @@ -0,0 +1,152 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +/* +|-------------------------------------------------------------------------- +| Application Routes +|-------------------------------------------------------------------------- +| +| Here is where you can register all of the routes for an application. +| It is a breeze. Simply tell Lumen the URIs it should respond to +| and give it the Closure to call when that URI is requested. +| +*/ +$api = $this->app->make('Dingo\Api\Routing\Router'); +$api->version(['v1'], function ($api) { + + //Admin Booking + $api->group(['prefix' => 'admin', 'namespace' => 'Plugins\Vehicles\Controllers\Admin', 'middleware' => 'apitracking'], function () use ($api) { + $api->get('vehicle_makes', 'AdminVehicleMakesController@index'); + $api->post('vehicle_makes', 'AdminVehicleMakesController@store'); + $api->get('vehicle_makes/{id}/edit', 'AdminVehicleMakesController@edit'); + $api->put('vehicle_makes/{id}', 'AdminVehicleMakesController@update'); + $api->get('vehicle_makes/{id}', 'AdminVehicleMakesController@show'); + $api->delete('vehicle_makes/{id}', 'AdminVehicleMakesController@destroy'); + + $api->get('vehicle_types', 'AdminVehicleTypesController@index'); + $api->post('vehicle_types', 'AdminVehicleTypesController@store'); + $api->get('vehicle_types/{id}/edit', 'AdminVehicleTypesController@edit'); + $api->put('vehicle_types/{id}', 'AdminVehicleTypesController@update'); + $api->get('vehicle_types/{id}', 'AdminVehicleTypesController@show'); + $api->delete('vehicle_types/{id}', 'AdminVehicleTypesController@destroy'); + + $api->get('vehicle_type_prices', 'AdminVehicleTypePricesController@index'); + $api->post('vehicle_type_prices', 'AdminVehicleTypePricesController@store'); + $api->get('vehicle_type_prices/{id}/edit', 'AdminVehicleTypePricesController@edit'); + $api->put('vehicle_type_prices/{id}', 'AdminVehicleTypePricesController@update'); + $api->get('vehicle_type_prices/{id}', 'AdminVehicleTypePricesController@show'); + $api->delete('vehicle_type_prices/{id}', 'AdminVehicleTypePricesController@destroy'); + + $api->get('vehicle_special_prices', 'AdminVehicleSpecialPricesController@index'); + $api->post('vehicle_special_prices', 'AdminVehicleSpecialPricesController@store'); + $api->get('vehicle_special_prices/{id}/edit', 'AdminVehicleSpecialPricesController@edit'); + $api->put('vehicle_special_prices/{id}', 'AdminVehicleSpecialPricesController@update'); + $api->get('vehicle_special_prices/{id}', 'AdminVehicleSpecialPricesController@show'); + $api->delete('vehicle_special_prices/{id}', 'AdminVehicleSpecialPricesController@destroy'); + + $api->get('vehicle_companies', 'AdminVehicleCompaniesController@index'); + $api->post('vehicle_companies', 'AdminVehicleCompaniesController@store'); + $api->get('vehicle_companies/{id}/edit', 'AdminVehicleCompaniesController@edit'); + $api->put('vehicle_companies/{id}', 'AdminVehicleCompaniesController@update'); + $api->get('vehicle_companies/{id}', 'AdminVehicleCompaniesController@show'); + $api->delete('vehicle_companies/{id}', 'AdminVehicleCompaniesController@destroy'); + $api->put('vehicle_companies/{id}/active', 'AdminVehicleCompaniesController@active'); + $api->put('vehicle_companies/{id}/reject', 'AdminVehicleCompaniesController@reject'); + $api->put('vehicle_companies/{id}/deactive', 'AdminVehicleCompaniesController@deactive'); + + $api->get('vehicle_models', 'AdminVehicleModelsController@index'); + $api->post('vehicle_models', 'AdminVehicleModelsController@store'); + $api->get('vehicle_models/{id}/edit', 'AdminVehicleModelsController@edit'); + $api->put('vehicle_models/{id}', 'AdminVehicleModelsController@update'); + $api->get('vehicle_models/{id}', 'AdminVehicleModelsController@show'); + $api->delete('vehicle_models/{id}', 'AdminVehicleModelsController@destroy'); + + $api->get('counter_locations', 'AdminCounterLocationsController@index'); + $api->post('counter_locations', 'AdminCounterLocationsController@store'); + $api->get('counter_locations/{id}/edit', 'AdminCounterLocationsController@edit'); + $api->put('counter_locations/{id}', 'AdminCounterLocationsController@update'); + $api->get('counter_locations/{id}', 'AdminCounterLocationsController@show'); + $api->delete('counter_locations/{id}', 'AdminCounterLocationsController@destroy'); + + $api->get('vehicles', 'AdminVehiclesController@index'); + $api->post('vehicles', 'AdminVehiclesController@store'); + $api->get('vehicles/{id}/edit', 'AdminVehiclesController@edit'); + $api->post('vehicles/{id}', 'AdminVehiclesController@update'); + $api->get('vehicles/{id}', 'AdminVehiclesController@show'); + $api->delete('vehicles/{id}', 'AdminVehiclesController@destroy'); + $api->get('vehicle/add', 'AdminVehiclesController@getVehicleRelatedDetail'); + $api->put('vehicles/{id}/deactive', 'AdminVehiclesController@deactive'); + $api->put('vehicles/{id}/active', 'AdminVehiclesController@active'); + + $api->get('fuel_types', 'AdminFuelTypesController@index'); + $api->post('fuel_types', 'AdminFuelTypesController@store'); + $api->get('fuel_types/{id}/edit', 'AdminFuelTypesController@edit'); + $api->put('fuel_types/{id}', 'AdminFuelTypesController@update'); + $api->get('fuel_types/{id}', 'AdminFuelTypesController@show'); + $api->delete('fuel_types/{id}', 'AdminFuelTypesController@destroy'); + + $api->get('unavailable_vehicles', 'AdminUnavailableVehiclesController@index'); + $api->post('unavailable_vehicles', 'AdminUnavailableVehiclesController@store'); + $api->get('unavailable_vehicles/{id}/edit', 'AdminUnavailableVehiclesController@edit'); + $api->put('unavailable_vehicles/{id}', 'AdminUnavailableVehiclesController@update'); + $api->delete('unavailable_vehicles/{id}', 'AdminUnavailableVehiclesController@destroy'); + $api->get('unavailable_vehicles/{id}', 'AdminUnavailableVehiclesController@show'); + + }); + $api->group(['namespace' => 'Plugins\Vehicles\Controllers', 'middleware' => 'apitracking'], function () use ($api) { + $api->get('vehicles/filters', 'VehiclesController@getVehicleRelatedFilters'); + $api->get('vehicles/me', 'VehiclesController@index'); + $api->post('vehicles/search', 'VehiclesController@search'); + $api->post('vehicles', 'VehiclesController@store'); + $api->get('vehicles/{id}/edit', 'VehiclesController@edit'); + $api->post('vehicles/paynow', 'VehiclesController@payNow'); + $api->post('vehicles/{id}', 'VehiclesController@update'); + $api->get('vehicles/{id}', 'VehiclesController@show'); + $api->delete('vehicles/{id}', 'VehiclesController@destroy'); + $api->get('vehicle/add', 'VehiclesController@getVehicleRelatedDetail'); + + + $api->get('vehicle_type_prices', 'VehicleTypePricesController@index'); + $api->get('vehicle_type_prices/{id}/edit', 'VehicleTypePricesController@edit'); + $api->get('vehicle_type_prices/{id}', 'VehicleTypePricesController@show'); + + $api->get('vehicle_special_prices', 'VehicleSpecialPricesController@index'); + $api->get('vehicle_special_prices/{id}/edit', 'VehicleSpecialPricesController@edit'); + $api->get('vehicle_special_prices/{id}', 'VehicleSpecialPricesController@show'); + + $api->get('vehicle_companies', 'VehicleCompaniesController@index'); + $api->post('vehicle_companies', 'VehicleCompaniesController@store'); + $api->get('vehicle_companies/edit', 'VehicleCompaniesController@edit'); + $api->get('vehicle_companies/show', 'VehicleCompaniesController@show'); + $api->delete('vehicle_companies/{id}', 'VehicleCompaniesController@destroy'); + + $api->get('vehicle_makes', 'VehicleMakesController@index'); + + $api->get('vehicle_models', 'VehicleModelsController@index'); + + $api->get('vehicle_types', 'VehicleTypesController@index'); + $api->get('vehicle_types/{id}', 'VehicleTypesController@show'); + + $api->get('counter_locations', 'CounterLocationsController@index'); + + $api->get('fuel_types', 'FuelTypesController@index'); + + $api->get('unavailable_vehicles', 'UnavailableVehiclesController@index'); + $api->post('unavailable_vehicles', 'UnavailableVehiclesController@store'); + $api->get('unavailable_vehicles/{id}/edit', 'UnavailableVehiclesController@edit'); + $api->put('unavailable_vehicles/{id}', 'UnavailableVehiclesController@update'); + $api->delete('unavailable_vehicles/{id}', 'UnavailableVehiclesController@destroy'); + }); +}); diff --git a/app/Plugins/Withdrawals/Controllers/Admin/AdminUserCashWithdrawalsController.php b/app/Plugins/Withdrawals/Controllers/Admin/AdminUserCashWithdrawalsController.php new file mode 100644 index 0000000..8ec3e2d --- /dev/null +++ b/app/Plugins/Withdrawals/Controllers/Admin/AdminUserCashWithdrawalsController.php @@ -0,0 +1,187 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Withdrawals\Controllers\Admin; + +use Plugins\Withdrawals\Model\MoneyTransferAccount; +use Illuminate\Http\Request; + +use App\Http\Controllers\Controller; +use Plugins\Withdrawals\Model\UserCashWithdrawal; +use JWTAuth; +use Validator; +use Tymon\JWTAuth\Exceptions\JWTException; +use Plugins\Withdrawals\Transformers\UserCashWithdrawalTransformer; +use App\User; +use App\Services\TransactionService; +use Plugins\Withdrawals\Services\UserCashWithdrawalService; +use DB; + +/** + * UserCashWithdrawals resource representation. + * @Resource("Admin/AdminUserCashWithdrawals") + */ +class AdminUserCashWithdrawalsController extends Controller +{ + /** + * @var + */ + protected $withdrawalService; + /** + * @var TransactionService + */ + protected $transactionService; + + /** + * AdminUserCashWithdrawalsController constructor. + */ + public function __construct() + { + // check whether the user is logged in or not. + $this->middleware('jwt.auth'); + // Check the logged user role. + $this->middleware('role'); + $this->setTransactionService(); + $this->setUserCashWithdrawalService(); + } + + public function setTransactionService() + { + $this->transactionService = new TransactionService(); + } + + public function setUserCashWithdrawalService() + { + $this->withdrawalService = new UserCashWithdrawalService(); + } + + /** + * Show all user cash withdrawals. + * Get a JSON representation of all the user cash withdrawals. + * + * @Get("/user_cash_withdrawals?filter={filter}&sort={sort}&sortby={sortby}&q={q}") + * @Parameters({ + * @Parameter("filter", type="integer", required=false, description="Filter the user_cash_withdrawals list by status.", default=null), + * @Parameter("sort", type="string", required=false, description="Sort the user_cash_withdrawals list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort user_cash_withdrawals by Ascending / Descending Order.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1) + * }) + */ + public function index(Request $request) + { + $user_cash_withdrawals = UserCashWithdrawal::with('user', 'money_transfer_account', 'withdrawal_status') + ->select(DB::raw('user_cash_withdrawals.*')) + ->leftJoin(DB::raw('(select id,username from users) as user'), 'user.id', '=', 'user_cash_withdrawals.user_id') + ->leftJoin(DB::raw('(select id,name from withdrawal_statuses) as withdrawal_status'), 'withdrawal_status.id', '=', 'user_cash_withdrawals.withdrawal_status_id') + ->leftJoin(DB::raw('(select id,account from money_transfer_accounts) as money_transfer_account'), 'money_transfer_account.id', '=', 'user_cash_withdrawals.money_transfer_account_id') + ->filterByRequest($request)->paginate(config('constants.ConstPageLimit')); + return $this->response->paginator($user_cash_withdrawals, (new UserCashWithdrawalTransformer)->setDefaultIncludes(['user', 'money_transfer_account', 'withdrawal_status'])); + } + + /** + * Edit the specified user cash withdrawal. + * Edit the user cash withdrawal with a `id`. + * @Get("/user_cash_withdrawals/{id}/edit") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"id": 1, "user_id": 1, "withdrwa_status_id": 1, "amount": 100, "money_transfer_account_id": 1, "User": {}, "WithdrawalStatus": {}, "MoneyTransferAccount": {}}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function edit($id) + { + $user_cash_withdrawal = UserCashWithdrawal::with('user', 'money_transfer_account', 'withdrawal_status')->find($id); + if (!$user_cash_withdrawal) { + return $this->response->errorNotFound("Invalid Request"); + } + return $this->response->item($user_cash_withdrawal, (new UserCashWithdrawalTransformer)->setDefaultIncludes(['user', 'money_transfer_account', 'withdrawal_status'])); + } + + /** + * Update the specified user cash withdrawal. + * Update the user cash withdrawal with a `id`. + * @Put("/user_cash_withdrawals/{id}") + * @Transaction({ + * @Request({"id": 1, "withdrwa_status_id": 1, "amount": 100}), + * @Response(200, body={"success": "Record has been updated."}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {}, "status_code": 422}) + * }) + */ + public function update(Request $request, $id) + { + $user_cash_withdrawal_data = $request->only('withdrawal_status_id'); + $validator = Validator::make($user_cash_withdrawal_data, UserCashWithdrawal::GetValidationRule(), UserCashWithdrawal::GetValidationMessage()); + $user_cash_withdrawal = false; + if ($request->has('id')) { + $user_cash_withdrawal = UserCashWithdrawal::find($id); + $user_cash_withdrawal = ($request->id != $id) ? false : $user_cash_withdrawal; + } + if (($user_cash_withdrawal->withdrawal_status_id == config('constants.ConstWithdrawalStatus.Rejected')) || ($user_cash_withdrawal->withdrawal_status_id == config('constants.ConstWithdrawalStatus.Success'))) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Status already changed.'); + } + $check_money_transfer_account = MoneyTransferAccount::find($user_cash_withdrawal->money_transfer_account_id); + if (!$check_money_transfer_account) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('No Money Transfer Account is added or set as primary.'); + } + if ($validator->passes() && $user_cash_withdrawal) { + try { + $user_cash_withdrawal->update($user_cash_withdrawal_data); + if ($user_cash_withdrawal) { + $user = User::find($user_cash_withdrawal->user_id); + if ($user_cash_withdrawal->withdrawal_status_id == config('constants.ConstWithdrawalStatus.Rejected')) { + //transaction logs + $this->transactionService->log(config('constants.ConstUserTypes.Admin'), $user->id, config('constants.ConstTransactionTypes.CashWithdrawalRequestRejected'), $user_cash_withdrawal->amount, $user_cash_withdrawal->id, 'Withdrawals', config('constants.ConstPaymentGateways.Wallet')); + $user->available_wallet_amount = $user->available_wallet_amount + $user_cash_withdrawal->amount; + $user->blocked_amount = $user->blocked_amount - $user_cash_withdrawal->amount; + $user->save(); + } + if ($user_cash_withdrawal->withdrawal_status_id == config('constants.ConstWithdrawalStatus.Success')) { + //transaction logs + $this->transactionService->log(config('constants.ConstUserTypes.Admin'), $user->id, config('constants.ConstTransactionTypes.CashWithdrawalRequestApproved'), $user_cash_withdrawal->amount, $user_cash_withdrawal->id, 'Withdrawals', config('constants.ConstPaymentGateways.Wallet')); + $user->blocked_amount = $user->blocked_amount - $user_cash_withdrawal->amount; + $user->save(); + } + $this->withdrawalService->withdrawMail($user->id, $user->username, $user->email, $user_cash_withdrawal); + return response()->json(['Success' => 'UserCashWithdrawal has been updated'], 200); + } + } catch (\Exception $e) { + throw new \Dingo\Api\Exception\StoreResourceFailedException('UserCashWithdrawal could not be updated. Please, try again.'); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('UserCashWithdrawal could not be updated. Please, try again.', $validator->errors()); + } + } + + /** + * Delete the specified user cash withdrawal. + * Delete the user cash withdrawal with a `id`. + * @Delete("/user_cash_withdrawals/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"success": "Record Deleted."}), + * @Response(404, body={"message": "Invalid Request", "status_code": 404}) + * }) + */ + public function destroy($id) + { + $user_cash_withdrawal = UserCashWithdrawal::find($id); + if (!$user_cash_withdrawal) { + return $this->response->errorNotFound("Invalid Request"); + } else { + $user_cash_withdrawal->delete(); + } + return response()->json(['Success' => 'UserCashWithdrawal deleted'], 200); + } +} diff --git a/app/Plugins/Withdrawals/Controllers/Admin/AdminWithdrawalStatusesController.php b/app/Plugins/Withdrawals/Controllers/Admin/AdminWithdrawalStatusesController.php new file mode 100644 index 0000000..573c586 --- /dev/null +++ b/app/Plugins/Withdrawals/Controllers/Admin/AdminWithdrawalStatusesController.php @@ -0,0 +1,62 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Withdrawals\Controllers\Admin; + +use Illuminate\Http\Request; + +use App\Http\Controllers\Controller; +use Plugins\Withdrawals\Model\WithdrawalStatus; +use JWTAuth; +use Tymon\JWTAuth\Exceptions\JWTException; +use Plugins\Withdrawals\Transformers\WithdrawalStatusTransformer; + +/** + * WithdrawalStatuses resource representation. + * @Resource("Admin/WithdrawalStatuses") + */ +class AdminWithdrawalStatusesController extends Controller +{ + /** + * Create a new controller instance. + * + * @return void + */ + public function __construct() + { + // Check the logged user authentication. + $this->middleware('jwt.auth'); + // Check the logged user role. + $this->middleware('role'); + } + + /** + * Show all withdrawal_statuses + * Get a JSON representation of all the withdrawal_statuses. + * + * @Get("/withdrawal_statuses?filter={filter}&sort={sort}&sortby={sortby}&q={q}") + * @Parameters({ + * @Parameter("filter", type="integer", required=false, description="Filter the withdrawal_statuses list by status.", default=null), + * @Parameter("sort", type="string", required=false, description="Sort the withdrawal_statuses list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort withdrawal_statuses by Ascending / Descending Order.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1) + * }) + */ + public function index(Request $request) + { + $withdrawal_statuses = WithdrawalStatus::filterByRequest($request)->paginate(config('constants.ConstPageLimit')); + return $this->response->paginator($withdrawal_statuses, (new WithdrawalStatusTransformer)); + } +} diff --git a/app/Plugins/Withdrawals/Controllers/MoneyTransferAccountsController.php b/app/Plugins/Withdrawals/Controllers/MoneyTransferAccountsController.php new file mode 100644 index 0000000..ad7ca59 --- /dev/null +++ b/app/Plugins/Withdrawals/Controllers/MoneyTransferAccountsController.php @@ -0,0 +1,118 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Withdrawals\Controllers; + +use Illuminate\Http\Request; + + + +use App\Http\Controllers\Controller; +use Plugins\Withdrawals\Model\MoneyTransferAccount; +use Plugins\Withdrawals\Transformers\MoneyTransferAccountTransformer; +use JWTAuth; +use Validator; + +/** + * Money Transfer Accounts resource representation. + * @Resource("MoneyTransferAccounts") + */ +class MoneyTransferAccountsController extends Controller +{ + /** + * MoneyTransferAccountsController constructor. + */ + public function __construct() + { + // Check the logged user authentication. + $this->middleware('jwt.auth'); + } + + /** + * Show all money transfer accounts + * Get a JSON representation of all the money transfer account. + * + * @Get("/money_transfer_accounts?page={page}") + * @Parameters({ + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1) + * }) + */ + public function index() + { + $user = $this->auth->user(); + $money_transfer_accounts = MoneyTransferAccount::with('user')->where('user_id', '=', $user->id)->get(); + return $this->response->collection($money_transfer_accounts, (new MoneyTransferAccountTransformer)->setDefaultIncludes(['user'])); + } + + /** + * Store a new money transfer account. + * Store a new money transfer account with a a `user_id` and `account`. + * @Post("/money_transfer_accounts") + * @Transaction({ + * @Request({"user_id": 1, "account": "XXXXXX"}), + * @Response(200, body={"success": "Record has been added."}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {"account": {}}, "status_code": 422}) + * }) + */ + public function store(Request $request) + { + $money_transfer_account_data = $request->only('account'); + $user = $this->auth->user(); + if ($user) { + $money_transfer_account_data['user_id'] = $user->id; + } + $validator = Validator::make($money_transfer_account_data, MoneyTransferAccount::GetValidationRule(), MoneyTransferAccount::GetValidationMessage()); + if ($validator->passes()) { + $money_transfer_account = MoneyTransferAccount::create($money_transfer_account_data); + if ($money_transfer_account) { + return response()->json(['Success' => 'Money Transfer Account has been added'], 200); + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Money Transfer Account could not be updated. Please, try again.'); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Money Transfer Account could not be updated. Please, try again.', $validator->errors()); + } + } + + /** + * Delete the specified money transfer account. + * Delete the money transfer account with a `id`. + * @Delete("/money_transfer_accounts/{id}") + * @Transaction({ + * @Request({"id": 1}), + * @Response(200, body={"success": "Record Deleted."}), + * @Response(500, body={"message": "Invalid Request", "status_code": 500}) + * }) + */ + public function destroy($id) + { + $money_transfer_account = MoneyTransferAccount::find($id); + $user = $this->auth->user(); + if ($money_transfer_account && $money_transfer_account->user_id == $user->id) { + $money_transfer_account_verify = MoneyTransferAccount::with('user_cash_withdrawal')->where("id", $id)->whereHas('user_cash_withdrawal', function ($query) { + $query->whereIn('withdrawal_status_id', [config('constants.ConstWithdrawalStatus.Pending'), config('constants.ConstWithdrawalStatus.Approved')]); + })->first(); + if (!$money_transfer_account_verify) { + $money_transfer_account->delete(); + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('One of your withdrawal request is in pending status,So you can\'t delete this now.'); + } + } else { + return $this->response->errorNotFound("Invalid Request"); + + } + return response()->json(['Success' => 'MoneyTransferAccount deleted'], 200); + } +} \ No newline at end of file diff --git a/app/Plugins/Withdrawals/Controllers/UserCashWithdrawalsController.php b/app/Plugins/Withdrawals/Controllers/UserCashWithdrawalsController.php new file mode 100644 index 0000000..d1438e1 --- /dev/null +++ b/app/Plugins/Withdrawals/Controllers/UserCashWithdrawalsController.php @@ -0,0 +1,122 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Withdrawals\Controllers; + +use Illuminate\Http\Request; + +use App\Http\Controllers\Controller; +use Plugins\Withdrawals\Model\UserCashWithdrawal; +use JWTAuth; +use Validator; +use Plugins\Withdrawals\Transformers\UserCashWithdrawalTransformer; +use Plugins\Withdrawals\Services\MoneyTransferAccountService; +use App\Services\TransactionService; + +/** + * UserCashWithdrawals resource representation. + * @Resource("UserCashWithdrawals") + */ +class UserCashWithdrawalsController extends Controller +{ + /** + * @var + */ + protected $transactionService; + /** + * @var MoneyTransferAccountService + */ + protected $MoneyTransferAccountService; + + /** + * UserCashWithdrawalsController constructor. + */ + public function __construct() + { + // Check the logged user authentication. + $this->middleware('jwt.auth'); + $this->setMoneyTransferAccountService(); + $this->setTransactionService(); + } + + public function setMoneyTransferAccountService() + { + $this->MoneyTransferAccountService = new MoneyTransferAccountService(); + } + + public function setTransactionService() + { + $this->transactionService = new TransactionService(); + } + + /** + * Show all user cash withdrawals. + * Get a JSON representation of all the user cash withdrawals. + * + * @Get("/user_cash_withdrawals?filter={filter}&sort={sort}&sortby={sortby}&q={q}") + * @Parameters({ + * @Parameter("filter", type="integer", required=false, description="Filter the user_cash_withdrawals list by status.", default=null), + * @Parameter("sort", type="string", required=false, description="Sort the user_cash_withdrawals list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort user_cash_withdrawals by Ascending / Descending Order.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1) + * }) + */ + public function index(Request $request) + { + $user_cash_withdrawals = UserCashWithdrawal::with('user', 'money_transfer_account', 'withdrawal_status')->filterByRequest($request)->paginate(config('constants.ConstPageLimit')); + return $this->response->paginator($user_cash_withdrawals, (new UserCashWithdrawalTransformer)->setDefaultIncludes(['user', 'money_transfer_account', 'withdrawal_status'])); + } + + /** + * Store a new user cash withdrawal. + * Store a new user cash withdrawal with a 'amount', 'user_id', 'money_transfer_account_id'. + * @Post("/user_cash_withdrawals") + * @Transaction({ + * @Request({"amount": 1000, "user_id": 1, "money_transfer_account_id": 1}), + * @Response(200, body={"success": "Record has been added."}), + * @Response(422, body={"message": "Record could not be updated. Please, try again.", "errors": {"amount": {}}, "status_code": 422}) + * }) + */ + public function store(Request $request) + { + $user_cash_withdrawal_data = $request->only('amount', 'user_id', 'money_transfer_account_id'); + $user = $this->auth->user(); + if ($user) { + $user_cash_withdrawal_data['user_id'] = $user->id; + } + $user_cash_withdrawal_data['withdrawal_status_id'] = 1; + $validator = Validator::make($user_cash_withdrawal_data, UserCashWithdrawal::GetValidationRule(), UserCashWithdrawal::GetValidationMessage()); + if ($validator->passes()) { + if ($user_cash_withdrawal_data['amount'] <= $user->available_wallet_amount) { + $user_cash_withdrawal = UserCashWithdrawal::create($user_cash_withdrawal_data); + if ($user_cash_withdrawal) { + //transaction logs + $this->transactionService->log(config('constants.ConstUserTypes.Admin'), $user->id, config('constants.ConstTransactionTypes.CashWithdrawalRequest'), $user_cash_withdrawal_data['amount'], $user_cash_withdrawal->id, 'Withdrawals', config('constants.ConstPaymentGateways.Wallet')); + //get amount from wallet and stored to blocked amount + $user->available_wallet_amount = $user->available_wallet_amount - $user_cash_withdrawal_data['amount']; + $user->blocked_amount = $user->blocked_amount + $user_cash_withdrawal_data['amount']; + $user->save(); + return response()->json(['Success' => 'User cash withdrawal request has been added'], 200); + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('User Cash Withdrawal could not be updated. Please, try again.'); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('You Dont have sufficient amount in your wallet.'); + } + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('User Cash Withdrawal could not be updated. Please, try again.', $validator->errors()); + } + } +} diff --git a/app/Plugins/Withdrawals/Controllers/WithdrawalStatusesController.php b/app/Plugins/Withdrawals/Controllers/WithdrawalStatusesController.php new file mode 100644 index 0000000..d92cba7 --- /dev/null +++ b/app/Plugins/Withdrawals/Controllers/WithdrawalStatusesController.php @@ -0,0 +1,59 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Withdrawals\Controllers; + +use Illuminate\Http\Request; + +use App\Http\Controllers\Controller; +use Plugins\Withdrawals\Model\WithdrawalStatus; +use JWTAuth; +use Plugins\Withdrawals\Transformers\WithdrawalStatusTransformer; + +/** + * WithdrawalStatuses resource representation. + * @Resource("WithdrawalStatuses") + */ +class WithdrawalStatusesController extends Controller +{ + /** + * Create a new controller instance. + * + * @return void + */ + public function __construct() + { + // Check the logged user authentication. + $this->middleware('jwt.auth'); + } + + /** + * Show all withdrawal statuses. + * Get a JSON representation of all the withdrawal statuses. + * + * @Get("/user_cash_withdrawals?filter={filter}&sort={sort}&sortby={sortby}&q={q}") + * @Parameters({ + * @Parameter("filter", type="integer", required=false, description="Filter the user_cash_withdrawals list by status.", default=null), + * @Parameter("sort", type="string", required=false, description="Sort the user_cash_withdrawals list by sort ley.", default=null), + * @Parameter("sortby", type="string", required=false, description="Sort user_cash_withdrawals by Ascending / Descending Order.", default=null), + * @Parameter("page", type="integer", required=false, description="The page of results to view.", default=1) + * }) + */ + public function index(Request $request) + { + $withdrawal_statuses = WithdrawalStatus::filterByRequest($request)->paginate(config('constants.ConstPageLimit')); + return $this->response->paginator($withdrawal_statuses, (new WithdrawalStatusTransformer)); + } +} diff --git a/app/Plugins/Withdrawals/Model/MoneyTransferAccount.php b/app/Plugins/Withdrawals/Model/MoneyTransferAccount.php new file mode 100644 index 0000000..4918619 --- /dev/null +++ b/app/Plugins/Withdrawals/Model/MoneyTransferAccount.php @@ -0,0 +1,67 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Withdrawals\Model; + +use Illuminate\Database\Eloquent\Model; +use App\User; + +class MoneyTransferAccount extends Model +{ + protected $table = "money_transfer_accounts"; + + /** + * The attributes that are mass assignable. + * + * @var array + */ + protected $fillable = [ + 'account', 'user_id', 'is_primary' + ]; + + public function scopeGetValidationRule() + { + return [ + 'account' => 'required', + 'user_id' => 'required|integer' + ]; + } + + public function scopeGetValidationMessage() + { + return [ + 'account.required' => 'Required', + 'user_id.required' => 'Required', + 'user_id.integer' => 'user_id must be a number!', + ]; + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\HasMany + */ + public function user_cash_withdrawal() + { + return $this->hasMany(UserCashWithdrawal::class); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function user() + { + return $this->belongsTo(User::class); + } + +} diff --git a/app/Plugins/Withdrawals/Model/UserCashWithdrawal.php b/app/Plugins/Withdrawals/Model/UserCashWithdrawal.php new file mode 100644 index 0000000..fe77e11 --- /dev/null +++ b/app/Plugins/Withdrawals/Model/UserCashWithdrawal.php @@ -0,0 +1,146 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Withdrawals\Model; + +use App\Message; +use Illuminate\Http\Request; +use Illuminate\Database\Eloquent\Model; + +use JWTAuth; +use App\User; +use App\Transaction; + +/** + * Class UserCashWithdrawal + * @package App + */ +class UserCashWithdrawal extends Model +{ + /** + * @var string + */ + protected $table = "user_cash_withdrawals"; + /** + * The attributes that are mass assignable. + * + * @var array + */ + protected $fillable = [ + 'amount', 'user_id', 'money_transfer_account_id', 'withdrawal_status_id' + ]; + + + /** + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function money_transfer_account() + { + return $this->belongsTo(MoneyTransferAccount::class); + } + + + /** + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function user() + { + return $this->belongsTo(User::class); + } + + + /** + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function withdrawal_status() + { + return $this->belongsTo(WithdrawalStatus::class); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\MorphTo + */ + public function transactions() + { + return $this->morphMany(Transaction::class, 'transactionable'); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\MorphMany + */ + public function message() + { + return $this->morphMany(Message::class, 'messageable'); + } + + /** + * @param $query + * @param Request $request + * @return mixed + */ + public function scopeFilterByRequest($query, Request $request) + { + $query->orderBy($request->input('sort', 'id'), $request->input('sortby', 'desc')); + if ($request->has('filter')) { + $query->where('withdrawal_status_id', '=', $request->input('filter')); + } + if ($request->has('q')) { + $query->where('user_cash_withdrawals.amount', 'like', '%' . $request->input('q') . '%'); + $query->orWhereHas('user', function ($q) use ($request) { + $q->where('username', 'like', '%' . $request->input('q') . '%'); + }); + $query->orWhereHas('money_transfer_account', function ($q) use ($request) { + $q->where('account', 'like', '%' . $request->input('q') . '%'); + }); + $query->orWhereHas('withdrawal_status', function ($q) use ($request) { + $q->where('name', 'like', '%' . $request->input('q') . '%'); + }); + } + $user = JWTAuth::parseToken()->authenticate(); + if ($user->id != config('constants.ConstUserTypes.Admin')) { + $query->where('user_id', '=', $user->id); + } + return $query; + } + + /** + * @return array + */ + public function scopeGetValidationRule() + { + return [ + 'amount' => 'sometimes|required|min:1|max:4', + 'user_id' => 'sometimes|required|integer', + 'money_transfer_account_id' => 'sometimes|required|integer', + 'withdrawal_status_id' => 'required|integer' + ]; + } + + public function scopeGetValidationMessage() + { + return [ + 'amount.required' => 'Required', + 'amount.min' => 'amount - Minimum length is 1!', + 'amount.max' => 'amount - Maximum length is 4!', + 'user_id.required' => 'Required', + 'user_id.integer' => 'user_id must be anumber!', + 'money_transfer_account_id.required' => 'Required', + 'money_transfer_account_id.integer' => 'money_transfer_account_id must be a number', + 'withdrawal_status_id.required' => 'Required', + 'withdrawal_status_id.integer' => 'withdrawal_status_id must be a number', + ]; + } + +} diff --git a/app/Plugins/Withdrawals/Model/WithdrawalStatus.php b/app/Plugins/Withdrawals/Model/WithdrawalStatus.php new file mode 100644 index 0000000..f00aecb --- /dev/null +++ b/app/Plugins/Withdrawals/Model/WithdrawalStatus.php @@ -0,0 +1,48 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Withdrawals\Model; + +use Illuminate\Http\Request; +use Illuminate\Database\Eloquent\Model; + +class WithdrawalStatus extends Model +{ + /** + * @var string + */ + protected $table = "withdrawal_statuses"; + + + /** + * @return \Illuminate\Database\Eloquent\Relations\HasMany + */ + public function user_cash_withdrawal() + { + return $this->hasMany(UserCashWithdrawal::class); + } + + /** + * @param $query + * @param Request $request + * @return mixed + */ + public function scopeFilterByRequest($query, Request $request) + { + $query->orderBy($request->input('sort', 'id'), $request->input('sortby', 'desc')); + return $query; + } + +} diff --git a/app/Plugins/Withdrawals/Providers/WithdrawServiceProvider.php b/app/Plugins/Withdrawals/Providers/WithdrawServiceProvider.php new file mode 100644 index 0000000..25a3eaf --- /dev/null +++ b/app/Plugins/Withdrawals/Providers/WithdrawServiceProvider.php @@ -0,0 +1,44 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Withdrawals\Providers; + +use Illuminate\Support\ServiceProvider; + +class WithdrawServiceProvider extends ServiceProvider +{ + /** + * Register any application services. + * + * @return void + */ + public function register() + { + include __DIR__ . '/../routes.php'; + $this->app->make('Plugins\Withdrawals\Controllers\MoneyTransferAccountsController'); + $this->app->make('Plugins\Withdrawals\Controllers\UserCashWithdrawalsController'); + $this->app->make('Plugins\Withdrawals\Controllers\Admin\AdminUserCashWithdrawalsController'); + } + + /** + * Bootstrap the application services. + * + * @return void + */ + public function boot() + { + + } +} diff --git a/app/Plugins/Withdrawals/Services/MoneyTransferAccountService.php b/app/Plugins/Withdrawals/Services/MoneyTransferAccountService.php new file mode 100644 index 0000000..cad523f --- /dev/null +++ b/app/Plugins/Withdrawals/Services/MoneyTransferAccountService.php @@ -0,0 +1,34 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Withdrawals\Services; + +use Plugins\Withdrawals\Model\MoneyTransferAccount; + +class MoneyTransferAccountService +{ + /** + * get the active users MoneyTransferAccount + * @param $user_id + * @return $money_transfer_account + */ + public function getUserMoneyTransferAccount($user_id) + { + $money_transfer_account = MoneyTransferAccount::where('user_id', '=', $user_id) + ->where('is_primary', '=', 1) + ->first(); + return $money_transfer_account; + } +} diff --git a/app/Plugins/Withdrawals/Services/UserCashWithdrawalService.php b/app/Plugins/Withdrawals/Services/UserCashWithdrawalService.php new file mode 100644 index 0000000..a408877 --- /dev/null +++ b/app/Plugins/Withdrawals/Services/UserCashWithdrawalService.php @@ -0,0 +1,74 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Withdrawals\Services; + +use App\Services\MailService; +use App\Services\MessageService; + +class UserCashWithdrawalService +{ + /** + * UserCashWithdrawalService constructor. + */ + public function __construct() + { + $this->setMailService(); + $this->setMessageService(); + } + + public function setMailService() + { + $this->mailService = new MailService(); + } + + public function setMessageService() + { + $this->messageService = new MessageService(); + } + + /** + * @param $userid + * @param $username + * @param $email + * @param $withdrawal + */ + public function withdrawMail($userid, $username, $email, $withdrawal) + { + $from = config('constants.ConstUserIds.Admin'); + if ($withdrawal->withdrawal_status_id == config('constants.ConstWithdrawalStatus.Rejected')) { + $template = $this->mailService->getTemplate('Admin Reject Withdraw Request'); + } + if ($withdrawal->withdrawal_status_id == config('constants.ConstWithdrawalStatus.Success')) { + $template = $this->mailService->getTemplate('Admin Approve Withdraw Request'); + } + $emailFindReplace = array( + '##USERNAME##' => $username, + '##AMOUNT##' => $withdrawal->amount, + ); + $this->mailService->sendMail($template, $emailFindReplace, $email, $username); + $default_content = array( + '##SITE_NAME##' => config('site.name'), + '##SITE_URL##' => '' . url('/') . '', + '##FROM_EMAIL##' => config('site.from_email'), + '##CONTACT_MAIL##' => config('site.contact_email') + ); + $withdraw_template = array_merge($emailFindReplace, $default_content); + $message_content_arr = array(); + $message_content_arr['message'] = strtr($template['body_content'], $withdraw_template); + $message_content_arr['subject'] = strtr($template['subject'], $withdraw_template); + $this->messageService->saveMessageContent($message_content_arr, null, $withdrawal->id, $from, $userid, null, 'Withdrawals'); + } +} diff --git a/app/Plugins/Withdrawals/Transformers/MoneyTransferAccountTransformer.php b/app/Plugins/Withdrawals/Transformers/MoneyTransferAccountTransformer.php new file mode 100644 index 0000000..d7118ad --- /dev/null +++ b/app/Plugins/Withdrawals/Transformers/MoneyTransferAccountTransformer.php @@ -0,0 +1,52 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Withdrawals\Transformers; + +use League\Fractal; +use Plugins\Withdrawals\Model\MoneyTransferAccount; +use App\Transformers\UserTransformer; + +class MoneyTransferAccountTransformer extends Fractal\TransformerAbstract +{ + /** + * List of resources possible to include + * + * @var array + */ + protected $availableIncludes = [ + 'User' + ]; + + public function transform(MoneyTransferAccount $money_transfer_account) + { + $output = array_only($money_transfer_account->toArray(), ['id', 'account', 'user_id', 'is_primary']); + return $output; + } + + /** + * @param MoneyTransferAccount $money_transfer_account + * @return Fractal\Resource\Item + */ + public function includeUser(MoneyTransferAccount $money_transfer_account) + { + if ($money_transfer_account->user) { + return $this->item($money_transfer_account->user, new UserTransformer()); + } else { + return null; + } + + } +} diff --git a/app/Plugins/Withdrawals/Transformers/UserCashWithdrawalTransformer.php b/app/Plugins/Withdrawals/Transformers/UserCashWithdrawalTransformer.php new file mode 100644 index 0000000..614019d --- /dev/null +++ b/app/Plugins/Withdrawals/Transformers/UserCashWithdrawalTransformer.php @@ -0,0 +1,92 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Withdrawals\Transformers; + +use League\Fractal; +use Plugins\Withdrawals\Model\UserCashWithdrawal; +use App\Transformers\UserTransformer; +use Carbon\Carbon; + +/** + * Class UserCashWithdrawalsTransformer + * @package App\Transformers + */ +class UserCashWithdrawalTransformer extends Fractal\TransformerAbstract +{ + /** + * List of resources possible to include + * @var array + */ + protected $availableIncludes = [ + 'User', 'WithdrawalStatus', 'MoneyTransferAccount' + ]; + + /** + * @param UserCashWithdrawal $user_cash_withdrawal + * @return array + */ + public function transform(UserCashWithdrawal $user_cash_withdrawal) + { + $output = array_only($user_cash_withdrawal->toArray(), ['id', 'created_at', 'amount', 'withdrawal_status_id', 'user_id', 'money_transfer_account_id']); + $output['created_at'] = $user_cash_withdrawal->created_at->toDateTimeString(); + return $output; + } + + + /** + * @param UserCashWithdrawal $user_cash_withdrawal + * @return Fractal\Resource\Item + */ + public function includeUser(UserCashWithdrawal $user_cash_withdrawal) + { + if ($user_cash_withdrawal->user) { + return $this->item($user_cash_withdrawal->user, new UserTransformer()); + } else { + return null; + } + + } + + + /** + * @param UserCashWithdrawal $user_cash_withdrawal + * @return Fractal\Resource\Item + */ + public function includeWithdrawalStatus(UserCashWithdrawal $user_cash_withdrawal) + { + if ($user_cash_withdrawal->withdrawal_status) { + return $this->item($user_cash_withdrawal->withdrawal_status, new WithdrawalStatusTransformer()); + } else { + return null; + } + + } + + /** + * @param UserCashWithdrawal $user_cash_withdrawal + * @return Fractal\Resource\Item + */ + public function includeMoneyTransferAccount(UserCashWithdrawal $user_cash_withdrawal) + { + if ($user_cash_withdrawal->money_transfer_account) { + return $this->item($user_cash_withdrawal->money_transfer_account, new MoneyTransferAccountTransformer()); + } else { + return null; + } + + } + +} diff --git a/app/Plugins/Withdrawals/Transformers/WithdrawalStatusTransformer.php b/app/Plugins/Withdrawals/Transformers/WithdrawalStatusTransformer.php new file mode 100644 index 0000000..daa2040 --- /dev/null +++ b/app/Plugins/Withdrawals/Transformers/WithdrawalStatusTransformer.php @@ -0,0 +1,30 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace Plugins\Withdrawals\Transformers; + +use League\Fractal; +use Plugins\Withdrawals\Model\WithdrawalStatus; + +class WithdrawalStatusTransformer extends Fractal\TransformerAbstract +{ + public function transform(WithdrawalStatus $withdrawal_status) + { + $output = array_only($withdrawal_status->toArray(), ['id', 'name']); + return $output; + } +} + +?> \ No newline at end of file diff --git a/app/Plugins/Withdrawals/plugin.json b/app/Plugins/Withdrawals/plugin.json new file mode 100644 index 0000000..36a6102 --- /dev/null +++ b/app/Plugins/Withdrawals/plugin.json @@ -0,0 +1,9 @@ +{ + "name": "Withdrawals", + "class": "fa fa-2x fa-money", + "description": "By enabling this plugin, instructor can withdraw their revenue amount. The instructor can send the money withdrawal request to site with the account details. Site can transfer the amount to the user account and maked to paid.", + "dependencies": "", + "module_id": "", + "module_hash": "", + "display_order": "8" +} diff --git a/app/Plugins/Withdrawals/routes.php b/app/Plugins/Withdrawals/routes.php new file mode 100644 index 0000000..3043b51 --- /dev/null +++ b/app/Plugins/Withdrawals/routes.php @@ -0,0 +1,48 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +/* +|-------------------------------------------------------------------------- +| Application Routes +|-------------------------------------------------------------------------- +| +| Here is where you can register all of the routes for an application. +| It is a breeze. Simply tell Lumen the URIs it should respond to +| and give it the Closure to call when that URI is requested. +| +*/ +$api = $this->app->make('Dingo\Api\Routing\Router'); +$api->version(['v1'], function ($api) { + $api->group(['prefix' => 'admin', 'namespace' => 'Plugins\Withdrawals\Controllers\Admin', 'middleware' => 'apitracking'], function () use ($api) { + $api->delete('user_cash_withdrawals/{id}', 'AdminUserCashWithdrawalsController@destroy'); + $api->get('user_cash_withdrawals', 'AdminUserCashWithdrawalsController@index'); + $api->get('user_cash_withdrawals/{id}/edit', 'AdminUserCashWithdrawalsController@edit'); + $api->get('user_cash_withdrawals/{id}', 'AdminUserCashWithdrawalsController@edit'); + $api->put('user_cash_withdrawals/{id}', 'AdminUserCashWithdrawalsController@update'); + // withdrawal status + $api->get('withdrawal_statuses', 'AdminWithdrawalStatusesController@index'); + }); + $api->group(['namespace' => 'Plugins\Withdrawals\Controllers', 'middleware' => 'apitracking'], function () use ($api) { + // Money transfer accounts + $api->delete('/money_transfer_accounts/{id}', 'MoneyTransferAccountsController@destroy'); + $api->get('/money_transfer_accounts', 'MoneyTransferAccountsController@index'); + $api->post('/money_transfer_accounts', 'MoneyTransferAccountsController@store'); + // user cash withdrawals + $api->get('/user_cash_withdrawals', 'UserCashWithdrawalsController@index'); + $api->post('/user_cash_withdrawals', 'UserCashWithdrawalsController@store'); + // withdrawal status + $api->get('/withdrawal_statuses', 'WithdrawalStatusesController@index'); + }); +}); diff --git a/app/Plugins/composer.json b/app/Plugins/composer.json new file mode 100644 index 0000000..dd9f4e5 --- /dev/null +++ b/app/Plugins/composer.json @@ -0,0 +1,8 @@ +{ + "name": "App/Plugins", + "description": "Plugins", + "type": "project", + "license": "MIT", + "minimum-stability": "dev", + "require": {} +} diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php new file mode 100644 index 0000000..a61d3d6 --- /dev/null +++ b/app/Providers/AppServiceProvider.php @@ -0,0 +1,31 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Providers; + +use Illuminate\Support\ServiceProvider; + +class AppServiceProvider extends ServiceProvider +{ + /** + * Register any application services. + * + * @return void + */ + public function register() + { + // + } +} diff --git a/app/Providers/AuthServiceProvider.php b/app/Providers/AuthServiceProvider.php new file mode 100644 index 0000000..d2cd3c4 --- /dev/null +++ b/app/Providers/AuthServiceProvider.php @@ -0,0 +1,53 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Providers; + +use App\User; +use Illuminate\Support\Facades\Auth; +use Illuminate\Support\Facades\Gate; +use Illuminate\Support\ServiceProvider; + +class AuthServiceProvider extends ServiceProvider +{ + /** + * Register any application services. + * + * @return void + */ + public function register() + { + // + } + + /** + * Boot the authentication services for the application. + * + * @return void + */ + public function boot() + { + // Here you may define how you wish users to be authenticated for your Lumen + // application. The callback which receives the incoming request instance + // should return either a User instance or null. You're free to obtain + // the User instance via an API token or any other method necessary. + + Auth::viaRequest('api', function ($request) { + if ($request->input('api_token')) { + return User::where('api_token', $request->input('api_token'))->first(); + } + }); + } +} diff --git a/app/Providers/EventServiceProvider.php b/app/Providers/EventServiceProvider.php new file mode 100644 index 0000000..8403551 --- /dev/null +++ b/app/Providers/EventServiceProvider.php @@ -0,0 +1,32 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Providers; + +use Laravel\Lumen\Providers\EventServiceProvider as ServiceProvider; + +class EventServiceProvider extends ServiceProvider +{ + /** + * The event listener mappings for the application. + * + * @var array + */ + protected $listen = [ + 'App\Events\SomeEvent' => [ + 'App\Listeners\EventListener', + ], + ]; +} diff --git a/app/Providers/MessageServiceProvider.php b/app/Providers/MessageServiceProvider.php new file mode 100644 index 0000000..c60edd5 --- /dev/null +++ b/app/Providers/MessageServiceProvider.php @@ -0,0 +1,53 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Providers; + +use Illuminate\Support\ServiceProvider; +use Illuminate\Database\Eloquent\Relations\Relation; + +class MessageServiceProvider extends ServiceProvider +{ + /** + * Register any application services. + * + * @return void + */ + public function register() + { + // + } + + /** + * Bootstrap the application services. + * + * @return void + */ + public function boot() + { + $enabledIncludes = array(); + $enabledIncludes['MorphUser'] = \App\User::class; + + if (isPluginEnabled('VehicleRentals')) { + $enabledIncludes['MorphVehicleRental'] = \Plugins\VehicleRentals\Model\VehicleRental::class; + } + if (isPluginEnabled('VehicleDisputes')) { + $enabledIncludes['MorphVehicleRentalDispute'] = \Plugins\VehicleDisputes\Model\VehicleDispute::class; + } + if (!empty($enabledIncludes)) { + Relation::morphMap($enabledIncludes); + } + } +} diff --git a/app/Providers/SettingsServiceProvider.php b/app/Providers/SettingsServiceProvider.php new file mode 100644 index 0000000..0bb0338 --- /dev/null +++ b/app/Providers/SettingsServiceProvider.php @@ -0,0 +1,49 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Providers; + +use Illuminate\Support\ServiceProvider; +use Schema; +use DB; +use Cache; + +class SettingsServiceProvider extends ServiceProvider +{ + /** + * Register any application services. + * @return void + */ + public function register() + { + // + } + + /** + * Bootstrap the application services. + * @return void + */ + public function boot() + { + if (Schema::hasTable('settings')) { + $setting = Cache::rememberForever('settings_data', function () { + return DB::table('settings')->lists('value', 'name'); + }); + foreach ($setting as $key => $value) { + config()->set($key, $value); + } + } + } +} diff --git a/app/Providers/TransactionServiceProvider.php b/app/Providers/TransactionServiceProvider.php new file mode 100644 index 0000000..3d67916 --- /dev/null +++ b/app/Providers/TransactionServiceProvider.php @@ -0,0 +1,55 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Providers; + +use Illuminate\Support\ServiceProvider; +use Illuminate\Database\Eloquent\Relations\Relation; + +class TransactionServiceProvider extends ServiceProvider +{ + /** + * Register any application services. + * + * @return void + */ + public function register() + { + // + } + + /** + * Bootstrap the application services. + * + * @return void + */ + public function boot() + { + $enabledIncludes = array(); + $enabledIncludes['MorphWallet'] = \App\Wallet::class; + if (isPluginEnabled('VehicleRentals')) { + $enabledIncludes['MorphVehicleRental'] = \Plugins\VehicleRentals\Model\VehicleRental::class; + } + if (isPluginEnabled('VehicleDisputes')) { + $enabledIncludes['MorphVehicleRentalDispute'] = \Plugins\VehicleDisputes\Model\VehicleDispute::class; + } + if (isPluginEnabled('Withdrawals')) { + $enabledIncludes['MorphWithdrawals'] = \Plugins\Withdrawals\Model\UserCashWithdrawal::class; + } + if (!empty($enabledIncludes)) { + Relation::morphMap($enabledIncludes); + } + } +} diff --git a/app/Role.php b/app/Role.php new file mode 100644 index 0000000..4b74c99 --- /dev/null +++ b/app/Role.php @@ -0,0 +1,34 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App; + +use Illuminate\Http\Request; +use Illuminate\Database\Eloquent\Model; + +class Role extends Model +{ + /** + * @var string + */ + protected $table = "roles"; + + public function scopeFilterByRequest($query, Request $request) + { + $query->orderBy($request->input('sort', 'id'), $request->input('sortby', 'desc')); + return $query; + } + +} diff --git a/app/Services/AttachmentService.php b/app/Services/AttachmentService.php new file mode 100644 index 0000000..1e36a0b --- /dev/null +++ b/app/Services/AttachmentService.php @@ -0,0 +1,121 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace app\Services; + +use App\User; +use App\Attachment; +use File; + +class AttachmentService +{ + + /** + * Attachment thumb url create + * @param Attachment $attachment + * @return array + */ + public static function getThumbUrl(Attachment $attachment, $user_id) + { + $thumb = array(); + $thumb_size_array = array(); + $model = ''; + $provider_user = array(); + $file_name = $attachment->id . '.' . md5($attachment->id . config('constants.Security.salt') . $attachment->filename) . '.' . File::extension($attachment->filename); + switch ($attachment['attachmentable_type']) { + case 'MorphUser': + $thumb_size_array = config('constants.thumb.user'); + $model = 'user'; + $enabledIncludes = array(); + (isPluginEnabled('SocialLogins')) ? $enabledIncludes[] = 'provider_user' : ''; + $user = User::with($enabledIncludes)->where('id', $user_id)->first(); + foreach ($user->provider_user as $value) { + if ($user->user_avatar_source_id == $value['provider_id']) { + $provider_user['provider_profile'] = $value['profile_picture_url']; + } + } + if (empty($provider_user)) { + $user->user_avatar_source_id = config('constants.ConstSocialLogin.User'); + } + break; + case 'MorphVehicle': + $thumb_size_array = config('constants.thumb.vehicle'); + $model = 'vehicle'; + break; + default: + break; + } + if ($model == 'user') { + if ($user->user_avatar_source_id == config('constants.ConstSocialLogin.Facebook')) { + foreach ($thumb_size_array as $size_name => $size) { + $thumb[$size_name] = $provider_user['provider_profile'] . '?type=normal&width=' . $size["width"] . '&height=' . $size["height"]; + } + } else if ($user->user_avatar_source_id == config('constants.ConstSocialLogin.Twitter')) { + foreach ($thumb_size_array as $size_name => $size) { + $thumb[$size_name] = $provider_user['provider_profile']; + } + } else if ($user->user_avatar_source_id == config('constants.ConstSocialLogin.Google')) { + foreach ($thumb_size_array as $size_name => $size) { + $profile_url = $provider_user['provider_profile']; + $url = explode('?', $provider_user['provider_profile']); + if ((count($url) > 1) && strpos($url[1], 'sz') !== false) { + $url[1] = 'sz=' . $size['width']; + $profile_url = implode('?', $url); + } + $thumb[$size_name] = $profile_url; + } + } else if ($user->user_avatar_source_id == config('constants.ConstSocialLogin.Github')) { + foreach ($thumb_size_array as $size_name => $size) { + $thumb[$size_name] = $provider_user['provider_profile']; + } + } else { + foreach ($thumb_size_array as $size_name => $size) { + $thumb[$size_name] = asset('api/img/' . $size_name . '/' . $model . '/' . $file_name); + } + } + + } else if ($model == 'vehicle') { + foreach ($thumb_size_array as $size_name => $size) { + $thumb[$size_name] = asset('api/img/' . $size_name . '/' . $model . '/' . $file_name); + } + } else { + foreach ($thumb_size_array as $size_name => $size) { + $thumb[$size_name] = asset('api/img/' . $size_name . '/' . $model . '/' . $file_name); + } + } + + return $thumb; + } + + /** + * User upload avatar OR default avatar return + * @param Attachment $attachment + * @param $user_id + * @return array + */ + public static function getUserUploadThumb(Attachment $attachment, $user_id) + { + $thumb = array(); + $thumb_size_array = config('constants.thumb.user'); + $model = 'user'; + $provider_user = array(); + $file_name = $attachment->id . '.' . md5($attachment->id . config('constants.Security.salt') . $attachment->filename) . '.' . File::extension($attachment->filename); + foreach ($thumb_size_array as $size_name => $size) { + $thumb[$size_name] = asset('api/img/' . $size_name . '/' . $model . '/' . $file_name); + } + return $thumb; + } + +} \ No newline at end of file diff --git a/app/Services/CityService.php b/app/Services/CityService.php new file mode 100644 index 0000000..63961e3 --- /dev/null +++ b/app/Services/CityService.php @@ -0,0 +1,36 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Services; + +use App\City; + +class CityService +{ + public function getCityId($name, $country_id) + { + $city = City::where(['country_id' => $country_id, 'name' => $name])->first(); + if ($city) { + return $city->id; + } else { + $city_obj = array(); + $city_obj['country_id'] = $country_id; + $city_obj['name'] = $name; + $city_obj['is_active'] = true; + $city = City::create($city_obj); + return $city->id; + } + } +} diff --git a/app/Services/CountryService.php b/app/Services/CountryService.php new file mode 100644 index 0000000..71483fd --- /dev/null +++ b/app/Services/CountryService.php @@ -0,0 +1,36 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Services; + +use App\Country; + +class CountryService +{ + public function getCountryId($code, $name) + { + $country = Country::where('iso2', strtoupper($code))->first(); + if ($country) { + return $country->id; + } else { + $country_obj = array(); + $country_obj['iso2'] = strtoupper($code); + $country_obj['name'] = $name; + $country_obj['is_active'] = true; + $country = Country::create($country_obj); + return $country->id; + } + } +} diff --git a/app/Services/IpService.php b/app/Services/IpService.php new file mode 100644 index 0000000..b60aec0 --- /dev/null +++ b/app/Services/IpService.php @@ -0,0 +1,58 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Services; + +use App\Ip; + +class IpService +{ + /** + * Get ip_id if exists else insert new record to ips table + * @param $ip + * @return ip id. + */ + public function getIpId($ip) + { + $ip_details = Ip::where('ip', '=', $ip)->first(); + if (!$ip_details) { + $ip_data = new Ip; + $ip_data->ip = $ip; + $ip_data->save(); + $ip_id = $ip_data->id; + } else { + $ip_id = $ip_details->id; + } + return $ip_id; + } + + /** + * Get ip from id + * @param $id + * @return mixed + */ + public function getIp($id) + { + $ip_details = Ip::find($id); + return $ip_details->ip; + } + + public function updateIpById($id,$ip_arr) { + $ip = Ip::find($id); + if($ip) { + $ip->update($ip_arr); + } + } +} diff --git a/app/Services/MailService.php b/app/Services/MailService.php new file mode 100644 index 0000000..fc79fdf --- /dev/null +++ b/app/Services/MailService.php @@ -0,0 +1,75 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Services; + +use Illuminate\Support\Facades\Mail; +use App\EmailTemplate; +use League\Flysystem\Exception; + +class MailService +{ + public function __construct() + { + + } + + /** + * Send Mail to users + * @param $template + * @param $replaceContent + * @param $to_email + * @param $to_username + */ + public function sendMail($template, $replaceContent, $to_email, $to_username) + { + $default_content = array( + '##SITE_NAME##' => config('site.name'), + '##SITE_URL##' => '' . url('/') . '', + '##FROM_EMAIL##' => config('site.from_email'), + '##CONTACT_MAIL##' => config('site.contact_email'), + '##CONTACT_URL##' => 'Contact Us', + '##USERNAME##' => $to_username + ); + $emailFindReplace = array_merge($default_content, $replaceContent); + $content = strtr($template['body_content'], $emailFindReplace); + $subject = strtr($template['subject'], $emailFindReplace); + try { + Mail::send('emails.mailContent', ['body' => $content], function ($m) use ($to_email, $to_username, $subject) { + $m->from(config('site.from_email'), config('site.name')); + $m->to($to_email, $to_username)->subject($subject); + }); + } catch (Exception $e) { + Log::info($e->getMessage()); + } + } + + /** + * get Template content for sending mail + * @param $name + * @return array + */ + public function getTemplate($name) + { + $email_template = EmailTemplate::where('name', $name)->get(); + $template_array = []; + foreach ($email_template as $template) { + $template_array['from'] = $template['from_name']; + $template_array['body_content'] = $template['body_content']; + $template_array['subject'] = $template['subject']; + } + return $template_array; + } +} diff --git a/app/Services/MessageService.php b/app/Services/MessageService.php new file mode 100644 index 0000000..ec29f4d --- /dev/null +++ b/app/Services/MessageService.php @@ -0,0 +1,134 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Services; + +use App\Message; +use App\MessageContent; +use App\User; +use Illuminate\Support\Facades\Auth; + +class MessageService +{ + + /** + * MessageService constructor. + */ + public function __construct() + { + } + + /** + * @param $item_id + * @param $vehicle_rental_id + * @param $from_user_id + * @param $from_username + * @param $to_user_id + * @param $morph_type + */ + public function saveMessageContent($message_content_arr, $item_id, $vehicle_rental_id, $from_user_id, $to_user_id, $status_id, $morph_type, $dispute_status_id = null) + { + //Save Message Contents + $message_content = MessageContent::create($message_content_arr); + //get message content id and save to message table + $message_array = array(); + $message_array['message_content_id'] = $message_content->id; + $message_array['item_user_status_id'] = $status_id; + $message_array['dispute_status_id'] = $dispute_status_id; + $message_array['user_id'] = $from_user_id; + $message_array['to_user_id'] = $to_user_id; + $message_array['is_sender'] = 0; + $message_array['is_read'] = 0; + $message_array['message_folder_id'] = config('constants.ConstMessageFolder.Inbox'); + $this->saveMessage($message_array, $vehicle_rental_id, $morph_type); + $message_array['user_id'] = $to_user_id; + $message_array['to_user_id'] = $from_user_id; + $message_array['is_sender'] = 1; + $message_array['is_read'] = 1; + $message_array['message_folder_id'] = config('constants.ConstMessageFolder.SentMail'); + $this->saveMessage($message_array, $vehicle_rental_id, $morph_type); + } + + /** + * @param $message + * @param $id + * @param $morph_type + */ + public function saveMessage($message, $id, $morph_type) + { + $message = Message::create($message); + if ($morph_type == 'VehicleRental') { + $message_data = \Plugins\VehicleRentals\Model\VehicleRental::with(['message'])->where('id', '=', $id)->first(); + } + if ($morph_type == 'User') { + $message_data = User::with(['message'])->where('id', '=', $id)->first(); + } + if ($morph_type == 'Withdrawals') { + $message_data = \Plugins\Withdrawals\Model\UserCashWithdrawal::with(['message'])->where('id', '=', $id)->first(); + } + $message_data->message()->save($message); + } + + /** + * @param $vehicle_rental + * @param $auth_user + * @return array + */ + public function getMessages($vehicle_rental, $user) + { + + $message_data_res = array(); + $return_data_res = array(); + if (!$vehicle_rental) { + return $this->response->errorNotFound('Invalid Request'); + } + $booker = $vehicle_rental->user->username; + $host = (!is_null($vehicle_rental->item_userable->user)) ? $vehicle_rental->item_userable->user->username : ""; + $check_user_id = $user->id; + if ($user->role_id == config('constants.ConstUserTypes.Admin')) { + $check_user_id = $vehicle_rental->user_id; + } + if ($vehicle_rental->message) { + foreach ($vehicle_rental->message as $message) { + if ($message->to_user_id == $check_user_id) { + $replace_content = array( + '##BOOKER##' => $booker, + '##CREATED_DATE##' => $message->created_at, + '##HOSTER##' => $host, + '##ACCEPTED_DATE##' => $message->created_at + ); + $message_data_res[$message->id]['id'] = $message->id; + $message_data_res[$message->id]['status_id'] = $message->item_user_status_id; + $message_data_res[$message->id]['status'] = $message->item_user_status->name; + $message_data_res[$message->id]['created_at'] = $message->created_at; + + if ($message->message_content->subject === 'Private Note' || $message->message_content->subject === 'Feedback') { + $message_data_res[$message->id]['description'] = $message->message_content->message; + } else if ($message->dispute_status_id) { + $message_data_res[$message->id]['description'] = $message->message_content->subject; + $message_data_res[$message->id]['status_id'] = $message->dispute_status_id; + $message_data_res[$message->id]['status'] = $message->dispute_status->name; + } else { + $message_data_res[$message->id]['description'] = strtr($message->item_user_status->description, $replace_content); + } + } + } + } + $return_data_res['vehicle_rentalDetails'] = $vehicle_rental; + $return_data_res['item'] = $vehicle_rental->item_userable; + $return_data_res['messages'] = $message_data_res; + return $return_data_res; + } +} diff --git a/app/Services/TokenService.php b/app/Services/TokenService.php new file mode 100644 index 0000000..6577a0f --- /dev/null +++ b/app/Services/TokenService.php @@ -0,0 +1,44 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Services; + +use Tymon\JWTAuth\Providers\JWT\JWTInterface; + +class TokenService +{ + /** + * TokenService constructor. + */ + public function __construct(JWTInterface $jwt) + { + $this->jwt = $jwt; + } + + /** + * Generate JSON Web Token. + * @param $user + * @return token + */ + public function createToken($user) + { + $payload = [ + 'sub' => $user->id, + 'iat' => time(), + 'exp' => time() + (2 * 7 * 24 * 60 * 60) + ]; + return $this->jwt->encode($payload, config('constants.token_secret')); + } +} diff --git a/app/Services/TransactionService.php b/app/Services/TransactionService.php new file mode 100644 index 0000000..4517069 --- /dev/null +++ b/app/Services/TransactionService.php @@ -0,0 +1,178 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Services; + +use App\Transaction; +use Illuminate\Support\Facades\Auth; +use Carbon; +use App\TransactionType; + +class TransactionService +{ + + /** + * TransactionService constructor. + */ + public function __construct() + { + } + + /** + * @param $booker_id + * @param $host_id + * @param $transaction_type_id + * @param $amount + * @param $foreign_id + * @param $plugin_name + * @param null $payment_gateway_id + * @param float $gateway_fees + * @param null $description + */ + public function log($booker_id, $host_id, $transaction_type_id, $amount, $foreign_id, $plugin_name, $payment_gateway_id = null, $gateway_fees = 0.00, $description = null) + { + + $transaction_arr['user_id'] = (!is_null($booker_id)) ? $booker_id : ''; + $transaction_arr['receiver_user_id'] = (!is_null($host_id)) ? $host_id : ''; + $transaction_type = TransactionType::find($transaction_type_id); + if (!empty($transaction_type_id)) { + $transaction_arr['transaction_type_id'] = $transaction_type_id; + } + if (!empty($amount)) { + $transaction_arr['amount'] = $amount; + } + if (!empty($payment_gateway_id)) { + $transaction_arr['payment_gateway_id'] = $payment_gateway_id; + } + if (!empty($gateway_fees)) { + $transaction_arr['gateway_fees'] = $gateway_fees; + } + $transaction_arr['description'] = $transaction_type->name; + $transaction = Transaction::create($transaction_arr); + if ($plugin_name == 'Vehicles' && isPluginEnabled('Vehicles')) { + $vehicle_transaction = \Plugins\Vehicles\Model\Vehicle::with(['transactions'])->where('id', '=', $foreign_id)->first(); + $vehicle_transaction->transactions()->save($transaction); + } + if ($plugin_name == 'VehicleRentals' && isPluginEnabled('VehicleRentals')) { + $vehicle_rental_transaction = \Plugins\VehicleRentals\Model\VehicleRental::with(['transactions'])->where('id', '=', $foreign_id)->first(); + $vehicle_rental_transaction->transactions()->save($transaction); + } + if ($plugin_name == 'Wallets') { + $wallet_transaction = \App\Wallet::with(['transactions'])->where('id', '=', $foreign_id)->first(); + $wallet_transaction->transactions()->save($transaction); + } + if ($plugin_name == 'Withdrawals' && isPluginEnabled('Withdrawals')) { + $Withdrawal_transaction = \Plugins\Withdrawals\Model\UserCashWithdrawal::with(['transactions'])->where('id', '=', $foreign_id)->first(); + $Withdrawal_transaction->transactions()->save($transaction); + } + } + + /** + * @param $transactions + * @return string + */ + function transactionDescription($transactions) + { + if (!empty($transactions)) { + try { + foreach ($transactions as $transaction) { + if (in_array($transaction->transaction_type_id, array(config('constants.ConstTransactionTypes.AddedToWallet'), config('constants.ConstTransactionTypes.AdminDeductFundFromWallet')))) { + $user_link = (!is_null($transaction->from_user)) ? '' . $transaction->from_user->username . '' : ''; + } else { + $user_link = (!is_null($transaction->to_user)) ? '' . $transaction->to_user->username . '' : ''; + } + $item_link = $host_link = $booker_link = $order_link = ''; + if ($transaction->transactionable_type == 'MorphVehicleRental' && isPluginEnabled('VehicleRentals')) { // + if (!is_null($transaction->transactionable)) { + if(!is_null($transaction->transactionable->item_userable)) { + $item_link = '' . $transaction->transactionable->item_userable->name . ''; + $host_link = (!is_null($transaction->transactionable) && !is_null($transaction->transactionable->item_userable->user)) ? '' . $transaction->transactionable->item_userable->user->username . '' : ''; + $booker_link = (!is_null($transaction->transactionable) && !is_null($transaction->transactionable->user)) ? '' . $transaction->transactionable->user->username . '' : ''; + $order_link = (!is_null($transaction->transactionable)) ? '' . $transaction->transactionable->id . '' : ''; + } + } + } elseif ($transaction->transactionable_type == 'MorphVehicle' && isPluginEnabled('Vehicles')) { + if (!is_null($transaction->transactionable)) { + $item_link = '' . $transaction->transactionable->name . ''; + } + if (!is_null($transaction->from_user)) { + $host_link = '' . $transaction->from_user->username . ''; + } + } + $transactionReplace = array( + '##USER##' => $user_link, + '##BOOKER##' => $booker_link, + '##HOST##' => $host_link, + '##ITEM##' => $item_link, + '##ORDER_NO##' => $order_link + ); + $user = Auth::user(); + if (!empty($transaction->transaction_type->message_for_receiver) && $transaction->receiver_user_id == $user->id) { + $transaction->description = strtr($transaction->transaction_type->message_for_receiver, $transactionReplace); + } elseif ($user->id == config('constants.ConstUserTypes.Admin')) { + $transaction->description = strtr($transaction->transaction_type->message_for_admin, $transactionReplace); + } else { + $transaction->description = strtr($transaction->transaction_type->message, $transactionReplace); + } + } + return $transactions; + } catch (Exception $e) { + return array('error' => 1, 'error_message' => $e->getMessage()); + } + } + } + + /** + * @param $request + * @param string $type + * @return mixed + */ + public function getTranactionCount($request, $type = 'filter') + { + $check_date = $this->getDateFilter($request); + $check_date = Carbon::parse($check_date)->format('Y-m-d'); + $tranaction_count = Transaction::where('created_at', '>=', $check_date)->count(); + return $tranaction_count; + } + + /** + * get the date filter + * @return $check_date + */ + public function getDateFilter($request) + { + $check_date = Carbon::now()->subDays(7); + if ($request->has('filter')) { + if ($request->filter == 'lastDays') { + $check_date = Carbon::now()->subDays(7); + } else if ($request->filter == 'lastWeeks') { + $check_date = Carbon::now()->subWeeks(4); + } else if ($request->filter == 'lastMonths') { + $check_date = Carbon::now()->subMonths(3); + } else if ($request->filter == 'lastYears') { + $check_date = Carbon::now()->subYears(3); + } + } + return $check_date; + } + + public function getAdminTotalRevenue() + { + $transaction_type_ids = array(config('constants.ConstTransactionTypes.AdminCommission'),config('constants.ConstTransactionTypes.VehicleListingFee')); + $admin_revenue = Transaction::whereIn('transaction_type_id', $transaction_type_ids)->sum('amount'); + return $admin_revenue; + } + +} diff --git a/app/Services/UserLoginService.php b/app/Services/UserLoginService.php new file mode 100644 index 0000000..381520e --- /dev/null +++ b/app/Services/UserLoginService.php @@ -0,0 +1,70 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Services; + +use App\UserLogin; +use App\User; +use Carbon; + +class UserLoginService +{ + + /** + * Save record to user_login table after login + * @param $request + * @param $ip_id + * @return void + */ + public function saveUserLogin($request, $ip_id) + { + $user_details = User::where('email', '=', $request->email)->first(); + $user_details['last_login_ip_id'] = $ip_id; + $user_details->save(); + $user_login = new UserLogin; + $user_login->user_id = $user_details->id; + $user_login->role_id = $user_details->role_id; + $user_login->user_agent = $request->header('User-Agent'); + $user_login->user_login_ip_id = $ip_id; + $user_login->save(); + // update login count in users table + $user_details->increment('user_login_count', 1); + return $user_details->role_id; + } + + /** + * get last logged record for admin dashboard + * @param $request + * @return UserLogin created_at + */ + public function getLastLogin() + { + $user_login_details = UserLogin::select('created_at')->orderBy('created_at', 'desc')->first(); + if($user_login_details) + return $user_login_details->created_at->diffForHumans(); + else + return '-'; + } + + /** + * decrease user_login_count when delete user_login record + * @param user_id + * @return void + */ + public function decreaseUserLoginCount($user_id){ + // update login count in users table + User::where('id', '=', $user_id)->decrement('user_login_count', 1); + } +} diff --git a/app/Services/UserService.php b/app/Services/UserService.php new file mode 100644 index 0000000..e3ca706 --- /dev/null +++ b/app/Services/UserService.php @@ -0,0 +1,323 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Services; + +use App\User; +use App\UserLogin; +use Carbon; +use ReCaptcha\ReCaptcha; + +class UserService extends MailService +{ + /** + * @var + */ + protected $tokenService; + /** + * @var IpService + */ + protected $ip_service; + + /** + * UserService constructor. + */ + public function __construct(TokenService $tokenService) + { + $this->setIpService(); + $this->tokenService = $tokenService; + } + + public function setIpService() + { + $this->IpService = new IpService(); + } + + /** + * To send email based on the settings + * @param $user + * @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response + */ + public function emailConditions($user, $type) + { + if (config('user.is_admin_mail_after_register') && $type != 'activate') { + $this->sendUserJoinAdminMail($user); + } + if (!config('user.is_email_verification_for_register') && config('user.is_admin_activate_after_register')) { + $this->sendWelcomeMail($user->id, $user->email, $user->username); + return response()->json(['Success' => 'You have successfully registered with our site. After administrator approval you can login to site.'], 200); + } else if (config('user.is_email_verification_for_register') && ($user->is_email_confirmed == 0)) { + $this->sendActivationMail($user->id, $user->email, $user->username, $this->getActivateHash($user->id, $user->activate_hash)); + return response()->json(['Success' => 'You have successfully registered with our site and your activation link has been sent to your mail inbox.'], 200); + } else if (config('user.is_admin_activate_after_register') && ($user->is_active == 0) && ($type == 'activate') ) { + return response()->json(['Success' => 'You have successfully activated your account with our site. After administrator approval you can login to site.'], 200); + } else if (!config('user.is_admin_activate_after_register') && config('user.is_auto_login_after_register') && ($type == 'activate')) { + return response()->json(['Success' => 'Account Activated Successfully.', 'token' => $this->tokenService->createToken($user)], 200); + } else if (!config('user.is_admin_activate_after_register') && !config('user.is_auto_login_after_register') && ($type == 'activate')) { + return response()->json(['Success' => 'Account Activated Successfully.'], 200); + } else if (!config('user.is_email_verification_for_register') && !config('user.is_admin_activate_after_register') && config('user.is_welcome_mail_after_register') && !config('user.is_auto_login_after_register')) { + $this->sendWelcomeMail($user->id, $user->email, $user->username); + return response()->json(['Success' => 'You have successfully registered with our site.'], 200); + } else if (!config('user.is_email_verification_for_register') && !config('user.is_admin_activate_after_register') && config('user.is_auto_login_after_register') && config('user.is_welcome_mail_after_register')) { + $this->sendWelcomeMail($user->id, $user->email, $user->username); + return response()->json(['Success' => 'You have successfully registered with our site.', 'token' => $this->tokenService->createToken($user)], 200); + } else if (config('user.is_auto_login_after_register') && config('user.is_welcome_mail_after_register')) { + $this->sendWelcomeMail($user->id, $user->email, $user->username); + return response()->json(['Success' => 'You have successfully registered with our site.', 'token' => $this->tokenService->createToken($user)], 200); + } + } + + /** + * Send welcome mail to users + * @param $user_id + * @param $to_email + * @param $to_username + */ + public function sendWelcomeMail($user_id, $to_email, $to_username) + { + $template = $this->getTemplate('Welcome Email'); + $emailFindReplace = array( + '##USERNAME##' => $to_username, + '##CONTACT_MAIL##' => config('site.contact_email'), + '##FROM_EMAIL##' => ($template['from'] == '##FROM_EMAIL##') ? config('site.from_email') : $template['from'], + ); + $this->sendMail($template, $emailFindReplace, $to_email, $to_username); + } + + /** + * Send Activation mail to users + * @param $user_id + * @param $to_email + * @param $to_username + * @param $hash + */ + + public function sendActivationMail($user_id, $to_email, $to_username, $hash) + { + $template = $this->getTemplate('Activation Request'); + $activation_link = '/#/users/' . $user_id . '/activate/' . $hash; + $emailFindReplace = array( + '##USERNAME##' => $to_username, + '##ACTIVATION_URL##' => url($activation_link), + '##FROM_EMAIL##' => ($template['from'] == '##FROM_EMAIL##') ? config('site.from_email') : $template['from'], + ); + $this->sendMail($template, $emailFindReplace, $to_email, $to_username); + } + + /** + * get last registered record for admin dashboard + * @param $request + * @return User created_at + */ + public function getLastRegistered() + { + $user_details = User::select('created_at')->orderBy('created_at', 'desc')->first(); + return $user_details->created_at->diffForHumans(); + } + + /** + * get registered in count for admin dashboard + * @param $request + * @return User count + */ + public function getRegisterCount($request) + { + $check_date = $this->getDateFilter($request); + $check_date = Carbon::parse($check_date)->format('Y-m-d'); + $user_count = User::where('created_at', '>=', $check_date) + ->where('role_id', '>', config('constants.ConstUserTypes.Admin')) + ->count(); + return $user_count; + } + + /** + * get last logged in count for admin dashboard + * @param $request + * @return UserLogin count + */ + public function getLoginCount($request) + { + $check_date = $this->getDateFilter($request); + $check_date = Carbon::parse($check_date)->format('Y-m-d'); + $user_login_details = UserLogin::where('created_at', '>=', $check_date)->count(); + return $user_login_details; + } + + /** + * get the total active users count + * @return active user count. + */ + public function getTotalUsers() + { + $total_user_count = User::where('role_id', '>', config('constants.ConstUserTypes.Admin')) + ->count(); + return $total_user_count; + } + + /** + * Verify captcha + */ + + public function captchaCheck($captcha) + { + $remoteip = $_SERVER['REMOTE_ADDR']; + $secret = config('captcha.secret_key'); + $recaptcha = new ReCaptcha($secret); + $response = $recaptcha->verify($captcha, $remoteip); + if ($response->isSuccess()) { + return true; + } else { + return false; + } + } + + /** + * get the date filter + * @return $check_date + */ + public function getDateFilter($request) + { + $check_date = Carbon::now()->subDays(7); + if ($request->has('filter')) { + if ($request->filter == 'lastDays') { + $check_date = Carbon::now()->subDays(7); + } else if ($request->filter == 'lastWeeks') { + $check_date = Carbon::now()->subWeeks(4); + } else if ($request->filter == 'lastMonths') { + $check_date = Carbon::now()->subMonths(3); + } else if ($request->filter == 'lastYears') { + $check_date = Carbon::now()->subYears(3); + } + } + return $check_date; + } + + /** + * Check facebook username + * @param $name + * @return bool + */ + public function CheckUsernameAvailable($name) + { + $user = User::where('username', '=', $name)->get(); + if ($user) { + return false; + } + return $name; + } + + /** + * Send Forgot Password Mail + * @param $new_password + * @param $to_email + * @param $to_username + */ + public function sendForgotPasswordMail($new_password, $to_email, $to_username) + { + $template = $this->getTemplate('Forgot Password'); + $emailFindReplace = array( + '##USERNAME##' => $to_username, + '##PASSWORD##' => $new_password + ); + $this->sendMail($template, $emailFindReplace, $to_email, $to_username); + } + + /** + * Send mail to admin reg user join + * @param $user + */ + public function sendUserJoinAdminMail($user) + { + $ip = $this->IpService->getIp($user->register_ip_id); + $template = $this->getTemplate('New User Join'); + $emailFindReplace = array( + '##USERNAME##' => '' . $user->username . '', + '##EMAIL##' => $user->email, + '##SIGNUP_IP##' => $ip + ); + $this->sendMail($template, $emailFindReplace, config('site.from_email'), 'Admin'); + } + + /** + * Send mail to user reg active / deactive status change + * @param $username + * @param $email + * @param $status + */ + public function sendStatusMail($username, $email, $status) + { + $template = $this->getTemplate($status); + $emailFindReplace = array( + '##USERNAME##' => $username + ); + $this->sendMail($template, $emailFindReplace, $email, $username); + } + + /** + * get Activate hash + * @param $user_id + * @return string + */ + public function getActivateHash($user_id, $activate_hash) + { + return md5($user_id . '-' . config('Security.salt') . '-' . $activate_hash); + } + + /** + * Validate Activate Hash + * @param $user_id + * @param $hash + * @return bool + */ + public function validateHash($user_id, $hash, $activate_hash) + { + return (md5($user_id . '-' . config('Security.salt') . '-' . $activate_hash) === $hash); + } + + public function checkBalanceAvailability($user_id, $amount) + { + $user = User::where('id', '=', $user_id)->first(); + if ($user->available_wallet_amount < $amount) { + return false; + } + return true; + } + + public function updateFeedbackDetails($user, $average_rating) + { + $user->increment('feedback_count', 1); + // update average rating + $user->feedback_rating = $average_rating; + $user->save(); + } + + /** + * Send Admin add user mail to users + * @param $to_username + * @param $password + * @param $to_email + */ + public function sendAdminAddUserMail($to_username, $password, $to_email) + { + $template = $this->getTemplate('Admin User Add'); + $emailFindReplace = array( + '##USERNAME##' => $to_username, + '##USEREMAIL##' => $to_email, + '##PASSWORD##' => $password, + '##FROM_EMAIL##' => ($template['from'] == '##FROM_EMAIL##') ? config('site.from_email') : $template['from'], + ); + $this->sendMail($template, $emailFindReplace, $to_email, $to_username); + } +} diff --git a/app/Services/WalletService.php b/app/Services/WalletService.php new file mode 100644 index 0000000..a46503f --- /dev/null +++ b/app/Services/WalletService.php @@ -0,0 +1,216 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Services; + +use App\Services\MailService; +use Illuminate\Database\Eloquent\Model; +use App\Wallet; +use App\User; +use Illuminate\Support\Facades\Auth; +use App\Services\TransactionService; +use App\Services\MessageService; +use App\WalletTransactionLog; +use App\Services\WalletTransactionLogService; +use Log; + +class WalletService +{ + /** + * @var + */ + protected $mailService; + /** + * @var \App\Services\MessageService + */ + protected $messageService; + /** + * @var + */ + protected $transactionService; + + /** + * WalletService constructor. + */ + public function __construct() + { + $this->setMailService(); + $this->setMessageService(); + $this->setTransactionService(); + } + + /** + * mail service object created + */ + public function setMailService() + { + $this->mailService = new MailService(); + } + + /** + * message service object created + */ + public function setMessageService() + { + $this->messageService = new MessageService(); + } + + /** + * TransactionService object created + */ + public function setTransactionService() + { + $this->transactionService = new TransactionService(); + } + + /** + * @param $walletId + * @param $paymentGatewayId + * @return bool + */ + public function processAddToWallet($walletId, $paymentGatewayId, $transaction_fee) + { + $wallet = Wallet::with('user')->where('id', $walletId)->first(); + if (empty($wallet)) { + return $this->response->errorNotFound("Invalid Request"); + } + if (empty($wallet['is_success'])) { + $this->transactionService->log($wallet->user->id, $wallet->user->id, config('constants.ConstTransactionTypes.AddedToWallet'), $wallet->amount, $wallet->id, 'Wallets', $wallet->payment_gateway_id, $transaction_fee, $wallet->description); + $data['is_success'] = 1; + $wallet->update($data); + $user['id'] = $wallet->user->id; + $user['available_wallet_amount'] = $wallet->user->available_wallet_amount + $wallet->amount; + $wallet->user->update($user); + //$this->sendAmountToWalletMail($wallet); + return true; + } else { + return true; + } + return false; + } + + public function getWalletDetails() + { + $wallet_response = array( + 'error' => array( + 'code' => 0 + ), + 'wallet_enabled' => true + ); + return $wallet_response; + } + + public function createPayment($log_id) + { + $transaction_log = WalletTransactionLog::where('id', '=', $log_id)->first(); + $related_details = $transaction_log->wallet_transaction_logable; + $user = $related_details->user; + if ((($user->available_wallet_amount >= $related_details->total_amount) && ($transaction_log->wallet_transaction_logable_type == 'MorphVehicleRental')) || ( ($user->available_wallet_amount >= config('vehicle.listing_fee') )&& ( $transaction_log->wallet_transaction_logable_type == 'MorphVehicle')) ) { + $transaction_log->status = 'created'; + $transaction_log->payment_type = 'initiated'; + $transaction_log->save(); + return true; + } else { + throw new \Dingo\Api\Exception\StoreResourceFailedException('Your Wallet has insufficient money. Please, try again.'); + } + } + + public function executePayment($related_model, $type, $log_id) + { + $process = false; + if($type == 'MorphVehicle'){ + $user = $related_model->user; + $user->available_wallet_amount = $user->available_wallet_amount - config('vehicle.listing_fee'); + if ($user->save()) { + $transaction_log = WalletTransactionLog::where('id', $log_id)->first(); + $transaction_log->payment_type = 'Captured'; + $transaction_log->status = 'approved'; + $transaction_log->save(); + $vehicleService = new \Plugins\Vehicles\Services\VehicleService(); + $vehicleService->processVehicleLisitngFee($related_model->id, config('constants.ConstPaymentGateways.Wallet'), 0.00); + $process = true; + } + } + if($type == 'MorphVehicleRental'){ + $user = $related_model->user; + if($user->available_wallet_amount >= $related_model->total_amount) { + $user->available_wallet_amount = $user->available_wallet_amount - $related_model->total_amount; + if ($user->save()) { + $transaction_log = WalletTransactionLog::where('id', $log_id)->first(); + $transaction_log->payment_type = 'Captured'; + $transaction_log->status = 'approved'; + $transaction_log->save(); + $vehicleRentalService = new \Plugins\VehicleRentals\Services\VehicleRentalService(); + $vehicleRentalService->updateVehicleRental($related_model->id, config('constants.ConstPaymentGateways.Wallet')); + $process = true; + } + } + } + return array( + 'status' => $process, + ); + } + + public function voidPayment($vehicle_rental) + { + $process_status = false; + $transaction_log = array(); + if ($vehicle_rental && !is_null($vehicle_rental->wallet_transaction_log)) { + if ($vehicle_rental->wallet_transaction_log->payment_type == 'Captured') { + $transaction_log['payment_type'] = 'voided'; + $vehicle_rental->wallet_transaction_log->update($transaction_log); + $vehicle_rental->user->increment('available_wallet_amount', $vehicle_rental->total_amount); + $process_status = true; + } + } + return $process_status; + } + + /** + * @param $user_id + * @param $amount + * @param $foreign_id + * @param $morph_type + */ + public function updateWalletForUser($user_id, $amount, $foreign_id, $morph_type) + { + // update user wallet amount + User::where('id', '=', $user_id)->increment('available_wallet_amount', $amount); + // update wallet transaction log + $walletLogService = new \App\Services\WalletTransactionLogService(); + $transaction_log_data = array(); + $transaction_log_data['amount'] = $amount; + $transaction_log_data['status'] = 'Completed'; + $transaction_log_data['payment_type'] = 'Paid'; + $wallet_log = $walletLogService->log($transaction_log_data); + if ($morph_type == 'VehicleRentals') { + $model_data = \Plugins\VehicleRentals\Model\VehicleRental::where('id', '=', $foreign_id)->first(); + } + $model_data->wallet_transaction_log()->save($wallet_log); + } + + public function updateRefund($sudopay_transaction_log, $gateway_id, $post_data) + { + $wallet = Wallet::with('user')->where('id', $sudopay_transaction_log->sudopay_transaction_logable_id)->first(); + if ($wallet) { + $user['id'] = $wallet->user->id; + $sudopay_revised_amount = $post_data['amount'] - $sudopay_transaction_log->sudopay_transaction_fee; + $user['available_wallet_amount'] = $wallet->user->available_wallet_amount - $sudopay_revised_amount; + $wallet->user->update($user); + $this->transactionService->log(config('constants.ConstUserTypes.Admin'), $wallet->user_id, config('constants.ConstTransactionTypes.RefundForWallet'), $sudopay_revised_amount, $wallet->id, 'Wallets', $gateway_id); + return true; + } + } +} diff --git a/app/Services/WalletTransactionLogService.php b/app/Services/WalletTransactionLogService.php new file mode 100644 index 0000000..35456e1 --- /dev/null +++ b/app/Services/WalletTransactionLogService.php @@ -0,0 +1,34 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Services; + +use App\WalletTransactionLog; + +class WalletTransactionLogService +{ + public function log($data) { + return WalletTransactionLog::create($data); + } + + public function updateLogById($data, $id = '') + { + if ($id) { + $log = WalletTransactionLog::where('id', '=', $id)->first(); + if ($log) + $log->update($data); + } + } +} diff --git a/app/Setting.php b/app/Setting.php new file mode 100644 index 0000000..a539ef8 --- /dev/null +++ b/app/Setting.php @@ -0,0 +1,84 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App; + +use Illuminate\Http\Request; +use Illuminate\Database\Eloquent\Model; + +/** + * Class Setting + * @package App + */ +class Setting extends Model +{ + /** + * @var string + */ + protected $table = "settings"; + /** + * The attributes that are mass assignable. + * + * @var array + */ + protected $fillable = [ + 'value' + ]; + + + /** + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function setting_category() + { + return $this->belongsTo(SettingCategory::class); + } + + + /** + * @return array + */ + public function scopeGetValidationRule() + { + return [ + 'value' => 'required' + ]; + } + + public function scopeGetValidationMessage() + { + return [ + 'value.required' => 'Required', + ]; + } + + /** + * @param $query + * @param Request $request + * @return mixed + */ + public function scopeFilterByRequest($query, Request $request) + { + $query->orderBy($request->input('sort', 'display_order'), $request->input('sortby', 'ASC')); + if ($request->has('q')) { + $query->where('name', 'LIKE', '%' . $request->input('q') . '%'); + } + if ($request->has('setting_category_id')) { + $query->where('setting_category_id', '=', $request->input('setting_category_id')); + } + return $query; + } + +} diff --git a/app/SettingCategory.php b/app/SettingCategory.php new file mode 100644 index 0000000..0e226f9 --- /dev/null +++ b/app/SettingCategory.php @@ -0,0 +1,73 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + + +namespace App; + +use Illuminate\Http\Request; +use Illuminate\Database\Eloquent\Model; + +class SettingCategory extends Model +{ + protected $table = "setting_categories"; + + /** + * The attributes that are mass assignable. + * + * @var array + */ + protected $fillable = [ + 'name', 'description', 'display_order' + ]; + + + /** + * @param $query + * @param Request $request + * @return mixed + */ + public function scopeFilterByRequest($query, Request $request, $notInCategories = array()) + { + $query->orderBy($request->input('sort', 'name'), $request->input('sortby', 'ASC')); + if(!empty($notInCategories)) { + $query->whereNotIn('id', $notInCategories); + } + return $query; + } + + /** + * @return array + */ + public function scopeGetValidationRule() + { + return [ + 'name' => 'required', + 'description' => 'required', + 'display_order' => 'required' + ]; + } + + /** + * @return array + */ + public function scopeGetValidationMessage() + { + return [ + 'name.required' => 'Required', + 'description.required' => 'Required', + 'display_order.required' => 'Required', + ]; + } +} diff --git a/app/State.php b/app/State.php new file mode 100644 index 0000000..b68d01e --- /dev/null +++ b/app/State.php @@ -0,0 +1,110 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App; + +use Illuminate\Http\Request; +use Illuminate\Database\Eloquent\Model; + +/** + * Class State + * @package App + */ +class State extends Model +{ + /** + * @var string + */ + protected $table = "states"; + /** + * The attributes that are mass assignable. + * + * @var array + */ + protected $fillable = [ + 'name', 'country_id', 'is_active' + ]; + + + /** + * @return \Illuminate\Database\Eloquent\Relations\HasMany + */ + public function city() + { + return $this->hasMany(City::class); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function country() + { + return $this->belongsTo(Country::class); + } + + + /** + * @param $query + * @param Request $request + * @return mixed + */ + public function scopeFilterByRequest($query, Request $request) + { + if ($request->input('sort', 'id') == 'Country.name') { + $query->orderBy('country_name', $request->input('sortby', 'desc')); + } else { + $query->orderBy($request->input('sort', 'id'), $request->input('sortby', 'desc')); + } + if ($request->has('filter')) { + $filter = false; + if ($request->input('filter') == 'active') { + $filter = true; + } + $query->where('is_active', '=', $filter); + } + if ($request->has('q')) { + $query->where('name', 'LIKE', '%' . $request->input('q') . '%'); + $query->orWhereHas('Country', function ($q) use ($request) { + $q->Where('name', 'like', '%' . $request->input('q') . '%'); + }); + } + if ($request->has('name')) { + $query->where('name', 'LIKE', '%' . $request->input('name') . '%'); + } + return $query; + } + + /** + * @return array + */ + public function scopeGetValidationRule() + { + return [ + 'name' => 'required|min:2', + 'country_id' => 'required|integer|exists:countries,id' + ]; + } + + public function scopeGetValidationMessage() + { + return [ + 'name.required' => 'Required', + 'name.min' => 'name - minimum length is 2', + 'country_id.required' => 'Required', + 'country_id.integer' => 'Country id must be a number!', + 'country_id.exists' => 'Invalid country id' + ]; + } +} diff --git a/app/Transaction.php b/app/Transaction.php new file mode 100644 index 0000000..62e50b1 --- /dev/null +++ b/app/Transaction.php @@ -0,0 +1,142 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App; + +use Illuminate\Http\Request; +use Illuminate\Database\Eloquent\Model; +use App\User; +use JWTAuth; +use Tymon\JWTAuth\Exceptions\JWTException; +use App\TransactionType; +use Carbon; + +/** + * Class Transaction + * @package App + */ +class Transaction extends Model +{ + /** + * @var string + */ + protected $table = "transactions"; + /** + * @var array + */ + protected $fillable = [ + 'user_id', 'receiver_user_id', 'transactionable_id', 'transactionable_type', 'transaction_type_id', 'amount', 'description', 'payment_gateway_id', 'gateway_fees' + ]; + + /** + * @param $query + * @param Request $request + * @return mixed + */ + public function scopeFilterByRequest($query, Request $request) + { + + if ($request->input('sort', 'id') == 'credit_amount' || $request->input('sort', 'id') == 'debit_amount') { + $query->orderBy('amount', $request->input('sortby', 'desc')); + } else { + $query->orderBy($request->input('sort', 'id'), $request->input('sortby', 'desc')); + } + if ($request->has('q')) { + $query->whereHas('from_user', function ($q) use ($request) { + $q->where('username', 'like', '%' . $request->input('q') . '%'); + }); + $query->orWhereHas('to_user', function ($q) use ($request) { + $q->Where('username', 'like', '%' . $request->input('q') . '%'); + }); + $query->orWhereHas('transaction_type', function ($q) use ($request) { + $q->Where('message', 'like', '%' . $request->input('q') . '%'); + }); + } + if ($request->has('end_date') && $request->has('start_date')) { + $start_date = date("Y-m-d 00:00:00", strtotime($request->input('start_date'))); + $end_date = date("Y-m-d 23:59:00", strtotime($request->input('end_date'))); + $query->whereBetween('created_at', array($start_date, $end_date)); + } elseif ($request->has('end_date')) { + $end_date = date("Y-m-d 00:00:00", strtotime($request->input('end_date'))); + $end_date1 = date("Y-m-d 23:59:00", strtotime($request->input('end_date'))); + $query->whereBetween('created_at', array($end_date, $end_date1)); + } elseif ($request->has('start_date')) { + $start_date = date("Y-m-d 00:00:00", strtotime($request->input('start_date'))); + $start_date1 = date("Y-m-d 23:59:00", strtotime($request->input('start_date'))); + $query->whereBetween('created_at', array($start_date, $start_date1)); + } + + if ($request->has('from_user')) { + $query->where('user_id', '=', $request->input('from_user')); + } + if ($request->has('to_user')) { + $query->where('receiver_user_id', '=', $request->input('to_user')); + } + if ($request->has('filter')) { + if ($request->input('filter') == 'Admin') { + $query->where('user_id', config('constants.ConstUserTypes.Admin'))->orWhere('receiver_user_id', config('constants.ConstUserTypes.Admin')); + } else if ($request->input('filter') == 'this_week') { + $check_date = Carbon::now()->subDays(7); + $check_date = Carbon::parse($check_date)->format('Y-m-d'); + $query->where('created_at', '>=', $check_date); + } else if ($request->input('filter') == 'this_month') { + $check_date = Carbon::now()->subMonth(); + $check_date = Carbon::parse($check_date)->format('Y-m-d'); + $query->where('created_at', '>=', $check_date); + } else if ($request->input('filter') == 'today') { + $check_date = Carbon::now(); + $check_date = Carbon::parse($check_date)->format('Y-m-d'); + $query->where('created_at', '>=', $check_date); + } + } + if($request->has('transaction_type_id')){ + $transaction_type_ids = explode(',',$request->input('transaction_type_id')); + $query->whereIn('transaction_type_id', $transaction_type_ids); + } + return $query; + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function from_user() + { + return $this->belongsTo(User::class, 'user_id'); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function to_user() + { + return $this->belongsTo(User::class, 'receiver_user_id'); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function transaction_type() + { + return $this->belongsTo(TransactionType::class); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\MorphTo + */ + public function transactionable() + { + return $this->morphTo(); + } +} diff --git a/app/TransactionType.php b/app/TransactionType.php new file mode 100644 index 0000000..5c543aa --- /dev/null +++ b/app/TransactionType.php @@ -0,0 +1,76 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App; + +use Illuminate\Http\Request; +use Illuminate\Database\Eloquent\Model; + +use JWTAuth; +use Tymon\JWTAuth\Exceptions\JWTException; + +/** + * Class TransactionType + * @package App + */ +class TransactionType extends Model +{ + /** + * @var string + */ + protected $table = "transaction_types"; + + /** + * @param $query + * @param Request $request + * @return mixed + */ + public function scopeFilterByRequest($query, Request $request) + { + $query->orderBy($request->input('sort', 'id'), $request->input('sortby', 'desc')); + if ($request->has('q')) { + $query->where('name', 'LIKE', '%' . $request->input('q') . '%') + ->orWhere('message', 'LIKE', '%' . $request->input('q') . '%'); + } + if ($request->has('transaction_type_group_id')) { + if ($request->input('transaction_type_group_id') == config('constants.ConstTransactionTypeGroups.Wallet')) { + $query->where('transaction_type_group_id', '=', config('constants.ConstTransactionTypeGroups.Wallet')); + } else if ($request->input('transaction_type_group_id') == config('constants.ConstTransactionTypeGroups.CashWithdrawal')) { + $query->where('transaction_type_group_id', '=', config('constants.ConstTransactionTypeGroups.CashWithdrawal')); + } else if ($request->input('transaction_type_group_id') == config('constants.ConstTransactionTypeGroups.Renting')) { + $query->where('transaction_type_group_id', '=', config('constants.ConstTransactionTypeGroups.Renting')); + } + } + return $query; + } + + /** + * @return array + */ + public function scopeGetValidationRule() + { + return [ + 'message' => 'required|min:10' + ]; + } + + public function scopeGetValidationMessage() + { + return [ + 'message.required' => 'Required', + 'message.min' => 'message - Minimum length is 10!', + ]; + } +} diff --git a/app/Transformers/ApiRequestTransformer.php b/app/Transformers/ApiRequestTransformer.php new file mode 100644 index 0000000..296b3a2 --- /dev/null +++ b/app/Transformers/ApiRequestTransformer.php @@ -0,0 +1,73 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Transformers; + +use League\Fractal; +use App\ApiRequest; + +/** + * Class ApiRequestTransformer + * @package App\Transformers + */ +class ApiRequestTransformer extends Fractal\TransformerAbstract +{ + /** + * List of resources possible to include + * + * @var array + */ + protected $availableIncludes = [ + 'User', 'Ip' + ]; + + /** + * @param ApiRequest $api_request + * @return array + */ + public function transform(ApiRequest $api_request) + { + $output = array_only($api_request->toArray(), ['id', 'created_at', 'user_id', 'ip_id', 'path', 'method', 'http_response_code']); + return $output; + } + + /** + * @param ApiRequest $api_request + * @return Fractal\Resource\Item + */ + public function includeUser(ApiRequest $api_request) + { + if ($api_request->user) { + return $this->item($api_request->user, new UserTransformer()); + } else { + return null; + } + + } + + /** + * @param ApiRequest $api_request + * @return Fractal\Resource\Item + */ + public function includeIp(ApiRequest $api_request) + { + if ($api_request->ip) { + return $this->item($api_request->ip, new IpTransformer()); + } else { + return null; + } + + } +} \ No newline at end of file diff --git a/app/Transformers/AttachmentTransformer.php b/app/Transformers/AttachmentTransformer.php new file mode 100644 index 0000000..d3a7c33 --- /dev/null +++ b/app/Transformers/AttachmentTransformer.php @@ -0,0 +1,41 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Transformers; + +use League\Fractal; +use App\Attachment; +use App\Services\AttachmentService; +use File; + +/** + * Class AttachmentTransformer + * @package App\Transformers + */ +class AttachmentTransformer extends Fractal\TransformerAbstract +{ + /** + * @param Attachment $attachment + * @return array + */ + public function transform(Attachment $attachment) + { + $output = array(); + $output['thumb'] = AttachmentService::getThumbUrl($attachment, $attachment->attachmentable_id); + return $output; + } + +} + diff --git a/app/Transformers/CityTransformer.php b/app/Transformers/CityTransformer.php new file mode 100644 index 0000000..07131fa --- /dev/null +++ b/app/Transformers/CityTransformer.php @@ -0,0 +1,74 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Transformers; + +use League\Fractal; +use App\City; + +/** + * Class CityTransformer + * @package App\Transformers + */ +class CityTransformer extends Fractal\TransformerAbstract +{ + /** + * List of resources possible to include + * + * @var array + */ + protected $availableIncludes = [ + 'State', 'Country' + ]; + + /** + * @param City $city + * @return array + */ + public function transform(City $city) + { + $output = array_only($city->toArray(), ['id', 'name', 'state_id', 'country_id', 'is_active', 'latitude', 'longitude']); + $output['is_active'] = ($output['is_active'] == 1) ? true : false; + return $output; + } + + /** + * @param City $city + * @return Fractal\Resource\Item + */ + public function includeState(City $city) + { + if ($city->state) { + return $this->item($city->state, new StateTransformer()); + } else { + return null; + } + + } + + /** + * @param City $city + * @return Fractal\Resource\Item + */ + public function includeCountry(City $city) + { + if ($city->country) { + return $this->item($city->country, new CountryTransformer()); + } else { + return null; + } + + } +} \ No newline at end of file diff --git a/app/Transformers/CountryTransformer.php b/app/Transformers/CountryTransformer.php new file mode 100644 index 0000000..282de06 --- /dev/null +++ b/app/Transformers/CountryTransformer.php @@ -0,0 +1,37 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace app\Transformers; + +use League\Fractal; +use App\Country; + +/** + * Class CountryTransformer + * @package app\Transformers + */ +class CountryTransformer extends Fractal\TransformerAbstract +{ + /** + * @param Country $country + * @return array + */ + public function transform(Country $country) + { + $output = array_only($country->toArray(), ['id', 'name', 'iso2', 'iso3', 'is_active']); + $output['is_active'] = ($output['is_active'] == 1) ? true : false; + return $output; + } +} \ No newline at end of file diff --git a/app/Transformers/CurrencyTransformer.php b/app/Transformers/CurrencyTransformer.php new file mode 100644 index 0000000..ed214ae --- /dev/null +++ b/app/Transformers/CurrencyTransformer.php @@ -0,0 +1,37 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace app\Transformers; + +use League\Fractal; +use App\Currency; + +/** + * Class CurrencyTransformer + * @package app\Transformers + */ +class CurrencyTransformer extends Fractal\TransformerAbstract +{ + /** + * @param Currency $currency + * @return array + */ + public function transform(Currency $currency) + { + $output = array_only($currency->toArray(), ['id', 'created_at', 'name', 'code', 'symbol', 'prefix', 'suffix', 'decimals', 'dec_point', 'thousands_sep', 'is_prefix_display_on_left', 'is_use_graphic_symbol', 'is_active']); + $output['is_active'] = ($output['is_active'] == 1) ? true : false; + return $output; + } +} \ No newline at end of file diff --git a/app/Transformers/DiscountTypeTransformer.php b/app/Transformers/DiscountTypeTransformer.php new file mode 100644 index 0000000..7020e30 --- /dev/null +++ b/app/Transformers/DiscountTypeTransformer.php @@ -0,0 +1,28 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Transformers; + +use League\Fractal; +use App\DiscountType; + +class DiscountTypeTransformer extends Fractal\TransformerAbstract +{ + public function transform(DiscountType $discount_type) + { + $output = array_only($discount_type->toArray(), ['id', 'type']); + return $output; + } +} diff --git a/app/Transformers/DurationTypeTransformer.php b/app/Transformers/DurationTypeTransformer.php new file mode 100644 index 0000000..4629825 --- /dev/null +++ b/app/Transformers/DurationTypeTransformer.php @@ -0,0 +1,28 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Transformers; + +use League\Fractal; +use App\DurationType; + +class DurationTypeTransformer extends Fractal\TransformerAbstract +{ + public function transform(DurationType $duration_type) + { + $output = array_only($duration_type->toArray(), ['id', 'name']); + return $output; + } +} diff --git a/app/Transformers/EmailTemplateTransformer.php b/app/Transformers/EmailTemplateTransformer.php new file mode 100644 index 0000000..b7db57c --- /dev/null +++ b/app/Transformers/EmailTemplateTransformer.php @@ -0,0 +1,36 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace app\Transformers; + +use League\Fractal; +use App\EmailTemplate; + +/** + * Class EmailTemplateTransformer + * @package app\Transformers + */ +class EmailTemplateTransformer extends Fractal\TransformerAbstract +{ + /** + * @param EmailTemplate $email_template + * @return array + */ + public function transform(EmailTemplate $email_template) + { + $output = array_only($email_template->toArray(), ['id', 'name', 'subject', 'body_content', 'from_name', 'reply_to', 'info']); + return $output; + } +} \ No newline at end of file diff --git a/app/Transformers/IpTransformer.php b/app/Transformers/IpTransformer.php new file mode 100644 index 0000000..61d28ef --- /dev/null +++ b/app/Transformers/IpTransformer.php @@ -0,0 +1,86 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Transformers; + +use League\Fractal; +use App\Ip; + +/** + * Class IpTransformer + * @package App\Transformers + */ +class IpTransformer extends Fractal\TransformerAbstract +{ + /** + * List of resources possible to include + * + * @var array + */ + protected $availableIncludes = [ + 'City', 'State', 'Country' + ]; + + /** + * @param Ip $ip + * @return array + */ + public function transform(Ip $ip) + { + $output = array_only($ip->toArray(), ['id', 'ip', 'city_id', 'state_id', 'country_id', 'latitude', 'longitude']); + return $output; + } + + /** + * @param Ip $ip + * @return Fractal\Resource\Item + */ + public function includeCity(Ip $ip) + { + if ($ip->city) { + return $this->item($ip->city, new CityTransformer()); + } else { + return null; + } + } + + /** + * @param Ip $ip + * @return Fractal\Resource\Item + */ + public function includeState(Ip $ip) + { + if ($ip->state) { + return $this->item($ip->state, new StateTransformer()); + } else { + return null; + } + + } + + /** + * @param Ip $ip + * @return Fractal\Resource\Item + */ + public function includeCountry(Ip $ip) + { + if ($ip->country) { + return $this->item($ip->country, new CountryTransformer()); + } else { + return null; + } + + } +} \ No newline at end of file diff --git a/app/Transformers/LanguageTransformer.php b/app/Transformers/LanguageTransformer.php new file mode 100644 index 0000000..e9206fc --- /dev/null +++ b/app/Transformers/LanguageTransformer.php @@ -0,0 +1,37 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace app\Transformers; + +use League\Fractal; +use App\Language; + +/** + * Class LanguageTransformer + * @package app\Transformers + */ +class LanguageTransformer extends Fractal\TransformerAbstract +{ + /** + * @param Language $language + * @return array + */ + public function transform(Language $language) + { + $output = array_only($language->toArray(), ['id', 'name', 'iso2', 'iso3', 'is_active']); + $output['is_active'] = ($output['is_active'] == 1) ? true : false; + return $output; + } +} \ No newline at end of file diff --git a/app/Transformers/MessageContentTransformer.php b/app/Transformers/MessageContentTransformer.php new file mode 100644 index 0000000..17c773f --- /dev/null +++ b/app/Transformers/MessageContentTransformer.php @@ -0,0 +1,36 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Transformers; + +use League\Fractal; +use App\MessageContent; + +/** + * Class MessageContentTransformer + * @package MessageContent\Transformers + */ +class MessageContentTransformer extends Fractal\TransformerAbstract +{ + /** + * @param MessageContent $message_content + * @return array + */ + public function transform(MessageContent $message_content) + { + $output = array_only($message_content->toArray(), ['subject', 'message', 'admin_suspend', 'is_system_flagged', 'detected_suspicious_words']); + return $output; + } +} \ No newline at end of file diff --git a/app/Transformers/MessageTransformer.php b/app/Transformers/MessageTransformer.php new file mode 100644 index 0000000..18b9fcd --- /dev/null +++ b/app/Transformers/MessageTransformer.php @@ -0,0 +1,137 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Transformers; + +use League\Fractal; +use App\Message; + +/** + * Class MessageTransformer + * @package Messages\Transformers + */ +class MessageTransformer extends Fractal\TransformerAbstract +{ + /** + * @var array + */ + protected $availableIncludes = [ + 'FromUser', 'ToUser', 'Messageable', 'MessageContent', 'ItemUserStatus', 'DisputeStatus' + ]; + + /** + * @param Message $message + * @return array + */ + public function transform(Message $message) + { + $output = array_only($message->toArray(), ['id', 'created_at', 'user_id', 'to_user_id', 'item_id', 'message_content_id', 'message_folder_id', 'messageable_id', 'messageable_type', 'is_sender', 'is_starred', 'is_read', 'is_deleted', 'is_archived', 'is_review', 'is_communication', 'hash', 'size', 'dispute_status_id']); + $output['is_sender'] = ($output['is_sender'] == 1) ? 1 : 0; + $output['is_starred'] = ($output['is_starred'] == 1) ? 1 : 0; + $output['is_read'] = ($output['is_read'] == 1) ? 1 : 0; + $output['is_deleted'] = ($output['is_deleted'] == 1) ? 1 : 0; + $output['is_archived'] = ($output['is_archived'] == 1) ? 1 : 0; + $output['is_review'] = ($output['is_review'] == 1) ? 1 : 0; + $output['is_communication'] = ($output['is_communication'] == 1) ? 1 : 0; + return $output; + } + + /** + * @param Message $message + * @return Fractal\Resource\Item|null + */ + public function includeFromUser(Message $message) + { + if ($message->from_user) { + return $this->item($message->from_user, new UserTransformer()); + } else { + return null; + } + } + + /** + * @param Message $message + * @return Fractal\Resource\Item|null + */ + public function includeToUser(Message $message) + { + if ($message->to_user) { + return $this->item($message->to_user, new UserTransformer()); + } else { + return null; + } + } + + /** + * @param Message $message + * @return Fractal\Resource\Item|null + */ + public function includeMessageable(Message $message) + { + if ($message->messageable) { + if ($message->messageable_type == 'MorphVehicle') { + return $this->item($message->messageable, new \Plugins\Vehicles\Transformers\VehicleTransformer()); + } + if ($message->messageable_type == 'MorphVehicleRental') { + return $this->item($message->messageable, new \Plugins\VehicleRentals\Transformers\VehicleRentalTransformer()); + } + if ($message->messageable_type == 'MorphVehicleRentalDispute') { + return $this->item($message->messageable, new \Plugins\VehicleDisputes\Transformers\VehicleDisputeTransformer()); + } + } else { + return null; + } + } + + + /** + * @param Message $message + * @return Fractal\Resource\Item|null + */ + public function includeMessageContent(Message $message) + { + if ($message->message_content) { + return $this->item($message->message_content, new MessageContentTransformer()); + } else { + return null; + } + } + + /** + * @param Message $message + * @return Fractal\Resource\Item|null + */ + public function includeItemUserStatus(Message $message) + { + if ($message->item_user_status) { + return $this->item($message->item_user_status, new \Plugins\VehicleRentals\Transformers\VehicleRentalStatusTransformer()); + } else { + return null; + } + } + + /** + * @param Message $message + * @return Fractal\Resource\Item|null + */ + public function includeDisputeStatus(Message $message) + { + if ($message->dispute_status) { + return $this->item($message->dispute_status, new \Plugins\VehicleDisputes\Transformers\VehicleDisputeStatusTransformer()); + } else { + return null; + } + } +} \ No newline at end of file diff --git a/app/Transformers/RoleTransformer.php b/app/Transformers/RoleTransformer.php new file mode 100644 index 0000000..f429704 --- /dev/null +++ b/app/Transformers/RoleTransformer.php @@ -0,0 +1,28 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Transformers; + +use League\Fractal; +use App\Role; + +class RoleTransformer extends Fractal\TransformerAbstract +{ + public function transform(Role $role) + { + $output = array_only($role->toArray(), ['id', 'created_at', 'name']); + return $output; + } +} diff --git a/app/Transformers/SettingCategoryTransformer.php b/app/Transformers/SettingCategoryTransformer.php new file mode 100644 index 0000000..5eaddfb --- /dev/null +++ b/app/Transformers/SettingCategoryTransformer.php @@ -0,0 +1,37 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + + +namespace app\Transformers; + +use League\Fractal; +use App\SettingCategory; + +/** + * Class SettingCategoryTransformer + * @package app\Transformers + */ +class SettingCategoryTransformer extends Fractal\TransformerAbstract +{ + /** + * @param SettingCategory $setting_category + * @return array + */ + public function transform(SettingCategory $setting_category) + { + $output = array_only($setting_category->toArray(), ['id', 'name', 'description', 'display_order']); + return $output; + } +} \ No newline at end of file diff --git a/app/Transformers/SettingTransformer.php b/app/Transformers/SettingTransformer.php new file mode 100644 index 0000000..bb7fdb1 --- /dev/null +++ b/app/Transformers/SettingTransformer.php @@ -0,0 +1,58 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Transformers; + +use League\Fractal; +use App\Setting; + +/** + * Class SettingTransformer + * @package App\Transformers + */ +class SettingTransformer extends Fractal\TransformerAbstract +{ + /** + * List of resources possible to include + * @var array + */ + protected $availableIncludes = [ + 'SettingCategory' + ]; + + /** + * @param Setting $setting + * @return array + */ + public function transform(Setting $setting) + { + $output = array_only($setting->toArray(), ['id', 'name', 'setting_category_id', 'value', 'label', 'description']); + return $output; + } + + /** + * @param Setting $setting + * @return Fractal\Resource\Item + */ + public function includeSettingCategory(Setting $setting) + { + if ($setting->setting_category) { + return $this->item($setting->setting_category, new SettingCategoryTransformer()); + } else { + return null; + } + + } +} diff --git a/app/Transformers/StateTransformer.php b/app/Transformers/StateTransformer.php new file mode 100644 index 0000000..0d567a5 --- /dev/null +++ b/app/Transformers/StateTransformer.php @@ -0,0 +1,59 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Transformers; + +use League\Fractal; +use App\State; + +/** + * Class StateTransformer + * @package App\Transformers + */ +class StateTransformer extends Fractal\TransformerAbstract +{ + /** + * List of resources possible to include + * @var array + */ + protected $availableIncludes = [ + 'Country' + ]; + + /** + * @param State $state + * @return array + */ + public function transform(State $state) + { + $output = array_only($state->toArray(), ['id', 'name', 'country_id', 'is_active']); + $output['is_active'] = ($output['is_active'] == 1) ? true : false; + return $output; + } + + /** + * @param State $state + * @return Fractal\Resource\Item + */ + public function includeCountry(State $state) + { + if ($state->country) { + return $this->item($state->country, new CountryTransformer()); + } else { + return null; + } + + } +} diff --git a/app/Transformers/TransactionTransformer.php b/app/Transformers/TransactionTransformer.php new file mode 100644 index 0000000..583b3c4 --- /dev/null +++ b/app/Transformers/TransactionTransformer.php @@ -0,0 +1,113 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Transformers; + +use League\Fractal; +use App\Transaction; +use JWTAuth; +use Illuminate\Support\Facades\Auth; + +/** + * Class TransactionTransformer + * @package App\Transformers + */ +class TransactionTransformer extends Fractal\TransformerAbstract +{ + /** + * List of resources possible to include + * + * @var array + */ + protected $availableIncludes = [ + 'FromUser', 'ToUser', 'TransactionType' + ]; + + /** + * @param Transaction $converted_transactions + * @return array + */ + public function transform(Transaction $converted_transactions) + { + $user = Auth::user(); + $output = array_only($converted_transactions->toArray(), ['id', 'user_id', 'receiver_user_id', 'description', 'transaction_type_id', 'transactionable_type', 'amount', 'created_at']); + if ($user->role_id == config('constants.ConstUserTypes.Admin')) { + if ($converted_transactions->receiver_user_id == $user->id) { + $output['debit_amount'] = 0; + $output['credit_amount'] = $output['amount']; + } elseif ($converted_transactions->transactionable_type == "MorphWallet" && $converted_transactions->transaction_type_id == config('constants.ConstTransactionTypes.AddedToWallet')) { + $output['debit_amount'] = 0; + $output['credit_amount'] = $output['amount']; + } else { + $output['debit_amount'] = $output['amount']; + $output['credit_amount'] = 0; + } + } else { + if ($converted_transactions->receiver_user_id == $user->id) { + $output['debit_amount'] = 0; + $output['credit_amount'] = $output['amount']; + } elseif ($converted_transactions->transactionable_type == "MorphWallet" && $converted_transactions->transaction_type_id == config('constants.ConstTransactionTypes.AddedToWallet')) { + $output['debit_amount'] = 0; + $output['credit_amount'] = $output['amount']; + } elseif ($converted_transactions->user_id == $user->id) { + $output['debit_amount'] = $output['amount']; + $output['credit_amount'] = 0; + } + } + + return $output; + } + + /** + * @param Transaction $transaction + * @return Fractal\Resource\Item + */ + public function includeFromUser(Transaction $transaction) + { + if ($transaction->from_user) { + return $this->item($transaction->from_user, new UserTransformer()); + } else { + return null; + } + } + + /** + * @param Transaction $transaction + * @return Fractal\Resource\Item + */ + public function includeToUser(Transaction $transaction) + { + if ($transaction->to_user) { + return $this->item($transaction->to_user, new UserTransformer()); + } else { + return null; + } + } + + /** + * @param Transaction $transaction + * @return Fractal\Resource\Item + */ + public function includeTransactionType(Transaction $transaction) + { + if ($transaction->transaction_type) { + $a = $this->item($transaction->transaction_type, new TransactionTypeTransformer()); + return $a; + } else { + return null; + } + } + +} diff --git a/app/Transformers/TransactionTypeTransformer.php b/app/Transformers/TransactionTypeTransformer.php new file mode 100644 index 0000000..e59c751 --- /dev/null +++ b/app/Transformers/TransactionTypeTransformer.php @@ -0,0 +1,37 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Transformers; + +use League\Fractal; +use App\TransactionType; + +/** + * Class TransactionTypeTransformer + * @package App\Transformers + */ +class TransactionTypeTransformer extends Fractal\TransformerAbstract +{ + /** + * @param TransactionType $transaction_type + * @return array + */ + public function transform(TransactionType $transaction_type) + { + $output = array_only($transaction_type->toArray(), ['id', 'name', 'is_credit', 'is_credit_to_receiver', 'is_credit_to_admin', 'message', 'message_for_receiver', 'message_for_admin', 'transaction_type_group_id']); + return $output; + } + +} diff --git a/app/Transformers/UploadAttachmentTransformer.php b/app/Transformers/UploadAttachmentTransformer.php new file mode 100644 index 0000000..cfb329a --- /dev/null +++ b/app/Transformers/UploadAttachmentTransformer.php @@ -0,0 +1,41 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Transformers; + +use League\Fractal; +use App\Attachment; +use App\Services\AttachmentService; +use File; + +/** + * Class UploadAttachmentTransformer + * @package App\Transformers + */ +class UploadAttachmentTransformer extends Fractal\TransformerAbstract +{ + /** + * @param Attachment $attachment + * @return array + */ + public function transform(Attachment $attachment) + { + $output = array(); + $output['thumb'] = AttachmentService::getUserUploadThumb($attachment, $attachment->attachmentable_id); + return $output; + } + +} + diff --git a/app/Transformers/UserAuthTransformer.php b/app/Transformers/UserAuthTransformer.php new file mode 100644 index 0000000..9cdc526 --- /dev/null +++ b/app/Transformers/UserAuthTransformer.php @@ -0,0 +1,101 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Transformers; + +use League\Fractal; +use App\User; +use App\Transformers\AttachmentTransformer; +use App\Transformers\UserProfileTransformer; +use App\Attachment; + +class UserAuthTransformer extends Fractal\TransformerAbstract +{ + /** + * List of resources possible to include + * @var array + */ + protected $availableIncludes = [ + 'UserProfile', 'Attachmentable', 'ProviderUser', 'VehicleCompany' + ]; + + /** + * @param User $user + * @return array + */ + public function transform(User $user) + { + $output = array_only($user->toArray(), ['id', 'username', 'email', 'is_active', 'is_email_confirmed', 'role_id', 'register_ip_id', 'last_login_ip_id', 'available_wallet_amount', 'user_avatar_source_id']); + $output['is_active'] = ($output['is_active'] == 1) ? true : false; + $output['is_email_confirmed'] = ($output['is_email_confirmed'] == 1) ? true : false; + return $output; + } + + /** + * @param User $user + * @return Fractal\Resource\Item + */ + public function includeUserProfile(User $user) + { + if ($user->user_profile) { + return $this->item($user->user_profile, new UserProfileTransformer()); + } else { + return null; + } + + } + + /** + * @param User $user + * @return mixed + */ + public function includeAttachmentable(User $user) + { + if ($user->attachments) { + return $this->item($user->attachments, new AttachmentTransformer()); + } else { + $user->attachments = Attachment::where('id', '=', config('constants.ConstAttachment.UserAvatar'))->first(); + $user->attachments->attachmentable_id = $user->id; + return $this->item($user->attachments, new AttachmentTransformer()); + } + } + + /** + * @param User $user + * @return array|Fractal\Resource\Item + */ + public function includeProviderUser(User $user) + { + if ($user->provider_user) { + return $this->Collection($user->provider_user, new \Plugins\SocialLogins\Transformers\ProviderUserTransformer); + } else { + return null; + } + + } + /** + * @param User $user + * @return array|Fractal\Resource\Item + */ + public function includeVehicleCompany(User $user) + { + if ($user->vehicle_company) { + return $this->item($user->vehicle_company, new \Plugins\Vehicles\Transformers\VehicleCompanyTransformer); + } else { + return null; + } + + } +} diff --git a/app/Transformers/UserLoginTransformer.php b/app/Transformers/UserLoginTransformer.php new file mode 100644 index 0000000..ef69d55 --- /dev/null +++ b/app/Transformers/UserLoginTransformer.php @@ -0,0 +1,88 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + + +namespace App\Transformers; + +use League\Fractal; +use App\UserLogin; + +/** + * Class UserLoginTransformer + * @package App\Transformers + */ +class UserLoginTransformer extends Fractal\TransformerAbstract +{ + /** + * List of resources possible to include + * + * @var array + */ + protected $availableIncludes = [ + 'UserLoginIp', 'User', 'Role' + ]; + + /** + * @param UserLogin $user_login + * @return array + */ + public function transform(UserLogin $user_login) + { + $output = array_only($user_login->toArray(), ['id', 'created_at', 'user_id', 'user_login_ip_id', 'role_id', 'user_agent']); + return $output; + } + + /** + * @param UserLogin $user_login + * @return Fractal\Resource\Item + */ + public function includeUserLoginIp(UserLogin $user_login) + { + if ($user_login->user_login_ip) { + return $this->item($user_login->user_login_ip, new IpTransformer()); + } else { + return null; + } + + } + + /** + * @param UserLogin $user_login + * @return Fractal\Resource\Item + */ + public function includeUser(UserLogin $user_login) + { + if ($user_login->user) { + return $this->item($user_login->user, new UserSimpleTransformer()); + } else { + return null; + } + + } + + /** + * @param UserLogin $user_login + * @return Fractal\Resource\Item + */ + public function includeRole(UserLogin $user_login) + { + if ($user_login->role) { + return $this->item($user_login->role, new RoleTransformer()); + } else { + return null; + } + + } +} \ No newline at end of file diff --git a/app/Transformers/UserProfileTransformer.php b/app/Transformers/UserProfileTransformer.php new file mode 100644 index 0000000..28a3c12 --- /dev/null +++ b/app/Transformers/UserProfileTransformer.php @@ -0,0 +1,62 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Transformers; + +use League\Fractal; +use App\UserProfile; + +/** + * Class UserProfileTransformer + * @package App\Transformers + */ +class UserProfileTransformer extends Fractal\TransformerAbstract +{ + /** + * List of resources possible to include + * + * @var array + */ + protected $availableIncludes = [ + 'User' + ]; + + /** + * @param UserProfile $user_profile + * @return array + */ + public function transform(UserProfile $user_profile) + { + $output = array_only($user_profile->toArray(), ['id', 'user_id', 'first_name', 'last_name', 'about_me', 'website', 'facebook_profile_link', 'twitter_profile_link', 'google_plus_profile_link', 'linkedin_profile_link', 'youtube_profile_link']); + return $output; + } + + + /** + * @param UserProfile $user_profile + * @return Fractal\Resource\Item + */ + public function includeUser(UserProfile $user_profile) + { + if ($user_profile->user) { + return $this->item($user_profile->user, (new UserTransformer())->setDefaultIncludes(['attachmentable'])); + } else { + return null; + } + + } + + +} \ No newline at end of file diff --git a/app/Transformers/UserSimpleFeedbackTransformer.php b/app/Transformers/UserSimpleFeedbackTransformer.php new file mode 100644 index 0000000..8dea5ff --- /dev/null +++ b/app/Transformers/UserSimpleFeedbackTransformer.php @@ -0,0 +1,59 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Transformers; + +use League\Fractal; +use App\User; +use App\Attachment; + +class UserSimpleFeedbackTransformer extends Fractal\TransformerAbstract +{ + /** + * List of resources possible to include + * @var array + */ + protected $availableIncludes = [ + 'Attachmentable' + ]; + + /** + * @param User $user + * @return array + */ + public function transform(User $user) + { + $output = array_only($user->toArray(), ['id', 'username']); + $output['name'] = $output['username']; + unset($output['username']); + return $output; + } + + /** + * @param User $user + * @return mixed + */ + public function includeAttachmentable(User $user) + { + if ($user->attachments) { + return $this->item($user->attachments, new AttachmentTransformer()); + } else { + $user->attachments = Attachment::where('id', '=', config('constants.ConstAttachment.UserAvatar'))->first(); + $user->attachments->attachmentable_id = $user->id; + return $this->item($user->attachments, new AttachmentTransformer()); + } + } + +} diff --git a/app/Transformers/UserSimpleTransformer.php b/app/Transformers/UserSimpleTransformer.php new file mode 100644 index 0000000..560b300 --- /dev/null +++ b/app/Transformers/UserSimpleTransformer.php @@ -0,0 +1,57 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Transformers; + +use League\Fractal; +use App\User; +use App\Attachment; + +class UserSimpleTransformer extends Fractal\TransformerAbstract +{ + /** + * List of resources possible to include + * @var array + */ + protected $availableIncludes = [ + 'Attachmentable' + ]; + + /** + * @param User $user + * @return array + */ + public function transform(User $user) + { + $output = array_only($user->toArray(), ['id', 'username']); + return $output; + } + + /** + * @param User $user + * @return mixed + */ + public function includeAttachmentable(User $user) + { + if ($user->attachments) { + return $this->item($user->attachments, new AttachmentTransformer()); + } else { + $user->attachments = Attachment::where('id', '=', config('constants.ConstAttachment.UserAvatar'))->first(); + $user->attachments->attachmentable_id = $user->id; + return $this->item($user->attachments, new AttachmentTransformer()); + } + } + +} diff --git a/app/Transformers/UserTransformer.php b/app/Transformers/UserTransformer.php new file mode 100644 index 0000000..5391953 --- /dev/null +++ b/app/Transformers/UserTransformer.php @@ -0,0 +1,129 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Transformers; + +use League\Fractal; +use App\User; +use App\Services\AttachmentService; +use App\Attachment; + +class UserTransformer extends Fractal\TransformerAbstract +{ + /** + * List of resources possible to include + * @var array + */ + protected $availableIncludes = [ + 'RegisterIp', 'LastLoginIp', 'UserProfile', 'Attachmentable', 'ProviderUser', 'Vehicle' + ]; + + /** + * @param User $user + * @return array + */ + public function transform(User $user) + { + $output = array_only($user->toArray(), ['id', 'created_at', 'username', 'email', 'is_active', 'is_email_confirmed', 'role_id', 'password', 'register_ip_id', 'last_login_ip_id', 'available_wallet_amount', 'user_login_count', 'vehicle_rental_order_count', 'vehicle_rental_count', 'user_avatar_source_id']); + $output['is_active'] = ($output['is_active'] == 1) ? true : false; + $output['is_email_confirmed'] = ($output['is_email_confirmed'] == 1) ? true : false; + return $output; + } + + /** + * @param User $user + * @return Fractal\Resource\Item + */ + public function includeRegisterIp(User $user) + { + if ($user->register_ip) { + return $this->item($user->register_ip, new IpTransformer()); + } else { + return null; + } + + } + + /** + * @param User $user + * @return Fractal\Resource\Item|null + */ + public function includeLastLoginIp(User $user) + { + if ($user->last_login_ip) { + return $this->item($user->last_login_ip, new IpTransformer()); + } else { + return null; + } + + } + + /** + * @param User $user + * @return Fractal\Resource\Item|null + */ + public function includeUserProfile(User $user) + { + if ($user->user_profile) { + return $this->item($user->user_profile, new UserProfileTransformer()); + } else { + return null; + } + + } + + /** + * @param User $user + * @return mixed + */ + public function includeAttachmentable(User $user) + { + if ($user->attachments) { + return $this->item($user->attachments, new AttachmentTransformer()); + } else { + $user->attachments = Attachment::where('id', '=', config('constants.ConstAttachment.UserAvatar'))->first(); + $user->attachments->attachmentable_id = $user->id; + return $this->item($user->attachments, new AttachmentTransformer()); + } + } + + /** + * @param User $user + * @return Fractal\Resource\Item|null + */ + public function includeVehicle(User $user) + { + if ($user->Vehicle) { + return $this->Collection($user->Vehicle, new VehicleTransformer()); + } else { + return null; + } + + } + + /** + * @param User $user + * @return array|Fractal\Resource\Item + */ + public function includeProviderUser(User $user) + { + if ($user->provider_user) { + return $this->Collection($user->provider_user, new \Plugins\SocialLogins\Transformers\ProviderUserTransformer); + } else { + return null; + } + + } +} diff --git a/app/Transformers/WalletTransactionLogTransformer.php b/app/Transformers/WalletTransactionLogTransformer.php new file mode 100644 index 0000000..f1da2e8 --- /dev/null +++ b/app/Transformers/WalletTransactionLogTransformer.php @@ -0,0 +1,60 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App\Transformers; + +use League\Fractal; +use App\WalletTransactionLog; +use Plugins\VehicleRentals\Transformers\VehicleRentalTransformer; + +/** + * Class WalletTransactionLogTransformer + * @package App\Transformers + */ +class WalletTransactionLogTransformer extends Fractal\TransformerAbstract +{ + /** + * List of resources possible to include + * @var array + */ + protected $availableIncludes = [ + 'VehicleRental' + ]; + + /** + * @param Item $item + * @return array + */ + public function transform(WalletTransactionLog $wallet_transaction_log) + { + $output = array_only($wallet_transaction_log->toArray(), ['id', 'created_at', 'amount', 'wallet_transaction_logable_id', 'wallet_transaction_logable_type', 'status', 'payment_type']); + return $output; + } + + /** + * @param VehicleRental $vehicle_rental + * @return Fractal\Resource\Item + */ + public function includeVehicleRental(WalletTransactionLog $wallet_transaction_log) + { + if ($wallet_transaction_log->wallet_transaction_logable) { + if ($wallet_transaction_log->wallet_transaction_logable_type == 'MorphVehicleRental') { + return $this->item($wallet_transaction_log->wallet_transaction_logable, new VehicleRentalTransformer()); + } + } else { + return null; + } + } +} diff --git a/app/User.php b/app/User.php new file mode 100644 index 0000000..961e30f --- /dev/null +++ b/app/User.php @@ -0,0 +1,246 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App; + +use Illuminate\Auth\Authenticatable; +use Laravel\Lumen\Auth\Authorizable; +use Illuminate\Database\Eloquent\Model; +use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract; +use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract; +use Illuminate\Http\Request; + +class User extends Model implements AuthenticatableContract +{ + use Authenticatable, Authorizable; + + /** + * The attributes that are mass assignable. + * @var array + */ + protected $fillable = [ + 'role_id', 'username', 'email', 'password', 'available_wallet_amount', 'blocked_amount', 'Vehicle_count', 'vehicle_rental_count', 'vehicle_rental_order_count', 'user_login_count', 'is_agree_terms_conditions', 'is_active', 'is_email_confirmed', 'register_ip_id', 'last_login_ip_id', 'user_avatar_source_id', 'activate_hash' + ]; + + /** + * The attributes excluded from the model's JSON form. + * @var array + */ + protected $hidden = [ + 'password', 'remember_token', + ]; + + /** + * @param $query + * @param Request $request + * @return mixed + */ + public function scopeFilterByRequest($query, Request $request) + { + if ($request->input('sort', 'id') == 'last_login_ip.ip') { + $query->orderBy('ip', $request->input('sortby', 'desc')); + } else { + $query->orderBy($request->input('sort', 'id'), $request->input('sortby', 'desc')); + } + if ($request->has('filter')) { + $filter = false; + if ($request->input('filter') == 'active') { + $filter = true; + } + $query->where('is_active', '=', $filter); + } + if ($request->has('is_email_confirmed')) { + $filter = false; + if ($request->input('is_email_confirmed') == 'yes') { + $filter = true; + } + $query->where('is_email_confirmed', '=', $filter); + } + if ($request->has('role_id')) { + if ($request->input('role_id') == 'userpass') { + $query->where('role_id', '=', config('constants.ConstUserTypes.User')); + } else if ($request->input('role_id') == 'admin') { + $query->where('role_id', '=', config('constants.ConstUserTypes.Admin')); + } + } + if ($request->has('q')) { + $query->where('username', 'LIKE', '%' . $request->input('q') . '%') + ->orWhere('email', 'LIKE', '%' . $request->input('q') . '%'); + } + if ($request->has('username')) { + $query->where('username', 'LIKE', '%' . $request->input('q') . '%'); + } + return $query; + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\HasMany + */ + public function provider_user() + { + return $this->hasMany(\Plugins\SocialLogins\Model\ProviderUser::class); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\HasMany + */ + public function user_login() + { + return $this->hasMany(UserLogin::class); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function last_login_ip() + { + return $this->belongsTo(Ip::class, 'last_login_ip_id'); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function register_ip() + { + return $this->belongsTo(Ip::class, 'register_ip_id'); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\HasOne + */ + public function user_profile() + { + return $this->hasOne(UserProfile::class); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\HasMany + */ + public function user_cash_withdrawal() + { + return $this->hasMany(UserCashWithdrawal::class); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\HasMany + */ + public function money_transfer_account() + { + return $this->hasMany(MoneyTransferAccount::class); + } + + /** + * Get all of the users attachment. + */ + public function attachments() + { + return $this->morphOne(Attachment::class, 'attachmentable'); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\HasMany + */ + public function vehicle() + { + return $this->hasMany(\Plugins\Vehicles\Model\Vehicle::class); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\HasOne + */ + public function vehicle_company() + { + return $this->hasOne(\Plugins\Vehicles\Model\VehicleCompany::class); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\morphMany + */ + public function message() + { + return $this->morphMany(\App\Message::class, 'messageable'); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\MorphMany + */ + public function vehicle_feedback() + { + return $this->morphMany(\Plugins\VehicleFeedbacks\Model\VehicleFeedback::class, 'feedbackable'); + } + + /** + * @return array + */ + public function scopeGetValidationRule() + { + return [ + 'username' => 'sometimes|required|min:3|unique:users', + 'email' => 'sometimes|required|email|unique:users', + 'password' => 'sometimes|required|min:6|max:20', + 'confirm_password' => 'sometimes|required|min:6|max:20|same:password', + 'is_agree_terms_conditions' => 'sometimes|required', + 'is_active' => 'sometimes|boolean', + 'is_email_confirmed' => 'sometimes|boolean', + 'role_id' => 'sometimes|required|integer' + ]; + } + + /** + * @return array + */ + public function scopeGetEditValidationRule() + { + return [ + 'username' => 'sometimes|required|min:3', + 'email' => 'required|email', + ]; + } + + /** + * @return array + */ + public function scopeGetForgotPasswordValidationRule() + { + return [ + 'email' => 'required|email' + ]; + } + + /** + * @return array + */ + public function scopeGetValidationMessage() + { + return [ + 'email.required' => 'Required', + 'email.email' => 'Enter valid e-mail address!', + 'email.unique' => 'E-mail address already exists!', + 'username.required' => 'Required', + 'username.min' => 'username - minimum length is 3!', + 'username.unique' => 'Username already exists!', + 'password.required' => 'Required', + 'password.min' => 'password - minimum length is 6', + 'password.max' => 'password - maximum length is 20', + 'confirm_password.required' => 'Required', + 'confirm_password.min' => 'confirm_password - Minimum length is 6', + 'confirm_password.max' => 'confirm_password - Maximum length is 20', + 'confirm_password.same' => 'Password Mismatch', + 'is_agree_terms_conditions.required' => 'Required', + 'is_active.boolean' => 'Enter 1 for activate or 0 for inacivate', + 'is_email_confirmed.boolean' => 'Enter 1 for email verified or 0 for not verified', + ]; + } +} diff --git a/app/UserLogin.php b/app/UserLogin.php new file mode 100644 index 0000000..1925730 --- /dev/null +++ b/app/UserLogin.php @@ -0,0 +1,88 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App; + +use Illuminate\Http\Request; +use Illuminate\Database\Eloquent\Model; + +class UserLogin extends Model +{ + /** + * @var string + */ + protected $table = "user_logins"; + + /** + * The attributes that are mass assignable. + * + * @var array + */ + protected $fillable = [ + 'user_id', 'user_login_ip_id', 'role_id', 'user_agent' + ]; + + /** + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function user() + { + return $this->belongsTo(User::class); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function user_login_ip() + { + return $this->belongsTo(Ip::class, 'user_login_ip_id'); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function role() + { + return $this->belongsTo(Role::class); + } + + /** + * @param $query + * @param Request $request + * @return mixed + */ + public function scopeFilterByRequest($query, Request $request) + { + if ($request->input('sort', 'id') == 'User.name') { + $query->orderBy('name', $request->input('sortby', 'desc')); + } elseif ($request->input('sort', 'id') == 'user_login_ip.ip') { + $query->orderBy('ip', $request->input('sortby', 'desc')); + } else { + $query->orderBy($request->input('sort', 'id'), $request->input('sortby', 'desc')); + } + if ($request->has('q')) { + $query->whereHas('user', function ($q) use ($request) { + $q->where('username', 'like', '%' . $request->input('q') . '%'); + }); + } + if($request->has('user_id') && !empty($request->user_id)) { + $query->whereHas('user', function ($q) use ($request) { + $q->where('id', '=', $request->user_id); + }); + } + return $query; + } + +} diff --git a/app/UserProfile.php b/app/UserProfile.php new file mode 100644 index 0000000..7ab4cd1 --- /dev/null +++ b/app/UserProfile.php @@ -0,0 +1,75 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App; + +use Illuminate\Http\Request; +use Illuminate\Database\Eloquent\Model; +use App\Attachment; + +class UserProfile extends Model +{ + /** + * @var string + */ + protected $table = "user_profiles"; + + /** + * The attributes that are mass assignable. + * + * @var array + */ + protected $fillable = [ + 'user_id', 'first_name', 'last_name', 'about_me', 'attachment_id', 'website', 'facebook_profile_link', 'twitter_profile_link', 'google_plus_profile_link', 'linkedin_profile_link', 'youtube_profile_link' + ]; + + /** + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function user() + { + return $this->belongsTo(User::class); + } + + + /** + * @param $query + * @param Request $request + * @return mixed + */ + public function scopeFilterByRequest($query, Request $request) + { + $query->orderBy($request->input('sort', 'id'), $request->input('sortby', 'desc')); + return $query; + } + + public function scopeGetValidationRule() + { + return [ + 'first_name' => 'required|min:3', + 'last_name' => 'required|min:1' + ]; + } + + public function scopeGetValidationMessage() + { + return [ + 'first_name.required' => 'Required', + 'first_name.min' => 'first_name - minimum length is 3', + 'last_name.required' => 'Required', + 'last_name.min' => 'last_name - minimum length is 1', + ]; + } +} diff --git a/app/Wallet.php b/app/Wallet.php new file mode 100644 index 0000000..3b8fa83 --- /dev/null +++ b/app/Wallet.php @@ -0,0 +1,86 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App; + +use Illuminate\Http\Request; +use Illuminate\Database\Eloquent\Model; +use App\User; + +class Wallet extends Model +{ + protected $table = "user_add_wallet_amounts"; + + /** + * The attributes that are mass assignable. + * + * @var array + */ + protected $fillable = [ + 'user_id', 'description', 'amount', 'payment_gateway_id', 'user_paypal_connection_id', 'payment_id', 'pay_key', 'is_success' + ]; + + /** + * @return \Illuminate\Database\Eloquent\Relations\MorphMany + */ + public function paypal_transaction_logs() + { + return $this->morphMany(\Plugins\Paypal\Model\PaypalTransactionLog::class, 'paypal_transaction_logable'); + } + + /** + * @return mixed + */ + public function sudopay_transaction_logs() + { + return $this->morphMany(\Plugins\Sudopays\Model\SudopayTransactionLog::class, 'sudopay_transaction_logable'); + } + + public function user() + { + return $this->belongsTo(User::class); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\MorphMany + */ + public function transactions() + { + return $this->morphMany(\App\Transaction::class, 'transactionable'); + } + + /** + * @return array + */ + public function scopeGetValidationRule() + { + $min = config('wallet.min_wallet_amount'); + $max = config('wallet.max_wallet_amount'); + return [ + 'amount' => 'required|numeric|min:' . $min . '|max:' . $max + ]; + } + + public function scopeGetValidationMessage() + { + return [ + 'amount.required' => 'Required', + 'amount.numeric' => 'Enter valid amount', + 'amount.min' => 'amount - Enter greater or equal minimum amount', + 'amount.max' => 'amount - Enter less or equal maximum amount' + ]; + } + +} diff --git a/app/WalletTransactionLog.php b/app/WalletTransactionLog.php new file mode 100644 index 0000000..3cea2e0 --- /dev/null +++ b/app/WalletTransactionLog.php @@ -0,0 +1,60 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +namespace App; + +use Illuminate\Http\Request; +use Illuminate\Database\Eloquent\Model; + +class WalletTransactionLog extends Model +{ + protected $table = "wallet_transaction_logs"; + + /** + * The attributes that are mass assignable. + * + * @var array + */ + protected $fillable = [ + 'amount', 'status', 'payment_type' + ]; + + /** + * @param $query + * @param Request $request + * @return mixed + */ + public function scopeFilterByRequest($query, Request $request) + { + $query->orderBy($request->input('sort', 'id'), $request->input('sortby', 'desc')); + if ($request->has('q')) { + $query->where('wallet_transaction_logable_type', 'LIKE', '%' . $request->input('q') . '%') + ->orWhere('amount', 'LIKE', '%' . $request->input('q') . '%') + ->orWhere('status', 'LIKE', '%' . $request->input('q') . '%') + ->orWhere('payment_type', 'LIKE', '%' . $request->input('q') . '%'); + } + return $query; + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\MorphTo + */ + public function wallet_transaction_logable() + { + return $this->morphTo(); + } + + +} diff --git a/app/helpers.php b/app/helpers.php new file mode 100644 index 0000000..393d5f4 --- /dev/null +++ b/app/helpers.php @@ -0,0 +1,253 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +/** + * Because Lumen has no config_path function, we need to add this function + * to make JWT Auth works. + */ +if (!function_exists('config_path')) { + /** + * Get the configuration path. + * @param string $path + * @return string + */ + function config_path($path = '') + { + return app()->basePath() . '/config' . ($path ? '/' . $path : $path); + } +} +if (!function_exists('public_path')) { + + /** + * Return the path to public dir + * @param null $path + * @return string + */ + function public_path($path = null) + { + return rtrim(app()->basePath('public/' . $path), '/'); + } +} + +if (!function_exists('storage_path')) { + + /** + * Return the path to storage dir + * @param null $path + * @return string + */ + function storage_path($path = null) + { + return app()->storagePath($path); + } +} + +if (!function_exists('database_path')) { + + /** + * Return the path to database dir + * @param null $path + * @return string + */ + function database_path($path = null) + { + return app()->databasePath($path); + } +} + +if (!function_exists('resource_path')) { + + /** + * Return the path to resource dir + * @param null $path + * @return string + */ + function resource_path($path = null) + { + return app()->resourcePath($path); + } +} + + +if (!function_exists('asset')) { + /** + * Generate an asset path for the application. + * @param string $path + * @param bool $secure + * @return string + */ + function asset($path, $secure = null) + { + return app('url')->asset($path, $secure); + } +} + +if (!function_exists('elixir')) { + /** + * Get the path to a versioned Elixir file. + * @param string $file + * @return string + */ + function elixir($file) + { + static $manifest = null; + if (is_null($manifest)) { + $manifest = json_decode(file_get_contents(public_path() . '/build/rev-manifest.json'), true); + } + if (isset($manifest[$file])) { + return '/build/' . $manifest[$file]; + } + throw new InvalidArgumentException("File {$file} not defined in asset manifest."); + } +} +if (!function_exists('bcrypt')) { + /** + * Hash the given value. + * @param string $value + * @param array $options + * @return string + */ + function bcrypt($value, $options = array()) + { + return app('hash')->make($value, $options); + } +} + +if (!function_exists('redirect')) { + /** + * Get an instance of the redirector. + * @param string|null $to + * @param int $status + * @param array $headers + * @param bool $secure + * @return \Illuminate\Routing\Redirector|\Illuminate\Http\RedirectResponse + */ + function redirect($to = null, $status = 302, $headers = array(), $secure = null) + { + if (is_null($to)) return app('redirect'); + return app('redirect')->to($to, $status, $headers, $secure); + } +} + +if (!function_exists('response')) { + /** + * Return a new response from the application. + * @param string $content + * @param int $status + * @param array $headers + * @return \Symfony\Component\HttpFoundation\Response|\Illuminate\Contracts\Routing\ResponseFactory + */ + function response($content = '', $status = 200, array $headers = array()) + { + $factory = app('Illuminate\Contracts\Routing\ResponseFactory'); + if (func_num_args() === 0) { + return $factory; + } + return $factory->make($content, $status, $headers); + } +} + +if (!function_exists('secure_asset')) { + /** + * Generate an asset path for the application. + * @param string $path + * @return string + */ + function secure_asset($path) + { + return asset($path, true); + } +} + +if (!function_exists('secure_url')) { + /** + * Generate a HTTPS url for the application. + * @param string $path + * @param mixed $parameters + * @return string + */ + function secure_url($path, $parameters = array()) + { + return url($path, $parameters, true); + } +} + + +if (!function_exists('session')) { + /** + * Get / set the specified session value. + * If an array is passed as the key, we will assume you want to set an array of values. + * @param array|string $key + * @param mixed $default + * @return mixed + */ + function session($key = null, $default = null) + { + if (is_null($key)) return app('session'); + if (is_array($key)) return app('session')->put($key); + return app('session')->get($key, $default); + } +} + + +if (!function_exists('cookie')) { + /** + * Create a new cookie instance. + * @param string $name + * @param string $value + * @param int $minutes + * @param string $path + * @param string $domain + * @param bool $secure + * @param bool $httpOnly + * @return \Symfony\Component\HttpFoundation\Cookie + */ + function cookie($name = null, $value = null, $minutes = 0, $path = null, $domain = null, $secure = false, $httpOnly = true) + { + $cookie = app('Illuminate\Contracts\Cookie\Factory'); + if (is_null($name)) { + return $cookie; + } + return $cookie->make($name, $value, $minutes, $path, $domain, $secure, $httpOnly); + } +} + +if (!function_exists('enabled_plugins')) { + /** + * @return array + */ + function enabled_plugins() + { + $enabled_plugins = explode(',', trim(config('site.enabled_plugins'))); + $enabled_plugins = array_map('trim', $enabled_plugins); + return $enabled_plugins; + } +} + +if (!function_exists('isPluginEnabled')) { + /** + * check the given plugin is enabled or not + * @param $plugin_name + * @return bool + */ + function isPluginEnabled($plugin_name) + { + if (in_array($plugin_name, enabled_plugins())) { + return true; + } else { + return false; + } + } +} diff --git a/artisan b/artisan new file mode 100644 index 0000000..6a9d095 --- /dev/null +++ b/artisan @@ -0,0 +1,35 @@ +#!/usr/bin/env php +make( + 'Illuminate\Contracts\Console\Kernel' +); + +exit($kernel->handle(new ArgvInput, new ConsoleOutput)); diff --git a/bootstrap/app.php b/bootstrap/app.php new file mode 100644 index 0000000..84dd679 --- /dev/null +++ b/bootstrap/app.php @@ -0,0 +1,203 @@ + + * @copyright 2018 Agriya Infoway Private Ltd + * @license http://www.agriya.com/ Agriya Infoway Licence + * @link http://www.agriya.com + */ + +require_once __DIR__ . '/../vendor/autoload.php'; + +try { + (new Dotenv\Dotenv(__DIR__ . '/../'))->load(); +} catch (Dotenv\Exception\InvalidPathException $e) { + // +} + +/* +|-------------------------------------------------------------------------- +| Create The Application +|-------------------------------------------------------------------------- +| +| Here we will load the environment and create the application instance +| that serves as the central piece of this framework. We'll use this +| application as an "IoC" container and router for this framework. +| +*/ + +$app = new Laravel\Lumen\Application( + realpath(__DIR__ . '/../') +); + +$app->withFacades(); + +$app->configure('app'); +$app->configure('cache'); +$app->configure('api'); +$app->configure('jwt'); +$app->configure('auth'); +$app->configure('session'); +$app->configure('constants'); +$app->configure('filesystems'); +$app->configure('mail'); +$app->configure('services'); +$app->configure('paypal'); +class_alias(Tymon\JWTAuth\Facades\JWTAuth::class, 'JWTAuth'); +class_alias(Tymon\JWTAuth\Facades\JWTFactory::class, 'JWTFactory'); +class_alias(Intervention\Image\Facades\Image::class, 'Image'); +class_alias(Illuminate\Support\Facades\File::class, 'File'); +class_alias(Illuminate\Support\Facades\Storage::class, 'Storage'); +class_alias(Carbon\Carbon::class, 'Carbon'); +class_alias(EasySlug\EasySlug\EasySlugFacade::class, 'EasySlug'); +class_alias(Netshell\Paypal\Facades\Paypal::class, 'Paypal'); + +$app->withEloquent(); + +/* +|-------------------------------------------------------------------------- +| Register Container Bindings +|-------------------------------------------------------------------------- +| +| Now we will register a few bindings in the service container. We will +| register the exception handler and the console kernel. You may add +| your own bindings here if you like or you can make another file. +| +*/ + +$app->singleton( + Illuminate\Contracts\Debug\ExceptionHandler::class, + App\Exceptions\Handler::class +); + +$app->singleton( + Illuminate\Contracts\Console\Kernel::class, + App\Console\Kernel::class +); + +/* todo: */ +$app->singleton( + Illuminate\Contracts\Routing\ResponseFactory::class, + Illuminate\Routing\ResponseFactory::class +); + +$app->singleton( + Illuminate\Auth\AuthManager::class, + function ($app) { + return $app->make('auth'); + } +); + +$app->singleton( + Illuminate\Cache\CacheManager::class, + function ($app) { + return $app->make('cache'); + } +); +/* todo: */ + + +/* +|-------------------------------------------------------------------------- +| Register Middleware +|-------------------------------------------------------------------------- +| +| Next, we will register the middleware with the application. These can +| be global middleware that run before and after each request into a +| route or middleware that'll be assigned to some specific routes. +| +*/ + +/*$app->middleware([ + App\Http\Middleware\Tracking::class + ]);*/ + +$app->routeMiddleware([ + 'auth' => App\Http\Middleware\Authenticate::class, + 'jwt.auth' => Tymon\JWTAuth\Middleware\GetUserFromToken::class, + 'jwt.refresh' => Tymon\JWTAuth\Middleware\RefreshToken::class, + 'apitracking' => App\Http\Middleware\Tracking::class, + 'role' => App\Http\Middleware\AuthenticateRole::class +]); + +/* +|-------------------------------------------------------------------------- +| Register Service Providers +|-------------------------------------------------------------------------- +| +| Here we will register all of the application's service providers which +| are used to bind services into the container. Service providers are +| totally optional, so you are not required to uncomment this line. +| +*/ + +$app->register(App\Providers\AppServiceProvider::class); +// $app->register(App\Providers\AuthServiceProvider::class); +// $app->register(App\Providers\EventServiceProvider::class); + +/* todo: */ +// JWTAuth Dependencies +$app->register(Illuminate\Session\SessionServiceProvider::class); +$app->register(Illuminate\Cookie\CookieServiceProvider::class); +$app->register(\Tymon\JWTAuth\Providers\JWTAuthServiceProvider::class); +$app->register(\Dingo\Api\Provider\LumenServiceProvider::class); +$app->register(\App\Providers\SettingsServiceProvider::class); +$app->register(\App\Providers\MessageServiceProvider::class); +$app->register(\App\Providers\TransactionServiceProvider::class); +$app->register(Illuminate\Mail\MailServiceProvider::class); +$app->register(Illuminate\Filesystem\FilesystemServiceProvider::class); +$app->register(Intervention\Image\ImageServiceProvider::class); +$app->register(Plugins\PluginServiceProvider::class); +$app->register(Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider::class); +$app->register(EasySlug\EasySlug\EasySlugServiceProvider::class); +$app->register(Netshell\Paypal\PaypalServiceProvider::class); + +$app->make(\Dingo\Api\Auth\Auth::class)->extend('jwt', function ($app) { + return new Dingo\Api\Auth\Provider\JWT($app->make(Tymon\JWTAuth\JWTAuth::class)); +}); +/* todo: */ + +$app['Dingo\Api\Transformer\Factory']->setAdapter(function ($app) { + $fractal = new League\Fractal\Manager; + $fractal->setSerializer(new League\Fractal\Serializer\ArraySerializer); + return new \Dingo\Api\Transformer\Adapter\Fractal($fractal); +}); + +function getFolderList($dir) +{ + $subFolders = array(); + $paths = scandir($dir); + foreach ($paths as $path) { + if ($path != '.' && $path != '..') { + if (is_dir($dir . '/' . $path)) { + $subFolders[] = $path; + } + + } + } + return $subFolders; +} + +/* +|-------------------------------------------------------------------------- +| Load The Application Routes +|-------------------------------------------------------------------------- +| +| Next we will include the routes file so that they can all be added to +| the application. This will provide all of the URLs the application +| can respond to, as well as the controllers that may handle them. +| +*/ + +$app->group(['namespace' => 'App\Http\Controllers'], function ($app) { + require __DIR__ . '/../app/Http/routes.php'; +}); + +return $app; + diff --git a/bower.json b/bower.json new file mode 100644 index 0000000..7f6a369 --- /dev/null +++ b/bower.json @@ -0,0 +1,51 @@ +{ + "name": "bookorrent", + "version": "0.0.1", + "_comment": "Any dependencies added here require a manual edit to vendor_files in /Gruntfile.js and (??? verify the following) /build/karma-unit.js (e.g 'vendor/angular-resource/angular-resource.js')", + "devDependencies": { + "angular": "1.5.2", + "angular-resource": "1.5.2", + "angular-mocks": "1.5.2", + "angular-sanitize": "1.5.2", + "angular-animate": "1.5.2", + "angular-i18n": "1.5.2", + "angular-cookies": "1.5.2", + "bootstrap": "~3.3", + "angular-bootstrap": "~1.3.2", + "angular-ui-router": "~0.2.13", + "ng-admin": "1.0.0-alpha4", + "ng-admin.jwt-auth": "~0.0.1", + "satellizer": "~0.14.0", + "angular-growl-v2": "~0.7.5", + "angular-translate": "~2.11.0", + "angular-translate-loader-static-files": "~2.11.0", + "angular-translate-storage-cookie": "~2.11.0", + "angular-translate-storage-local": "~2.11.0", + "angular-translate-handler-log": "~2.11.0", + "jquery": "~2.2.2", + "angular-slugify": "1.0.1", + "angulartics": "~1.0.3", + "angulartics-facebook-pixel": "~0.1.0", + "angulartics-google-analytics": "~0.1.4", + "angular-recaptcha": "~3.0.3", + "ng-file-upload-shim": "~1.6.4", + "ng-file-upload": "~12.0.4", + "angular-dynamic-locale": "~0.1.30", + "angular-credit-cards": "3.1.2", + "angular-loading-bar": "~0.9.0", + "bootstrap-ui-datetime-picker": "^2.3.1", + "accounting": "0.3.2", + "angular-google-places-autocomplete": "0.2.7", + "angularjs-slider":"4.0.2", + "angular-bootstrap-calendar":"0.21.3", + "angularjs-socialshare":"2.2.2", + "angular-moment":"1.0.0-beta.5" + }, + "dependencies": { + }, + "resolutions": { + "angular": ">=1.5.2", + "angular-bootstrap": ">=1.3.2", + "ng-admin": "1.0.0-alpha4" + } +} diff --git a/client/.npmignore b/client/.npmignore new file mode 100644 index 0000000..e9b6da3 --- /dev/null +++ b/client/.npmignore @@ -0,0 +1,32 @@ +~ +build/ +builds/ +[Bb]in +[Dd]ebug*/ +obj/ +[Rr]elease*/ +zip/ +_[Rr]e[Ss]harper*/ +_[Rr]eSharper.* +*.user +*.[Rr]e[Ss]harper +*.suo +*.cache +*.swp +*.dot[Cc]over +packages/* +[Bb]ackup +[Uu]pgrade[Ll]og.xml +[Uu]pgrade[Ll]og.htm +_[Uu]pgrade[Rr]eport_[Ff]iles +.idea/ +*.log +*.log.* +*node_modules* +vendor/ +vendor/* +vendor/*/* +vendor/*/*/* +vendor/*/*/*/* + + diff --git a/client/.yo-rc.json b/client/.yo-rc.json new file mode 100644 index 0000000..7d523fd --- /dev/null +++ b/client/.yo-rc.json @@ -0,0 +1,6 @@ +{ + "generator-ngbp": { + "projectName": "BookorRent", + "useCoffeescript": false + } +} \ No newline at end of file diff --git a/client/README.md b/client/README.md new file mode 100644 index 0000000..2f130d7 --- /dev/null +++ b/client/README.md @@ -0,0 +1,7 @@ +# Agriya base + +A simplified version of the ngBoilerplate angular project template. + +*** + +## Quick Start diff --git a/client/src/README.md b/client/src/README.md new file mode 100644 index 0000000..e0e861c --- /dev/null +++ b/client/src/README.md @@ -0,0 +1,47 @@ +# The `src` Directory + +## Overview + +The `src/` directory contains all code used in the application along with all +tests of such code. + +``` +src/ + |- app/ + | |- about/ + | |- home/ + | |- app.js + | |- app.spec.js + |- assets/ + |- common/ + |- less/ + | |- main.less + | |- variables.less + |- index.html +``` + +- `src/app/` - application-specific code, i.e. code not likely to be reused in + another application. [Read more »](app/README.md) +- `src/assets/` - static files like fonts and images. + [Read more »](assets/README.md) +- `src/common/` - third-party libraries or components likely to be reused in + another application. [Read more »](common/README.md) +- `src/less/` - LESS CSS files. [Read more »](less/README.md) +- `src/index.html` - this is the HTML document of the single-page application. + See below. + +See each directory for a detailed explanation. + +## `index.html` + +The `index.html` file is the HTML document of the single-page application (SPA) +that should contain all markup that applies to everything in the app, such as +the header and footer. It declares with `ngApp` that this is `BookorRent`, +specifies the main `AppController` controller, and contains the `ngView` directive +into which route templates are placed. + +Unlike any other HTML document (e.g. the templates), `index.html` is compiled as +a Grunt template, so variables from `Gruntfile.js` and `package.json` can be +referenced from within it. Changing `name` in `package.json` from +"BookorRent" will rename the resultant CSS and JavaScript placed in `build/`, +so this HTML references them by variable for convenience. diff --git a/client/src/ag-admin/index.html b/client/src/ag-admin/index.html new file mode 100644 index 0000000..0cbe69b --- /dev/null +++ b/client/src/ag-admin/index.html @@ -0,0 +1,33 @@ + + + + Admin Panel + + + <% styles.forEach( function ( file ) { %> + + <% }); %> + + + + + + + + + + + +
+
 
+
+
+ + +<% ngAdminScripts.forEach( function ( file ) { %> + +<% +}); %> + + + \ No newline at end of file diff --git a/client/src/ag-admin/js/ng-admin.app.js b/client/src/ag-admin/js/ng-admin.app.js new file mode 100644 index 0000000..778ef96 --- /dev/null +++ b/client/src/ag-admin/js/ng-admin.app.js @@ -0,0 +1,7709 @@ +var ngapp = angular.module('BookorRent', ['ng-admin', 'ng-admin.jwt-auth', 'google.places', 'mwl.calendar']); +var admin_api_url = '/bookorrent/public'; +var limit_per_page = 20; +var no_limit_per_page = 100; +var enabledPlugins; +// dashboard page redirect changes +function homeController($scope, $http, $location) { + $location.path('/dashboard'); +} +//Custom directives controlller function called here +//State Provider defined for custom pages. +//Templates created under 'tpl' directory and controller functions defined above. +ngapp.config(function ($stateProvider) { + $stateProvider + .state('home', { + url: '/', + controller: homeController, + controllerAs: 'controller' + }) + .state('pages', { + parent: 'main', + url: '/pages/add', + templateUrl: '../ag-admin/tpl/pages.tpl.html', + params: { + id: null + }, + controller: pagesController, + controllerAs: 'controller', + resolve: { + AuthCheck: function ($http) { + var token = localStorage.userToken; + if (!token) { + return false; + } else { + $http.defaults.headers.common['Authorization'] = 'Bearer ' + token; + return $http.get(admin_api_url + '/api/languages?filter=active&sort=name&sortby=asc'); + } + } + } + }) + .state('plugins', { + parent: 'main', + url: '/plugins', + templateUrl: '../ag-admin/tpl/plugins.tpl.html', + controller: pluginsController, + controllerAs: 'controller', + resolve: { + AuthCheck: function ($http) { + var token = localStorage.userToken; + if (!token) { + return false; + } else { + $http.defaults.headers.common['Authorization'] = 'Bearer ' + token; + return $http.get(admin_api_url + '/api/admin/plugins', {}); + } + } + } + }) + .state('users/change_password', { + parent: 'main', + url: '/change_password', + templateUrl: '../ag-admin/tpl/changePassword.tpl.html', + params: { + id: null + }, + controller: changePasswordController, + controllerAs: 'controller', + resolve: {} + }) + .state('counter_locations/add', { + parent: 'main', + url: '/counter_locations/add', + templateUrl: '../ag-admin/tpl/counterLocationAdd.tpl.html', + controller: counterLocationController, + controllerAs: 'controller', + resolve: { + AuthCheck: function ($http) { + var token = localStorage.userToken; + if (!token) { + return false; + } else { + $http.defaults.headers.common['Authorization'] = 'Bearer ' + token; + } + } + } + }) + .state('counter_locations/:id/edit', { + parent: 'main', + url: '/counter_locations/:id/edit', + templateUrl: '../ag-admin/tpl/counterLocationEdit.tpl.html', + controller: counterLocationController, + controllerAs: 'controller', + params: { + id: null + }, + resolve: { + AuthCheck: function ($http) { + var token = localStorage.userToken; + if (!token) { + return false; + } else { + $http.defaults.headers.common['Authorization'] = 'Bearer ' + token; + } + } + } + }) + .state('vehicle_type_prices/add', { + parent: 'main', + url: '/vehicle_type_prices/add', + templateUrl: '../ag-admin/tpl/vehicleTypePrice.tpl.html', + controller: vehicleTypePriceController, + controllerAs: 'controller', + resolve: { + AuthCheck: function ($http) { + var token = localStorage.userToken; + if (!token) { + return false; + } else { + $http.defaults.headers.common['Authorization'] = 'Bearer ' + token; + } + } + } + }) + .state('vehicle_companies/add', { + parent: 'main', + url: '/vehicle_companies/add', + templateUrl: '../ag-admin/tpl/vehicleCompaniesAdd.tpl.html', + controller: vehicleCompaniesController, + controllerAs: 'controller', + resolve: { + AuthCheck: function ($http) { + var token = localStorage.userToken; + if (!token) { + return false; + } else { + $http.defaults.headers.common['Authorization'] = 'Bearer ' + token; + } + } + } + }) + .state('vehicle_companies/:id/edit', { + parent: 'main', + url: '/vehicle_companies/:id/edit', + templateUrl: '../ag-admin/tpl/vehicleCompaniesEdit.tpl.html', + controller: vehicleCompaniesController, + controllerAs: 'controller', + params: { + id: null + }, + resolve: { + AuthCheck: function ($http) { + var token = localStorage.userToken; + if (!token) { + return false; + } else { + $http.defaults.headers.common['Authorization'] = 'Bearer ' + token; + } + } + } + }) + .state('vehicle/add', { + parent: 'main', + url: '/vehicle/add', + templateUrl: '../ag-admin/tpl/vehicleAdd.tpl.html', + controller: vehicleController, + controllerAs: 'controller', + resolve: { + AuthCheck: function ($http) { + var token = localStorage.userToken; + if (!token) { + return false; + } else { + $http.defaults.headers.common['Authorization'] = 'Bearer ' + token; + } + } + } + }) + .state('vehicles/:id/edit', { + parent: 'main', + url: '/vehicles/:id/edit', + templateUrl: '../ag-admin/tpl/vehicleEdit.tpl.html', + controller: vehicleController, + controllerAs: 'controller', + params: { + id: null + }, + resolve: { + AuthCheck: function ($http) { + var token = localStorage.userToken; + if (!token) { + return false; + } else { + $http.defaults.headers.common['Authorization'] = 'Bearer ' + token; + } + } + } + }) + .state('vehicles/:id/calendar', { + parent: 'main', + url: '/vehicles/:id/calendar', + templateUrl: '../ag-admin/tpl/vehicle_calendar.tpl.html', + controller: vehicleCalendarController, + controllerAs: 'controller', + params: { + id: null + }, + resolve: { + AuthCheck: function ($http) { + var token = localStorage.userToken; + if (!token) { + return false; + } else { + $http.defaults.headers.common['Authorization'] = 'Bearer ' + token; + } + } + } + }) + .state('vehicle_rentals/:id/checkout', { + parent: 'main', + url: '/vehicle_rentals/:id/checkout', + templateUrl: '../ag-admin/tpl/vehiclecheckOut.tpl.html', + controller: vehiclecheckOutController, + controllerAs: 'controller', + params: { + id: null + }, + resolve: { + AuthCheck: function ($http) { + var token = localStorage.userToken; + if (!token) { + return false; + } else { + $http.defaults.headers.common['Authorization'] = 'Bearer ' + token; + } + } + } + }) + .state('vehicles/view/:id', { + parent: 'main', + url: '/vehicles/view/:id', + templateUrl: '../ag-admin/tpl/vehicleView.tpl.html', + controller: vehicleViewController, + controllerAs: 'controller', + params: { + id: null + }, + resolve: { + AuthCheck: function ($http) { + var token = localStorage.userToken; + if (!token) { + return false; + } else { + $http.defaults.headers.common['Authorization'] = 'Bearer ' + token; + } + } + } + }).state('vehicle_view_page', { + parent: 'main', + url: '/vehicle/:id/:slug', + templateUrl: '../ag-admin/tpl/vehicleView.tpl.html', + controller: vehicleViewController, + controllerAs: 'controller', + params: { + id: null + }, + resolve: { + AuthCheck: function ($http) { + var token = localStorage.userToken; + if (!token) { + return false; + } else { + $http.defaults.headers.common['Authorization'] = 'Bearer ' + token; + } + } + } + }); +}); +//Customize API Mapping +//Referenced Document Link: http://ng-admin-book.marmelab.com/doc/API-mapping.html +ngapp.config(['RestangularProvider', function (RestangularProvider) { + // use the custom query parameters function to format the API request correctly + RestangularProvider.addFullRequestInterceptor(function (element, operation, what, url, headers, params) { + // custom pagination params + if (params._filters) { + angular.forEach(params._filters, function (value, i) { + params[i] = value; + }); + delete params._filters; + } + if (params._sortField) { + params.sort = params._sortField; + } + delete params._sortField; + if (params._sortDir) { + params.sortby = params._sortDir; + } + delete params._sortDir; + if (params._perPage !== null && params._perPage !== 'all' && params._page) { + params._start = (params._page - 1) * params._perPage; + params._end = params._page * params._perPage; + //In REST file, we added page and limit query parameters for pagination + //Get Reference from http://ng-admin-book.marmelab.com/doc/API-mapping.html + //Keyword - pagination + params.page = params._page; + params.limit = params._perPage; + } + delete params._start; + delete params._end; + if (params._perPage === null) { + params.limit = limit_per_page; + } + /*if (angular.isUndefined(params._perPage)) { + params.limit = 'all'; + }*/ + //limit('all') is used for dropdown values, our api default limit value is '10', to show all the value we should pass string 'all' in limit parameter. + if (params._perPage == 'all') { + params.limit = 'all'; + } + delete params._page; + delete params._perPage; + // custom sort params + if (params._sortField) { + delete params._sortField; + delete params._sortDir; + } + return { + params: params + }; + }); + //Total Number of Results + //Our API doesn't return a X-Total-Count header, so we added a totalCount property to the response object using a Restangular response interceptor. + //Removed metadata info from response + RestangularProvider.addResponseInterceptor(function (data, operation, what, url, response) { + if (operation === "getList") { + var headers = response.headers(); + if (response.data.meta.pagination.total !== null) { + response.totalCount = response.data.meta.pagination.total; + } + } + return data; + }); + //To cutomize single view results, we added setResponseExtractor. + //Our API Edit view results single array with following data format data[{}], Its not working with ng-admin format + //so we returned data like data[0]; + RestangularProvider.setResponseExtractor(function (response, operation, what, url) { + if (response.data) { + if (operation === "getList") { + // Use results as the return type, and save the result metadata + var newResponse = response.data; + newResponse._metadata = response.meta.pagination; + return newResponse; + } + return response.data[0]; + } else { + return response; + } + }); +}]); +//Custom Header +//Referenced Link: http://ng-admin-book.marmelab.com/doc/Dashboard.html +//Above link has details about dashboard customization, we follwed the same steps for header customization. +//Created custom directive for header, reference http://ng-admin-book.marmelab.com/doc/Custom-pages.html keyword - directive. +//Template files created under 'tpl' directory. +ngapp.directive('customHeader', ['$location', '$state', '$http', function ($location, $state, $http, $scope) { + return { + restrict: 'E', + scope: {}, + templateUrl: '../ag-admin/tpl/customHeader.tpl.html', + link: function (scope) { + scope.siteUrl = admin_api_url; + }, + controller: customHeaderController, + controllerAs: 'controller', + resolve: {} + }; +}]); +//Custom Dashboard +//Referenced Link: http://ng-admin-book.marmelab.com/doc/Dashboard.html +//Created custom directive for header, reference http://ng-admin-book.marmelab.com/doc/Custom-pages.html keyword - directive. +//Template files created under 'tpl' directory. +ngapp.directive('dashboardSummary', ['$location', '$state', '$http', function ($location, $state, $http) { + return { + restrict: 'E', + scope: { + entity: "&", + entityName: "@", + entry: "&", + size: "@", + label: "@", + revenueDetails: "&" + }, + templateUrl: '../ag-admin/tpl/dashboardSummary.tpl.html', + link: function (scope) { + scope.rangeVal = [{ + "key": "lastDays", + "value": "Last 7 Days" + }, { + "key": "lastWeeks", + "value": "Last 4 Weeks" + }, { + "key": "lastMonths", + "value": "Last 3 Months" + }, { + "key": "lastYears", + "value": "Last 3 Years" + }]; + if (scope.rangeText === undefined) { + scope.rangeText = "Last 7 Days"; + } + scope.selectedRangeItem = function (rangeVal, rangeText) { + $http.get(admin_api_url + '/api/admin/stats', { + params: { + filter: rangeVal + } + }).success(function (response) { + scope.adminstats = response; + scope.rangeText = rangeText; + }); + }; + var token = localStorage.userToken; + if (!token) { + $state.go('logout'); + } else { + $http.defaults.headers.common['Authorization'] = 'Bearer ' + token; + } + $http.get(admin_api_url + '/api/admin/stats').success(function (response) { + scope.adminstats = response; + scope.adminactivities = response; + }); + scope.enabled_plugin = localStorage.getItem('enabled_plugins'); + scope.site_version = localStorage.getItem('site_version'); + } + }; +}]); +ngapp.directive('batchDeactive', ['$location', '$state', 'notification', '$q', 'Restangular', function ($location, $state, notification, $q, Restangular) { + return { + restrict: 'E', + scope: { + selection: '=', + type: '@' + }, + link: function (scope, element, attrs) { + const status_name = attrs.type == 'deactive' ? 'Deactive' : 'Deactive'; + scope.icon = attrs.type == 'deactive' ? 'glyphicon-remove' : 'glyphicon-remove'; + scope.label = attrs.type == 'deactive' ? 'Deactive' : 'Deactive'; + scope.updateStatus = function () { + $q.all(scope.selection.map(function (e) { + Restangular.one('/users/' + e.values.id + '/deactive').put() + .then(function () { + $state.reload() + }) + })) + .then(function () { + notification.log(scope.selection.length + ' User status changed to ' + status_name, {addnCls: 'humane-flatty-success'}); + }) + } + }, + template: ' {{ label }}' + }; +}]); +ngapp.directive('batchActive', ['$location', '$state', 'notification', '$q', 'Restangular', function ($location, $state, notification, $q, Restangular) { + return { + restrict: 'E', + scope: { + selection: '=', + type: '@' + }, + link: function (scope, element, attrs) { + const status_name = attrs.type == 'active' ? 'Active' : 'Active'; + scope.icon = attrs.type == 'active' ? 'glyphicon-ok' : 'glyphicon-ok'; + scope.label = attrs.type == 'active' ? 'Active' : 'Active'; + scope.updateStatus = function () { + $q.all(scope.selection.map(function (e) { + Restangular.one('/users/' + e.values.id + '/active').put() + .then(function () { + $state.reload() + }) + })) + .then(function () { + notification.log(scope.selection.length + ' User status changed to ' + status_name, {addnCls: 'humane-flatty-success'}); + }) + } + }, + template: ' {{ label }}' + }; +}]); +ngapp.directive('batchReject', ['$location', '$state', 'notification', '$q', 'Restangular', function ($location, $state, notification, $q, Restangular) { + return { + restrict: 'E', + scope: { + selection: '=', + type: '@' + }, + link: function (scope, element, attrs) { + const status_name = attrs.type == 'reject' ? 'Reject' : 'Reject'; + scope.icon = attrs.type == 'reject' ? 'glyphicon-remove' : 'glyphicon-ok'; + scope.label = attrs.type == 'reject' ? 'Reject' : 'Reject'; + scope.updateStatus = function () { + $q.all(scope.selection.map(function (e) { + Restangular.one('/vehicle_companies/' + e.values.id + '/reject').put() + .then(function () { + $state.reload() + }) + })) + .then(function () { + notification.log(scope.selection.length + ' Vehicle Comapany status changed to ' + status_name, {addnCls: 'humane-flatty-success'}); + }) + } + }, + template: ' {{ label }}' + }; +}]); +ngapp.directive('batchVehicleDeactive', ['$location', '$state', 'notification', '$q', 'Restangular', function ($location, $state, notification, $q, Restangular) { + return { + restrict: 'E', + scope: { + selection: '=', + type: '@' + }, + link: function (scope, element, attrs) { + const status_name = attrs.type == 'deactive' ? 'Deactive' : 'Deactive'; + scope.icon = attrs.type == 'deactive' ? 'glyphicon-remove' : 'glyphicon-remove'; + scope.label = attrs.type == 'deactive' ? 'Deactive' : 'Deactive'; + scope.updateStatus = function () { + $q.all(scope.selection.map(function (e) { + Restangular.one('/vehicle_companies/' + e.values.id + '/deactive').put() + .then(function () { + $state.reload() + }) + })) + .then(function () { + notification.log(scope.selection.length + ' Vehicle Comapany status changed to ' + status_name, {addnCls: 'humane-flatty-success'}); + }) + } + }, + template: ' {{ label }}' + }; +}]); +ngapp.directive('batchVehicleActive', ['$location', '$state', 'notification', '$q', 'Restangular', function ($location, $state, notification, $q, Restangular) { + return { + restrict: 'E', + scope: { + selection: '=', + type: '@' + }, + link: function (scope, element, attrs) { + const status_name = attrs.type == 'active' ? 'Active' : 'Active'; + scope.icon = attrs.type == 'active' ? 'glyphicon-ok' : 'glyphicon-ok'; + scope.label = attrs.type == 'active' ? 'Active' : 'Active'; + scope.updateStatus = function () { + $q.all(scope.selection.map(function (e) { + Restangular.one('/vehicle_companies/' + e.values.id + '/active').put() + .then(function () { + $state.reload() + }) + })) + .then(function () { + notification.log(scope.selection.length + ' Vehicle Comapany status changed to ' + status_name, {addnCls: 'humane-flatty-success'}); + }) + } + }, + template: ' {{ label }}' + }; +}]); +ngapp.directive('batchVehiclesDeactive', ['$location', '$state', 'notification', '$q', 'Restangular', function ($location, $state, notification, $q, Restangular) { + return { + restrict: 'E', + scope: { + selection: '=', + type: '@' + }, + link: function (scope, element, attrs) { + const status_name = attrs.type == 'deactive' ? 'Deactive' : 'Deactive'; + scope.icon = attrs.type == 'deactive' ? 'glyphicon-remove' : 'glyphicon-remove'; + scope.label = attrs.type == 'deactive' ? 'Deactive' : 'Deactive'; + scope.updateStatus = function () { + $q.all(scope.selection.map(function (e) { + Restangular.one('/vehicles/' + e.values.id + '/deactive').put() + .then(function () { + $state.reload() + }) + })) + .then(function () { + notification.log(scope.selection.length + ' Vehicle status changed to ' + status_name, {addnCls: 'humane-flatty-success'}); + }) + } + }, + template: ' {{ label }}' + }; +}]); + +ngapp.directive('batchStatesDeactive', ['$location', '$state', 'notification', '$q', 'Restangular', function ($location, $state, notification, $q, Restangular) { + return { + restrict: 'E', + scope: { + selection: '=', + type: '@' + }, + link: function (scope, element, attrs) { + const status_name = attrs.type == 'deactive' ? 'Deactive' : 'Deactive'; + scope.icon = attrs.type == 'deactive' ? 'glyphicon-remove' : 'glyphicon-remove'; + scope.label = attrs.type == 'deactive' ? 'Deactive' : 'Deactive'; + scope.updateStatus = function () { + $q.all(scope.selection.map(function (e) { + Restangular.one('/states/' + e.values.id + '/deactive').put() + .then(function () { + $state.reload() + }) + })) + .then(function () { + notification.log(scope.selection.length + ' State status changed to ' + status_name, {addnCls: 'humane-flatty-success'}); + }) + } + }, + template: ' {{ label }}' + }; +}]); +ngapp.directive('batchCitiesDeactive', ['$location', '$state', 'notification', '$q', 'Restangular', function ($location, $state, notification, $q, Restangular) { + return { + restrict: 'E', + scope: { + selection: '=', + type: '@' + }, + link: function (scope, element, attrs) { + const status_name = attrs.type == 'deactive' ? 'Deactive' : 'Deactive'; + scope.icon = attrs.type == 'deactive' ? 'glyphicon-remove' : 'glyphicon-remove'; + scope.label = attrs.type == 'deactive' ? 'Deactive' : 'Deactive'; + scope.updateStatus = function () { + $q.all(scope.selection.map(function (e) { + Restangular.one('/cities/' + e.values.id + '/deactive').put() + .then(function () { + $state.reload() + }) + })) + .then(function () { + notification.log(scope.selection.length + ' City status changed to ' + status_name, {addnCls: 'humane-flatty-success'}); + }) + } + }, + template: ' {{ label }}' + }; +}]); +ngapp.directive('batchCountriesDeactive', ['$location', '$state', 'notification', '$q', 'Restangular', function ($location, $state, notification, $q, Restangular) { + return { + restrict: 'E', + scope: { + selection: '=', + type: '@' + }, + link: function (scope, element, attrs) { + const status_name = attrs.type == 'deactive' ? 'Deactive' : 'Deactive'; + scope.icon = attrs.type == 'deactive' ? 'glyphicon-remove' : 'glyphicon-remove'; + scope.label = attrs.type == 'deactive' ? 'Deactive' : 'Deactive'; + scope.updateStatus = function () { + $q.all(scope.selection.map(function (e) { + Restangular.one('/countries/' + e.values.id + '/deactive').put() + .then(function () { + $state.reload() + }) + })) + .then(function () { + notification.log(scope.selection.length + ' Country status changed to ' + status_name, {addnCls: 'humane-flatty-success'}); + }) + } + }, + template: ' {{ label }}' + }; +}]); +ngapp.directive('batchVehiclesActive', ['$location', '$state', 'notification', '$q', 'Restangular', function ($location, $state, notification, $q, Restangular) { + return { + restrict: 'E', + scope: { + selection: '=', + type: '@' + }, + link: function (scope, element, attrs) { + const status_name = attrs.type == 'active' ? 'Active' : 'Active'; + scope.icon = attrs.type == 'active' ? 'glyphicon-ok' : 'glyphicon-ok'; + scope.label = attrs.type == 'active' ? 'Active' : 'Active'; + scope.updateStatus = function () { + $q.all(scope.selection.map(function (e) { + Restangular.one('/vehicles/' + e.values.id + '/active').put() + .then(function () { + $state.reload() + }) + })) + .then(function () { + notification.log(scope.selection.length + ' Vehicle status changed to ' + status_name, {addnCls: 'humane-flatty-success'}); + }) + } + }, + template: ' {{ label }}' + }; +}]); +ngapp.directive('batchStatesActive', ['$location', '$state', 'notification', '$q', 'Restangular', function ($location, $state, notification, $q, Restangular) { + return { + restrict: 'E', + scope: { + selection: '=', + type: '@' + }, + link: function (scope, element, attrs) { + const status_name = attrs.type == 'active' ? 'Active' : 'Active'; + scope.icon = attrs.type == 'active' ? 'glyphicon-ok' : 'glyphicon-ok'; + scope.label = attrs.type == 'active' ? 'Active' : 'Active'; + scope.updateStatus = function () { + $q.all(scope.selection.map(function (e) { + Restangular.one('/states/' + e.values.id + '/active').put() + .then(function () { + $state.reload() + }) + })) + .then(function () { + notification.log(scope.selection.length + ' State status changed to ' + status_name, {addnCls: 'humane-flatty-success'}); + }) + } + }, + template: ' {{ label }}' + }; +}]); +ngapp.directive('batchCitiesActive', ['$location', '$state', 'notification', '$q', 'Restangular', function ($location, $state, notification, $q, Restangular) { + return { + restrict: 'E', + scope: { + selection: '=', + type: '@' + }, + link: function (scope, element, attrs) { + const status_name = attrs.type == 'active' ? 'Active' : 'Active'; + scope.icon = attrs.type == 'active' ? 'glyphicon-ok' : 'glyphicon-ok'; + scope.label = attrs.type == 'active' ? 'Active' : 'Active'; + scope.updateStatus = function () { + $q.all(scope.selection.map(function (e) { + Restangular.one('/cities/' + e.values.id + '/active').put() + .then(function () { + $state.reload() + }) + })) + .then(function () { + notification.log(scope.selection.length + ' City status changed to ' + status_name, {addnCls: 'humane-flatty-success'}); + }) + } + }, + template: ' {{ label }}' + }; +}]); +ngapp.directive('batchCountriesActive', ['$location', '$state', 'notification', '$q', 'Restangular', function ($location, $state, notification, $q, Restangular) { + return { + restrict: 'E', + scope: { + selection: '=', + type: '@' + }, + link: function (scope, element, attrs) { + const status_name = attrs.type == 'active' ? 'Active' : 'Active'; + scope.icon = attrs.type == 'active' ? 'glyphicon-ok' : 'glyphicon-ok'; + scope.label = attrs.type == 'active' ? 'Active' : 'Active'; + scope.updateStatus = function () { + $q.all(scope.selection.map(function (e) { + Restangular.one('/countries/' + e.values.id + '/active').put() + .then(function () { + $state.reload() + }) + })) + .then(function () { + notification.log(scope.selection.length + ' Country status changed to ' + status_name, {addnCls: 'humane-flatty-success'}); + }) + } + }, + template: ' {{ label }}' + }; +}]); +//Custom button Creation +//Synchronize button to synchronize payment gateways +//Referenced Link: http://ng-admin-book.marmelab.com/doc/reference/View.html +ngapp.directive('addSync', ['$location', '$state', '$http', 'notification', function ($location, $state, $http, notification) { + return { + restrict: 'E', + scope: { + entity: "&", + entityName: "@", + entry: "&", + size: "@", + label: "@" + }, + template: "\n  {{label}} \n", + link: function (scope, element) { + scope.syncSudopay = false; + if (scope.entry().values.name === 'ZazPay') { + scope.syncSudopay = true; + } + scope.sync = function () { + scope.disableButton = true; + $http.get(admin_api_url + '/api/admin/sudopay/synchronize').success(function (response) { + scope.disableButton = false; + notification.log('Synchronized Successfully', {addnCls: 'humane-flatty-success'}); + }); + }; + } + }; +}]); +//Cancel button to cancel vehicle_rentals. +//Referenced Link: http://ng-admin-book.marmelab.com/doc/reference/View.html +ngapp.directive('addCancel', ['$location', '$state', '$http', 'notification', function ($location, $state, $http, notification) { + return { + restrict: 'E', + scope: { + entity: "&", + entityName: "@", + entry: "&", + size: "@", + label: "@", + post: '&' + }, + template: "\n  {{label}} \n", + link: function (scope, element) { + scope.removeCancel = false; + if (scope.entry().values.item_user_status_id === 2 || scope.entry().values.item_user_status_id === 7) { + scope.removeCancel = true; + } + var id = scope.entry().values.id; + scope.cancel = function () { + $http.put(admin_api_url + '/api/admin/vehicle_rentals/' + id + '/cancelled-by-admin').success(function (response) { + notification.log(response.Success, {addnCls: 'humane-flatty-success'}); + $state.reload(); + scope.removeCancel = false; + }).catch(function (error) { + notification.log(error.data.message, {addnCls: 'humane-flatty-error'}); + }); + }; + } + + }; +}]); +ngapp.directive('viewActivity', ['$location', '$state', function ($location, $state) { + return { + restrict: 'E', + scope: { + entity: "&", + entityName: "@", + entry: "&", + size: "@", + label: "@" + }, + template: '\n \n', + link: function (scope) { + if (scope.entry()._entityName == 'vehicle_rentals') { + scope.vehicle_rental_id = scope.entry().values.id + '/all'; + } else { + scope.vehicle_rental_id = scope.entry().values['item_user_disputable_id'] + '/dispute'; + } + } + }; +}]); +ngapp.directive('editCompany', ['$location', '$state', function ($location, $state) { + return { + restrict: 'E', + scope: { + entity: "&", + entityName: "@", + entry: "&", + size: "@", + label: "@" + }, + template: '\n \n', + link: function (scope, element) { + scope.vehicle_company_id = scope.entry().values.id; + } + }; +}]); +ngapp.directive('editCounterLocation', ['$location', '$state', function ($location, $state) { + return { + restrict: 'E', + scope: { + entity: "&", + entityName: "@", + entry: "&", + size: "@", + label: "@" + }, + template: '\n \n', + link: function (scope, element) { + scope.counter_location_id = scope.entry().values.id; + } + }; +}]); +ngapp.directive('editVehicle', ['$location', '$state', function ($location, $state) { + return { + restrict: 'E', + scope: { + entity: "&", + entityName: "@", + entry: "&", + size: "@", + label: "@" + }, + template: '\n \n', + link: function (scope, element) { + scope.vehicle_id = scope.entry().values.id; + } + }; +}]); +ngapp.directive('vehicleCalendar', ['$location', '$state', function ($location, $state) { + return { + restrict: 'E', + scope: { + entity: "&", + entityName: "@", + entry: "&", + size: "@", + label: "@" + }, + template: '\n \n', + link: function (scope, element) { + scope.vehicle_id = scope.entry().values.id; + } + }; +}]); + +ngapp.directive('showVehicle', ['$location', '$state', function ($location, $state) { + return { + restrict: 'E', + scope: { + entity: "&", + entityName: "@", + entry: "&", + size: "@", + label: "@" + }, + template: '\n \n', + link: function (scope, element) { + scope.vehicle_id = scope.entry().values.id; + scope.vehicle_slug = scope.entry().values.slug; + } + }; +}]); +ngapp.directive('checkIn', ['$location', '$state', '$http', 'notification', function ($location, $state, $http, notification) { + return { + restrict: 'E', + scope: { + entity: "&", + entityName: "@", + entry: "&", + size: "@", + label: "@", + post: '&' + }, + template: "\n  {{label}} \n", + link: function (scope, element) { + scope.removecheckIn = false; + if (scope.entry().values.checkin === 1) { + scope.removecheckIn = true; + } + var rental_id = scope.entry().values.id; + scope.checkIn = function () { + $http.get(admin_api_url + '/api/admin/vehicle_rentals/' + rental_id + '/checkin').success(function (response) { + notification.log(response.Success, {addnCls: 'humane-flatty-success'}); + $state.reload(); + scope.removecheckIn = false; + }).catch(function (error) { + notification.log(error.data.message, {addnCls: 'humane-flatty-error'}); + }); + }; + } + + }; +}]); +ngapp.directive('checkOut', ['$location', '$state', function ($location, $state) { + return { + restrict: 'E', + scope: { + entity: "&", + entityName: "@", + entry: "&", + size: "@", + label: "@" + }, + template: '\n \n', + link: function (scope, element) { + scope.removecheckOut = false; + if (scope.entry().values.checkout === 1) { + scope.rental_id = scope.entry().values.id; + scope.removecheckOut = true; + } + } + }; +}]); +ngapp.directive('tripDetail', ['$location', '$state', '$http', function ($location, $state, $http, $scope) { + return { + restrict: 'E', + templateUrl: '../ag-admin/tpl/trip_detail.tpl.html', + }; +}]); +ngapp.directive('vehicleDetail', ['$location', '$state', '$http', function ($location, $state, $http, $scope) { + return { + restrict: 'E', + templateUrl: '../ag-admin/tpl/vehicle.tpl.html', + }; +}]); +//Custom button for change password +//Referenced Link: http://ng-admin-book.marmelab.com/doc/reference/View.html +ngapp.directive('addPassword', ['$location', '$state', '$http', 'notification', function ($location, $state, $http, notification) { + return { + restrict: 'E', + scope: { + entity: "&", + entityName: "@", + entry: "&", + size: "@", + label: "@" + }, + template: '\n  {{label}} \n', + link: function (scope, element) { + var id = scope.entry().values.id; + scope.password = function () { + $state.go('users/change_password', {id: id}); + }; + } + }; +}]); +//Refrech link on settings page +ngapp.directive('refreshPage', function() { + return { + restrict: 'E', + template: '
To reflect settings changes, you need to refresh
', + controller: function ($scope, $window) { + $scope.fullRefresh = function () { + $window.location.reload(); + }; + } + }; +}); + +//custom header controller defined here. +function customHeaderController($state, $scope, $http, $location, notification) { + id = 1; + $http.get(admin_api_url + '/api/admin/users/' + id).success(function (response) { + $scope.adminDetail = response; + }); +} + + +//Change password controller defined here. +function changePasswordController($state, $scope, $http, $location, notification) { + var id = $state.params.id; + $scope.ChangePassword = function () { + $http.put(admin_api_url + '/api/admin/users/' + id + '/change_password', $scope.passwordArr).success(function (response) { + if (response.Success !== undefined) { + notification.log(response.Success, {addnCls: 'humane-flatty-success'}); + $location.path('/users/list'); + } + }).catch(function (error) { + notification.log(error.data.message, {addnCls: 'humane-flatty-error'}); + }); + }; +} +//Pages controller defined here. +function pagesController($scope, $http, $location, notification, AuthCheck) { + $scope.languageArr = []; + $scope.init = function () { + if (!AuthCheck) { + $location.path('/logout'); + } else { + $scope.languageList = AuthCheck.data; + } + } + $scope.pageAdd = function () { + angular.forEach($scope.languageArr.pages, function (value, key) { + $scope.languageArr.pages[key]['language_id'] = key; + $scope.languageArr.pages[key]['slug'] = $scope.languageArr.pages.slug; + }, $scope.languageArr.pages); + $http.post(admin_api_url + '/api/admin/pages', $scope.languageArr.pages).success(function (response) { + if (response.Success !== undefined) { + notification.log(response.Success, {addnCls: 'humane-flatty-success'}); + $location.path('/pages/list'); + } else { + notification.log('Page could not be updated. Please, try again.', {addnCls: 'humane-flatty-error'}); + } + }); + }; + $scope.init(); +} +//plugins controller function +function pluginsController($scope, $http, notification, $state, $window, AuthCheck) { + getPluginDetails(); + function getPluginDetails() { + if (!AuthCheck) { + $location.path('/logout'); + } else { + $scope.item_plugin = AuthCheck.data.item_plugin; + $scope.property_plugin = AuthCheck.data.property_plugin; + $scope.payment_gateway_plugin = AuthCheck.data.payment_gateway_plugin; + $scope.other_plugin = AuthCheck.data.other_plugin; + $scope.enabled_plugin = AuthCheck.data.enabled_plugin; + localStorage.setItem('enabled_plugins', JSON.stringify(AuthCheck.data.enabled_plugin)); + } + }; + $scope.checkStatus = function (plugin, enabled_plugins) { + if ($.inArray(plugin, enabled_plugins) > -1) { + return true; + } else { + return false; + } + } + $scope.updatePluginStatus = function (e, plugin_name, status) { + e.preventDefault(); + var target = angular.element(e.target); + checkDisabled = target.parent().hasClass('disabled'); + if (checkDisabled === true) { + return false; + } + var params = {}; + var confirm_msg = ''; + params.plugin_name = plugin_name; + params.is_enabled = status; + confirm_msg = (status === 0) ? "Are you sure want to disable?" : "Are you sure want to enable?"; + notification_msg = (status === 0) ? "disabled" : "enabled"; + if (confirm(confirm_msg)) { + $http.put(admin_api_url + '/api/admin/plugins', params).success(function (response) { + if (response.Success !== undefined) { + notification.log(plugin_name + ' Plugin update successfully.', {addnCls: 'humane-flatty-success'}); + $state.reload(); + } + }, function (error) { + notification.log(plugin_name + ' Plugin could not be update', {addnCls: 'humane-flatty-error'}); + $state.reload(); + }); + } + } + $scope.fullRefresh = function () { + $window.location.reload(); + } +} +//Counter location add controller defined here. +function counterLocationController($state, $scope, $http, $location, notification) { + var counter_location_id = 0; + $scope.init = function () { + if ($state.params.id) { + counter_location_id = $state.params.id; + $http.get(admin_api_url + '/api/admin/counter_locations/' + counter_location_id).success(function (response) { + $scope.counterLocation = response; + $scope.counterLocation.full_address = response.address; + }); + } + $scope.$on('g-places-autocomplete:select', function (event) { + if (event.targetScope.model.formatted_address.indexOf(event.targetScope.model.name)) { + $scope.counterLocation.address = event.targetScope.model.name + ', ' + event.targetScope.model.formatted_address; + } else { + $scope.counterLocation.address = event.targetScope.model.formatted_address; + } + $scope.counterLocation.latitude = event.targetScope.model.geometry.location.lat(); + $scope.counterLocation.longitude = event.targetScope.model.geometry.location.lng(); + }); + }; + $scope.CounterLocationAdd = function (isvalid) { + if (isvalid) { + $scope.LocationAdd.$setPristine(); + $scope.LocationAdd.$setUntouched(); + $http.post(admin_api_url + '/api/admin/counter_locations', $scope.counterLocation).success(function (response) { + if (response.Success !== undefined) { + notification.log(response.Success, {addnCls: 'humane-flatty-success'}); + $location.path('/counter_locations/list'); + } + }).error(function (error) { + notification.log(error.message, {addnCls: 'humane-flatty-error'}); + }); + } + }; + $scope.CounterLocationEdit = function (isvalid) { + if (isvalid) { + $scope.counterLocation.id = counter_location_id; + $http.put(admin_api_url + '/api/admin/counter_locations/' + counter_location_id, $scope.counterLocation).success(function (response) { + if (response.Success !== undefined) { + notification.log(response.Success, {addnCls: 'humane-flatty-success'}); + $location.path('/counter_locations/list'); + } + }).error(function(error) { + notification.log(error.message, {addnCls: 'humane-flatty-error'}); + }); + } + }; + $scope.init(); +} +//Vehicle company add controller defined here. +function vehicleCompaniesController($state, $scope, $http, $location, notification) { + var model = this; + var vehicle_company_id = 0; + $scope.init = function () { + if ($state.params.id) { + vehicle_company_id = $state.params.id; + $http.get(admin_api_url + '/api/admin/vehicle_companies/' + vehicle_company_id).success(function (response) { + $scope.vehicleCompanies = response; + $scope.vehicleCompanies.full_address = response.address; + }); + } + $http.get(admin_api_url + '/api/admin/users?limit=all').success(function (response) { + $scope.users = response.data; + }); + + $scope.$on('g-places-autocomplete:select', function (event) { + if (event.targetScope.model.formatted_address.indexOf(event.targetScope.model.name)) { + $scope.vehicleCompanies.address = event.targetScope.model.name + ', ' + event.targetScope.model.formatted_address; + } else { + $scope.vehicleCompanies.address = event.targetScope.model.formatted_address; + } + $scope.vehicleCompanies.latitude = event.targetScope.model.geometry.location.lat(); + $scope.vehicleCompanies.longitude = event.targetScope.model.geometry.location.lng(); + }); + }; + $scope.VehicleCompaniesAdd = function (isvalid) { + if (isvalid) { + $http.post(admin_api_url + '/api/admin/vehicle_companies', $scope.vehicleCompanies).success(function (response) { + if (response.Success !== undefined) { + notification.log(response.Success, {addnCls: 'humane-flatty-success'}); + $location.path('/vehicle_companies/list'); + } + }).catch(function (message) { + angular.forEach(message.data.errors, function (value, key) { + if (key == 'address') { + model.full_addressErr = value; + } + }); + notification.log(message.data.message, {addnCls: 'humane-flatty-error'}); + }); + } + }; + $scope.VehicleCompaniesEdit = function (isvalid) { + if (isvalid) { + $scope.vehicleCompanies.id = vehicle_company_id; + $http.put(admin_api_url + '/api/admin/vehicle_companies/' + vehicle_company_id, $scope.vehicleCompanies).success(function (response) { + if (response.Success !== undefined) { + notification.log(response.Success, {addnCls: 'humane-flatty-success'}); + $location.path('/vehicle_companies/list'); + } + }, function (error) { + notification.log(error.data.message, {addnCls: 'humane-flatty-error'}); + }); + } + }; + $scope.init(); +} +//Vehicle type price controller defined here. +function vehicleTypePriceController($state, $scope, $http, $location, notification) { + $http.get(admin_api_url + '/api/admin/vehicle_types').success(function (response) { + $scope.vehicleTypes = response.data; + }); + $scope.choices = [{group: 1}]; + $scope.addNewChoice = function () { + var newItemNo = $scope.choices.length + 1; + $scope.choices.push({group: newItemNo}); + }; + $scope.removeChoice = function () { + var lastItem = $scope.choices.length - 1; + $scope.choices.splice(lastItem); + }; + $scope.VehicleTypePrices = function (isvalid) { + if (isvalid) { + $http.post(admin_api_url + '/api/admin/vehicle_type_prices', $scope.vehicleTypePrices).success(function (response) { + if (response.Success !== undefined) { + notification.log(response.Success, {addnCls: 'humane-flatty-success'}); + $location.path('/vehicle_type_prices/list'); + } + }).catch(function (error) { + notification.log(error.data.message, {addnCls: 'humane-flatty-error'}); + }); + } + }; +} +//Default pages/create changed here to pages/add. +ngapp.directive('createPage', ['$location', '$state', function ($location, $state) { + return { + restrict: 'E', + scope: { + entity: "&", + entityName: "@", + entry: "&", + size: "@", + label: "@" + }, + template: '\n \n', + link: function (scope) { + } + }; +}]); +function vehicleViewController($state, $scope, $http, $location, notification) { + var model = this; + var vehicle_id = 0; + $scope.enabled_plugin = localStorage.getItem('enabled_plugins'); + $scope.siteCurrency = localStorage.getItem('site_currency'); + $scope.init = function () { + $scope.currentPage = ($scope.currentPage !== undefined) ? parseInt($scope.currentPage) : 1; + $scope.maxRatings = []; + $scope.maxRating = 5; + for (var i = 0; i < $scope.maxRating; i++) { + $scope.maxRatings.push(i); + } + if ($state.params.id) { + vehicle_id = $state.params.id; + $http.get(admin_api_url + '/api/admin/vehicles/' + vehicle_id).success(function (response) { + $scope.vehicle = response; + $scope.vehicle.roundedRating = response.feedback_rating | 0; + $scope.pickup_locations = response.pickup_locations; + $scope.drop_locations = response.drop_locations; + if (response.vehicle_type && response.vehicle_type.vehicle_type_extra_accessory) { + $scope.vehicle_extra_accessories = response.vehicle_type.vehicle_type_extra_accessory.data; + } + if (response.vehicle_type && response.vehicle_type.vehicle_type_insurance) { + $scope.vehicle_insurance = response.vehicle_type.vehicle_type_insurance.data; + } + if (response.vehicle_type && response.vehicle_type.vehicle_type_fuel_option) { + $scope.vehicle_fuel_option = response.vehicle_type.vehicle_type_fuel_option.data; + } + }); + $http.get(admin_api_url + '/api/admin/vehicle_feedbacks?vehicle_id=' + vehicle_id + '&page=' + $scope.currentPage).success(function (response) { + $scope.vehicleFeedbacks = response.data; + $scope.vehicle_metadata = response.meta.pagination; + }); + } + }; + $scope.init(); + $scope.paginate = function (pageno) { + $scope.currentPage = parseInt(pageno); + $scope.init(); + }; +} +//Vehicle Add +function vehicleController($state, $scope, $http, Upload, $location, notification) { + var vehicle_id = 0; + $scope.settings = localStorage.getItem('settings'); + angular.forEach(JSON.parse($scope.settings), function (setting, key) { + if (setting.name == 'vehicle.driver_min_age') { + $scope.driver_min_age = parseInt(setting.value); + } + if (setting.name == 'vehicle.driver_max_age') { + $scope.driver_max_age = parseInt(setting.value); + } + }); + $scope.vehicle = {}; + $scope.vehicle.pickup_counter_locations = []; + $scope.vehicle.drop_counter_locations = []; + $scope.init = function () { + if ($state.params.id) { + vehicle_id = $state.params.id; + $http.get(admin_api_url + '/api/admin/vehicles/' + vehicle_id).success(function (response) { + $scope.vehicle = response; + pickup_counter_locations = []; + drop_counter_locations = []; + angular.forEach(response.pickup_locations, function (value, key) { + pickup_counter_locations.push(value.id); + }); + angular.forEach(response.drop_locations, function (value, key) { + drop_counter_locations.push(value.id); + }); + $scope.vehicle.minimum_age_of_driver = parseInt(response.minimum_age_of_driver); + $scope.vehicle.pickup_counter_locations = pickup_counter_locations; + $scope.vehicle.drop_counter_locations = drop_counter_locations; + $scope.getVehicleModel(response.vehicle_make_id); + $scope.getVehicleTypePrice(response.vehicle_type_id); + }); + } + }; + $http.get(admin_api_url + '/api/admin/vehicle/add').success(function (response) { + $scope.vehicleCompanies = response.vehicle_company_list; + $scope.vehicleTypes = response.vehicle_type_list; + $scope.vehicleMakes = response.vehicle_make_list; + $scope.counter_locations = response.counter_location_list; + $scope.fuelTypes = response.fuel_type_list; + $scope.seats = parseInt(response.settings.seats); + $scope.doors = parseInt(response.settings.doors); + $scope.small_bags = parseInt(response.settings.small_bags); + $scope.large_bags = parseInt(response.settings.large_bags); + $scope.gears = parseInt(response.settings.gears); + $scope.air_bags = parseInt(response.settings.airbags); + //covert counter location object to array + $scope.vehicle_counter_locations = []; + angular.forEach ($scope.counter_locations, function(value, key){ + var obj = {}; + obj.id = value; + obj.name = key; + $scope.vehicle_counter_locations.push(obj); + }); + }); + $scope.getVehicleModel = function (vehicle_make_id) { + $http.get(admin_api_url + '/api/admin/vehicle_models?vehicle_make_id=' + vehicle_make_id).success(function (response) { + $scope.vehicleModels = response.data; + }); + }; + $scope.getVehicleTypePrice = function (vehicle_type_id) { + $http.get(admin_api_url + '/api/admin/vehicle_types/' + vehicle_type_id).success(function (response) { + $scope.vehicleType = response; + }); + }; + $scope.getNumber = function (num) { + return new Array(num); + }; + $scope.Range = function (min, max) { + var result = []; + for (var i = parseFloat(min); i <= parseFloat(max); i++) { + result.push(i); + } + return result; + }; + $scope.pickupSelection = function pickupSelection(location_id) { + location_id = parseInt(location_id); + var selected_id = $scope.vehicle.pickup_counter_locations.indexOf(location_id); + if (selected_id > -1) { + $scope.vehicle.pickup_counter_locations.splice(selected_id, 1); + $scope.all_pickup_location = false; + } else { + $scope.vehicle.pickup_counter_locations.push(location_id); + if($scope.vehicle.pickup_counter_locations.length == $scope.vehicle_counter_locations.length) { + $scope.all_pickup_location = true; + } + } + }; + $scope.dropSelection = function dropSelection(location_id) { + location_id = parseInt(location_id); + var selected_id = $scope.vehicle.drop_counter_locations.indexOf(location_id); + if (selected_id > -1) { + $scope.vehicle.drop_counter_locations.splice(selected_id, 1); + $scope.all_drop_location = false; + } else { + $scope.vehicle.drop_counter_locations.push(location_id); + if($scope.vehicle.drop_counter_locations.length == $scope.vehicle_counter_locations.length) { + $scope.all_drop_location = true; + } + } + }; + $scope.selectAllPickupLocation = function() { + $scope.vehicle.pickup_counter_locations = []; + if ($scope.all_pickup_location) { + $scope.all_pickup_location = true; + } else { + $scope.all_pickup_location = false; + } + angular.forEach($scope.vehicle_counter_locations, function (value, key) { + value.selected = $scope.all_pickup_location; + if($scope.all_pickup_location) { + $scope.vehicle.pickup_counter_locations.push(value.id); + } + }); + }; + $scope.selectAllDropLocation = function() { + $scope.vehicle.drop_counter_locations = []; + if ($scope.all_drop_location) { + $scope.all_drop_location = true; + } else { + $scope.all_drop_location = false; + } + angular.forEach($scope.vehicle_counter_locations, function (value, key) { + value.checked = $scope.all_drop_location; + if($scope.all_drop_location) { + $scope.vehicle.drop_counter_locations.push(value.id); + } + }); + }; + $scope.vehicleSubmit = function ($valid, file) { + if ($valid) { + $scope.vehicle.file = file; + Upload.upload({ + url: admin_api_url + '/api/admin/vehicles', + data: $scope.vehicle + }).then(function (response) { + if (response.data.Success !== undefined) { + notification.log(response.data.Success, {addnCls: 'humane-flatty-success'}); + $location.path('/vehicles/list'); + } else { + notification.log('Vehicle could not be updated. Please, try again.', {addnCls: 'humane-flatty-error'}); + } + }); + } + }; + $scope.checkStatus = function (id, selected_list) { + if ($.inArray(parseInt(id), selected_list) > -1) { + return true; + } else { + return false; + } + } + $scope.vehicleEdit = function ($valid, file) { + if ($valid) { + if ($scope.file !== undefined) { + Upload.upload({ + url: admin_api_url + '/api/admin/vehicles/' + vehicle_id, + data: { + file: $scope.file, + 'id': vehicle_id, + 'vehicle_make_id': $scope.vehicle.vehicle_make_id, + 'vehicle_model_id': $scope.vehicle.vehicle_model_id, + 'vehicle_type_id': $scope.vehicle.vehicle_type_id, + 'pickup_counter_locations': $scope.vehicle.pickup_counter_locations, + 'drop_counter_locations': $scope.vehicle.drop_counter_locations, + 'driven_kilometer': $scope.vehicle.driven_kilometer, + 'vehicle_no': $scope.vehicle.vehicle_no, + 'no_of_seats': $scope.vehicle.no_of_seats, + 'no_of_doors': $scope.vehicle.no_of_doors, + 'no_of_gears': $scope.vehicle.no_of_gears, + 'is_manual_transmission': $scope.vehicle.is_manual_transmission, + 'no_small_bags': $scope.vehicle.no_small_bags, + 'no_large_bags': $scope.vehicle.no_large_bags, + 'is_ac': $scope.vehicle.is_ac, + 'minimum_age_of_driver': $scope.vehicle.minimum_age_of_driver, + 'mileage': $scope.vehicle.mileage, + 'is_airbag': $scope.vehicle.mileage, + 'no_of_airbags': $scope.vehicle.no_of_airbags, + 'is_abs': $scope.vehicle.is_abs, + 'per_hour_amount': $scope.vehicle.per_hour_amount, + 'per_day_amount': $scope.vehicle.per_day_amount, + 'fuel_type_id': $scope.vehicle.fuel_type_id, + 'vehicle_company_id': $scope.vehicle.vehicle_company_id, + 'is_active': $scope.vehicle.is_active + } + }).then(function (response) { + if (response.data.Success !== undefined) { + notification.log(response.data.Success, {addnCls: 'humane-flatty-success'}); + $location.path('/vehicles/list'); + } else { + notification.log(error.data.message, {addnCls: 'humane-flatty-error'}); + } + }); + + } else { + $scope.vehicle.id = vehicle_id; + $http.post(admin_api_url + '/api/admin/vehicles/' + vehicle_id, $scope.vehicle).success(function (response) { + if (response.Success !== undefined) { + notification.log(response.Success, {addnCls: 'humane-flatty-success'}); + $location.path('/vehicles/list'); + } + }, function (error) { + notification.log(error.data.message, {addnCls: 'humane-flatty-error'}); + }); + } + } + }; + $scope.init(); +} +//vehicle calendar controller +function vehicleCalendarController ($state, $scope, $http, $location, notification, $filter) { + $scope.getEvents = function() { + $http.get(admin_api_url + '/api/admin/vehicle_rentals?type=booking&vehicle_id='+$state.params.id).success(function(response) { + if(response.data) { + $scope.events = $scope.setEvents(response.data); + } + }); + }; + $scope.init = function () { + $scope.calendarView = 'month'; + $scope.viewDate = new Date(); + $scope.isCellOpen = true; + $scope.calendarTitle = 'Vehicle Calendar'; + $scope.getEvents(); + }; + $scope.setEvents = function(vehicles) { + var eventsLists = []; + var types = ['info', 'warning', 'primary', 'danger', 'success']; + angular.forEach(vehicles, function(value, key) { + var start_date = $filter("date")(new Date(value.item_booking_start_date), "MMM d, y h:mm a"); + var end_date = $filter('date')(new Date(value.item_booking_end_date), 'MMM d, y h:mm a'); + eventsList = { + title: value.item_userable.name+' '+start_date+' - '+end_date, + type: types[key % 5], + startsAt: value.item_booking_start_date, + endsAt: value.item_booking_end_date, + draggable: false, + resizable: false, + editable: false, + deletable: false, + event: value + }; + eventsLists.push(eventsList); + }); + return eventsLists; + }; + $scope.eventClicked = function(cal_event) { + window.location = '../#/activity/'+cal_event.event.id+'/note'; + }; + $scope.init(); +} +//Vehicle Add +function vehiclecheckOutController($state, $scope, $http, $location, notification, $window) { + var vehicle_rental_id = 0; + $scope.check_out = {}; + $scope.init = function () { + $scope.enabled_plugin = localStorage.getItem('enabled_plugins'); + $scope.siteCurrency = localStorage.getItem('site_currency'); + if ($state.params.id) { + vehicle_rental_id = $state.params.id; + $http.get(admin_api_url + '/api/admin/vehicle_rentals/' + vehicle_rental_id).success(function (response) { + $scope.vehicleDetails = response.item_userable; + $scope.VehicleRentalDetails = response; + }); + } + }; + $scope.calculateAmount = function (amount) { + if ($scope.VehicleRentalDetails.late_checkout_total_fee) { + amount = amount + $scope.VehicleRentalDetails.late_checkout_total_fee; + } + if (($scope.VehicleRentalDetails.deposit_amount > 0)) { + if ($scope.VehicleRentalDetails.deposit_amount > amount) { + $scope.manualPay = 0; + $scope.claimToDeposit = amount; + } else { + $scope.manualPay = amount - $scope.VehicleRentalDetails.deposit_amount; + $scope.claimToDeposit = $scope.VehicleRentalDetails.deposit_amount; + } + } else { + $scope.manualPay = amount; + } + }; + $scope.checkout = function ($valid) { + var checkout = $window.confirm('Are you sure want to checkout?'); + $scope.check_out.id = $state.params.id; + $scope.check_out.claim_request_amount = $scope.claim_amount; + $http.post(admin_api_url + '/api/admin/vehicle_rentals/' + vehicle_rental_id + '/checkout', $scope.check_out).success(function (response) { + if (response.Success !== undefined) { + notification.log(response.Success, {addnCls: 'humane-flatty-success'}); + $location.path('/vehicle_rentals/list'); + } + }, function (error) { + notification.log(error.data.message, {addnCls: 'humane-flatty-error'}); + }); + }; + $scope.init(); +} +ngapp.config(['NgAdminConfigurationProvider', 'RestangularProvider', 'ngAdminJWTAuthConfiguratorProvider', function (NgAdminConfigurationProvider, RestangularProvider, ngAdminJWTAuthConfigurator) { + var enabledPlugins = localStorage.getItem('enabled_plugins'); + var siteCurrency = localStorage.getItem('site_currency'); + var nga = NgAdminConfigurationProvider; + ngAdminJWTAuthConfigurator.setJWTAuthURL(admin_api_url + '/api/users/login'); + ngAdminJWTAuthConfigurator.setCustomLoginTemplate('tpl/customLoginTemplate.html'); + ngAdminJWTAuthConfigurator.setCustomAuthHeader({ + name: 'Authorization', + template: 'Bearer {{token}}' + }); + //trunctate function to shorten text length. + function truncate(value) { + if (!value) { + return ''; + } + return value.length > 50 ? value.substr(0, 50) + '...' : value; + } + + // create an admin application + var admin = nga.application('BookorRent') // application main title + .debug(true) // debug disabled + .baseApiUrl(admin_api_url + '/api/admin/'); // main API endpoint + // Creating all entities + var users = nga.entity('users'); + var user_logins = nga.entity('user_logins'); + var cities = nga.entity('cities'); + var states = nga.entity('states'); + var countries = nga.entity('countries'); + var pages = nga.entity('pages'); + var email_templates = nga.entity('email_templates'); + var languages = nga.entity('languages'); + var settings = nga.entity('settings'); + var setting_categories = nga.entity('setting_categories'); + var ips = nga.entity('ips'); + var providers = nga.entity('providers'); + var roles = nga.entity('roles'); + var pages = nga.entity('pages'); + var contacts = nga.entity('contacts'); + var user_cash_withdrawals = nga.entity('user_cash_withdrawals'); + var user_logins = nga.entity('user_logins'); + var plugins = nga.entity('plugins'); + var vehicles = nga.entity('vehicles'); + var vehicle_coupons = nga.entity('vehicle_coupons'); + var vehicle_disputes = nga.entity('vehicle_disputes'); + var transaction_types = nga.entity('transaction_types'); + var transactions = nga.entity('transactions'); + var sudopay_transaction_logs = nga.entity('sudopay_transaction_logs'); + var paypal_transaction_logs = nga.entity('paypal_transaction_logs'); + var wallet_transaction_logs = nga.entity('wallet_transaction_logs'); + var sudopay_ipn_logs = nga.entity('sudopay_ipn_logs'); + var cancellation_types = nga.entity('cancellation_types'); + var vehicle_rentals = nga.entity('vehicle_rentals'); + var messages = nga.entity('messages'); + var vehicle_feedbacks = nga.entity('vehicle_feedbacks'); + var currencies = nga.entity('currencies'); + var currency_conversions = nga.entity('currency_conversions'); + var currency_conversion_histories = nga.entity('currency_conversion_histories'); + var api_requests = nga.entity('api_requests'); + var vehicle_dispute_types = nga.entity('vehicle_dispute_types'); + var vehicle_dispute_closed_types = nga.entity('vehicle_dispute_closed_types'); + var provider_users = nga.entity('provider_users'); + var vehicle_companies = nga.entity('vehicle_companies'); + var vehicle_makes = nga.entity('vehicle_makes'); + var vehicle_models = nga.entity('vehicle_models'); + var vehicle_types = nga.entity('vehicle_types'); + var vehicle_taxes = nga.entity('vehicle_taxes'); + var vehicle_type_taxes = nga.entity('vehicle_type_taxes'); + var vehicle_surcharges = nga.entity('vehicle_surcharges'); + var vehicle_type_surcharges = nga.entity('vehicle_type_surcharges'); + var vehicle_insurances = nga.entity('vehicle_insurances'); + var vehicle_type_insurances = nga.entity('vehicle_type_insurances'); + var vehicle_extra_accessories = nga.entity('vehicle_extra_accessories'); + var vehicle_type_extra_accessories = nga.entity('vehicle_type_extra_accessories'); + var vehicle_fuel_options = nga.entity('vehicle_fuel_options'); + var vehicle_type_fuel_options = nga.entity('vehicle_type_fuel_options'); + var vehicle_special_prices = nga.entity('vehicle_special_prices'); + var counter_locations = nga.entity('counter_locations'); + var vehicle_type_prices = nga.entity('vehicle_type_prices'); + var vehicle_search = nga.entity('vehicle_search'); + var unavailable_vehicles = nga.entity('unavailable_vehicles'); + //Adding all the entities to the admin application. + admin.addEntity(users); + admin.addEntity(user_logins); + admin.addEntity(cities); + admin.addEntity(states); + admin.addEntity(countries); + admin.addEntity(pages); + admin.addEntity(email_templates); + admin.addEntity(languages); + admin.addEntity(settings); + admin.addEntity(setting_categories); + admin.addEntity(ips); + admin.addEntity(providers); + admin.addEntity(roles); + admin.addEntity(pages); + admin.addEntity(contacts); + admin.addEntity(user_cash_withdrawals); + admin.addEntity(user_logins); + admin.addEntity(plugins); + admin.addEntity(vehicles); + admin.addEntity(transaction_types); + admin.addEntity(vehicle_coupons); + admin.addEntity(vehicle_disputes); + admin.addEntity(transactions); + admin.addEntity(sudopay_transaction_logs); + admin.addEntity(paypal_transaction_logs); + admin.addEntity(wallet_transaction_logs); + admin.addEntity(sudopay_ipn_logs); + admin.addEntity(cancellation_types); + admin.addEntity(vehicle_rentals); + admin.addEntity(messages); + admin.addEntity(vehicle_feedbacks); + admin.addEntity(currencies); + admin.addEntity(currency_conversions); + admin.addEntity(currency_conversion_histories); + admin.addEntity(api_requests); + admin.addEntity(vehicle_dispute_types); + admin.addEntity(vehicle_dispute_closed_types); + admin.addEntity(provider_users); + admin.addEntity(vehicle_companies); + admin.addEntity(vehicle_makes); + admin.addEntity(vehicle_models); + admin.addEntity(vehicle_types); + admin.addEntity(vehicle_taxes); + admin.addEntity(vehicle_type_taxes); + admin.addEntity(vehicle_surcharges); + admin.addEntity(vehicle_type_surcharges); + admin.addEntity(vehicle_insurances); + admin.addEntity(vehicle_type_insurances); + admin.addEntity(vehicle_extra_accessories); + admin.addEntity(vehicle_type_extra_accessories); + admin.addEntity(vehicle_fuel_options); + admin.addEntity(vehicle_type_fuel_options); + admin.addEntity(vehicle_special_prices); + admin.addEntity(counter_locations); + admin.addEntity(vehicle_type_prices); + admin.addEntity(vehicle_search); + admin.addEntity(unavailable_vehicles); + roles.listView().title('Roles') + .fields([ + nga.field('id').label('ID'), + nga.field('name').label('Name') + ]) + .perPage(limit_per_page) + .listActions(['edit', 'delete']) + .filters([ + nga.field('q').label('Search', 'template') + .pinned(true) + .template('
') + ]); + var countries_custom_tmp = ''; + countries.listView().title('Countries') + .fields([ + nga.field('name').label('Name'), + nga.field('iso2').label('iso2') + ]) + .infinitePagination(false) + .perPage(limit_per_page) + .listActions(['edit', 'delete']) + .filters([ + nga.field('q').label('Search', 'template') + .pinned(true) + .template('
') + ]) + .actions(['create', 'batch', countries_custom_tmp]) + .batchActions([ + '', + '', + 'delete' + ]); + countries.creationView().title('Add Country') + .fields([ + nga.field('name').label('Country') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Country' + }), + nga.field('iso2').label('iso2') + .validation({ + required: true + }) + .attributes({ + placeholder: 'iso2' + }), + nga.field('iso3').label('iso3') + .validation({ + required: true + }) + .attributes({ + placeholder: 'iso3' + }) + ]) + .onSubmitSuccess(['progression', 'notification', '$state', 'entry', 'entity', function (progression, notification, $state, entry, entity) { + // stop the progress bar + progression.done(); + // add a notification + notification.log(entry.values.Success, {addnCls: 'humane-flatty-success'}); + // redirect to the list view + $state.go($state.get('list'), {entity: entity.name()}); + // cancel the default action (redirect to the add view) + return false; + }]) + .onSubmitError(['error', 'form', 'progression', 'notification', function (error, form, progression, notification) { + // Error return to form fields. + angular.forEach(error.data.errors, function (value, key) { + if (this[key]) { + this[key].$valid = false; + } + }, form); + // stop the progress bar + progression.done(); + // add a notification + notification.log(error.data.message, {addnCls: 'humane-flatty-error'}); + return false; + }]); + countries.editionView().title('Edit Country') + .fields([ + nga.field('name').label('Name'), + nga.field('iso2').label('iso2'), + nga.field('iso3').label('iso3') + ]) + .onSubmitSuccess(['progression', 'notification', '$state', 'entry', 'entity', function (progression, notification, $state, entry, entity) { + progression.done(); + notification.log(entry.values.Success, {addnCls: 'humane-flatty-success'}); + $state.go($state.get('list'), {entity: entity.name()}); + return false; + }]) + .onSubmitError(['error', 'form', 'progression', 'notification', function (error, form, progression, notification) { + angular.forEach(error.data.errors, function (value, key) { + if (this[key]) { + this[key].$valid = false; + } + }, form); + progression.done(); + notification.log(error.data.message, {addnCls: 'humane-flatty-error'}); + return false; + }]); + var states_custom_tmp = ''; + states.listView().title('States') + .fields([ + nga.field('name').label('Name'), + nga.field('Country.name').label('Country'), + nga.field('is_active', 'boolean').label('Active?') + ]) + .perPage(limit_per_page) + .listActions(['edit', 'delete']) + .filters([ + nga.field('q').label('Search', 'template') + .pinned(true) + .template('
'), + nga.field('filter', 'choice').label('Status').attributes({ + placeholder: 'Status?' + }) + .choices([{ + label: 'Active', + value: 'active' + }, { + label: 'Inactive', + value: 'inactive' + }]) + ]) + .actions(['create', 'batch', states_custom_tmp]) + .batchActions([ + '', + '', + 'delete' + ]); + states.creationView().title('Add State') + .fields([ + nga.field('name') + .label('State') + .validation({ + required: true + }) + .attributes({ + placeholder: 'State' + }), + nga.field('country_id', 'reference') + .label('Country') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Country' + }) + .targetEntity(nga.entity('countries')) + .perPage('all') // For getting all list + .targetField(nga.field('name').map(truncate)), + nga.field('is_active', 'choice').label('Active?') + .attributes({ + placeholder: 'Active?' + }) + .validation({ + required: true + }) + .choices([{ + label: 'Yes', + value: true + }, { + label: 'No', + value: false + }]) + ]) + .onSubmitSuccess(['progression', 'notification', '$state', 'entry', 'entity', function (progression, notification, $state, entry, entity) { + progression.done(); + notification.log(entry.values.Success, {addnCls: 'humane-flatty-success'}); + $state.go($state.get('list'), {entity: entity.name()}); + return false; + }]) + .onSubmitError(['error', 'form', 'progression', 'notification', function (error, form, progression, notification) { + angular.forEach(error.data.errors, function (value, key) { + if (this[key]) { + this[key].$valid = false; + } + }, form); + progression.done(); + notification.log(error.data.message, {addnCls: 'humane-flatty-error'}); + return false; + }]); + states.editionView().title('Edit State') + .fields([ + nga.field('name') + .validation({ + required: true + }) + .label('State'), + nga.field('country_id', 'reference') + .label('Country') + .validation({ + required: true + }) + .perPage('all') // For getting all list + .targetEntity(nga.entity('countries')) + .targetField(nga.field('name').map(truncate)), + nga.field('is_active', 'choice').label('Active?') + .validation({ + required: true + }) + .choices([{ + label: 'Yes', + value: true + }, { + label: 'No', + value: false + }]) + ]) + .onSubmitSuccess(['progression', 'notification', '$state', 'entry', 'entity', function (progression, notification, $state, entry, entity) { + progression.done(); + notification.log(entry.values.Success, {addnCls: 'humane-flatty-success'}); + $state.go($state.get('list'), {entity: entity.name()}); + return false; + }]) + .onSubmitError(['error', 'form', 'progression', 'notification', function (error, form, progression, notification) { + angular.forEach(error.data.errors, function (value, key) { + if (this[key]) { + this[key].$valid = false; + } + }, form); + progression.done(); + notification.log(error.data.message, {addnCls: 'humane-flatty-error'}); + return false; + }]); + var cities_custom_tmp = ''; + cities.listView().title('Cities') + .fields([ + nga.field('name').label('Name'), + nga.field('State.name').label('State'), + nga.field('Country.name').label('Country'), + nga.field('is_active', 'boolean').label('Active?') + ]) + .perPage(limit_per_page) + .listActions(['edit', 'delete']) + .filters([ + nga.field('q').label('Search', 'template') + .pinned(true) + .template('
'), + nga.field('filter', 'choice').label('Status').attributes({ + placeholder: 'Status?' + }) + .choices([{ + label: 'Active', + value: 'active' + }, { + label: 'Inactive', + value: 'inactive' + }]) + ]) + .actions(['create', 'batch', cities_custom_tmp]) + .batchActions([ + '', + '', + 'delete' + ]); + cities.creationView().title('Add City') + .fields([ + nga.field('name').label('Name') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Name' + }), + nga.field('state_id', 'reference') + .label('State') + .validation({ + required: true + }) + .attributes({ + placeholder: 'State' + }) + .targetEntity(nga.entity('states')) + .perPage('all') // For getting all list + .targetField(nga.field('name').map(truncate)), + nga.field('country_id', 'reference') + .label('Country') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Country' + }) + .perPage('all') // For getting all list + .targetEntity(nga.entity('countries')) + .targetField(nga.field('name').map(truncate)), + nga.field('latitude').label('Latitude') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Latitude' + }), + nga.field('longitude').label('Longitude') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Longitude' + }), + nga.field('is_active', 'choice').label('Active?') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Active?' + }) + .choices([{ + label: 'Yes', + value: true + }, { + label: 'No', + value: false + }]) + ]) + .onSubmitSuccess(['progression', 'notification', '$state', 'entry', 'entity', function (progression, notification, $state, entry, entity) { + progression.done(); + notification.log(entry.values.Success, {addnCls: 'humane-flatty-success'}); + $state.go($state.get('list'), {entity: entity.name()}); + return false; + }]) + .onSubmitError(['error', 'form', 'progression', 'notification', function (error, form, progression, notification) { + angular.forEach(error.data.errors, function (value, key) { + if (this[key]) { + this[key].$valid = false; + } + }, form); + progression.done(); + notification.log(error.data.message, {addnCls: 'humane-flatty-error'}); + return false; + }]); + cities.editionView().title('Edit City') + .fields([ + nga.field('name') + .label('Name') + .validation({ + required: true + }), + nga.field('state_id', 'reference') + .label('State') + .validation({ + required: true + }) + .targetEntity(nga.entity('states')) + .perPage('all') // For getting all list + .targetField(nga.field('name').map(truncate)), + nga.field('country_id', 'reference') + .label('Country') + .validation({ + required: true + }) + .targetEntity(nga.entity('countries')) + .perPage('all') // For getting all list + .targetField(nga.field('name').map(truncate)), + nga.field('latitude') + .label('Latitude') + .validation({ + required: true + }), + nga.field('longitude') + .label('longitude') + .validation({ + required: true + }), + nga.field('is_active', 'choice').label('Active?') + .validation({ + required: true + }) + .choices([{ + label: 'Yes', + value: true + }, { + label: 'No', + value: false + }]) + ]) + .onSubmitSuccess(['progression', 'notification', '$state', 'entry', 'entity', function (progression, notification, $state, entry, entity) { + progression.done(); + notification.log(entry.values.Success, {addnCls: 'humane-flatty-success'}); + $state.go($state.get('list'), {entity: entity.name()}); + return false; + }]) + .onSubmitError(['error', 'form', 'progression', 'notification', function (error, form, progression, notification) { + angular.forEach(error.data.errors, function (value, key) { + if (this[key]) { + this[key].$valid = false; + } + }, form); + progression.done(); + notification.log(error.data.message, {addnCls: 'humane-flatty-error'}); + return false; + }]); + var providers_custom_tmp = ''; + providers.listView().title('Providers') + .fields([ + nga.field('id').label('ID'), + nga.field('name').label('Name'), + nga.field('api_key').label('Client ID').map(truncate), + nga.field('secret_key').label('Secret Key').map(truncate), + nga.field('display_order').label('Display Order'), + nga.field('is_active', 'boolean').label('Active?'), + ]).listActions(['delete', 'edit']) + .sortField('id') + .sortDir('ASC') + .filters([ + nga.field('q').label('Search', 'template') + .pinned(true) + .template('
') + ]) + .actions(['batch', providers_custom_tmp]); + providers.editionView().title('Edit Providers') // "Social Login" plugins + .fields([ + nga.field('name') + .label('Name') + .validation({ + required: true + }), + nga.field('api_key') + .label('Client ID'), + nga.field('secret_key') + .label('Secret Key'), + nga.field('display_order') + .label('Display Order'), + nga.field('is_active', 'choice').label('Active?') + .validation({ + required: true + }) + .choices([{ + label: 'Yes', + value: true + }, { + label: 'No', + value: false + }]) + ]) + .onSubmitSuccess(['progression', 'notification', '$state', 'entry', 'entity', function (progression, notification, $state, entry, entity) { + progression.done(); + notification.log(entry.values.Success, {addnCls: 'humane-flatty-success'}); + $state.go($state.get('list'), {entity: entity.name()}); + return false; + }]) + .onSubmitError(['error', 'form', 'progression', 'notification', function (error, form, progression, notification) { + angular.forEach(error.data.errors, function (value, key) { + if (this[key]) { + this[key].$valid = false; + } + }, form); + progression.done(); + notification.log(error.data.message, {addnCls: 'humane-flatty-error'}); + return false; + }]); + email_templates.listView().title('Email Templates') + .fields([ + nga.field('name').label('Name'), + nga.field('from_name').label('From Name'), + nga.field('subject').label('Subject').map(truncate), + nga.field('body_content').label('Content').map(truncate) + ]) + .perPage(limit_per_page) + .listActions(['edit']) + .batchActions([]) + .filters([ + nga.field('q').label('Search', 'template') + .pinned(true) + .template('
') + ]) + .actions([]); + email_templates.editionView().title('Edit Email Template') + .fields([ + nga.field('name').editable(false).label('Name'), + nga.field('from_name') + .label('From Name') + .validation({ + required: true + }), + nga.field('subject') + .label('Subject') + .validation({ + required: true + }), + nga.field('body_content', 'wysiwyg') + .validation({ + required: true + }) + .stripTags(true), + nga.field('info').editable(false).label('Constant for Subject and Content'), + ]) + .onSubmitSuccess(['progression', 'notification', '$state', 'entry', 'entity', function (progression, notification, $state, entry, entity) { + progression.done(); + notification.log(entry.values.Success, {addnCls: 'humane-flatty-success'}); + $state.go($state.get('list'), {entity: entity.name()}); + return false; + }]) + .onSubmitError(['error', 'form', 'progression', 'notification', function (error, form, progression, notification) { + angular.forEach(error.data.errors, function (value, key) { + if (this[key]) { + this[key].$valid = false; + } + }, form); + progression.done(); + notification.log(error.data.message, {addnCls: 'humane-flatty-error'}); + return false; + }]); + var languages_custom_tmp = ''; + languages.listView().title('Languages') + .fields([ + nga.field('name').label('Name'), + nga.field('iso2').label('ISO2'), + nga.field('is_active', 'boolean').label('Active?') + ]) + .perPage(limit_per_page) + .listActions(['edit', 'delete']) + .filters([ + nga.field('q').label('Search', 'template') + .pinned(true) + .template('
'), + nga.field('filter', 'choice').label('Status').attributes({ + placeholder: 'Status?' + }) + .choices([{ + label: 'Active', + value: 'active' + }, { + label: 'Inactive', + value: 'inactive' + },]) + ]) + .actions(['create', 'batch', languages_custom_tmp]); + languages.creationView().title('Add Language') + .fields([ + nga.field('name').label('Name') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Name' + }), + nga.field('iso2').label('ISO2') + .validation({ + required: true, + minlength: 2, + maxlength: 2 + }) + .attributes({ + placeholder: 'ISO2' + }), + nga.field('iso3').label('ISO3') + .validation({ + required: true, + minlength: 3, + maxlength: 3 + }) + .attributes({ + placeholder: 'ISO3' + }), + nga.field('is_active', 'choice').label('Active?') + .validation({ + required: true + }) + .choices([{ + label: 'Yes', + value: true + }, { + label: 'No', + value: false + }]) + ]) + .onSubmitSuccess(['progression', 'notification', '$state', 'entry', 'entity', function (progression, notification, $state, entry, entity) { + progression.done(); + notification.log(entry.values.Success, {addnCls: 'humane-flatty-success'}); + $state.go($state.get('list'), {entity: entity.name()}); + return false; + }]) + .onSubmitError(['error', 'form', 'progression', 'notification', function (error, form, progression, notification) { + angular.forEach(error.data.errors, function (value, key) { + if (this[key]) { + this[key].$valid = false; + } + }, form); + progression.done(); + notification.log(error.data.message, {addnCls: 'humane-flatty-error'}); + return false; + }]); + languages.editionView().title('Edit Language') + .fields([ + nga.field('name') + .label('Name') + .validation({ + required: true + }), + nga.field('iso2').label('ISO2') + .validation({ + required: true + }), + nga.field('iso3').label('ISO3') + .validation({ + required: true + }), + nga.field('is_active', 'choice').label('Active?') + .validation({ + required: true + }) + .choices([{ + label: 'Yes', + value: true + }, { + label: 'No', + value: false + }]) + ]) + .onSubmitSuccess(['progression', 'notification', '$state', 'entry', 'entity', function (progression, notification, $state, entry, entity) { + progression.done(); + notification.log(entry.values.Success, {addnCls: 'humane-flatty-success'}); + $state.go($state.get('list'), {entity: entity.name()}); + return false; + }]) + .onSubmitError(['error', 'form', 'progression', 'notification', function (error, form, progression, notification) { + angular.forEach(error.data.errors, function (value, key) { + if (this[key]) { + this[key].$valid = false; + } + }, form); + progression.done(); + notification.log(error.data.message, {addnCls: 'humane-flatty-error'}); + return false; + }]); + var users_custom_tmp = ''; + users.listView() + .fields([ + nga.field('created_at').label('Registered On'), + nga.field('role_id', 'choice').label('User Type') + .choices([{ + label: 'Admin', + value: '1' + }, { + label: 'User', + value: '2' + }]), + nga.field('username').label('Name'), + nga.field('email').label('Email'), + nga.field('available_wallet_amount', 'number').format('0.00').label('Available Balance (' + siteCurrency + ')'), + nga.field('user_login_count', 'number').label('Login Count'), + nga.field('is_active', 'boolean').label('Active?'), + nga.field('is_email_confirmed', 'boolean').label('Email Confirmed?'), + ]) + .filters([ + nga.field('q').label('Search') + .pinned(true) + .template('
'), + nga.field('filter', 'choice').label('Status').attributes({ + placeholder: 'Status?' + }) + .choices([{ + label: 'Active', + value: 'active' + }, { + label: 'Inactive', + value: 'inactive' + },]), + nga.field('role_id', 'choice').label('User Type').attributes({ + placeholder: 'Select User Type' + }) + .choices([{ + label: 'User', + value: 'userpass' + }, { + label: 'Admin', + value: 'admin' + } + ]), + nga.field('is_email_confirmed', 'choice').label('Email Verified Status').attributes({ + placeholder: 'Email Verified?' + }) + .choices([{ + label: 'Yes', + value: 'yes' + }, { + label: 'No', + value: 'no' + }]) + ]) + .actions(['create', 'batch', users_custom_tmp]); + // set the fields of the user entity list view + users.listView().title('Users') // default title is "[Entity_name] list" + .infinitePagination(false) // load pages as the user scrolls + .perPage(limit_per_page) + .batchActions([ + '', + '', + 'delete' + ]) + .listActions(['', 'show', 'edit', 'delete']); + users.creationView().title('Add User') + .fields([ + nga.field('role_id', 'choice').label('User Type') + .choices([{ + label: 'Admin', + value: '1' + }, { + label: 'User', + value: '2' + }]) + .attributes({ + placeholder: 'User Type' + }) + .validation({ + required: true + }), + nga.field('username').label('Name').map(truncate) + .attributes({ + placeholder: 'Name' + }) + .validation({ + required: true + }), + nga.field('email', 'email').label('Email') + .attributes({ + placeholder: 'Email' + }) + .validation({ + required: true + }), + nga.field('password', 'password').label('Password') + .attributes({ + placeholder: 'Password' + }) + .validation({ + required: true + }), + nga.field('is_active', 'choice').label('Active?') + .attributes({ + placeholder: 'Active?' + }) + .validation({ + required: true + }) + .choices([{ + label: 'Yes', + value: true + }, { + label: 'No', + value: false + },]), + nga.field('is_email_confirmed', 'choice').label('Email Confirmed?') + .attributes({ + placeholder: 'Email Confirmed?' + }) + .validation({ + required: true + }) + .choices([{ + label: 'Yes', + value: 1 + }, { + label: 'No', + value: 0 + }]), + ]) + .onSubmitSuccess(['progression', 'notification', '$state', 'entry', 'entity', function (progression, notification, $state, entry, entity) { + progression.done(); + notification.log(entry.values.Success, {addnCls: 'humane-flatty-success'}); + $state.go($state.get('list'), {entity: entity.name()}); + return false; + }]) + .onSubmitError(['error', 'form', 'progression', 'notification', function (error, form, progression, notification) { + angular.forEach(error.data.errors, function (value, key) { + if (this[key]) { + this[key].$valid = false; + } + }, form); + progression.done(); + notification.log(error.data.message, {addnCls: 'humane-flatty-error'}); + return false; + }]); + users.showView() + .title('Show #{{ entry.values.username }}') + .fields([ + nga.field('created_at').label('Registered On'), + nga.field('role_id', 'choice').label('User Type') + .choices([{ + label: 'Admin', + value: '1' + }, { + label: 'User', + value: '2' + }]), + nga.field('username').label('Name'), + nga.field('email').label('Email'), + nga.field('available_wallet_amount', 'number').format('0.00').label('Available Balance (' + siteCurrency + ')'), + nga.field('user_login_count', 'number').label('Login Count'), + nga.field('vehicle_rental_count', 'number').label('Vehicle Rental Count'), + nga.field('vehicle_rental_order_count', 'number').label('Vehicle Rental Order Count'), + nga.field('is_active', 'boolean').label('Active?'), + nga.field('is_email_confirmed', 'boolean').label('Email Confirmed?'), + nga.field('register_ip.ip').label('Register IP'), + nga.field('last_login_ip.ip').label('Last Login IP'), + nga.field('', 'template').label('Related User Logins') + .template(''), + ]); + users.editionView().title('Edit User') + .fields([ + nga.field('role_id', 'choice').label('User Type') + .choices([{ + label: 'Admin', + value: 1 + }, { + label: 'User', + value: 2 + }]).validation({ + required: true + }), + nga.field('username').label('Name').map(truncate) + .validation({ + required: true + }), + nga.field('email', 'email').label('Email') + .validation({ + required: true + }), + nga.field('is_active', 'choice').label('Active?') + .validation({ + required: true + }) + .choices([{ + label: 'Yes', + value: 1 + }, { + label: 'No', + value: 0 + },]), + nga.field('is_email_confirmed', 'choice').label('Email Confirmed?') + .validation({ + required: true + }) + .choices([{ + label: 'Yes', + value: 1 + }, { + label: 'No', + value: 0 + }]) + ]) + .onSubmitSuccess(['progression', 'notification', '$state', 'entry', 'entity', function (progression, notification, $state, entry, entity) { + progression.done(); + notification.log(entry.values.Success, {addnCls: 'humane-flatty-success'}); + $state.go($state.get('list'), {entity: entity.name()}); + return false; + }]) + .onSubmitError(['error', 'form', 'progression', 'notification', function (error, form, progression, notification) { + angular.forEach(error.data.errors, function (value, key) { + if (this[key]) { + this[key].$valid = false; + } + }, form); + progression.done(); + notification.log(error.data.message, {addnCls: 'humane-flatty-error'}); + return false; + }]); + var setting_category_list_tpl = ''; + var setting_category_action_tpl = ''+''; + setting_categories.listView().title('Site Settings') + .fields([ + nga.field('name').label('Name'), + nga.field('description').label('Description') + ]) + .sortField('display_order') + .sortDir('ASC') + .batchActions([]) + .perPage(limit_per_page) + .actions(setting_category_action_tpl) + .listActions(setting_category_list_tpl) + + settings_category_edit_template = ''; + setting_categories.editionView().title('Edit Settings') + .fields([ + nga.field('name').editable(false).label('Name'), + nga.field('description').editable(false).label('Description'), + nga.field('Related Settings', 'referenced_list') // display list of related settings + .targetEntity(nga.entity('settings')) + .targetReferenceField('setting_category_id') + .targetFields([ + nga.field('label').label('Name'), + nga.field('value').label('Value') + ]) + .listActions(['edit']), + nga.field('', 'template').label('').template(''), + ]) + .actions(settings_category_edit_template) + + var setting_edit_template = ''; + settings.editionView().title('Edit - {{entry.values.label}}') + .fields([ + nga.field('label').editable(false).label('Name'), + nga.field('description', 'wysiwyg').editable(false).label('Description'), + nga.field('value', 'text').label('Value') + .validation({ + validator: function (value, entry) { + if (entry.name === "payment.is_live_mode" || entry.name === "paypal.is_live_mode" || entry.name === "facebook.is_enabled_facebook_comment" || entry.name === "analytics.is_enabled_facebook_pixel" || entry.name === "analytics.is_enabled_google_analytics" || entry.name === "paypal.is_paypal_enabled_for_payments" || entry.name === "payment.is_sudopay_enabled_for_payments") { + if (value !== "0" && value !== "1") { + throw new Error('Value must be either 0 or 1'); + } + } + } + }) + ]) + .actions(setting_edit_template); + var ips_custom_tmp = ''; + ips.listView().title('IPs') + .fields([ + nga.field('ip').label('IP'), + nga.field('City.name') + .label('City') + .map(truncate), + nga.field('State.name') + .label('State') + .map(truncate), + nga.field('Country.name') + .label('Country') + .map(truncate), + nga.field('latitude').label('Latitude'), + nga.field('longitude').label('Longitude') + ]).listActions(['delete']) + .perPage(limit_per_page) + .filters([ + nga.field('q').label('Search', 'template') + .pinned(true) + .template('
') + ]) + .actions(['batch', ips_custom_tmp]); + var pages_custom_tmp = '' + + ''; + pages.listView().title('Pages') + .fields([ + nga.field('id').label('ID'), + nga.field('language_id', 'reference') + .editable(false) + .label('Language') + .targetEntity(nga.entity('languages')) + .perPage('all') // For getting all list + .targetField(nga.field('name')) + .validation({ + required: true + }), + nga.field('title').label('Title').map(truncate), + nga.field('page_content').label('Content').map(truncate), + nga.field('slug').label('Page Slug'), + ]) + .perPage(limit_per_page) + .listActions(['show', 'edit', 'delete']) + .filters([ + nga.field('q').label('Search', 'template') + .pinned(true) + .template('
') + ]) + .actions(['batch', pages_custom_tmp]); + pages.showView().title('Pages - {{ entry.values.id }}') + .fields([ + nga.field('language_id', 'reference') + .label('Language') + .targetEntity(nga.entity('languages')) + .perPage('all') // For getting all list + .targetField(nga.field('name')), + nga.field('title').label('Title'), + nga.field('page_content', 'wysiwyg').label('Content'), + nga.field('slug').label('Page Slug') + ]); + pages.editionView().title('Pages - {{ entry.values.title }}') + .fields([ + nga.field('title') + .validation({ + required: true + }) + .label('Title'), + nga.field('page_content', 'wysiwyg') + .stripTags(true) + .validation({ + required: true + }), + nga.field('slug') + .label('Page Slug') + .validation({ + required: true + }) + ]) + .onSubmitSuccess(['progression', 'notification', '$state', 'entry', 'entity', function (progression, notification, $state, entry, entity) { + progression.done(); + notification.log(entry.values.Success, {addnCls: 'humane-flatty-success'}); + $state.go($state.get('list'), {entity: entity.name()}); + return false; + }]) + .onSubmitError(['error', 'form', 'progression', 'notification', function (error, form, progression, notification) { + angular.forEach(error.data.errors, function (value, key) { + if (this[key]) { + this[key].$valid = false; + } + }, form); + progression.done(); + notification.log(error.data.message, {addnCls: 'humane-flatty-error'}); + return false; + }]); + var contacts_custom_tmp = ''; + contacts.listView().title('Contacts') + .fields([ + nga.field('user_type').label('Submitter'), + nga.field('first_name').label('First Name'), + nga.field('last_name').label('Last Name'), + nga.field('email').label('Email'), + nga.field('subject').label('Subject').map(truncate), + nga.field('message').label('Message').map(truncate), + nga.field('ip.ip').label('IP') + ]).listActions(['show', 'delete']) + .filters([ + nga.field('q').label('Search', 'template') + .pinned(true) + .template('
') + ]) + .actions(['batch', contacts_custom_tmp]); + contacts.showView().title('Contact - {{ entry.values.id }}') + .fields([ + nga.field('user.username').label('User'), + nga.field('first_name').label('First Name'), + nga.field('last_name').label('Last Name'), + nga.field('email').label('Email'), + nga.field('subject').label('Subject'), + nga.field('message').label('Message'), + nga.field('ip.ip').label('IP') + ]); + var user_cash_withdrawals_custom_tmp = ''; + user_cash_withdrawals.listView().title('Withdraw Requests') + .infinitePagination(false) // load pages as the user scrolls + .perPage(limit_per_page) + .fields([ + nga.field('created_at').label('Created'), + nga.field('user.username').label('User'), + nga.field('amount', 'number').format('0.00').label('Amount'), + nga.field('withdrawal_status.name').label('Status'), + nga.field('money_transfer_account.account', 'wysiwyg').label('Money Transfer Account').map(truncate) + ]) + .listActions(['edit', 'delete']) + .filters([ + nga.field('q').label('Search') + .pinned(true) + .template('
'), + nga.field('filter', 'choice').label('Status').attributes({ + placeholder: 'Status?' + }) + .choices([{ + label: 'Pending', + value: '1' + }, { + label: 'Rejected', + value: '2' + }, { + label: 'Success', + value: '3' + }]) + ]) + .actions(['batch', user_cash_withdrawals_custom_tmp]); + user_cash_withdrawals.editionView().title('Edit Withdraw Requests') + .fields([ + nga.field('amount') + .label('Amount') + .validation({ + required: true + }), + nga.field('withdrawal_status_id', 'choice').label('Status') + .validation({ + required: true + }) + .choices([{ + label: 'Pending', + value: '1' + }, { + label: 'Rejected', + value: '2' + }, { + label: 'Success', + value: '3' + }]) + ]) + .onSubmitSuccess(['progression', 'notification', '$state', 'entry', 'entity', function (progression, notification, $state, entry, entity) { + progression.done(); + notification.log(entry.values.Success, {addnCls: 'humane-flatty-success'}); + $state.go($state.get('list'), {entity: entity.name()}); + return false; + }]) + .onSubmitError(['error', 'form', 'progression', 'notification', function (error, form, progression, notification) { + angular.forEach(error.data.errors, function (value, key) { + if (this[key]) { + this[key].$valid = false; + } + }, form); + progression.done(); + notification.log(error.data.message, {addnCls: 'humane-flatty-error'}); + return false; + }]); + var user_logins_custom_tmp = ''; + user_logins.listView().title('User Logins') + .fields([ + nga.field('created_at').label('Created'), + nga.field('user.username').label('User'), + nga.field('user_login_ip.ip').label('IP'), + nga.field('user_agent').label('User Agent').map(truncate) + ]) + .perPage(limit_per_page) + .listActions(['show', 'delete']) + .filters([ + nga.field('q').label('Search', 'template') + .pinned(true) + .template('
') + ]) + .actions(['batch', user_logins_custom_tmp]); + + user_logins.showView().title('View User Login') + .fields([ + nga.field('created_at').label('Created'), + nga.field('user.username').label('User'), + nga.field('role_id', 'choice').label('User Type') + .choices([{ + label: 'Admin', + value: '1' + }, { + label: 'User', + value: '2' + }]), + nga.field('user_login_ip.ip').label('IP'), + nga.field('user_agent').label('User Agent') + ]); + + var transaction_types_custom_tmp = ''; + transaction_types.listView().title('Transaction Types') + .fields([ + nga.field('name').label('Name'), + nga.field('transaction_type_group_id', 'choice').label('Type') + .choices([{ + label: 'Wallet', + value: '1' + }, { + label: 'Cash Withdrawal', + value: '2' + }, { + label: 'VehicleRental', + value: '3' + }]), + nga.field('message').label('Message'), + nga.field('is_credit', 'boolean').label('Credit'), + ]) + .sortField('name') + .sortDir('ASC') + .infinitePagination(false) + .perPage(limit_per_page) + .listActions(['edit']) + .filters([ + nga.field('q').label('Search') + .pinned(true) + .template('
'), + nga.field('transaction_type_group_id', 'choice').label('Type').attributes({ + placeholder: 'Select Type' + }) + .choices([{ + label: 'Wallet', + value: '1' + }, { + label: 'Cash Withdrawal', + value: '2' + }, { + label: 'VehicleRental', + value: '3' + }]) + ]) + .batchActions([]) + .actions([transaction_types_custom_tmp]); + + transaction_types.editionView().title('Edit Transaction Type') + .fields([ + nga.field('name').label('Name'), + nga.field('is_credit', 'choice').label('Is credit?') + .validation({ + required: true + }) + .choices([{ + label: 'Yes', + value: true + }, { + label: 'No', + value: false + }]), + nga.field('message', 'text').label('Message') + ]) + .onSubmitSuccess(['progression', 'notification', '$state', 'entry', 'entity', function (progression, notification, $state, entry, entity) { + progression.done(); + notification.log(entry.values.Success, {addnCls: 'humane-flatty-success'}); + $state.go($state.get('list'), {entity: entity.name()}); + return false; + }]) + .onSubmitError(['error', 'form', 'progression', 'notification', function (error, form, progression, notification) { + angular.forEach(error.data.errors, function (value, key) { + if (this[key]) { + this[key].$valid = false; + } + }, form); + progression.done(); + notification.log(error.data.message, {addnCls: 'humane-flatty-error'}); + return false; + }]); + var vehicles_custom_tmp = '\n \n'; + vehicles.listView().title('Vehicles') + .fields([ + nga.field('created_at').label('Created'), + nga.field('vehicle_company.name').label('Company Name'), + nga.field('name').label('') + .template('{{entry.values.name}}') + .label('Vehicle Name'), + nga.field('vehicle_make.name').label('Make'), + nga.field('vehicle_model.name').label('Model'), + nga.field('vehicle_type.name').label('Type'), + nga.field('per_hour_amount', 'number').format('0.00').label('Hour Amount(' + siteCurrency + ')'), + nga.field('per_day_amount', 'number').format('0.00').label('Day Amount(' + siteCurrency + ')'), + nga.field('feedback_count', 'number').label('Feedback Count').cssClasses(function () { + if (enabledPlugins.indexOf("VehicleFeedbacks") === -1) { + return "ng-hide"; + } + }), + nga.field('is_active', 'boolean').label('Active?'), + ]) + .filters([ + nga.field('q').label('Search') + .pinned(true) + .template('
'), + nga.field('filter', 'choice').label('Status').attributes({ + placeholder: 'Status?' + }) + .choices([{ + label: 'Active', + value: 'active' + }, { + label: 'Inactive', + value: 'inactive' + },]), + nga.field('vehicle_company_id', 'reference') + .attributes({ + placeholder: 'Company' + }) + .targetEntity(nga.entity('vehicle_companies?filter=active')) + .targetField(nga.field('name')) + .label('Company'), + nga.field('vehicle_make_id', 'reference') + .attributes({ + placeholder: 'Make' + }) + .targetEntity(nga.entity('vehicle_makes?filter=active')) + .targetField(nga.field('name')) + .label('Make'), + nga.field('vehicle_model_id', 'reference') + .attributes({ + placeholder: 'Model' + }) + .targetEntity(nga.entity('vehicle_models?filter=active')) + .targetField(nga.field('name')) + .label('Model'), + nga.field('vehicle_type_id', 'reference') + .attributes({ + placeholder: 'Type' + }) + .targetEntity(nga.entity('vehicle_types?filter=active')) + .targetField(nga.field('name')) + .label('Type') + ]) + .infinitePagination(false) + .perPage(limit_per_page) + .listActions(['', '', '', 'delete']) + .actions(['batch', vehicles_custom_tmp]) + .batchActions([ + '', + '', + 'delete' + ]); + vehicles.creationView().title('Add Item') + .fields([ + nga.field('user_id', 'reference') + .label('User') + .validation({ + required: true + }) + .attributes({ + placeholder: 'User' + }) + .perPage('all') + .targetEntity(nga.entity('users')) + .targetField(nga.field('username').map(truncate)), + nga.field('name').label('Item Name').map(truncate) + .attributes({ + placeholder: 'Item Name' + }) + .validation({ + required: true + }), + nga.field('description').label('Description') + .attributes({ + placeholder: 'Description' + }), + nga.field('amount').label('Amount') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Amount' + }) + ]) + .onSubmitSuccess(['progression', 'notification', '$state', 'entry', 'entity', function (progression, notification, $state, entry, entity) { + progression.done(); + notification.log(entry.values.Success, {addnCls: 'humane-flatty-success'}); + $state.go($state.get('list'), {entity: entity.name()}); + return false; + }]) + .onSubmitError(['error', 'form', 'progression', 'notification', function (error, form, progression, notification) { + angular.forEach(error.data.errors, function (value, key) { + if (this[key]) { + this[key].$valid = false; + } + }, form); + progression.done(); + notification.log(error.data.message, {addnCls: 'humane-flatty-error'}); + return false; + }]); + vehicles.showView().title('Show Vehicle') + .fields([ + nga.field('created_at').label('Created'), + nga.field('vehicle_company.name').label('Company Name'), + nga.field('name').label('Vehicle Name'), + nga.field('vehicle_make.name').label('Make'), + nga.field('vehicle_model.name').label('Model'), + nga.field('vehicle_type.name').label('Type'), + nga.field('vehicle_no').label('Vehicle No'), + nga.field('no_of_seats').label('Seats'), + nga.field('no_of_doors').label('Doors'), + nga.field('no_of_gears').label('Gears'), + nga.field('no_small_bags').label('Small bags'), + nga.field('no_large_bags').label('Large bags'), + nga.field('is_manual_transmission', 'boolean').label('Manual Transmission?'), + nga.field('is_ac', 'boolean').label('AC'), + nga.field('is_abs', 'boolean').label('Abs'), + nga.field('is_airbag', 'boolean').label('Airbag?'), + nga.field('no_of_airbags').label('Airbags'), + nga.field('minimum_age_of_driver').label('Minimum age of driver'), + nga.field('mileage').label('Mileage'), + nga.field('per_hour_amount', 'number').format('0.00').label('Per hour amount(' + siteCurrency + ')'), + nga.field('per_day_amount', 'number').format('0.00').label('Per day amount(' + siteCurrency + ')'), + nga.field('fuel_type.name').label('Fuel Type'), + nga.field('feedback_count', 'number').label('Feedback Count').cssClasses(function () { + if (enabledPlugins.indexOf("VehicleFeedbacks") === -1) { + return "ng-hide"; + } + }), + nga.field('vehicle_rental_count').label('Vehicle Rental Count'), + nga.field('is_active', 'boolean').label('Active?'), + nga.field('Counter Locations', 'referenced_list') + .targetEntity(nga.entity('counter_locations')) + .targetReferenceField('vehicle_id') + .targetFields([ + nga.field('address').label('Address').map(truncate) + ]) + ]) + .actions(['batch', '\n \n']); + vehicles.editionView().title('Edit Item') + .fields([ + nga.field('user_id', 'reference') + .label('User') + .validation({ + required: true + }) + .attributes({ + placeholder: 'User' + }) + .perPage('all') + .targetEntity(nga.entity('users')) + .targetField(nga.field('username').map(truncate)), + nga.field('name').label('Item Name').map(truncate) + .attributes({ + placeholder: 'Item Name' + }) + .validation({ + required: true + }), + nga.field('description').label('Description') + .attributes({ + placeholder: 'Description' + }), + nga.field('amount').label('Amount') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Amount' + }), + nga.field('is_active', 'choice').label('Active?') + .validation({ + required: true + }) + .choices([{ + label: 'Yes', + value: 1 + }, { + label: 'No', + value: 0 + },]), + nga.field('is_paid', 'choice').label('Paid?') + .validation({ + required: true + }) + .choices([{ + label: 'Yes', + value: 1 + }, { + label: 'No', + value: 0 + }]) + ]) + .onSubmitSuccess(['progression', 'notification', '$state', 'entry', 'entity', function (progression, notification, $state, entry, entity) { + progression.done(); + notification.log(entry.values.Success, {addnCls: 'humane-flatty-success'}); + $state.go($state.get('list'), {entity: entity.name()}); + return false; + }]) + .onSubmitError(['error', 'form', 'progression', 'notification', function (error, form, progression, notification) { + angular.forEach(error.data.errors, function (value, key) { + if (this[key]) { + this[key].$valid = false; + } + }, form); + progression.done(); + notification.log(error.data.message, {addnCls: 'humane-flatty-error'}); + return false; + }]); + var vehicle_coupons_custom_tmp = ''; + vehicle_coupons.listView().title('Vehicle Coupons') + .fields([ + nga.field('couponable.name').label('Vehicle'), + nga.field('name').label('Coupon'), + nga.field('discount', 'number').format('0.00').label('Discount'), + nga.field('discount_type_id', 'choice').label('Discount Type(' + siteCurrency + '/%)') + .choices([{ + label: 'Percentage', + value: '1' + }, { + label: 'Amount', + value: '2' + }]), + nga.field('validity_start_date').label('Start Date'), + nga.field('validity_end_date').label('End Date'), + nga.field('no_of_quantity').label('Quantity'), + nga.field('no_of_quantity_used', 'number').label('Quantity Used'), + nga.field('is_active', 'boolean').label('Active?'), + ]) + .filters([ + nga.field('q').label('Search') + .pinned(true) + .template('
'), + nga.field('filter', 'choice').label('Status').attributes({ + placeholder: 'Status?' + }) + .choices([{ + label: 'Active', + value: 'active' + }, { + label: 'Inactive', + value: 'inactive' + },]), + nga.field('start_date', 'date').format("MM/dd/yyyy").attributes({'placeholder': 'Select Start date'}).label("Start Date"), + nga.field('end_date', 'date').format("MM/dd/yyyy").attributes({'placeholder': 'Select End date'}).label("End Date") + ]) + .actions(['batch', 'create']) + .listActions(['edit', 'delete']) + .actions(['create', 'batch', vehicle_coupons_custom_tmp]); + + vehicle_coupons.creationView().title('Add Vehicle Coupon') + .fields([ + nga.field('vehicle_id', 'reference') + .label('Vehicle') + .attributes({ + placeholder: 'Vehicle' + }) + .perPage('all') + .targetEntity(nga.entity('vehicles')) + .targetField(nga.field('name').map(truncate)), + nga.field('name') + .label('Coupon') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Coupon' + }), + nga.field('description') + .label('Description') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Description' + }), + nga.field('discount') + .label('Discount') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Discount' + }), + nga.field('discount_type_id', 'choice').label('Discount Type(' + siteCurrency + '/%)') + .choices([{ + label: 'Percentage', + value: '1' + }, { + label: 'Amount', + value: '2' + }]) + .attributes({ + placeholder: 'Discount Type' + }) + .validation({ + required: true + }), + nga.field('no_of_quantity', 'number') + .label('Quantity') + .attributes({ + placeholder: 'Quantity' + }) + .validation({ + required: true, + validator: function (value) { + if (value <= 0) throw new Error('Enter Valid Quantity'); + } + }), + nga.field('maximum_discount_amount') + .label('Maximum Discount Amount') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Maximum Discount Amount' + }), + nga.field('validity_start_date', 'date').label('Start Date'), + nga.field('validity_end_date', 'date').label('End Date'), + nga.field('is_active', 'choice').label('Active?') + .attributes({ + placeholder: 'Active?' + }) + .validation({ + required: true + }) + .choices([{ + label: 'Yes', + value: '1' + }, { + label: 'No', + value: '0' + }]) + ]) + .onSubmitSuccess(['progression', 'notification', '$state', 'entry', 'entity', function (progression, notification, $state, entry, entity) { + progression.done(); + notification.log(entry.values.Success, {addnCls: 'humane-flatty-success'}); + $state.go($state.get('list'), {entity: entity.name()}); + return false; + }]) + .onSubmitError(['error', 'form', 'progression', 'notification', function (error, form, progression, notification) { + angular.forEach(error.data.errors, function (value, key) { + if (this[key]) { + this[key].$valid = false; + } + }, form); + progression.done(); + notification.log(error.data.message, {addnCls: 'humane-flatty-error'}); + return false; + }]); + + vehicle_coupons.editionView().title('Edit Vehicle Coupon') + .fields([ + nga.field('vehicle_id', 'reference') + .label('Vehicle') + .attributes({ + placeholder: 'Vehicle' + }) + .perPage('all') + .targetEntity(nga.entity('vehicles')) + .targetField(nga.field('name').map(truncate)), + nga.field('name') + .label('Coupon') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Coupon' + }), + nga.field('description') + .label('Description') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Description' + }), + nga.field('discount') + .label('Discount') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Discount' + }), + nga.field('discount_type_id', 'choice') + .label('Discount Type(' + siteCurrency + '/%)') + .choices([{ + label: 'Percentage', + value: '1' + }, { + label: 'Amount', + value: '2' + }]), + nga.field('no_of_quantity', 'number') + .label('Quantity') + .attributes({ + placeholder: 'Quantity' + }) + .validation({ + required: true, + validator: function (value) { + if (value <= 0) throw new Error('Enter Valid Quantity'); + } + }), + nga.field('maximum_discount_amount') + .label('Maximum Discount Amount') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Maximum Discount Amount' + }), + nga.field('validity_start_date', 'datetime').label('Start Date'), + nga.field('validity_end_date', 'datetime').label('End Date'), + nga.field('is_active', 'choice').label('Active?') + .validation({ + required: true + }) + .choices([{ + label: 'Yes', + value: '1' + }, { + label: 'No', + value: '0' + }]) + ]) + .onSubmitSuccess(['progression', 'notification', '$state', 'entry', 'entity', function (progression, notification, $state, entry, entity) { + progression.done(); + notification.log(entry.values.Success, {addnCls: 'humane-flatty-success'}); + $state.go($state.get('list'), {entity: entity.name()}); + return false; + }]) + .onSubmitError(['error', 'form', 'progression', 'notification', function (error, form, progression, notification) { + angular.forEach(error.data.errors, function (value, key) { + if (this[key]) { + this[key].$valid = false; + } + }, form); + progression.done(); + notification.log(error.data.message, {addnCls: 'humane-flatty-error'}); + return false; + }]); + sudopay_ipn_logs.listView().title('ZazPay Ipn Logs') + .fields([ + nga.field('id').label('ID'), + nga.field('created_at').label('Created'), + nga.field('ip').label('IP'), + nga.field('post_variable').label('Post Variable') + ]) + .infinitePagination(false) + .perPage(limit_per_page) + .batchActions([]) + .actions([]); + + var transactions_custom_tmp = ''; + transactions.listView().title('Transactions') + .fields([ + nga.field('id').label('ID'), + nga.field('created_at').label('Date'), + nga.field('from_user.username').label('From'), + nga.field('to_user.username').label('To'), + nga.field('description', 'wysiwyg').label('Description'), + nga.field('credit_amount', 'number').format('0.00').label('Credit(' + siteCurrency + ')'), + nga.field('debit_amount', 'number').format('0.00').label('Debit(' + siteCurrency + ')') + ]) + .filters([ + nga.field('q').label('Search') + .pinned(true) + .template('
'), + nga.field('start_date', 'date').format("MM/dd/yyyy").attributes({'placeholder': 'Select From Date'}).label("From Date"), + nga.field('end_date', 'date').format("MM/dd/yyyy").attributes({'placeholder': 'Select To Date'}).label("To Date"), + nga.field('from_user', 'reference') + .attributes({ + placeholder: 'From User' + }) + .perPage('all') + .targetEntity(nga.entity('users')) + .targetField(nga.field('username')) + .label('From User'), + nga.field('to_user', 'reference') + .attributes({ + placeholder: 'To User' + }) + .perPage('all') + .targetEntity(nga.entity('users')) + .targetField(nga.field('username')) + .label('To User') + ]) + .infinitePagination(false) + .perPage(limit_per_page) + .batchActions([]) + .actions(['batch', transactions_custom_tmp]); + + sudopay_transaction_logs.listView().title('ZazPay Transaction Logs') + .fields([ + nga.field('created_at').label('Created'), + nga.field('sudopay_transaction_logable_type').label('Class'), + nga.field('sudopay_pay_key').label('Pay Key'), + nga.field('gateway_name').label('Gateway'), + nga.field('status').label('Status'), + nga.field('payment_type').label('Payment Type'), + nga.field('sudopay_transaction_fee').label('Transaction Fee(' + siteCurrency + ')'), + nga.field('amount', 'number').format('0.00').label('Amount(' + siteCurrency + ')'), + ]) + .filters([ + nga.field('q').label('Search') + .pinned(true) + .template('
') + ]) + .infinitePagination(false) + .perPage(limit_per_page) + .batchActions([]) + .actions([]) + .listActions(['show']); + + sudopay_transaction_logs.showView().title('View ZazPay Transaction Log') + .fields([ + nga.field('created_at').label('Created'), + nga.field('sudopay_transaction_logable_type').label('Class'), + nga.field('sudopay_pay_key').label('Pay Key'), + nga.field('gateway_name').label('Gateway'), + nga.field('status').label('Status'), + nga.field('payment_type').label('Payment Type'), + nga.field('sudopay_transaction_fee').label('Transaction Fee(' + siteCurrency + ')'), + nga.field('amount', 'number').format('0.00').label('Amount(' + siteCurrency + ')'), + nga.field('buyer_email').label('Buyer email'), + nga.field('buyer_address').label('Buyer Address') + ]); + + paypal_transaction_logs.listView().title('Paypal Transaction Logs') + .fields([ + nga.field('created_at').label('Created'), + nga.field('paypal_transaction_logable_type').label('Class'), + nga.field('paypal_pay_key').label('Pay Key'), + nga.field('payer_id').label('Payer Id'), + nga.field('authorization_id').label('Authorization Id'), + nga.field('capture_id').label('Capture Id'), + nga.field('void_id').label('Void Id'), + nga.field('status').label('Status'), + nga.field('payment_type').label('Payment Type'), + nga.field('paypal_transaction_fee', 'number').format('0.00').label('Transaction Fee(' + siteCurrency + ')'), + nga.field('amount', 'number').format('0.00').label('Amount(' + siteCurrency + ')') + ]) + .filters([ + nga.field('q').label('Search') + .pinned(true) + .template('
') + ]) + .infinitePagination(false) + .perPage(limit_per_page) + .batchActions([]) + .actions([]) + .listActions(['show']); + + paypal_transaction_logs.showView().title('view Paypal Transaction Log') + .fields([ + nga.field('created_at').label('Created'), + nga.field('paypal_transaction_logable_type').label('Class'), + nga.field('paypal_pay_key').label('Pay Key'), + nga.field('payer_id').label('Payer Id'), + nga.field('authorization_id').label('Authorization Id'), + nga.field('capture_id').label('Capture Id'), + nga.field('void_id').label('Void Id'), + nga.field('refund_id').label('Refund Id'), + nga.field('status').label('Status'), + nga.field('payment_type').label('Payment Type'), + nga.field('paypal_transaction_fee', 'number').format('0.00').label('Transaction Fee(' + siteCurrency + ')'), + nga.field('amount', 'number').format('0.00').label('Amount(' + siteCurrency + ')'), + nga.field('buyer_email').label('Buyer email'), + nga.field('buyer_address').label('Buyer Address') + ]); + + wallet_transaction_logs.listView().title('Wallet Transaction Logs') + .fields([ + nga.field('created_at').label('Created'), + nga.field('wallet_transaction_logable_type').label('Class'), + nga.field('status').label('Status'), + nga.field('payment_type').label('Payment Type'), + nga.field('amount', 'number').format('0.00').label('Amount(' + siteCurrency + ')') + ]) + .filters([ + nga.field('q').label('Search') + .pinned(true) + .template('
') + ]) + .infinitePagination(false) + .perPage(limit_per_page) + .batchActions([]) + .actions([]) + .listActions(['show']); + + wallet_transaction_logs.showView().title('View Wallet Transaction Log') + .fields([ + nga.field('created_at').label('Created'), + nga.field('wallet_transaction_logable_type').label('Class'), + nga.field('status').label('Status'), + nga.field('payment_type').label('Payment Type'), + nga.field('amount', 'number').format('0.00').label('Amount(' + siteCurrency + ')') + ]); + + cancellation_types.listView().title('Cancellation Types') + .fields([ + nga.field('name').label('Name'), + nga.field('description').label('Description').map(truncate), + nga.field('minimum_duration').label('Minimum Duration'), + nga.field('maximum_duration').label('Maximum Duration'), + nga.field('deduct_rate', 'number').format('0.00').label('Deduct Rate(' + siteCurrency + ')') + ]) + .filters([ + nga.field('q').label('Search') + .pinned(true) + .template('
') + ]) + .infinitePagination(false) + .perPage(limit_per_page) + .listActions(['edit']) + .actions(['create']); + + cancellation_types.creationView().title('Add Cancellation Type') + .fields([ + nga.field('name').label('Name') + .attributes({ + placeholder: 'Name' + }) + .validation({ + required: true + }), + nga.field('description', 'text').label('Description') + .attributes({ + placeholder: 'description' + }) + .validation({ + required: true + }), + nga.field('minimum_duration').label('Minimum Duration') + .attributes({ + placeholder: 'Minimum Duration' + }) + .validation({ + required: true + }), + nga.field('maximum_duration').label('Maximum Duration') + .attributes({ + placeholder: 'Maximum Duration' + }) + .validation({ + required: true + }), + nga.field('deduct_rate').label('Deduct Rate') + .attributes({ + placeholder: 'Deduct Rate' + }) + .validation({ + required: true + }) + ]) + .onSubmitSuccess(['progression', 'notification', '$state', 'entry', 'entity', function (progression, notification, $state, entry, entity) { + progression.done(); + notification.log(entry.values.Success, {addnCls: 'humane-flatty-success'}); + $state.go($state.get('list'), {entity: entity.name()}); + return false; + }]) + .onSubmitError(['error', 'form', 'progression', 'notification', function (error, form, progression, notification) { + angular.forEach(error.data.errors, function (value, key) { + if (this[key]) { + this[key].$valid = false; + } + }, form); + progression.done(); + notification.log(error.data.message, {addnCls: 'humane-flatty-error'}); + return false; + }]); + cancellation_types.editionView().title('Edit Cancellation Type') + .fields([ + nga.field('name').label('Name') + .attributes({ + placeholder: 'Name' + }) + .validation({ + required: true + }), + nga.field('description', 'text').label('Description') + .attributes({ + placeholder: 'description' + }) + .validation({ + required: true + }), + nga.field('minimum_duration').label('Minimum Duration') + .attributes({ + placeholder: 'Minimum Duration' + }) + .validation({ + required: true + }), + nga.field('maximum_duration').label('Maximum Duration') + .attributes({ + placeholder: 'Maximum Duration' + }) + .validation({ + required: true + }), + nga.field('deduct_rate').label('Deduct Rate') + .attributes({ + placeholder: 'Deduct Rate' + }) + .validation({ + required: true + }) + ]) + .onSubmitSuccess(['progression', 'notification', '$state', 'entry', 'entity', function (progression, notification, $state, entry, entity) { + progression.done(); + notification.log(entry.values.Success, {addnCls: 'humane-flatty-success'}); + $state.go($state.get('list'), {entity: entity.name()}); + return false; + }]) + .onSubmitError(['error', 'form', 'progression', 'notification', function (error, form, progression, notification) { + angular.forEach(error.data.errors, function (value, key) { + if (this[key]) { + this[key].$valid = false; + } + }, form); + progression.done(); + notification.log(error.data.message, {addnCls: 'humane-flatty-error'}); + return false; + }]); + var vehicle_rentals_custom_tmp = ''; + vehicle_rentals.listView().title('Vehicle Rentals') + .fields([ + nga.field('created_at').label('Created'), + nga.field('user.username').label('User'), + nga.field('item_userable.name').label('Vehicle Name'), + nga.field('item_user_status.name').label('Status'), + nga.field('item_booking_start_date').label('Start Date'), + nga.field('item_booking_end_date').label('End Date'), + nga.field('booking_amount', 'number').format('0.00').label('Rental Amount(' + siteCurrency + ')'), + nga.field('deposit_amount', 'number').format('0.00').label('Deposit Amount(' + siteCurrency + ')'), + nga.field('coupon_discount_amount', 'number').format('0.00').label('Coupon Discount(' + siteCurrency + ')').cssClasses(function () { + if (enabledPlugins.indexOf("VehicleCoupons") === -1) { + return "ng-hide"; + } + }), + nga.field('total_amount', 'number').format('0.00').label('Total(' + siteCurrency + ')') + ]) + .filters([ + nga.field('q').label('Search', 'template') + .pinned(true) + .template('
'), + nga.field('filter', 'choice').label('Status').attributes({ + placeholder: 'Status?' + }) + .choices([{ + label: 'Payment Pending', + value: 'payment_pending' + }, { + label: 'Waiting For Acceptance', + value: 'waiting_for_acceptance' + }, { + label: 'Rejected', + value: 'rejected' + }, { + label: 'Cancelled', + value: 'cancelled' + }, { + label: 'Expired', + value: 'expired' + }, { + label: 'Confirmed', + value: 'confirmed' + }, { + label: 'Waiting For Review', + value: 'waiting_for_review' + }, { + label: 'Completed', + value: 'completed' + }]), + nga.field('start_date', 'date').format("MM/dd/yyyy").attributes({'placeholder': 'Select Start date'}).label("Start Date"), + nga.field('end_date', 'date').format("MM/dd/yyyy").attributes({'placeholder': 'Select End date'}).label("End Date") + ]) + .infinitePagination(false) + .perPage(limit_per_page) + .listActions(['', 'show', '', '', '']) + .batchActions([]) + .actions(['batch', vehicle_rentals_custom_tmp]); + vehicle_rentals.showView().title('View Vehicle Rental') + .fields([ + nga.field('created_at').label('Created'), + nga.field('user.username').label('User'), + nga.field('item_userable.name').label('Vehicle Name'), + nga.field('item_user_status.name').label('Status'), + nga.field('item_booking_start_date').label('Start Date'), + nga.field('item_booking_end_date').label('End Date'), + nga.field('is_dispute', 'boolean').label('Is Dispute?'), + nga.field('is_payment_cleared', 'boolean').label('Is Payment Cleared'), + nga.field('additional_fee', 'number').format('0.00').label('Additional Fee(' + siteCurrency + ')'), + nga.field('admin_commission_amount', 'number').format('0.00').label('Admin Commission Amount(' + siteCurrency + ')'), + nga.field('claim_request_amount', 'number').format('0.00').label('Claim Request Amount(' + siteCurrency + ')'), + nga.field('coupon_discount_amount', 'number').format('0.00').label('Coupon Discount Amount(' + siteCurrency + ')'), + nga.field('drop_location_differ_charges', 'number').format('0.00').label('Drop Location Differ Charges(' + siteCurrency + ')'), + nga.field('extra_accessory_amount', 'number').format('0.00').label('Extra Accessory Amount(' + siteCurrency + ')'), + nga.field('fuel_option_amount', 'number').format('0.00').label('Fuel Option Amount(' + siteCurrency + ')'), + nga.field('special_discount_amount', 'number').format('0.00').label('Special Discount Amount(' + siteCurrency + ')'), + nga.field('surcharge_amount', 'number').format('0.00').label('Surcharge Amount(' + siteCurrency + ')'), + nga.field('tax_amount', 'number').format('0.00').label('Tax Amount(' + siteCurrency + ')'), + nga.field('type_discount_amount', 'number').format('0.00').label('Type Discount Amount(' + siteCurrency + ')'), + nga.field('insurance_amount', 'number').format('0.00').label('Insurance Amount(' + siteCurrency + ')'), + nga.field('booking_amount', 'number').format('0.00').label('Rental Amount(' + siteCurrency + ')'), + nga.field('deposit_amount', 'number').format('0.00').label('Deposit Amount(' + siteCurrency + ')'), + nga.field('coupon_discount_amount', 'number').format('0.00').label('Coupon Discount(' + siteCurrency + ')').cssClasses(function () { + if (enabledPlugins.indexOf("VehicleCoupons") === -1) { + return "ng-hide"; + } + }), + nga.field('total_amount', 'number').format('0.00').label('Total(' + siteCurrency + ')') + ]) + .actions(['batch', 'list']); + var messages_custom_tmp = ''; + messages.listView().title('Messages') + .fields([ + nga.field('created_at').label('Created'), + nga.field('from_user.username').label('From'), + nga.field('to_user.username').label('To'), + nga.field('message_content.subject', 'wysiwyg').label('Subject').map(truncate) + ]) + .filters([ + nga.field('q').label('Search') + .pinned(true) + .template('
'), + nga.field('filter', 'choice').label('Filter').attributes({ + placeholder: 'Select Filter' + }) + .choices([{ + label: 'VehicleRental messages', + value: 'vehicle_rental_messages' + }, { + label: 'User messages', + value: 'user_messages' + },]) + ]) + .infinitePagination(false) + .perPage(limit_per_page) + .listActions(['show', 'delete']) + .actions(['batch', messages_custom_tmp]); + messages.showView().title('Messages') + .fields([ + nga.field('created_at').label('Created'), + nga.field('from_user.username').label('From'), + nga.field('to_user.username').label('To'), + nga.field('message_content.subject', 'wysiwyg').label('Subject'), + nga.field('message_content.message', 'wysiwyg').label('Message') + ]); + var vehicle_feedbacks_custom_tmp = ''; + vehicle_feedbacks.listView().title('Feedbacks') + .fields([ + nga.field('created_at').label('Created'), + nga.field('user.username').label('From'), + nga.field('to_user.username').label('To'), + nga.field('feedbackable.name').label('Item'), + nga.field('feedback','wysiwyg').label('Feedback').map(truncate), + nga.field('rating').label('Rating'), + nga.field('ip.ip').label('IP') + ]) + .filters([ + nga.field('q').label('Search') + .pinned(true) + .template('
'), + nga.field('filter', 'choice').label('Filter').attributes({ + placeholder: 'Filter' + }) + .choices([{ + label: 'Feedback To Host', + value: 'feedback_to_host' + }, { + label: 'Feedback To Booker', + value: 'feedback_to_booker' + },]) + ]) + .infinitePagination(false) + .perPage(limit_per_page) + .listActions(['edit', 'delete']) + .actions(['batch', vehicle_feedbacks_custom_tmp]); + vehicle_feedbacks.editionView().title('Edit Feedback') + .fields([ + nga.field('feedback', 'text').label('Message'), + nga.field('rating', 'choice').label('Rating') + .validation({ + required: true + }) + .choices([{ + label: '0', + value: 0 + }, { + label: '1', + value: 1 + }, { + label: '2', + value: 2 + }, { + label: '3', + value: 3 + }, { + label: '4', + value: 4 + }, { + label: '5', + value: 5 + },]), + ]) + .onSubmitSuccess(['progression', 'notification', '$state', 'entry', 'entity', function (progression, notification, $state, entry, entity) { + progression.done(); + notification.log(entry.values.Success, {addnCls: 'humane-flatty-success'}); + $state.go($state.get('list'), {entity: entity.name()}); + return false; + }]) + .onSubmitError(['error', 'form', 'progression', 'notification', function (error, form, progression, notification) { + angular.forEach(error.data.errors, function (value, key) { + if (this[key]) { + this[key].$valid = false; + } + }, form); + progression.done(); + notification.log(error.data.message, {addnCls: 'humane-flatty-error'}); + return false; + }]); + var currencies_custom_tmp = ''; + currencies.listView().title('Currencies') + .fields([ + nga.field('created_at').label('Created'), + nga.field('name').label('Name'), + nga.field('code').label('Code'), + nga.field('symbol').label('Symbol'), + nga.field('decimals').label('Decimals'), + nga.field('dec_point').label('Dec Point'), + nga.field('thousands_sep').label('Thousand Sep'), + nga.field('is_active', 'boolean').label('Active?') + ]) + .filters([ + nga.field('q').label('Search') + .pinned(true) + .template('
'), + nga.field('filter', 'choice').label('Status').attributes({ + placeholder: 'Status?' + }) + .choices([{ + label: 'Active', + value: 'active' + }, { + label: 'Inactive', + value: 'inactive' + },]) + ]) + .perPage(limit_per_page) + .actions(['batch', 'create']) + .listActions(['show', 'edit', 'delete']) + .actions(['create', 'batch', currencies_custom_tmp]); + + currencies.creationView().title('Add Currency') + .fields([ + nga.field('name') + .label('Name') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Name' + }), + nga.field('code') + .label('Code') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Code' + }), + nga.field('symbol') + .label('Symbol') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Symbol' + }), + nga.field('decimals') + .label('Decimals') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Decimals' + }), + nga.field('dec_point') + .label('Decimal Point') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Decimal Point' + }), + nga.field('thousands_sep') + .label('Thousand Separate') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Thousand Separate' + }), + nga.field('prefix') + .label('Prefix') + .attributes({ + placeholder: 'Prefix' + }), + nga.field('suffix') + .label('Suffix') + .attributes({ + placeholder: 'Suffix' + }), + nga.field('is_prefix_display_on_left', 'choice').label('Is prefix display on left?') + .validation({ + required: true + }) + .choices([{ + label: 'Yes', + value: 1 + }, { + label: 'No', + value: 0 + }]), + nga.field('is_use_graphic_symbol', 'choice').label('Is use graphic symbol?') + .validation({ + required: true + }) + .choices([{ + label: 'Yes', + value: 1 + }, { + label: 'No', + value: 0 + }]) + ]) + .onSubmitSuccess(['progression', 'notification', '$state', 'entry', 'entity', function (progression, notification, $state, entry, entity) { + progression.done(); + notification.log(entry.values.Success, {addnCls: 'humane-flatty-success'}); + $state.go($state.get('list'), {entity: entity.name()}); + return false; + }]) + .onSubmitError(['error', 'form', 'progression', 'notification', function (error, form, progression, notification) { + angular.forEach(error.data.errors, function (value, key) { + if (this[key]) { + this[key].$valid = false; + } + }, form); + progression.done(); + notification.log(error.data.message, {addnCls: 'humane-flatty-error'}); + return false; + }]); + + currencies.editionView().title('Edit Currency') + .fields([ + nga.field('name') + .label('Name') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Name' + }), + nga.field('code') + .label('Code') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Code' + }), + nga.field('symbol') + .label('Symbol') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Symbol' + }), + nga.field('decimals') + .label('Decimals') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Decimals' + }), + nga.field('dec_point') + .label('Decimal Point') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Decimal Point' + }), + nga.field('thousands_sep') + .label('Thousand Separate') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Thousand Separate' + }), + nga.field('prefix') + .label('Prefix') + .attributes({ + placeholder: 'Prefix' + }), + nga.field('suffix') + .label('Suffix') + .attributes({ + placeholder: 'Suffix' + }), + nga.field('is_prefix_display_on_left', 'choice').label('Is prefix display on left?') + .validation({ + required: true + }) + .choices([{ + label: 'Yes', + value: 1 + }, { + label: 'No', + value: 0 + }]), + nga.field('is_use_graphic_symbol', 'choice').label('Is use graphic symbol?') + .validation({ + required: true + }) + .choices([{ + label: 'Yes', + value: 1 + }, { + label: 'No', + value: 0 + }]), + nga.field('is_active', 'choice').label('Active?') + .validation({ + required: true + }) + .choices([{ + label: 'Yes', + value: 1 + }, { + label: 'No', + value: 0 + }]) + ]) + .onSubmitSuccess(['progression', 'notification', '$state', 'entry', 'entity', function (progression, notification, $state, entry, entity) { + progression.done(); + notification.log(entry.values.Success, {addnCls: 'humane-flatty-success'}); + $state.go($state.get('list'), {entity: entity.name()}); + return false; + }]) + .onSubmitError(['error', 'form', 'progression', 'notification', function (error, form, progression, notification) { + angular.forEach(error.data.errors, function (value, key) { + if (this[key]) { + this[key].$valid = false; + } + }, form); + progression.done(); + notification.log(error.data.message, {addnCls: 'humane-flatty-error'}); + return false; + }]); + + currencies.showView().title('View Currency') + .fields([ + nga.field('created_at').label('Created'), + nga.field('name').label('Name'), + nga.field('code').label('Code'), + nga.field('symbol').label('Symbol'), + nga.field('decimals').label('Decimals'), + nga.field('dec_point').label('Dec Point'), + nga.field('thousands_sep').label('Thousand Sep'), + nga.field('prefix').label('Prefix'), + nga.field('suffix').label('Suffix'), + nga.field('is_prefix_display_on_left', 'choice').label('Is prefix display on left?') + .choices([{ + label: 'Yes', + value: '1' + }, { + label: 'no', + value: '0' + }]), + nga.field('is_use_graphic_symbol', 'choice').label('Is use graphic symbol?') + .choices([{ + label: 'Yes', + value: '1' + }, { + label: 'No', + value: '0' + }]), + nga.field('is_active', 'boolean').label('Active?') + ]); + + var currency_conversions_custom_tmp = ''; + currency_conversions.listView().title('Currency Conversions') + .fields([ + nga.field('updated_at').label('Created'), + nga.field('currency.name').label('Currency'), + nga.field('converted_currency.name').label('Converted Currency'), + nga.field('rate', 'number').format('0.000000').label('Rate') + ]) + .perPage(limit_per_page) + .filters([ + nga.field('from_currency', 'reference') + .attributes({ + placeholder: 'From Currency' + }) + .targetEntity(nga.entity('currencies?type=list')) + .targetField(nga.field('name')) + .label('From Currency'), + nga.field('to_currency', 'reference') + .attributes({ + placeholder: 'Converted Currency' + }) + .targetEntity(nga.entity('currencies?type=list')) + .targetField(nga.field('name')) + .label('Converted Currency') + ]) + .batchActions([]) + .actions(['batch', currency_conversions_custom_tmp]); + + var currency_conversion_histories_custom_tmp = ''; + currency_conversion_histories.listView().title('Currency Conversion History') + .fields([ + nga.field('created_at').label('Created'), + nga.field('currency_conversion.currency.name').label('Currency'), + nga.field('currency_conversion.converted_currency.name').label('Converted Currency'), + nga.field('rate_before_change', 'number').format('0.00').label('Rate before change'), + nga.field('rate', 'number').format('0.00').label('Rate') + ]) + .perPage(limit_per_page) + .filters([ + nga.field('from_currency', 'reference') + .attributes({ + placeholder: 'From Currency' + }) + .targetEntity(nga.entity('currencies?type=list')) + .targetField(nga.field('name')) + .label('From Currency'), + nga.field('to_currency', 'reference') + .attributes({ + placeholder: 'Converted Currency' + }) + .targetEntity(nga.entity('currencies?type=list')) + .targetField(nga.field('name')) + .label('Converted Currency'), + nga.field('start_date', 'date').format("MM/dd/yyyy").attributes({'placeholder': 'Select From Date'}).label("From Date"), + nga.field('end_date', 'date').format("MM/dd/yyyy").attributes({'placeholder': 'Select To Date'}).label("To Date") + ]) + .batchActions([]) + .actions(['batch', currency_conversion_histories_custom_tmp]); + + var api_requests_custom_tmp = ''; + api_requests.listView().title('Api Requests') + .fields([ + nga.field('created_at').label('Created'), + nga.field('User.username').label('User'), + nga.field('path').label('Path').map(truncate), + nga.field('method').label('Request'), + nga.field('http_response_code').label('Response Code'), + nga.field('Ip.ip').label('IP') + ]) + .perPage(limit_per_page) + .listActions(['show', 'delete']) + .filters([ + nga.field('q').label('Search', 'template') + .pinned(true) + .template('
'), + nga.field('filter', 'choice').label('Request').attributes({ + placeholder: 'Select Request' + }) + .choices([{ + label: 'GET', + value: 'GET' + }, { + label: 'POST', + value: 'POST' + }, { + label: 'PUT', + value: 'PUT' + }, { + label: 'DELETE', + value: 'DELETE' + },]) + ]) + .actions(['batch', api_requests_custom_tmp]); + + // booking dispute related pages + var vehicle_dispute_types_custom_tmp = ''; + vehicle_dispute_types.listView().title('Rental Dispute Types') + .fields([ + nga.field('id').label('ID'), + nga.field('name').label('Name'), + nga.field('is_booker', 'boolean').label('Booker?'), + nga.field('is_active', 'boolean').label('Active?') + ]) + .perPage(limit_per_page) + .filters([ + nga.field('q').label('Search', 'template') + .pinned(true) + .template('
'), + nga.field('filter', 'choice').label('Status').attributes({ + placeholder: 'Status?' + }) + .choices([{ + label: 'Active', + value: 'active' + }, { + label: 'Inactive', + value: 'inactive' + }]) + ]) + .actions(['batch', vehicle_dispute_types_custom_tmp]); + vehicle_dispute_types.creationView() + .fields([ + nga.field('name').label('Name') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Name' + }), + nga.field('is_booker', 'choice').label('Booker?') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Booker?' + }) + .choices([{ + label: 'Yes', + value: true + }, { + label: 'No', + value: false + }]), + nga.field('is_active', 'choice').label('Active?') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Active?' + }) + .choices([{ + label: 'Yes', + value: true + }, { + label: 'No', + value: false + }]) + ]) + .onSubmitSuccess(['progression', 'notification', '$state', 'entry', 'entity', function (progression, notification, $state, entry, entity) { + progression.done(); + notification.log(entry.values.Success, {addnCls: 'humane-flatty-success'}); + $state.go($state.get('list'), {entity: entity.name()}); + return false; + }]) + .onSubmitError(['error', 'form', 'progression', 'notification', function (error, form, progression, notification) { + angular.forEach(error.data.errors, function (value, key) { + if (this[key]) { + this[key].$valid = false; + } + }, form); + progression.done(); + notification.log(error.data.message, {addnCls: 'humane-flatty-error'}); + return false; + }]); + // TODO: is_booker should not be edited. so edit function commented + /*vehicle_dispute_types.editionView() + .fields([ + nga.field('name') + .label('Name') + .validation({ + required: true + }), + nga.field('is_booker', 'choice').label('Booker?') + .validation({ + required: true + }) + .choices([{ + label: 'Yes', + value: true + }, { + label: 'No', + value: false + }]), + nga.field('is_active', 'choice').label('Active?') + .validation({ + required: true + }) + .choices([{ + label: 'Yes', + value: true + }, { + label: 'No', + value: false + }]) + ]) + .onSubmitSuccess(['progression', 'notification', '$state', 'entry', 'entity', function (progression, notification, $state, entry, entity) { + progression.done(); + notification.log(entry.values.Success, {addnCls: 'humane-flatty-success'}); + $state.go($state.get('list'), {entity: entity.name()}); + return false; + }]) + .onSubmitError(['error', 'form', 'progression', 'notification', function (error, form, progression, notification) { + angular.forEach(error.data.errors, function (value, key) { + if (this[key]) { + this[key].$valid = false; + } + }, form); + progression.done(); + notification.log(error.data.message, {addnCls: 'humane-flatty-error'}); + return false; + }]);*/ + + var vehicle_dispute_closed_types_custom_tmp = ''; + vehicle_dispute_closed_types.listView().title('Rental Dispute Closed Types') + .fields([ + nga.field('id').label('ID'), + nga.field('name').label('Name'), + nga.field('dispute_type.name').label('Dispute Type'), + nga.field('resolved_type').label('Resolve Type'), + nga.field('reason').label('Reason'), + nga.field('is_booker', 'boolean').label('Booker?') + ]) + .perPage(limit_per_page).filters([ + nga.field('q').label('Search', 'template') + .pinned(true) + .template('
'), + nga.field('filter', 'choice').label('User Type').attributes({ + placeholder: 'User Type?' + }) + .choices([{ + label: 'Is Booker', + value: 'booker' + }, { + label: 'Is Host', + value: 'host' + }]) + ]) + .batchActions([]) + .actions(['batch', vehicle_dispute_closed_types_custom_tmp]); + vehicle_dispute_closed_types.creationView() + .fields([ + nga.field('name').label('Name') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Name' + }), + nga.field('dispute_type_id', 'reference') + .label('Dispute Type') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Dispute Type' + }) + .targetEntity(nga.entity('vehicle_dispute_types')) + .perPage('all') // For getting all list + .targetField(nga.field('name').map(truncate)), + nga.field('resolved_type') + .label('Resolve Type') + .validation({ + required: true + }), + nga.field('reason') + .label('Reason') + .validation({ + required: true + }), + nga.field('is_booker', 'choice').label('Booker?') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Booker?' + }) + .choices([{ + label: 'Yes', + value: 1 + }, { + label: 'No', + value: 0 + }]) + ]) + .onSubmitSuccess(['progression', 'notification', '$state', 'entry', 'entity', function (progression, notification, $state, entry, entity) { + progression.done(); + notification.log(entry.values.Success, {addnCls: 'humane-flatty-success'}); + $state.go($state.get('list'), {entity: entity.name()}); + return false; + }]) + .onSubmitError(['error', 'form', 'progression', 'notification', function (error, form, progression, notification) { + angular.forEach(error.data.errors, function (value, key) { + if (this[key]) { + this[key].$valid = false; + } + }, form); + progression.done(); + notification.log(error.data.message, {addnCls: 'humane-flatty-error'}); + return false; + }]); + // TODO: is_booker should not be edited. so edit function commented + /*vehicle_dispute_closed_types.editionView() + .fields([ + nga.field('name') + .label('Name') + .validation({ + required: true + }), + nga.field('dispute_type_id', 'reference') + .label('Dispute Type') + .validation({ + required: true + }) + .targetEntity(nga.entity('vehicle_dispute_types')) + .perPage('all') // For getting all list + .targetField(nga.field('name').map(truncate)), + nga.field('resolved_type') + .label('Resolve Type') + .validation({ + required: true + }), + nga.field('reason') + .label('Reason') + .validation({ + required: true + }), + nga.field('is_booker', 'choice').label('Booker?') + .validation({ + required: true + }) + .choices([{ + label: 'Yes', + value: 1 + }, { + label: 'No', + value: 0 + }]) + ]) + .onSubmitSuccess(['progression', 'notification', '$state', 'entry', 'entity', function (progression, notification, $state, entry, entity) { + progression.done(); + notification.log(entry.values.Success, {addnCls: 'humane-flatty-success'}); + $state.go($state.get('list'), {entity: entity.name()}); + return false; + }]) + .onSubmitError(['error', 'form', 'progression', 'notification', function (error, form, progression, notification) { + angular.forEach(error.data.errors, function (value, key) { + if (this[key]) { + this[key].$valid = false; + } + }, form); + progression.done(); + notification.log(error.data.message, {addnCls: 'humane-flatty-error'}); + return false; + }]);*/ + // dispute listings + var vehicle_disputes_custom_tmp = ''; + var activity_custom_tmp = '' + vehicle_disputes.listView().title('Vehicle Disputes') + .fields([ + nga.field('created_at').label('Created'), + nga.field('user.username').label('User'), + nga.field('item_user_disputable.item_userable.name').label('Vehicle'), + nga.field('item_user_disputable.item_user_status.name').label('Status'), + nga.field('dispute_type.name').label('Dispute Type'), + nga.field('dispute_status.name').label('Dispute Status'), + nga.field('last_replied_date').label('Last Replied'), + nga.field('dispute_conversation_count').label('Conversation Count'), + nga.field('is_favor_booker').label('Favour to'), + nga.field('resolved_date').label('Resolved'), + ]) + .filters([ + nga.field('q').label('Search') + .pinned(true) + .template('
'), + nga.field('filter', 'choice').label('Status').attributes({ + placeholder: 'Status?' + }) + .choices([{ + label: 'Open', + value: 'Open' + }, { + label: 'Under Discussion', + value: 'Under Discussion' + }, { + label: 'Waiting Administrator Decision', + value: 'Waiting Administrator Decision' + }, { + label: 'Closed', + value: 'Closed' + }]) + + ]) + .actions([]) + .listActions(['']); + + api_requests.showView().title('View Api Request') + .fields([ + nga.field('created_at').label('Created'), + nga.field('User.username').label('User'), + nga.field('path').label('Path'), + nga.field('method').label('Request'), + nga.field('http_response_code').label('Response Code'), + nga.field('Ip.ip').label('IP') + ]); + + var vehicle_makes_custom_tmp = ''; + vehicle_makes.listView().title('Vehicle Makes') + .fields([ + nga.field('created_at').label('Created'), + nga.field('name').label('Name'), + nga.field('vehicle_count').label('Vehicle Count'), + nga.field('vehicle_model_count').label('Vehicle Model Count'), + nga.field('is_active', 'boolean').label('Active?') + ]) + .infinitePagination(false) + .perPage(limit_per_page) + .listActions(['delete', 'edit','show']) + .filters([ + nga.field('q').label('Search') + .pinned(true) + .template('
'), + nga.field('filter', 'choice').label('Status').attributes({ + placeholder: 'Status?' + }) + .choices([{ + label: 'Active', + value: 'active' + }, { + label: 'Inactive', + value: 'inactive' + },]) + ]) + .batchActions([]) + .actions(['create', 'batch', vehicle_makes_custom_tmp]); + vehicle_makes.creationView().title('Add Vehicle Make') + .fields([ + nga.field('name').label('Name') + .attributes({ + placeholder: 'Name' + }) + .validation({ + required: true + }), + nga.field('is_active', 'choice').label('Active?') + .attributes({ + placeholder: 'Active?' + }) + .validation({ + required: true + }) + .choices([{ + label: 'Yes', + value: 1 + }, { + label: 'No', + value: 0 + },]) + ]) + .onSubmitSuccess(['progression', 'notification', '$state', 'entry', 'entity', function (progression, notification, $state, entry, entity) { + progression.done(); + notification.log(entry.values.Success, {addnCls: 'humane-flatty-success'}); + $state.go($state.get('list'), {entity: entity.name()}); + return false; + }]) + .onSubmitError(['error', 'form', 'progression', 'notification', function (error, form, progression, notification) { + angular.forEach(error.data.errors, function (value, key) { + if (this[key]) { + this[key].$valid = false; + } + }, form); + progression.done(); + notification.log(error.data.message, {addnCls: 'humane-flatty-error'}); + return false; + }]); + + vehicle_makes.showView().title('View Vehicle Make') + .fields([ + nga.field('created_at').label('Created'), + nga.field('name').label('Name'), + nga.field('vehicle_count').label('Vehicle Count'), + nga.field('vehicle_model_count').label('Vehicle Model Count'), + nga.field('is_active','boolean').label('Active?'), + nga.field('', 'template').label('Related Vehicles') + .template(''), + ]); + + vehicle_makes.editionView().title('Edit Vehicle Make') + .fields([ + nga.field('name').label('Name'), + nga.field('is_active', 'choice').label('Active?') + .validation({ + required: true + }) + .choices([{ + label: 'Yes', + value: 1 + }, { + label: 'No', + value: 0 + },]) + ]) + .onSubmitSuccess(['progression', 'notification', '$state', 'entry', 'entity', function (progression, notification, $state, entry, entity) { + progression.done(); + notification.log(entry.values.Success, {addnCls: 'humane-flatty-success'}); + $state.go($state.get('list'), {entity: entity.name()}); + return false; + }]) + .onSubmitError(['error', 'form', 'progression', 'notification', function (error, form, progression, notification) { + angular.forEach(error.data.errors, function (value, key) { + if (this[key]) { + this[key].$valid = false; + } + }, form); + progression.done(); + notification.log(error.data.message, {addnCls: 'humane-flatty-error'}); + return false; + }]); + var vehicle_models_custom_tmp = ''; + vehicle_models.listView().title('Vehicle Models') + .fields([ + nga.field('created_at').label('Created'), + nga.field('name').label('Name'), + nga.field('vehicle_make.name').label('Vehicle Make'), + nga.field('vehicle_count').label('Vehicle Count'), + nga.field('is_active', 'boolean').label('Active?') + ]) + .infinitePagination(false) + .perPage(limit_per_page) + .listActions(['delete', 'edit','show']) + .filters([ + nga.field('q').label('Search') + .pinned(true) + .template('
'), + nga.field('filter', 'choice').label('Status').attributes({ + placeholder: 'Status?' + }) + .choices([{ + label: 'Active', + value: 'active' + }, { + label: 'Inactive', + value: 'inactive' + },]) + ]) + .batchActions([]) + .actions(['create', 'batch', vehicle_models_custom_tmp]); + + vehicle_models.showView().title('View Vehicle Model') + .fields([ + nga.field('created_at').label('Created'), + nga.field('name').label('Name'), + nga.field('vehicle_make.name').label('Vehicle Make'), + nga.field('vehicle_count').label('Vehicle Count'), + nga.field('is_active','boolean').label('Active?'), + nga.field('', 'template').label('Related Vehicles') + .template(''), + ]); + + vehicle_models.creationView().title('Add Vehicle Model') + .fields([ + nga.field('name').label('Name') + .attributes({ + placeholder: 'Name' + }) + .validation({ + required: true + }), + nga.field('vehicle_make_id', 'reference') + .label('Vehicle Make') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Vehicle Make' + }) + .targetEntity(nga.entity('vehicle_makes?filter=active')) + .perPage('all') + .targetField(nga.field('name').map(truncate)), + nga.field('is_active', 'choice').label('Active?') + .attributes({ + placeholder: 'Active?' + }) + .validation({ + required: true + }) + .choices([{ + label: 'Yes', + value: 1 + }, { + label: 'No', + value: 0 + },]) + ]) + .onSubmitSuccess(['progression', 'notification', '$state', 'entry', 'entity', function (progression, notification, $state, entry, entity) { + progression.done(); + notification.log(entry.values.Success, {addnCls: 'humane-flatty-success'}); + $state.go($state.get('list'), {entity: entity.name()}); + return false; + }]) + .onSubmitError(['error', 'form', 'progression', 'notification', function (error, form, progression, notification) { + angular.forEach(error.data.errors, function (value, key) { + if (this[key]) { + this[key].$valid = false; + } + }, form); + progression.done(); + notification.log(error.data.message, {addnCls: 'humane-flatty-error'}); + return false; + }]); + vehicle_models.editionView().title('Edit Vehicle Model') + .fields([ + nga.field('name').label('Name'), + nga.field('vehicle_make_id', 'reference') + .label('Vehicle Make') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Vehicle Make' + }) + .targetEntity(nga.entity('vehicle_makes')) + .perPage('all') + .targetField(nga.field('name').map(truncate)), + nga.field('is_active', 'choice').label('Active?') + .validation({ + required: true + }) + .choices([{ + label: 'Yes', + value: 1 + }, { + label: 'No', + value: 0 + },]) + ]) + .onSubmitSuccess(['progression', 'notification', '$state', 'entry', 'entity', function (progression, notification, $state, entry, entity) { + progression.done(); + notification.log(entry.values.Success, {addnCls: 'humane-flatty-success'}); + $state.go($state.get('list'), {entity: entity.name()}); + return false; + }]) + .onSubmitError(['error', 'form', 'progression', 'notification', function (error, form, progression, notification) { + angular.forEach(error.data.errors, function (value, key) { + if (this[key]) { + this[key].$valid = false; + } + }, form); + progression.done(); + notification.log(error.data.message, {addnCls: 'humane-flatty-error'}); + return false; + }]); + + var vehicle_types_custom_tmp = ''; + vehicle_types.listView().title('Vehicle Types') + .fields([ + nga.field('created_at').label('Created'), + nga.field('name').label('Name'), + nga.field('minimum_hour_price', 'number').format('0.00').label('Minimum Hour Price'), + nga.field('maximum_hour_price', 'number').format('0.00').label('Maximum Hour Price'), + nga.field('minimum_day_price', 'number').format('0.00').label('Minimum Day Price'), + nga.field('maximum_day_price', 'number').format('0.00').label('Maximum Day Price'), + nga.field('drop_location_differ_unit_price', 'number').format('0.00').label('Drop location differ unit price'), + nga.field('drop_location_differ_additional_fee', 'number').format('0.00').label('Drop location additional fee'), + nga.field('deposit_amount', 'number').format('0.00').label('Deposit Amount(' + siteCurrency + ')'), + nga.field('vehicle_count').label('Vehicle Count'), + nga.field('is_active', 'boolean').label('Active?') + ]) + .infinitePagination(false) + .perPage(limit_per_page) + .listActions(['show', 'edit', 'delete']) + .filters([ + nga.field('q').label('Search') + .pinned(true) + .template('
'), + nga.field('filter', 'choice').label('Status').attributes({ + placeholder: 'Status?' + }) + .choices([{ + label: 'Active', + value: 'active' + }, { + label: 'Inactive', + value: 'inactive' + },]) + ]) + .batchActions([]) + .actions(['create', 'batch', vehicle_types_custom_tmp]); + + vehicle_types.showView().title('View Vehicle Type') + .fields([ + nga.field('created_at').label('Created'), + nga.field('name').label('Name'), + nga.field('minimum_hour_price', 'number').format('0.00').label('Minimum Hour Price(' + siteCurrency + ')'), + nga.field('maximum_hour_price', 'number').format('0.00').label('Maximum Hour Price(' + siteCurrency + ')'), + nga.field('minimum_day_price', 'number').format('0.00').label('Minimum Day Price(' + siteCurrency + ')'), + nga.field('maximum_day_price', 'number').format('0.00').label('Maximum Day Price(' + siteCurrency + ')'), + nga.field('drop_location_differ_unit_price', 'number').format('0.00').label('Drop location differ unit price(' + siteCurrency + ')'), + nga.field('drop_location_differ_additional_fee', 'number').format('0.00').label('Drop location additional fee(' + siteCurrency + ')'), + nga.field('deposit_amount', 'number').format('0.00').label('Deposit Amount(' + siteCurrency + ')'), + nga.field('vehicle_count','number').label('Vehicle Count'), + nga.field('is_active', 'boolean').label('Active?'), + nga.field('Discount Prices', 'referenced_list') + .targetEntity(nga.entity('vehicle_type_prices')) + .targetReferenceField('vehicle_type_id') + .targetFields([ + nga.field('created_at').label('Created'), + nga.field('minimum_no_of_day').label('Rental Min no of day'), + nga.field('maximum_no_of_day').label('Rental Max no of day'), + nga.field('discount_percentage', 'number').format('0.00').label('Discount(%)'), + nga.field('is_active', 'boolean').label('Active?') + ]), + nga.field('Special Prices', 'referenced_list') + .targetEntity(nga.entity('vehicle_special_prices')) + .targetReferenceField('vehicle_type_id') + .targetFields([ + nga.field('created_at').label('Created'), + nga.field('start_date').label('Start Date'), + nga.field('end_date').label('End Date'), + nga.field('discount_percentage', 'number').format('0.00').label('Discount(%)'), + nga.field('is_active', 'boolean').label('Active?') + ]), + nga.field('', 'template').label('Related Vehicles') + .template(''), + ]) + vehicle_types.editionView().title('Edit Vehicle Type') + .fields([ + nga.field('name').label('Name') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Name' + }), + nga.field('minimum_hour_price').label('Minimum Hour Price(' + siteCurrency + ')') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Minimum Hour Price' + }), + nga.field('maximum_hour_price').label('Maximum Hour Price(' + siteCurrency + ')') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Maximum Hour Price' + }), + nga.field('minimum_day_price').label('Minimum Day Price(' + siteCurrency + ')') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Minimum Day Price' + }), + nga.field('maximum_day_price').label('Maximum Day Price(' + siteCurrency + ')') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Maximum Day Price' + }), + nga.field('drop_location_differ_unit_price').label('Drop location differ unit price(' + siteCurrency + ')') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Drop location differ unit price' + }), + nga.field('drop_location_differ_additional_fee').label('Drop location additional fee(' + siteCurrency + ')') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Drop location additional fee' + }), + nga.field('deposit_amount').label('Deposit Amount(' + siteCurrency + ')') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Deposit Amount' + }), + nga.field('is_active', 'choice').label('Active?') + .validation({ + required: true + }) + .choices([{ + label: 'Yes', + value: 1 + }, { + label: 'No', + value: 0 + },]) + ]) + .onSubmitSuccess(['progression', 'notification', '$state', 'entry', 'entity', function (progression, notification, $state, entry, entity) { + progression.done(); + notification.log(entry.values.Success, {addnCls: 'humane-flatty-success'}); + $state.go($state.get('list'), {entity: entity.name()}); + return false; + }]) + .onSubmitError(['error', 'form', 'progression', 'notification', function (error, form, progression, notification) { + angular.forEach(error.data.errors, function (value, key) { + if (this[key]) { + this[key].$valid = false; + } + }, form); + progression.done(); + notification.log(error.data.message, {addnCls: 'humane-flatty-error'}); + return false; + }]); + + vehicle_types.creationView().title('Add Vehicle Type') + .fields([ + nga.field('name').label('Name') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Name' + }), + nga.field('minimum_hour_price').label('Minimum Hour Price(' + siteCurrency + ')') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Minimum Hour Price' + }), + nga.field('maximum_hour_price').label('Maximum Hour Price(' + siteCurrency + ')') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Maximum Hour Price' + }), + nga.field('minimum_day_price').label('Minimum Day Price(' + siteCurrency + ')') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Minimum Day Price' + }), + nga.field('maximum_day_price').label('Maximum Day Price(' + siteCurrency + ')') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Maximum Day Price' + }), + nga.field('drop_location_differ_unit_price').label('Drop location differ unit price(' + siteCurrency + ')') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Drop location differ unit price' + }), + nga.field('drop_location_differ_additional_fee').label('Drop location additional fee(' + siteCurrency + ')') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Drop location additional fee' + }), + nga.field('deposit_amount').label('Deposit Amount(' + siteCurrency + ')') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Deposit Amount' + }), + nga.field('is_active', 'choice').label('Active?') + .attributes({ + placeholder: 'Active?' + }) + .validation({ + required: true + }) + .choices([{ + label: 'Yes', + value: 1 + }, { + label: 'No', + value: 0 + },]) + ]) + .onSubmitSuccess(['progression', 'notification', '$state', 'entry', 'entity', function (progression, notification, $state, entry, entity) { + progression.done(); + notification.log(entry.values.Success, {addnCls: 'humane-flatty-success'}); + $state.go($state.get('list'), {entity: entity.name()}); + return false; + }]) + .onSubmitError(['error', 'form', 'progression', 'notification', function (error, form, progression, notification) { + angular.forEach(error.data.errors, function (value, key) { + if (this[key]) { + this[key].$valid = false; + } + }, form); + progression.done(); + notification.log(error.data.message, {addnCls: 'humane-flatty-error'}); + return false; + }]); + + var vehicle_taxes_custom_tmp = ''; + vehicle_taxes.listView().title('Taxes') + .fields([ + nga.field('created_at').label('Created'), + nga.field('name','wysiwyg').label('Name').map(truncate), + nga.field('short_description','wysiwyg').label('Short Description').map(truncate), + nga.field('is_active', 'boolean').label('Active?') + ]) + .infinitePagination(false) + .perPage(limit_per_page) + .listActions(['show', 'edit', 'delete']) + .filters([ + nga.field('q').label('Search') + .pinned(true) + .template('
'), + nga.field('filter', 'choice').label('Status').attributes({ + placeholder: 'Status?' + }) + .choices([{ + label: 'Active', + value: 'active' + }, { + label: 'Inactive', + value: 'inactive' + },]) + ]) + .batchActions([]) + .actions(['create', 'batch', vehicle_taxes_custom_tmp]); + vehicle_taxes.showView().title('View Tax') + .fields([ + nga.field('created_at').label('Created'), + nga.field('name').label('Name'), + nga.field('short_description').label('Short Description'), + nga.field('description', 'wysiwyg').label('Description'), + nga.field('is_active', 'boolean').label('Active?') + ]); + vehicle_taxes.creationView().title('Add Tax') + .fields([ + nga.field('name').label('Name') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Name' + }), + nga.field('short_description', 'text').label('Short Description') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Short Description' + }), + nga.field('description', 'wysiwyg').label('Description') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Short Description' + }), + nga.field('is_active', 'choice').label('Active?') + .attributes({ + placeholder: 'Active?' + }) + .validation({ + required: true + }) + .choices([{ + label: 'Yes', + value: 1 + }, { + label: 'No', + value: 0 + },]) + ]) + .onSubmitSuccess(['progression', 'notification', '$state', 'entry', 'entity', function (progression, notification, $state, entry, entity) { + progression.done(); + notification.log(entry.values.Success, {addnCls: 'humane-flatty-success'}); + $state.go($state.get('list'), {entity: entity.name()}); + return false; + }]) + .onSubmitError(['error', 'form', 'progression', 'notification', function (error, form, progression, notification) { + angular.forEach(error.data.errors, function (value, key) { + if (this[key]) { + this[key].$valid = false; + } + }, form); + progression.done(); + notification.log(error.data.message, {addnCls: 'humane-flatty-error'}); + return false; + }]); + + vehicle_taxes.editionView().title('Edit Tax') + .fields([ + nga.field('name').label('Name') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Name' + }), + nga.field('short_description', 'text').label('Short Description') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Short Description' + }), + nga.field('description', 'wysiwyg').label('Description') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Short Description' + }), + nga.field('is_active', 'choice').label('Active?') + .attributes({ + placeholder: 'Active?' + }) + .validation({ + required: true + }) + .choices([{ + label: 'Yes', + value: true + }, { + label: 'No', + value: false + },]) + ]) + .onSubmitSuccess(['progression', 'notification', '$state', 'entry', 'entity', function (progression, notification, $state, entry, entity) { + progression.done(); + notification.log(entry.values.Success, {addnCls: 'humane-flatty-success'}); + $state.go($state.get('list'), {entity: entity.name()}); + return false; + }]) + .onSubmitError(['error', 'form', 'progression', 'notification', function (error, form, progression, notification) { + angular.forEach(error.data.errors, function (value, key) { + if (this[key]) { + this[key].$valid = false; + } + }, form); + progression.done(); + notification.log(error.data.message, {addnCls: 'humane-flatty-error'}); + return false; + }]); + + var vehicle_type_taxes_custom_tmp = ''; + vehicle_type_taxes.listView().title('Vehicle Type Taxes') + .fields([ + nga.field('created_at').label('Created'), + nga.field('vehicle_type.name').label('Vehicle Type'), + nga.field('vehicle_tax.name','wysiwyg').label('Tax'), + nga.field('rate', 'number').format('0.00').label('Rate'), + nga.field('discount_type.type').label('Type(' + siteCurrency + '/%)'), + nga.field('duration_type.name').label('Duration Type'), + nga.field('max_allowed_amount', 'number').format('0.00').label('Max Amount Allowed(' + siteCurrency + ')'), + nga.field('is_active', 'boolean').label('Active?') + ]) + .infinitePagination(false) + .perPage(limit_per_page) + .listActions(['edit', 'delete']) + .filters([ + nga.field('q').label('Search') + .pinned(true) + .template('
'), + nga.field('filter', 'choice').label('Status').attributes({ + placeholder: 'Status?' + }) + .choices([{ + label: 'Active', + value: 'active' + }, { + label: 'Inactive', + value: 'inactive' + },]) + ]) + .batchActions([]) + .actions(['create', 'batch', vehicle_type_taxes_custom_tmp]); + + vehicle_type_taxes.creationView().title('Add Vehicle Type Tax') + .fields([ + nga.field('vehicle_type_id', 'reference') + .label('Vehicle Type') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Vehicle Type' + }) + .targetEntity(nga.entity('vehicle_types')) + .perPage('all') + .targetField(nga.field('name').map(truncate)), + nga.field('tax_id', 'reference') + .label('Tax') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Tax' + }) + .perPage('all') + .targetEntity(nga.entity('vehicle_taxes')) + .targetField(nga.field('name').map(truncate)), + nga.field('rate').label('Rate') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Rate' + }), + nga.field('max_allowed_amount').label('Maximum amount allowed(' + siteCurrency + ')') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Maximum amount allowed' + }), + nga.field('discount_type_id', 'choice').label('Tax Type(' + siteCurrency + '/%)') + .choices([{ + label: 'Percentage', + value: '1' + }, { + label: 'Amount', + value: '2' + }]) + .attributes({ + placeholder: 'Tax Type' + }) + .validation({ + required: true + }), + nga.field('duration_type_id', 'choice').label('Duration Type') + .choices([{ + label: 'Per day', + value: '1' + }, { + label: 'Per rental', + value: '2' + }]) + .attributes({ + placeholder: 'Duration Type' + }) + .validation({ + required: true + }), + nga.field('is_active', 'choice').label('Active?') + .attributes({ + placeholder: 'Active?' + }) + .validation({ + required: true + }) + .choices([{ + label: 'Yes', + value: true + }, { + label: 'No', + value: false + },]) + ]) + .onSubmitSuccess(['progression', 'notification', '$state', 'entry', 'entity', function (progression, notification, $state, entry, entity) { + progression.done(); + notification.log(entry.values.Success, {addnCls: 'humane-flatty-success'}); + $state.go($state.get('list'), {entity: entity.name()}); + return false; + }]) + .onSubmitError(['error', 'form', 'progression', 'notification', function (error, form, progression, notification) { + angular.forEach(error.data.errors, function (value, key) { + if (this[key]) { + this[key].$valid = false; + } + }, form); + progression.done(); + notification.log(error.data.message, {addnCls: 'humane-flatty-error'}); + return false; + }]); + + vehicle_type_taxes.editionView().title('Edit Vehicle Type Tax') + .fields([ + nga.field('vehicle_type_id', 'reference') + .label('Vehicle Type') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Vehicle Type' + }) + .targetEntity(nga.entity('vehicle_types')) + .perPage('all') + .targetField(nga.field('name').map(truncate)), + nga.field('tax_id', 'reference') + .label('Tax') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Tax' + }) + .perPage('all') + .targetEntity(nga.entity('vehicle_taxes')) + .targetField(nga.field('name').map(truncate)), + nga.field('rate').label('Rate') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Rate' + }), + nga.field('max_allowed_amount').label('Maximum amount allowed(' + siteCurrency + ')') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Maximum amount allowed' + }), + nga.field('discount_type_id', 'choice').label('Tax Type(' + siteCurrency + '/%)') + .choices([{ + label: 'Percentage', + value: '1' + }, { + label: 'Amount', + value: '2' + }]) + .attributes({ + placeholder: 'Tax Type' + }) + .validation({ + required: true + }), + nga.field('duration_type_id', 'choice').label('Duration Type') + .choices([{ + label: 'Per day', + value: '1' + }, { + label: 'Per rental', + value: '2' + }]) + .attributes({ + placeholder: 'Duration Type' + }) + .validation({ + required: true + }), + nga.field('is_active', 'choice').label('Active?') + .attributes({ + placeholder: 'Active?' + }) + .validation({ + required: true + }) + .choices([{ + label: 'Yes', + value: true + }, { + label: 'No', + value: false + },]) + ]) + .onSubmitSuccess(['progression', 'notification', '$state', 'entry', 'entity', function (progression, notification, $state, entry, entity) { + progression.done(); + notification.log(entry.values.Success, {addnCls: 'humane-flatty-success'}); + $state.go($state.get('list'), {entity: entity.name()}); + return false; + }]) + .onSubmitError(['error', 'form', 'progression', 'notification', function (error, form, progression, notification) { + angular.forEach(error.data.errors, function (value, key) { + if (this[key]) { + this[key].$valid = false; + } + }, form); + progression.done(); + notification.log(error.data.message, {addnCls: 'humane-flatty-error'}); + return false; + }]); + + var vehicle_insurances_custom_tmp = ''; + vehicle_insurances.listView().title('Insurance') + .fields([ + nga.field('created_at').label('Created'), + nga.field('name','wysiwyg').label('Name').map(truncate), + nga.field('short_description','wysiwyg').label('Short Description').map(truncate), + nga.field('is_active', 'boolean').label('Active?') + ]) + .infinitePagination(false) + .perPage(limit_per_page) + .listActions(['show', 'edit', 'delete']) + .filters([ + nga.field('q').label('Search') + .pinned(true) + .template('
'), + nga.field('filter', 'choice').label('Status').attributes({ + placeholder: 'Status?' + }) + .choices([{ + label: 'Active', + value: 'active' + }, { + label: 'Inactive', + value: 'inactive' + },]) + ]) + .batchActions([]) + .actions(['create', 'batch', vehicle_insurances_custom_tmp]); + vehicle_insurances.showView().title('View Insurance') + .fields([ + nga.field('created_at').label('Created'), + nga.field('name').label('Name'), + nga.field('short_description').label('Short Description'), + nga.field('description', 'wysiwyg').label('Description'), + nga.field('is_active', 'boolean').label('Active?') + ]); + vehicle_insurances.creationView().title('Add Insurance') + .fields([ + nga.field('name').label('Name') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Name' + }), + nga.field('short_description', 'text').label('Short Description') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Short Description' + }), + nga.field('description', 'wysiwyg').label('Description') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Short Description' + }), + nga.field('is_active', 'choice').label('Active?') + .attributes({ + placeholder: 'Active?' + }) + .validation({ + required: true + }) + .choices([{ + label: 'Yes', + value: 1 + }, { + label: 'No', + value: 0 + },]) + ]) + .onSubmitSuccess(['progression', 'notification', '$state', 'entry', 'entity', function (progression, notification, $state, entry, entity) { + progression.done(); + notification.log(entry.values.Success, {addnCls: 'humane-flatty-success'}); + $state.go($state.get('list'), {entity: entity.name()}); + return false; + }]) + .onSubmitError(['error', 'form', 'progression', 'notification', function (error, form, progression, notification) { + angular.forEach(error.data.errors, function (value, key) { + if (this[key]) { + this[key].$valid = false; + } + }, form); + progression.done(); + notification.log(error.data.message, {addnCls: 'humane-flatty-error'}); + return false; + }]); + + vehicle_insurances.editionView().title('Edit Insurance') + .fields([ + nga.field('name').label('Name') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Name' + }), + nga.field('short_description', 'text').label('Short Description') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Short Description' + }), + nga.field('description', 'wysiwyg').label('Description') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Short Description' + }), + nga.field('is_active', 'choice').label('Active?') + .attributes({ + placeholder: 'Active?' + }) + .validation({ + required: true + }) + .choices([{ + label: 'Yes', + value: true + }, { + label: 'No', + value: false + },]) + ]) + .onSubmitSuccess(['progression', 'notification', '$state', 'entry', 'entity', function (progression, notification, $state, entry, entity) { + progression.done(); + notification.log(entry.values.Success, {addnCls: 'humane-flatty-success'}); + $state.go($state.get('list'), {entity: entity.name()}); + return false; + }]) + .onSubmitError(['error', 'form', 'progression', 'notification', function (error, form, progression, notification) { + angular.forEach(error.data.errors, function (value, key) { + if (this[key]) { + this[key].$valid = false; + } + }, form); + progression.done(); + notification.log(error.data.message, {addnCls: 'humane-flatty-error'}); + return false; + }]); + + var vehicle_type_surcharges_custom_tmp = ''; + vehicle_type_surcharges.listView().title('Vehicle Type Surcharges') + .fields([ + nga.field('created_at').label('Created'), + nga.field('vehicle_type.name').label('Vehicle Type'), + nga.field('vehicle_surcharge.name','wysiwyg').label('Surcharge'), + nga.field('rate', 'number').format('0.00').label('Rate'), + nga.field('discount_type.type').label('Type(' + siteCurrency + '/%)'), + nga.field('duration_type.name').label('Duration Type'), + nga.field('max_allowed_amount', 'number').format('0.00').label('Max Amount Allowed(' + siteCurrency + ')'), + nga.field('is_active', 'boolean').label('Active?') + ]) + .infinitePagination(false) + .perPage(limit_per_page) + .listActions(['edit', 'delete']) + .filters([ + nga.field('q').label('Search') + .pinned(true) + .template('
'), + nga.field('filter', 'choice').label('Status').attributes({ + placeholder: 'Status?' + }) + .choices([{ + label: 'Active', + value: 'active' + }, { + label: 'Inactive', + value: 'inactive' + },]) + ]) + .batchActions([]) + .actions(['create', 'batch', vehicle_type_surcharges_custom_tmp]); + + vehicle_type_surcharges.creationView().title('Add Vehicle Type Surcharge') + .fields([ + nga.field('vehicle_type_id', 'reference') + .label('Vehicle Type') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Vehicle Type' + }) + .targetEntity(nga.entity('vehicle_types')) + .perPage('all') + .targetField(nga.field('name').map(truncate)), + nga.field('surcharge_id', 'reference') + .label('Surcharge') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Surcharge' + }) + .perPage('all') + .targetEntity(nga.entity('vehicle_surcharges')) + .targetField(nga.field('name').map(truncate)), + nga.field('rate').label('Rate') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Rate' + }), + nga.field('max_allowed_amount').label('Maximum amount allowed(' + siteCurrency + ')') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Maximum amount allowed' + }), + nga.field('discount_type_id', 'choice').label('Surcharge Type(' + siteCurrency + '/%)') + .choices([{ + label: 'Percentage', + value: '1' + }, { + label: 'Amount', + value: '2' + }]) + .attributes({ + placeholder: 'Surcharge Type' + }) + .validation({ + required: true + }), + nga.field('duration_type_id', 'choice').label('Duration Type') + .choices([{ + label: 'Per day', + value: '1' + }, { + label: 'Per rental', + value: '2' + }]) + .attributes({ + placeholder: 'Duration Type' + }) + .validation({ + required: true + }), + nga.field('is_active', 'choice').label('Active?') + .attributes({ + placeholder: 'Active?' + }) + .validation({ + required: true + }) + .choices([{ + label: 'Yes', + value: 1 + }, { + label: 'No', + value: 0 + },]) + ]) + .onSubmitSuccess(['progression', 'notification', '$state', 'entry', 'entity', function (progression, notification, $state, entry, entity) { + progression.done(); + notification.log(entry.values.Success, {addnCls: 'humane-flatty-success'}); + $state.go($state.get('list'), {entity: entity.name()}); + return false; + }]) + .onSubmitError(['error', 'form', 'progression', 'notification', function (error, form, progression, notification) { + angular.forEach(error.data.errors, function (value, key) { + if (this[key]) { + this[key].$valid = false; + } + }, form); + progression.done(); + notification.log(error.data.message, {addnCls: 'humane-flatty-error'}); + return false; + }]); + + vehicle_type_surcharges.editionView().title('Edit Vehicle Type Surcharge') + .fields([ + nga.field('vehicle_type_id', 'reference') + .label('Vehicle Type') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Vehicle Type' + }) + .targetEntity(nga.entity('vehicle_types')) + .perPage('all') + .targetField(nga.field('name').map(truncate)), + nga.field('surcharge_id', 'reference') + .label('Surcharge') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Surcharge' + }) + .perPage('all') + .targetEntity(nga.entity('vehicle_surcharges')) + .targetField(nga.field('name').map(truncate)), + nga.field('rate').label('Rate') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Rate' + }), + nga.field('max_allowed_amount').label('Maximum amount allowed(' + siteCurrency + ')') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Maximum amount allowed' + }), + nga.field('discount_type_id', 'choice').label('Surcharge Type(' + siteCurrency + '/%)') + .choices([{ + label: 'Percentage', + value: '1' + }, { + label: 'Amount', + value: '2' + }]) + .attributes({ + placeholder: 'Surcharge Type' + }) + .validation({ + required: true + }), + nga.field('duration_type_id', 'choice').label('Duration Type') + .choices([{ + label: 'Per day', + value: '1' + }, { + label: 'Per rental', + value: '2' + }]) + .attributes({ + placeholder: 'Duration Type' + }) + .validation({ + required: true + }), + nga.field('is_active', 'choice').label('Active?') + .attributes({ + placeholder: 'Active?' + }) + .validation({ + required: true + }) + .choices([{ + label: 'Yes', + value: 1 + }, { + label: 'No', + value: 0 + },]) + ]) + .onSubmitSuccess(['progression', 'notification', '$state', 'entry', 'entity', function (progression, notification, $state, entry, entity) { + progression.done(); + notification.log(entry.values.Success, {addnCls: 'humane-flatty-success'}); + $state.go($state.get('list'), {entity: entity.name()}); + return false; + }]) + .onSubmitError(['error', 'form', 'progression', 'notification', function (error, form, progression, notification) { + angular.forEach(error.data.errors, function (value, key) { + if (this[key]) { + this[key].$valid = false; + } + }, form); + progression.done(); + notification.log(error.data.message, {addnCls: 'humane-flatty-error'}); + return false; + }]); + + var vehicle_surcharges_custom_tmp = ''; + vehicle_surcharges.listView().title('Surcharges') + .fields([ + nga.field('created_at').label('Created'), + nga.field('name','wysiwyg').label('Name').map(truncate), + nga.field('short_description','wysiwyg').label('Short Description').map(truncate), + nga.field('is_active', 'boolean').label('Active?') + ]) + .infinitePagination(false) + .perPage(limit_per_page) + .listActions(['show', 'edit', 'delete']) + .filters([ + nga.field('q').label('Search') + .pinned(true) + .template('
'), + nga.field('filter', 'choice').label('Status').attributes({ + placeholder: 'Status?' + }) + .choices([{ + label: 'Active', + value: 'active' + }, { + label: 'Inactive', + value: 'inactive' + },]) + ]) + .batchActions([]) + .actions(['create', 'batch', vehicle_surcharges_custom_tmp]); + vehicle_surcharges.showView().title('View Surcharge') + .fields([ + nga.field('created_at').label('Created'), + nga.field('name','wysiwyg').label('Name'), + nga.field('short_description','wysiwyg').label('Short Description'), + nga.field('description', 'wysiwyg').label('Description'), + nga.field('is_active', 'boolean').label('Active?') + ]); + vehicle_surcharges.creationView().title('Add Surcharge') + .fields([ + nga.field('name').label('Name') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Name' + }), + nga.field('short_description', 'text').label('Short Description') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Short Description' + }), + nga.field('description', 'wysiwyg').label('Description') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Short Description' + }), + nga.field('is_active', 'choice').label('Active?') + .attributes({ + placeholder: 'Active?' + }) + .validation({ + required: true + }) + .choices([{ + label: 'Yes', + value: 1 + }, { + label: 'No', + value: 0 + },]) + ]) + .onSubmitSuccess(['progression', 'notification', '$state', 'entry', 'entity', function (progression, notification, $state, entry, entity) { + progression.done(); + notification.log(entry.values.Success, {addnCls: 'humane-flatty-success'}); + $state.go($state.get('list'), {entity: entity.name()}); + return false; + }]) + .onSubmitError(['error', 'form', 'progression', 'notification', function (error, form, progression, notification) { + angular.forEach(error.data.errors, function (value, key) { + if (this[key]) { + this[key].$valid = false; + } + }, form); + progression.done(); + notification.log(error.data.message, {addnCls: 'humane-flatty-error'}); + return false; + }]); + + vehicle_surcharges.editionView().title('Edit Surcharge') + .fields([ + nga.field('name').label('Name') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Name' + }), + nga.field('short_description', 'text').label('Short Description') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Short Description' + }), + nga.field('description', 'wysiwyg').label('Description') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Short Description' + }), + nga.field('is_active', 'choice').label('Active?') + .attributes({ + placeholder: 'Active?' + }) + .validation({ + required: true + }) + .choices([{ + label: 'Yes', + value: true + }, { + label: 'No', + value: false + },]) + ]) + .onSubmitSuccess(['progression', 'notification', '$state', 'entry', 'entity', function (progression, notification, $state, entry, entity) { + progression.done(); + notification.log(entry.values.Success, {addnCls: 'humane-flatty-success'}); + $state.go($state.get('list'), {entity: entity.name()}); + return false; + }]) + .onSubmitError(['error', 'form', 'progression', 'notification', function (error, form, progression, notification) { + angular.forEach(error.data.errors, function (value, key) { + if (this[key]) { + this[key].$valid = false; + } + }, form); + progression.done(); + notification.log(error.data.message, {addnCls: 'humane-flatty-error'}); + return false; + }]); + + var vehicle_type_insurances_custom_tmp = ''; + vehicle_type_insurances.listView().title('Vehicle Type Insurances') + .fields([ + nga.field('created_at').label('Created'), + nga.field('vehicle_type.name').label('Vehicle Type'), + nga.field('vehicle_insurance.name','wysiwyg').label('Insurance'), + nga.field('rate', 'number').format('0.00').label('Rate'), + nga.field('discount_type.type').label('Type(' + siteCurrency + '/%)'), + nga.field('duration_type.name').label('Duration Type'), + nga.field('max_allowed_amount', 'number').format('0.00').label('Max Amount Allowed(' + siteCurrency + ')'), + nga.field('is_active', 'boolean').label('Active?') + ]) + .infinitePagination(false) + .perPage(limit_per_page) + .listActions(['edit', 'delete']) + .filters([ + nga.field('q').label('Search') + .pinned(true) + .template('
'), + nga.field('filter', 'choice').label('Status').attributes({ + placeholder: 'Status?' + }) + .choices([{ + label: 'Active', + value: 'active' + }, { + label: 'Inactive', + value: 'inactive' + },]) + ]) + .batchActions([]) + .actions(['create', 'batch', vehicle_type_insurances_custom_tmp]); + + vehicle_type_insurances.creationView().title('Add Vehicle Type Insurance') + .fields([ + nga.field('vehicle_type_id', 'reference') + .label('Vehicle Type') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Vehicle Type' + }) + .targetEntity(nga.entity('vehicle_types')) + .perPage('all') + .targetField(nga.field('name').map(truncate)), + nga.field('insurance_id', 'reference') + .label('Insurance') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Insurance' + }) + .perPage('all') + .targetEntity(nga.entity('vehicle_insurances')) + .targetField(nga.field('name').map(truncate)), + nga.field('rate').label('Rate') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Rate' + }), + nga.field('max_allowed_amount').label('Maximum amount allowed(' + siteCurrency + ')') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Maximum amount allowed' + }), + nga.field('discount_type_id', 'choice').label('Insurance Type(' + siteCurrency + '/%)') + .choices([{ + label: 'Percentage', + value: '1' + }, { + label: 'Amount', + value: '2' + }]) + .attributes({ + placeholder: 'Insurance Type' + }) + .validation({ + required: true + }), + nga.field('duration_type_id', 'choice').label('Duration Type') + .choices([{ + label: 'Per day', + value: '1' + }, { + label: 'Per rental', + value: '2' + }]) + .attributes({ + placeholder: 'Duration Type' + }) + .validation({ + required: true + }), + nga.field('is_active', 'choice').label('Active?') + .attributes({ + placeholder: 'Active?' + }) + .validation({ + required: true + }) + .choices([{ + label: 'Yes', + value: 1 + }, { + label: 'No', + value: 0 + },]) + ]) + .onSubmitSuccess(['progression', 'notification', '$state', 'entry', 'entity', function (progression, notification, $state, entry, entity) { + progression.done(); + notification.log(entry.values.Success, {addnCls: 'humane-flatty-success'}); + $state.go($state.get('list'), {entity: entity.name()}); + return false; + }]) + .onSubmitError(['error', 'form', 'progression', 'notification', function (error, form, progression, notification) { + angular.forEach(error.data.errors, function (value, key) { + if (this[key]) { + this[key].$valid = false; + } + }, form); + progression.done(); + notification.log(error.data.message, {addnCls: 'humane-flatty-error'}); + return false; + }]); + + vehicle_type_insurances.editionView().title('Edit Vehicle Type Insurance') + .fields([ + nga.field('vehicle_type_id', 'reference') + .label('Vehicle Type') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Vehicle Type' + }) + .targetEntity(nga.entity('vehicle_types')) + .perPage('all') + .targetField(nga.field('name').map(truncate)), + nga.field('insurance_id', 'reference') + .label('Insurance') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Insurance' + }) + .perPage('all') + .targetEntity(nga.entity('vehicle_insurances')) + .targetField(nga.field('name').map(truncate)), + nga.field('rate').label('Rate') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Rate' + }), + nga.field('max_allowed_amount').label('Maximum amount allowed(' + siteCurrency + ')') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Maximum amount allowed' + }), + nga.field('discount_type_id', 'choice').label('Insurance Type(' + siteCurrency + '/%)') + .choices([{ + label: 'Percentage', + value: '1' + }, { + label: 'Amount', + value: '2' + }]) + .attributes({ + placeholder: 'Insurance Type' + }) + .validation({ + required: true + }), + nga.field('duration_type_id', 'choice').label('Duration Type') + .choices([{ + label: 'Per day', + value: '1' + }, { + label: 'Per rental', + value: '2' + }]) + .attributes({ + placeholder: 'Duration Type' + }) + .validation({ + required: true + }), + nga.field('is_active', 'choice').label('Active?') + .attributes({ + placeholder: 'Active?' + }) + .validation({ + required: true + }) + .choices([{ + label: 'Yes', + value: 1 + }, { + label: 'No', + value: 0 + },]) + ]) + .onSubmitSuccess(['progression', 'notification', '$state', 'entry', 'entity', function (progression, notification, $state, entry, entity) { + progression.done(); + notification.log(entry.values.Success, {addnCls: 'humane-flatty-success'}); + $state.go($state.get('list'), {entity: entity.name()}); + return false; + }]) + .onSubmitError(['error', 'form', 'progression', 'notification', function (error, form, progression, notification) { + angular.forEach(error.data.errors, function (value, key) { + if (this[key]) { + this[key].$valid = false; + } + }, form); + progression.done(); + notification.log(error.data.message, {addnCls: 'humane-flatty-error'}); + return false; + }]); + + var vehicle_extra_accessories_custom_tmp = ''; + vehicle_extra_accessories.listView().title('Extra Accessories') + .fields([ + nga.field('created_at').label('Created'), + nga.field('name','wysiwyg').label('Name').map(truncate), + nga.field('short_description','wysiwyg').label('Short Description').map(truncate), + nga.field('is_active', 'boolean').label('Active?') + ]) + .infinitePagination(false) + .perPage(limit_per_page) + .listActions(['show', 'edit', 'delete']) + .filters([ + nga.field('q').label('Search') + .pinned(true) + .template('
'), + nga.field('filter', 'choice').label('Status').attributes({ + placeholder: 'Status?' + }) + .choices([{ + label: 'Active', + value: 'active' + }, { + label: 'Inactive', + value: 'inactive' + },]) + ]) + .batchActions([]) + .actions(['create', 'batch', vehicle_extra_accessories_custom_tmp]); + vehicle_extra_accessories.showView().title('View Extra Accessory') + .fields([ + nga.field('created_at').label('Created'), + nga.field('name').label('Name'), + nga.field('short_description').label('Short Description'), + nga.field('description', 'wysiwyg').label('Description'), + nga.field('is_active', 'boolean').label('Active?') + ]); + vehicle_extra_accessories.creationView().title('Add Extra Accessory') + .fields([ + nga.field('name').label('Name') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Name' + }), + nga.field('short_description', 'text').label('Short Description') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Short Description' + }), + nga.field('description', 'wysiwyg').label('Description') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Short Description' + }), + nga.field('is_active', 'choice').label('Active?') + .attributes({ + placeholder: 'Active?' + }) + .validation({ + required: true + }) + .choices([{ + label: 'Yes', + value: true + }, { + label: 'No', + value: false + },]) + ]) + .onSubmitSuccess(['progression', 'notification', '$state', 'entry', 'entity', function (progression, notification, $state, entry, entity) { + progression.done(); + notification.log(entry.values.Success, {addnCls: 'humane-flatty-success'}); + $state.go($state.get('list'), {entity: entity.name()}); + return false; + }]) + .onSubmitError(['error', 'form', 'progression', 'notification', function (error, form, progression, notification) { + angular.forEach(error.data.errors, function (value, key) { + if (this[key]) { + this[key].$valid = false; + } + }, form); + progression.done(); + notification.log(error.data.message, {addnCls: 'humane-flatty-error'}); + return false; + }]); + vehicle_extra_accessories.editionView().title('Edit Extra Accessory') + .fields([ + nga.field('name').label('Name') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Name' + }), + nga.field('short_description', 'text').label('Short Description') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Short Description' + }), + nga.field('description', 'wysiwyg').label('Description') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Short Description' + }), + nga.field('is_active', 'choice').label('Active?') + .attributes({ + placeholder: 'Active?' + }) + .validation({ + required: true + }) + .choices([{ + label: 'Yes', + value: true + }, { + label: 'No', + value: false + },]) + ]) + .onSubmitSuccess(['progression', 'notification', '$state', 'entry', 'entity', function (progression, notification, $state, entry, entity) { + progression.done(); + notification.log(entry.values.Success, {addnCls: 'humane-flatty-success'}); + $state.go($state.get('list'), {entity: entity.name()}); + return false; + }]) + .onSubmitError(['error', 'form', 'progression', 'notification', function (error, form, progression, notification) { + angular.forEach(error.data.errors, function (value, key) { + if (this[key]) { + this[key].$valid = false; + } + }, form); + progression.done(); + notification.log(error.data.message, {addnCls: 'humane-flatty-error'}); + return false; + }]); + + var vehicle_type_extra_accessories_custom_tmp = ''; + vehicle_type_extra_accessories.listView().title('Vehicle Type Extra Accessories') + .fields([ + nga.field('created_at').label('Created'), + nga.field('vehicle_type.name').label('Vehicle Type'), + nga.field('vehicle_extra_accessory.name','wysiwyg').label('Extra Accessory'), + nga.field('rate', 'number').format('0.00').label('Rate'), + nga.field('discount_type.type').label('Type(' + siteCurrency + '/%)'), + nga.field('duration_type.name').label('Duration Type'), + nga.field('max_allowed_amount', 'number').format('0.00').label('Max Amount Allowed(' + siteCurrency + ')'), + nga.field('deposit_amount', 'number').format('0.00').label('Deposit Amount(' + siteCurrency + ')'), + nga.field('is_active', 'boolean').label('Active?') + ]) + .infinitePagination(false) + .perPage(limit_per_page) + .listActions(['edit', 'delete']) + .filters([ + nga.field('q').label('Search') + .pinned(true) + .template('
'), + nga.field('filter', 'choice').label('Status').attributes({ + placeholder: 'Status?' + }) + .choices([{ + label: 'Active', + value: 'active' + }, { + label: 'Inactive', + value: 'inactive' + },]) + ]) + .batchActions([]) + .actions(['create', 'batch', vehicle_type_extra_accessories_custom_tmp]); + + vehicle_type_extra_accessories.creationView().title('Add Vehicle Type Extra Accessory') + .fields([ + nga.field('vehicle_type_id', 'reference') + .label('Vehicle Type') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Vehicle Type' + }) + .targetEntity(nga.entity('vehicle_types')) + .perPage('all') + .targetField(nga.field('name').map(truncate)), + nga.field('extra_accessory_id', 'reference') + .label('Extra Accessory') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Extra Accessory' + }) + .perPage('all') + .targetEntity(nga.entity('vehicle_extra_accessories')) + .targetField(nga.field('name').map(truncate)), + nga.field('rate').label('Rate') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Rate' + }), + nga.field('max_allowed_amount').label('Maximum amount allowed(' + siteCurrency + ')') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Maximum amount allowed' + }), + nga.field('deposit_amount').label('Deposit Amount(' + siteCurrency + ')') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Deposit Amount' + }), + nga.field('discount_type_id', 'choice').label('Type(' + siteCurrency + '/%)') + .choices([{ + label: 'Percentage', + value: '1' + }, { + label: 'Amount', + value: '2' + }]) + .attributes({ + placeholder: 'Type' + }) + .validation({ + required: true + }), + nga.field('duration_type_id', 'choice').label('Duration Type') + .choices([{ + label: 'Per day', + value: '1' + }, { + label: 'Per rental', + value: '2' + }]) + .attributes({ + placeholder: 'Duration Type' + }) + .validation({ + required: true + }), + nga.field('is_active', 'choice').label('Active?') + .attributes({ + placeholder: 'Active?' + }) + .validation({ + required: true + }) + .choices([{ + label: 'Yes', + value: 1 + }, { + label: 'No', + value: 0 + },]) + ]) + .onSubmitSuccess(['progression', 'notification', '$state', 'entry', 'entity', function (progression, notification, $state, entry, entity) { + progression.done(); + notification.log(entry.values.Success, {addnCls: 'humane-flatty-success'}); + $state.go($state.get('list'), {entity: entity.name()}); + return false; + }]) + .onSubmitError(['error', 'form', 'progression', 'notification', function (error, form, progression, notification) { + angular.forEach(error.data.errors, function (value, key) { + if (this[key]) { + this[key].$valid = false; + } + }, form); + progression.done(); + notification.log(error.data.message, {addnCls: 'humane-flatty-error'}); + return false; + }]); + + vehicle_type_extra_accessories.editionView().title('Edit Vehicle Type Extra Accessory') + .fields([ + nga.field('vehicle_type_id', 'reference') + .label('Vehicle Type') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Vehicle Type' + }) + .targetEntity(nga.entity('vehicle_types')) + .perPage('all') + .targetField(nga.field('name').map(truncate)), + nga.field('extra_accessory_id', 'reference') + .label('Extra Accessory') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Extra Accessory' + }) + .perPage('all') + .targetEntity(nga.entity('vehicle_extra_accessories')) + .targetField(nga.field('name').map(truncate)), + nga.field('rate').label('Rate') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Rate' + }), + nga.field('max_allowed_amount').label('Maximum amount allowed(' + siteCurrency + ')') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Maximum amount allowed' + }), + nga.field('deposit_amount').label('Deposit Amount(' + siteCurrency + ')') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Deposit Amount' + }), + nga.field('discount_type_id', 'choice').label('Type(' + siteCurrency + '/%)') + .choices([{ + label: 'Percentage', + value: '1' + }, { + label: 'Amount', + value: '2' + }]) + .attributes({ + placeholder: 'Type' + }) + .validation({ + required: true + }), + nga.field('duration_type_id', 'choice').label('Duration Type') + .choices([{ + label: 'Per day', + value: '1' + }, { + label: 'Per rental', + value: '2' + }]) + .attributes({ + placeholder: 'Duration Type' + }) + .validation({ + required: true + }), + nga.field('is_active', 'choice').label('Active?') + .attributes({ + placeholder: 'Active?' + }) + .validation({ + required: true + }) + .choices([{ + label: 'Yes', + value: true + }, { + label: 'No', + value: false + }]) + ]) + .onSubmitSuccess(['progression', 'notification', '$state', 'entry', 'entity', function (progression, notification, $state, entry, entity) { + progression.done(); + notification.log(entry.values.Success, {addnCls: 'humane-flatty-success'}); + $state.go($state.get('list'), {entity: entity.name()}); + return false; + }]) + .onSubmitError(['error', 'form', 'progression', 'notification', function (error, form, progression, notification) { + angular.forEach(error.data.errors, function (value, key) { + if (this[key]) { + this[key].$valid = false; + } + }, form); + progression.done(); + notification.log(error.data.message, {addnCls: 'humane-flatty-error'}); + return false; + }]); + + var vehicle_fuel_options_custom_tmp = ''; + vehicle_fuel_options.listView().title('Fuel Options') + .fields([ + nga.field('created_at').label('Created'), + nga.field('name','wysiwyg').label('Name').map(truncate), + nga.field('short_description','wysiwyg').label('Short Description').map(truncate), + nga.field('is_active', 'boolean').label('Active?') + ]) + .infinitePagination(false) + .perPage(limit_per_page) + .listActions(['show', 'edit', 'delete']) + .filters([ + nga.field('q').label('Search') + .pinned(true) + .template('
'), + nga.field('filter', 'choice').label('Status').attributes({ + placeholder: 'Status?' + }) + .choices([{ + label: 'Active', + value: 'active' + }, { + label: 'Inactive', + value: 'inactive' + },]) + ]) + .batchActions([]) + .actions(['create', 'batch', vehicle_fuel_options_custom_tmp]); + vehicle_fuel_options.showView().title('View Fuel Option') + .fields([ + nga.field('created_at').label('Created'), + nga.field('name').label('Name'), + nga.field('short_description').label('Short Description'), + nga.field('description', 'wysiwyg').label('Description'), + nga.field('is_active', 'boolean').label('Active?') + ]); + vehicle_fuel_options.creationView().title('Add Fuel Option') + .fields([ + nga.field('name').label('Name') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Name' + }), + nga.field('short_description', 'text').label('Short Description') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Short Description' + }), + nga.field('description', 'wysiwyg').label('Description') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Short Description' + }), + nga.field('is_active', 'choice').label('Active?') + .attributes({ + placeholder: 'Active?' + }) + .validation({ + required: true + }) + .choices([{ + label: 'Yes', + value: true + }, { + label: 'No', + value: false + },]) + ]) + .onSubmitSuccess(['progression', 'notification', '$state', 'entry', 'entity', function (progression, notification, $state, entry, entity) { + progression.done(); + notification.log(entry.values.Success, {addnCls: 'humane-flatty-success'}); + $state.go($state.get('list'), {entity: entity.name()}); + return false; + }]) + .onSubmitError(['error', 'form', 'progression', 'notification', function (error, form, progression, notification) { + angular.forEach(error.data.errors, function (value, key) { + if (this[key]) { + this[key].$valid = false; + } + }, form); + progression.done(); + notification.log(error.data.message, {addnCls: 'humane-flatty-error'}); + return false; + }]); + vehicle_fuel_options.editionView().title('Edit Fuel Option') + .fields([ + nga.field('name').label('Name') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Name' + }), + nga.field('short_description', 'text').label('Short Description') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Short Description' + }), + nga.field('description', 'wysiwyg').label('Description') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Short Description' + }), + nga.field('is_active', 'choice').label('Active?') + .attributes({ + placeholder: 'Active?' + }) + .validation({ + required: true + }) + .choices([{ + label: 'Yes', + value: true + }, { + label: 'No', + value: false + },]) + ]) + .onSubmitSuccess(['progression', 'notification', '$state', 'entry', 'entity', function (progression, notification, $state, entry, entity) { + progression.done(); + notification.log(entry.values.Success, {addnCls: 'humane-flatty-success'}); + $state.go($state.get('list'), {entity: entity.name()}); + return false; + }]) + .onSubmitError(['error', 'form', 'progression', 'notification', function (error, form, progression, notification) { + angular.forEach(error.data.errors, function (value, key) { + if (this[key]) { + this[key].$valid = false; + } + }, form); + progression.done(); + notification.log(error.data.message, {addnCls: 'humane-flatty-error'}); + return false; + }]); + + var vehicle_type_fuel_options_custom_tmp = ''; + vehicle_type_fuel_options.listView().title('Vehicle Type Fuel Options') + .fields([ + nga.field('created_at').label('Created'), + nga.field('vehicle_type.name').label('Vehicle Type'), + nga.field('vehicle_fuel_option.name','wysiwyg').label('Fuel Option'), + nga.field('rate', 'number').format('0.00').label('Rate'), + nga.field('discount_type.type').label('Type(' + siteCurrency + '/%)'), + nga.field('duration_type.name').label('Duration Type'), + nga.field('max_allowed_amount', 'number').format('0.00').label('Max Amount Allowed(' + siteCurrency + ')'), + nga.field('is_active', 'boolean').label('Active?') + ]) + .infinitePagination(false) + .perPage(limit_per_page) + .listActions(['edit', 'delete']) + .filters([ + nga.field('q').label('Search') + .pinned(true) + .template('
'), + nga.field('filter', 'choice').label('Status').attributes({ + placeholder: 'Status?' + }) + .choices([{ + label: 'Active', + value: 'active' + }, { + label: 'Inactive', + value: 'inactive' + },]) + ]) + .batchActions([]) + .actions(['create', 'batch', vehicle_type_fuel_options_custom_tmp]); + + vehicle_type_fuel_options.creationView().title('Add Vehicle Type Fuel Option') + .fields([ + nga.field('vehicle_type_id', 'reference') + .label('Vehicle Type') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Vehicle Type' + }) + .targetEntity(nga.entity('vehicle_types')) + .perPage('all') + .targetField(nga.field('name').map(truncate)), + nga.field('fuel_option_id', 'reference') + .label('Fuel Option') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Fuel Option' + }) + .perPage('all') + .targetEntity(nga.entity('vehicle_fuel_options')) + .targetField(nga.field('name').map(truncate)), + nga.field('rate').label('Rate') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Rate' + }), + nga.field('max_allowed_amount').label('Maximum amount allowed(' + siteCurrency + ')') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Maximum amount allowed' + }), + nga.field('discount_type_id', 'choice').label('Type(' + siteCurrency + '/%)') + .choices([{ + label: 'Percentage', + value: '1' + }, { + label: 'Amount', + value: '2' + }]) + .attributes({ + placeholder: 'Type' + }) + .validation({ + required: true + }), + nga.field('duration_type_id', 'choice').label('Duration Type') + .choices([{ + label: 'Per day', + value: '1' + }, { + label: 'Per rental', + value: '2' + }]) + .attributes({ + placeholder: 'Duration Type' + }) + .validation({ + required: true + }), + nga.field('is_active', 'choice').label('Active?') + .attributes({ + placeholder: 'Active?' + }) + .validation({ + required: true + }) + .choices([{ + label: 'Yes', + value: 1 + }, { + label: 'No', + value: 0 + },]) + ]) + .onSubmitSuccess(['progression', 'notification', '$state', 'entry', 'entity', function (progression, notification, $state, entry, entity) { + progression.done(); + notification.log(entry.values.Success, {addnCls: 'humane-flatty-success'}); + $state.go($state.get('list'), {entity: entity.name()}); + return false; + }]) + .onSubmitError(['error', 'form', 'progression', 'notification', function (error, form, progression, notification) { + angular.forEach(error.data.errors, function (value, key) { + if (this[key]) { + this[key].$valid = false; + } + }, form); + progression.done(); + notification.log(error.data.message, {addnCls: 'humane-flatty-error'}); + return false; + }]); + + vehicle_type_fuel_options.editionView().title('Edit Vehicle Type Fuel Option') + .fields([ + nga.field('vehicle_type_id', 'reference') + .label('Vehicle Type') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Vehicle Type' + }) + .targetEntity(nga.entity('vehicle_types')) + .perPage('all') + .targetField(nga.field('name').map(truncate)), + nga.field('fuel_option_id', 'reference') + .label('Fuel Option') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Fuel Option' + }) + .perPage('all') + .targetEntity(nga.entity('vehicle_fuel_options')) + .targetField(nga.field('name').map(truncate)), + nga.field('rate').label('Rate') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Rate' + }), + nga.field('max_allowed_amount').label('Maximum amount allowed(' + siteCurrency + ')') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Maximum amount allowed' + }), + nga.field('discount_type_id', 'choice').label('Type(' + siteCurrency + '/%)') + .choices([{ + label: 'Percentage', + value: '1' + }, { + label: 'Amount', + value: '2' + }]) + .attributes({ + placeholder: 'Type' + }) + .validation({ + required: true + }), + nga.field('duration_type_id', 'choice').label('Duration Type') + .choices([{ + label: 'Per day', + value: '1' + }, { + label: 'Per rental', + value: '2' + }]) + .attributes({ + placeholder: 'Duration Type' + }) + .validation({ + required: true + }), + nga.field('is_active', 'choice').label('Active?') + .attributes({ + placeholder: 'Active?' + }) + .validation({ + required: true + }) + .choices([{ + label: 'Yes', + value: true + }, { + label: 'No', + value: false + }]) + ]) + .onSubmitSuccess(['progression', 'notification', '$state', 'entry', 'entity', function (progression, notification, $state, entry, entity) { + progression.done(); + notification.log(entry.values.Success, {addnCls: 'humane-flatty-success'}); + $state.go($state.get('list'), {entity: entity.name()}); + return false; + }]) + .onSubmitError(['error', 'form', 'progression', 'notification', function (error, form, progression, notification) { + angular.forEach(error.data.errors, function (value, key) { + if (this[key]) { + this[key].$valid = false; + } + }, form); + progression.done(); + notification.log(error.data.message, {addnCls: 'humane-flatty-error'}); + return false; + }]); + + var vehicle_special_prices_custom_tmp = ''; + vehicle_special_prices.listView().title('Special Discount Prices') + .fields([ + nga.field('created_at').label('Created'), + nga.field('vehicle_type.name').label('Vehicle Type'), + nga.field('start_date').label('Start Date'), + nga.field('end_date').label('End Date'), + nga.field('discount_percentage', 'number').format('0.00').label('Discount(%)'), + nga.field('is_active', 'boolean').label('Active?') + ]) + .infinitePagination(false) + .perPage(limit_per_page) + .listActions(['edit', 'delete']) + .filters([ + nga.field('filter', 'choice').label('Status').attributes({ + placeholder: 'Status?' + }) + .choices([{ + label: 'Active', + value: 'active' + }, { + label: 'Inactive', + value: 'inactive' + }]), + nga.field('vehicle_type_id', 'reference') + .attributes({ + placeholder: 'Type' + }) + .targetEntity(nga.entity('vehicle_types')) + .targetField(nga.field('name')) + .label('Type'), + nga.field('start_date', 'date').format("MM/dd/yyyy").attributes({'placeholder': 'Select Start date'}).label("Start Date"), + nga.field('end_date', 'date').format("MM/dd/yyyy").attributes({'placeholder': 'Select End date'}).label("End Date") + ]) + .batchActions([]) + .actions(['create', 'batch', vehicle_special_prices_custom_tmp]); + + vehicle_special_prices.creationView().title('Add Special Discount Price') + .fields([ + nga.field('vehicle_type_id', 'reference') + .label('Vehicle Type') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Vehicle Type' + }) + .targetEntity(nga.entity('vehicle_types?filter=active')) + .perPage('all') + .targetField(nga.field('name').map(truncate)), + nga.field('discount_percentage').label('Discount(%)') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Discount Percentage' + }), + nga.field('start_date', 'date') + .label('Start date') + .attributes({ + placeholder: 'Start Date' + }), + nga.field('end_date', 'date') + .label('End date') + .attributes({ + placeholder: 'End Date' + }), + nga.field('is_active', 'choice').label('Active?') + .attributes({ + placeholder: 'Active?' + }) + .validation({ + required: true + }) + .choices([{ + label: 'Yes', + value: true + }, { + label: 'No', + value: false + }]) + ]) + .onSubmitSuccess(['progression', 'notification', '$state', 'entry', 'entity', function (progression, notification, $state, entry, entity) { + progression.done(); + notification.log(entry.values.Success, {addnCls: 'humane-flatty-success'}); + $state.go($state.get('list'), {entity: entity.name()}); + return false; + }]) + .onSubmitError(['error', 'form', 'progression', 'notification', function (error, form, progression, notification) { + angular.forEach(error.data.errors, function (value, key) { + if (this[key]) { + this[key].$valid = false; + } + }, form); + progression.done(); + notification.log(error.data.message, {addnCls: 'humane-flatty-error'}); + return false; + }]); + + vehicle_special_prices.editionView().title('Edit Special Discount Price') + .fields([ + nga.field('vehicle_type_id', 'reference') + .label('Vehicle Type') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Vehicle Type' + }) + .targetEntity(nga.entity('vehicle_types')) + .perPage('all') + .targetField(nga.field('name').map(truncate)), + nga.field('discount_percentage').label('Discount(%)') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Discount Percentage' + }), + nga.field('start_date', 'date').label('Start date'), + nga.field('end_date', 'date').label('End date'), + nga.field('is_active', 'choice').label('Active?') + .attributes({ + placeholder: 'Active?' + }) + .validation({ + required: true + }) + .choices([{ + label: 'Yes', + value: true + }, { + label: 'No', + value: false + }]) + ]) + .onSubmitSuccess(['progression', 'notification', '$state', 'entry', 'entity', function (progression, notification, $state, entry, entity) { + progression.done(); + notification.log(entry.values.Success, {addnCls: 'humane-flatty-success'}); + $state.go($state.get('list'), {entity: entity.name()}); + return false; + }]) + .onSubmitError(['error', 'form', 'progression', 'notification', function (error, form, progression, notification) { + angular.forEach(error.data.errors, function (value, key) { + if (this[key]) { + this[key].$valid = false; + } + }, form); + progression.done(); + notification.log(error.data.message, {addnCls: 'humane-flatty-error'}); + return false; + }]); + + var vehicle_companies_custom_tmp = ''; + vehicle_companies.listView().title('Vehicle Companies') + .fields([ + nga.field('created_at').label('Created'), + nga.field('user.username').label('User'), + nga.field('name').label('Name'), + nga.field('address').label('Address').map(truncate), + nga.field('latitude').label('Latitude'), + nga.field('longitude').label('Longitude'), + nga.field('email').label('Email'), + nga.field('mobile').label('Mobile'), + nga.field('vehicle_count').label('Vehicle Count'), + nga.field('status').label('Status?'), + ]) + .filters([ + nga.field('q').label('Search') + .pinned(true) + .template('
'), + nga.field('is_active', 'choice').label('Status') + .attributes({ + placeholder: 'Status?' + }) + .choices([{ + label: 'Active', + value: 1 + }, { + label: 'Deactive', + value: 0 + }, { + label: 'Rejected', + value: 2 + }]) + ]) + .perPage(limit_per_page) + .actions(['batch', 'create']) + .listActions(['show', '', 'delete']) + .actions(['\n \n', 'batch', vehicle_companies_custom_tmp]) + .batchActions([ + '', + '', + '', + 'delete' + ]); + vehicle_companies.showView().title('View Company Details') + .fields([ + nga.field('created_at').label('Created'), + nga.field('user.username').label('User'), + nga.field('name').label('Name'), + nga.field('address').label('Address'), + nga.field('latitude').label('Latitude'), + nga.field('longitude').label('Longitude'), + nga.field('email').label('Email'), + nga.field('mobile').label('Mobile'), + nga.field('phone').label('Phone'), + nga.field('fax').label('Fax'), + nga.field('vehicle_count').label('Vehicle Count'), + nga.field('status').label('Status?') + ]); + counter_locations.listView().title('Counter Locations') + .fields([ + nga.field('created_at').label('Created'), + nga.field('address').label('Address').map(truncate), + nga.field('latitude').label('Latitude'), + nga.field('longitude').label('Longitude'), + nga.field('mobile').label('Mobile'), + nga.field('phone').label('Phone'), + nga.field('fax').label('Fax'), + nga.field('email').label('Email') + ]) + .filters([ + nga.field('q').label('Search') + .pinned(true) + .template('
'), + nga.field('filter', 'choice').label('Status').attributes({ + placeholder: 'Status?' + }) + .choices([{ + label: 'Active', + value: 'active' + }, { + label: 'Inactive', + value: 'inactive' + },]) + ]) + .perPage(limit_per_page) + .actions(['batch', 'create']) + .listActions(['', 'delete']) + .actions(['\n \n']) + .batchActions([]); + var vehicle_type_prices_custom_tmp = ''; + vehicle_type_prices.listView().title('Discount Prices') + .fields([ + nga.field('created_at').label('Created'), + nga.field('vehicle_type.name').label('Vehicle Type'), + nga.field('minimum_no_of_day').label('Rental Min no of day'), + nga.field('maximum_no_of_day').label('Rental Max no of day'), + nga.field('discount_percentage', 'number').format('0.00').label('Discount(%)'), + nga.field('is_active', 'boolean').label('Active?') + ]) + .infinitePagination(false) + .perPage(limit_per_page) + .listActions(['edit', 'delete']) + .filters([ + nga.field('q').label('Search') + .pinned(true) + .template('
'), + nga.field('filter', 'choice').label('Status').attributes({ + placeholder: 'Status?' + }) + .choices([{ + label: 'Active', + value: 'active' + }, { + label: 'Inactive', + value: 'inactive' + }]) + ]) + .batchActions([]) + .actions(['create', 'batch', vehicle_type_prices_custom_tmp]); + + vehicle_type_prices.creationView().title('Add Discount Price') + .fields([ + nga.field('vehicle_type_id', 'reference') + .label('Vehicle Type') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Vehicle Type' + }) + .targetEntity(nga.entity('vehicle_types?filter=active')) + .perPage('all') + .targetField(nga.field('name').map(truncate)), + nga.field('minimum_no_of_day').label('Rental Min no of day') + .attributes({ + placeholder: 'Rental Min no of day' + }) + .validation({ + required: true + }), + nga.field('maximum_no_of_day').label('Rental Max no of day') + .attributes({ + placeholder: 'Rental Max no of day' + }) + .validation({ + required: true + }), + nga.field('discount_percentage').label('Discount Percentage') + .attributes({ + placeholder: 'Discount Percentage' + }) + .validation({ + required: true + }), + nga.field('is_active', 'choice').label('Active?') + .attributes({ + placeholder: 'Active?' + }) + .validation({ + required: true + }) + .choices([{ + label: 'Yes', + value: true + }, { + label: 'No', + value: false + },]) + ]) + .onSubmitSuccess(['progression', 'notification', '$state', 'entry', 'entity', function (progression, notification, $state, entry, entity) { + progression.done(); + notification.log(entry.values.Success, {addnCls: 'humane-flatty-success'}); + $state.go($state.get('list'), {entity: entity.name()}); + return false; + }]) + .onSubmitError(['error', 'form', 'progression', 'notification', function (error, form, progression, notification) { + angular.forEach(error.data.errors, function (value, key) { + if (this[key]) { + this[key].$valid = false; + } + }, form); + progression.done(); + notification.log(error.data.message, {addnCls: 'humane-flatty-error'}); + return false; + }]); + + vehicle_type_prices.editionView().title('Edit Discount Price') + .fields([ + nga.field('vehicle_type_id', 'reference') + .label('Vehicle Type') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Vehicle Type' + }) + .targetEntity(nga.entity('vehicle_types')) + .perPage('all') + .targetField(nga.field('name').map(truncate)), + nga.field('minimum_no_of_day').label('Rental Min no of day') + .validation({ + required: true + }), + nga.field('maximum_no_of_day').label('Rental Max no of day') + .validation({ + required: true + }), + nga.field('discount_percentage').label('Discount Percentage') + .validation({ + required: true + }), + nga.field('is_active', 'choice').label('Active?') + .validation({ + required: true + }) + .choices([{ + label: 'Yes', + value: 1 + }, { + label: 'No', + value: 0 + },]) + ]) + .onSubmitSuccess(['progression', 'notification', '$state', 'entry', 'entity', function (progression, notification, $state, entry, entity) { + progression.done(); + notification.log(entry.values.Success, {addnCls: 'humane-flatty-success'}); + $state.go($state.get('list'), {entity: entity.name()}); + return false; + }]) + .onSubmitError(['error', 'form', 'progression', 'notification', function (error, form, progression, notification) { + angular.forEach(error.data.errors, function (value, key) { + if (this[key]) { + this[key].$valid = false; + } + }, form); + progression.done(); + notification.log(error.data.message, {addnCls: 'humane-flatty-error'}); + return false; + }]); + var vehicle_search_custom_tmp = ''; + vehicle_search.listView().title('Vehicle Search') + .fields([ + nga.field('vehicle_type.name').label('Vehicle Type'), + nga.field('start_date').label('Start Date'), + nga.field('end_date').label('End Date'), + ]) + .infinitePagination(false) + .perPage(limit_per_page) + .listActions(['edit', 'delete']) + .filters([ + nga.field('q').label('Search') + .pinned(true) + .template('
'), + nga.field('start_date', 'date').format("MM/dd/yyyy").attributes({'placeholder': 'Select Start date'}).label("Start Date"), + nga.field('end_date', 'date').format("MM/dd/yyyy").attributes({'placeholder': 'Select End date'}).label("End Date") + ]) + .batchActions([]) + .actions(['create', 'batch', vehicle_search_custom_tmp]); + + var unavailable_vehicles_custom_tmp = ''; + unavailable_vehicles.listView().title('Maintenance') + .fields([ + nga.field('vehicle.name').label('Vehicle'), + nga.field('start_date').label('Start Date'), + nga.field('end_date').label('End Date'), + ]) + .infinitePagination(false) + .perPage(limit_per_page) + .listActions(['edit', 'delete']) + .filters([ + nga.field('q').label('Search') + .pinned(true) + .template('
'), + nga.field('start_date', 'date').format("MM/dd/yyyy").attributes({'placeholder': 'Select Start date'}).label("Start Date"), + nga.field('end_date', 'date').format("MM/dd/yyyy").attributes({'placeholder': 'Select End date'}).label("End Date"), + nga.field('vehicle_id', 'reference') + .label('Vehicle') + .attributes({ + placeholder: 'Vehicle' + }) + .targetEntity(nga.entity('vehicles')) + .perPage('all') + .targetField(nga.field('name').map(truncate)) + ]) + .batchActions([]) + .actions(['create', 'batch', unavailable_vehicles_custom_tmp]); + + unavailable_vehicles.creationView().title('Add Maintenance') + .fields([ + nga.field('vehicle_id', 'reference') + .label('Vehicle') + .validation({ + required: true + }) + .attributes({ + placeholder: 'Vehicle' + }) + .targetEntity(nga.entity('vehicles')) + .perPage('all') + .targetField(nga.field('name').map(truncate)), + nga.field('start_date', 'datetime').label('Start date'), + nga.field('end_date', 'datetime').label('End date') + ]) + .onSubmitSuccess(['progression', 'notification', '$state', 'entry', 'entity', function (progression, notification, $state, entry, entity) { + progression.done(); + notification.log(entry.values.Success, {addnCls: 'humane-flatty-success'}); + $state.go($state.get('list'), {entity: entity.name()}); + return false; + }]) + .onSubmitError(['error', 'form', 'progression', 'notification', function (error, form, progression, notification) { + angular.forEach(error.data.errors, function (value, key) { + if (this[key]) { + this[key].$valid = false; + } + }, form); + progression.done(); + notification.log(error.data.message, {addnCls: 'humane-flatty-error'}); + return false; + }]); + unavailable_vehicles.editionView().title('Edit Maintenance') + .fields([ + nga.field('start_date', 'datetime').label('Start date'), + nga.field('end_date', 'datetime').label('End date') + ]) + .onSubmitSuccess(['progression', 'notification', '$state', 'entry', 'entity', function (progression, notification, $state, entry, entity) { + progression.done(); + notification.log(entry.values.Success, {addnCls: 'humane-flatty-success'}); + $state.go($state.get('list'), {entity: entity.name()}); + return false; + }]) + .onSubmitError(['error', 'form', 'progression', 'notification', function (error, form, progression, notification) { + angular.forEach(error.data.errors, function (value, key) { + if (this[key]) { + this[key].$valid = false; + } + }, form); + progression.done(); + notification.log(error.data.message, {addnCls: 'humane-flatty-error'}); + return false; + }]); + // attach the admin application to the DOM and run it + nga.configure(admin); + //Menu configuration + admin.menu(nga.menu() + .addChild(nga.menu().title('Users').icon('') + .addChild(nga.menu(users).title('Users').icon('')) + ) + .addChild(nga.menu().title('Vehicles').icon('')) + .addChild(nga.menu().title('Payments').icon('') + .addChild(nga.menu(transactions).title('Transactions').icon('')) + ) + .addChild(nga.menu().title('Settings').icon('') + .addChild(nga.menu(setting_categories).title('Site Settings').icon('')) + ) + .addChild(nga.menu().title('Activities').icon('') + .addChild(nga.menu(api_requests).title('Api Requests').icon('')) + .addChild(nga.menu(user_logins).title('User Logins').icon('')) + .addChild(nga.menu(messages).title('Messages').icon('')) + ) + .addChild(nga.menu(plugins).title('Plugins').icon('').link("/plugins")) + .addChild(nga.menu().title('Master').icon('') + .addChild(nga.menu(cities).title('Cities').icon('')) + .addChild(nga.menu(states).title('States').icon('')) + .addChild(nga.menu(countries).title('Countries').icon('')) + .addChild(nga.menu(email_templates).title('Email Templates').icon('')) + .addChild(nga.menu(languages).title('Languages').icon('')) + .addChild(nga.menu(ips).title('IPs').icon('')) + .addChild(nga.menu(transaction_types).title('Transaction Types').icon('')) + .addChild(nga.menu(currencies).title('Currencies').icon('')) + //.addChild(nga.menu(cancellation_types).title('Cancellation Types').icon('')) + ) + .addChild(nga.menu().title('Vehicle Master').icon('')) + .addChild(nga.menu().title('Vehicle Rental Master').icon('')) + .addChild(nga.menu().title('Diagnostics').icon('') + .addChild(nga.menu(wallet_transaction_logs).title('Wallet Transaction Log').icon('')) + ) + .addChild(nga.menu().title('View Site').template(' View Site ')) + .addChild(nga.menu().title('Logout').icon('').link('/logout')) + ); + if (angular.isDefined(enabledPlugins)) { + //Add menu item if Plugin Enabled. + if (enabledPlugins.indexOf("Contacts") > -1) { + admin.menu().getChildByTitle('Users') + .addChild(nga.menu(contacts).title('Contacts').icon('')) + } + if (enabledPlugins.indexOf("Withdrawal") > -1) { + admin.menu().getChildByTitle('Users') + .addChild(nga.menu(user_cash_withdrawals).title('Withdraw Requests').icon('')) + } + if (enabledPlugins.indexOf("Pages") > -1) { + admin.menu().getChildByTitle('Master') + .addChild(nga.menu(pages).title('Pages').icon('')) + } + if (enabledPlugins.indexOf("SocialLogins") > -1) { + admin.menu().getChildByTitle('Master') + .addChild(nga.menu(providers).title('Providers').icon('')) + } + if (enabledPlugins.indexOf("Vehicles") > -1) { + admin.menu().getChildByTitle('Vehicles') + .addChild(nga.menu(vehicles).title('Vehicles').icon('')) + .addChild(nga.menu(counter_locations).title('Counter Locations').icon('')) + .addChild(nga.menu(vehicle_type_prices).title('Discount Prices').icon('')) + .addChild(nga.menu(vehicle_special_prices).title('Special Discount Prices').icon('')) + .addChild(nga.menu(unavailable_vehicles).title('Maintenance').icon('')) + admin.menu().getChildByTitle('Vehicle Master') + .addChild(nga.menu(vehicle_companies).title('Vehicle Companies').icon('')) + .addChild(nga.menu(vehicle_makes).title('Vehicle Makes').icon('')) + .addChild(nga.menu(vehicle_models).title('Vehicle Models').icon('')) + .addChild(nga.menu(vehicle_types).title('Vehicle Types').icon('')) + } + if (enabledPlugins.indexOf("VehicleRentals") > -1) { + admin.menu().getChildByTitle('Vehicles') + .addChild(nga.menu(vehicle_rentals).title('Rentals').icon('')) + } + if (enabledPlugins.indexOf("VehicleCoupons") > -1) { + admin.menu().getChildByTitle('Vehicles') + .addChild(nga.menu(vehicle_coupons).title('Coupons').icon('')) + } + if (enabledPlugins.indexOf("VehicleFeedbacks") > -1) { + admin.menu().getChildByTitle('Vehicles') + .addChild(nga.menu(vehicle_feedbacks).title('Feedbacks').icon('')) + } + if (enabledPlugins.indexOf("VehicleDisputes") > -1) { + admin.menu().getChildByTitle('Vehicles') + .addChild(nga.menu(vehicle_disputes).title('Disputes').icon('')) + admin.menu().getChildByTitle('Vehicle Rental Master') + .addChild(nga.menu(vehicle_dispute_types).title('Rental Dispute Types').icon('')) + .addChild(nga.menu(vehicle_dispute_closed_types).title('Rental Dispute Closed Types').icon('')) + } + if (enabledPlugins.indexOf("VehicleTaxes") > -1) { + admin.menu().getChildByTitle('Vehicle Rental Master') + .addChild(nga.menu(vehicle_taxes).title('Taxes').icon('')) + .addChild(nga.menu(vehicle_type_taxes).title('Vehicle Type Taxes').icon('')) + } + if (enabledPlugins.indexOf("VehicleSurcharges") > -1) { + admin.menu().getChildByTitle('Vehicle Rental Master') + .addChild(nga.menu(vehicle_surcharges).title('Surcharges').icon('')) + .addChild(nga.menu(vehicle_type_surcharges).title('Vehicle Type Surcharges').icon('')) + } + if (enabledPlugins.indexOf("VehicleInsurances") > -1) { + admin.menu().getChildByTitle('Vehicle Rental Master') + .addChild(nga.menu(vehicle_insurances).title('Insurances').icon('')) + .addChild(nga.menu(vehicle_type_insurances).title('Vehicle Type Insurances').icon('')) + } + if (enabledPlugins.indexOf("VehicleExtraAccessories") > -1) { + admin.menu().getChildByTitle('Vehicle Rental Master') + .addChild(nga.menu(vehicle_extra_accessories).title('Extra Accessories').icon('')) + .addChild(nga.menu(vehicle_type_extra_accessories).title('Vehicle Type Extra Accessory').icon('')) + } + if (enabledPlugins.indexOf("VehicleFuelOptions") > -1) { + admin.menu().getChildByTitle('Vehicle Rental Master') + .addChild(nga.menu(vehicle_fuel_options).title('Fuel Options').icon('')) + .addChild(nga.menu(vehicle_type_fuel_options).title('Vehicle Type Fuel Options').icon('')) + } + if (enabledPlugins.indexOf("Sudopays") > -1) { + admin.menu().getChildByTitle('Diagnostics') + .addChild(nga.menu(sudopay_transaction_logs).title('ZazPay Transaction Log').icon('')) + .addChild(nga.menu(sudopay_ipn_logs).title('ZazPay Ipn Log').icon('')) + } + if (enabledPlugins.indexOf("Paypal") > -1) { + admin.menu().getChildByTitle('Diagnostics') + .addChild(nga.menu(paypal_transaction_logs).title('Paypal Transaction Log').icon('')) + } + if (enabledPlugins.indexOf("CurrencyConversions") > -1) { + admin.menu().getChildByTitle('Activities') + .addChild(nga.menu(currency_conversions).title('Currency Conversion').icon('')) + .addChild(nga.menu(currency_conversion_histories).title('Currency Conversion History').icon('')) + } + //disable Listing parent menu if Item plugin disabled + if (enabledPlugins.indexOf("Vehicles") === -1) { + admin.menu().getChildByTitle('Vehicles') + .title('') + .template('') + .icon(''); + admin.menu().getChildByTitle('Vehicle Master') + .title('') + .template('') + .icon(''); + } + //disable Listing parent menu if Tax plugin disabled + if (enabledPlugins.indexOf("VehicleTaxes") === -1 && enabledPlugins.indexOf("VehicleSurcharges") === -1 && enabledPlugins.indexOf("VehicleInsurances") === -1 && enabledPlugins.indexOf("VehicleExtraAccessories") === -1 && enabledPlugins.indexOf("VehicleFuelOptions") === -1 && enabledPlugins.indexOf("VehicleDisputes") === -1) { + admin.menu().getChildByTitle('Vehicle Rental Master') + .title('') + .template('') + .icon(''); + } + } + // customize header + var customHeaderTemplate = '' + ''; // this is custom directive + admin.header(customHeaderTemplate); + // customize dashboard + var dashboardTpl = '
' + '' + '
'; + admin.dashboard(nga.dashboard() + .addCollection(nga.collection(users) + .name('users') + .title('Users') + .perPage(5) + .fields([ + nga.field('created_at').label('Register On'), + nga.field('role_id', 'choice').label('User Type') + .choices([{ + label: 'Admin', + value: '1' + }, { + label: 'User', + value: '2' + }]), + nga.field('username').label('Name'), + nga.field('email').label('Email'), + nga.field('available_wallet_amount', 'number').format('0.00').label('Available Balance (' + siteCurrency + ')'), + nga.field('user_login_count', 'number').label('Login Count'), + nga.field('is_active', 'boolean').label('Active?'), + nga.field('is_email_confirmed', 'boolean').label('Email Confirmed?'), + ]) + .listActions(['', 'show', 'edit', 'delete']) + .order(1)) + .addCollection(nga.collection(vehicles) + .name('vehicles') + .title('Vehicles') + .perPage(5) + .fields([ + nga.field('created_at').label('Created'), + nga.field('vehicle_company.name').label('Company Name'), + nga.field('name').label('') + .template('{{entry.values.name}}') + .label('Vehicle Name'), + nga.field('vehicle_make.name').label('Make'), + nga.field('vehicle_model.name').label('Model'), + nga.field('vehicle_type.name').label('Type'), + nga.field('per_hour_amount', 'number').format('0.00').label('Hour Amount(' + siteCurrency + ')'), + nga.field('per_day_amount', 'number').format('0.00').label('Day Amount(' + siteCurrency + ')'), + nga.field('feedback_count', 'number').label('Feedback Count').cssClasses(function () { + if (enabledPlugins.indexOf("VehicleFeedbacks") === -1) { + return "ng-hide"; + } + }), + nga.field('is_active', 'boolean').label('Active?'), + ]) + .listActions(['', '', '', 'delete']) + .order(2)) + .template(dashboardTpl) + ); +}]); +//Checking Admin Authentication by checking auth credentials, Redirected to site page if not admin logged in. +ngapp.run(function ($rootScope, $location) { + $rootScope.$on('$viewContentLoaded', function () { + if (!$('#preloader').hasClass('loadAG')) { + $('#status').fadeOut(600); + $('#preloader').delay(600).fadeOut(600 / 2); + } + var url_array = ['/login', '/logout', '']; + var path = $location.path(); + if ($.inArray(path, url_array) === -1) { + var token = localStorage.userToken; + var role = localStorage.userRole; + if (!token || parseInt(role) != 1) { + $location.path('/logout'); + } + } + }); +}); diff --git a/client/src/ag-admin/js/ng-admin.jwt-auth.js b/client/src/ag-admin/js/ng-admin.jwt-auth.js new file mode 100644 index 0000000..2a13ab5 --- /dev/null +++ b/client/src/ag-admin/js/ng-admin.jwt-auth.js @@ -0,0 +1,256 @@ +(function e(t, n, r) { + function s(o, u) { + if (!n[o]) { + if (!t[o]) { + var a = typeof require == "function" && require; + if (!u && a)return a(o, !0); + if (i)return i(o, !0); + var f = new Error("Cannot find module '" + o + "'"); + throw f.code = "MODULE_NOT_FOUND", f + } + var l = n[o] = {exports: {}}; + t[o][0].call(l.exports, function (e) { + var n = t[o][1][e]; + return s(n ? n : e) + }, l, l.exports, e, t, n, r) + } + return n[o].exports + } + + var i = typeof require == "function" && require; + for (var o = 0; o < r.length; o++)s(r[o]); + return s +})({ + 1: [function (require, module, exports) { + var ngAdminJWTAuthService = function ($http, jwtHelper, ngAdminJWTAuthConfigurator) { + return { + authenticate: function (data, successCallback, errorCallback) { + var url = ngAdminJWTAuthConfigurator.getAuthURL(); + return $http({ + url: url, + method: 'POST', + data: data + }).then(function (response) { + var payload = jwtHelper.decodeToken(response.data.token); + if (response.data.role != 1) { + response.data.message = "Authentication failed"; + errorCallback(response); + } else { + var enabled_plugins = response.data.enabled_plugins; + localStorage.userToken = response.data.token; + localStorage.userRole = response.data.role; + localStorage.enabled_plugins = JSON.stringify(enabled_plugins); + successCallback(response); + var customAuthHeader = ngAdminJWTAuthConfigurator.getCustomAuthHeader(); + if (customAuthHeader) { + $http.defaults.headers.common[customAuthHeader.name] = customAuthHeader.template.replace('{{token}}', response.data.token); + } else { + $http.defaults.headers.common.Authorization = 'Basic ' + response.data.token; + } + } + }, errorCallback); + }, + isAuthenticated: function () { + var token = localStorage.userToken; + if (!token) { + return false; + } + return jwtHelper.isTokenExpired(token) ? false : true; + }, + logout: function () { + localStorage.removeItem('userRole'); + localStorage.removeItem('userToken'); + localStorage.removeItem('auth'); + localStorage.removeItem('enabled_plugins'); + return true; + } + } + }; + ngAdminJWTAuthService.$inject = ['$http', 'jwtHelper', 'ngAdminJWTAuthConfigurator']; + module.exports = ngAdminJWTAuthService; + }, {}], 2: [function (require, module, exports) { + var ngAdminJWTAuthConfiguratorProvider = function () { + var authConfigs = {}; + this.setJWTAuthURL = function (url) { + authConfigs._authUrl = url; + }; + this.setCustomLoginTemplate = function (url) { + authConfigs._customLoginTemplate = url; + } + this.setLoginSuccessCallback = function (callback) { + authConfigs._loginSuccessCallback = callback; + } + this.setLoginErrorCallback = function (callback) { + authConfigs._loginErrorCallback = callback; + } + this.setCustomAuthHeader = function (obj) { + return authConfigs._customAuthHeader = obj; + } + this.$get = function () { + return { + getAuthURL: function () { + return authConfigs._authUrl; + }, + getCustomLoginTemplate: function () { + return authConfigs._customLoginTemplate; + }, + getLoginSuccessCallback: function () { + return authConfigs._loginSuccessCallback; + }, + getLoginErrorCallback: function () { + return authConfigs._loginErrorCallback; + }, + getCustomAuthHeader: function () { + return authConfigs._customAuthHeader; + } + }; + } + }; + module.exports = ngAdminJWTAuthConfiguratorProvider; + }, {}], 3: [function (require, module, exports) { + var loginController = function ($scope, $rootScope, ngAdminJWTAuthService, ngAdminJWTAuthConfigurator, notification, $location) { + this.$scope = $scope; + this.$rootScope = $rootScope; + this.ngAdminJWTAuthService = ngAdminJWTAuthService; + this.ngAdminJWTAuthConfigurator = ngAdminJWTAuthConfigurator; + this.notification = notification; + this.$location = $location; + }; + loginController.prototype.login = function () { + var that = this; + var success = this.ngAdminJWTAuthConfigurator.getLoginSuccessCallback() || function (response) { + that.notification.log(response.data.message, {addnCls: 'humane-flatty-success'}); + that.$location.path('/'); + }; + var error = this.ngAdminJWTAuthConfigurator.getLoginErrorCallback() || function (response) { + that.notification.log(response.data.message, {addnCls: 'humane-flatty-error'}); + }; + this.ngAdminJWTAuthService.authenticate(this.data, success, error); + }; + loginController.$inject = ['$rootScope', '$scope', 'ngAdminJWTAuthService', 'ngAdminJWTAuthConfigurator', 'notification', '$location']; + module.exports = loginController; + }, {}], 4: [function (require, module, exports) { + var loginTemplate = '
\n
\n
diff --git a/client/src/ag-admin/tpl/counterLocationAdd.tpl.html b/client/src/ag-admin/tpl/counterLocationAdd.tpl.html new file mode 100644 index 0000000..3e45972 --- /dev/null +++ b/client/src/ag-admin/tpl/counterLocationAdd.tpl.html @@ -0,0 +1,69 @@ +
+
+ +
+
+
+
+
+
+ + +
+ Required + {{model.full_addressErr}} +
+
+ +
+ + +
+ Required + {{model.latitudeErr}} +
+
+
+ + +
+ Required + {{model.longitudeErr}} +
+
+
+ + +
+
+ + +
+
+ + +
+ Required + {{model.mobileErr}} +
+
+
+ + +
+ Required + Enter valid email + {{model.emailErr}} +
+
+
+ +
+
+
+
diff --git a/client/src/ag-admin/tpl/counterLocationEdit.tpl.html b/client/src/ag-admin/tpl/counterLocationEdit.tpl.html new file mode 100644 index 0000000..dfd4e89 --- /dev/null +++ b/client/src/ag-admin/tpl/counterLocationEdit.tpl.html @@ -0,0 +1,69 @@ +
+
+ +
+
+
+
+
+
+ + +
+ Required + {{model.full_addressErr}} +
+
+ +
+ + +
+ Required + {{model.latitudeErr}} +
+
+
+ + +
+ Required + {{model.longitudeErr}} +
+
+
+ + +
+
+ + +
+
+ + +
+ Required + {{model.mobileErr}} +
+
+
+ + +
+ Required + Enter valid email + {{model.emailErr}} +
+
+
+ +
+
+
+
diff --git a/client/src/ag-admin/tpl/customHeader.tpl.html b/client/src/ag-admin/tpl/customHeader.tpl.html new file mode 100644 index 0000000..1d61a57 --- /dev/null +++ b/client/src/ag-admin/tpl/customHeader.tpl.html @@ -0,0 +1,18 @@ + diff --git a/client/src/ag-admin/tpl/customLoginTemplate.html b/client/src/ag-admin/tpl/customLoginTemplate.html new file mode 100644 index 0000000..f19a9d8 --- /dev/null +++ b/client/src/ag-admin/tpl/customLoginTemplate.html @@ -0,0 +1,27 @@ +
+
+
+ + +
+
+
\ No newline at end of file diff --git a/client/src/ag-admin/tpl/dashboardSummary.tpl.html b/client/src/ag-admin/tpl/dashboardSummary.tpl.html new file mode 100644 index 0000000..0547bf8 --- /dev/null +++ b/client/src/ag-admin/tpl/dashboardSummary.tpl.html @@ -0,0 +1,253 @@ +
+ + +
+
+
+
+
+ {{'Overview' | translate}} + +
+ +
+
+
+
+
    +
  • + + + +

    {{adminstats.user_register}}

    +

    {{'User Register' | translate}}

    +
  • +
  • + + + +

    {{adminstats.user_login}}

    +

    {{'User Login' | translate}}

    +
  • +
  • + + + +

    {{adminstats.vehicle_count}}

    +

    {{'Vehicles' | translate}}

    +
  • +
  • + + + +

    {{adminstats.booking_count}}

    +

    {{'Rentals' | translate}}

    +
  • +
  • + + + +

    {{adminstats.feedback_count}}

    +

    {{'Feedbacks' | translate}}

    +
  • +
  • + + + +

    {{adminstats.transaction_count}}

    +

    {{'Transactions' | translate}}

    +
  • +
+
+
+
+ + +
+
diff --git a/client/src/ag-admin/tpl/pages.tpl.html b/client/src/ag-admin/tpl/pages.tpl.html new file mode 100644 index 0000000..b6f50ce --- /dev/null +++ b/client/src/ag-admin/tpl/pages.tpl.html @@ -0,0 +1,42 @@ +
+
+ +
+
+
+
+
+ +
+ + it should be slugify url like page-slug +
+
+
+

{{languages.name}}

+ + +
+ +
+
+ + +
+
+ +
+
+
+
+
+ +
+
+
+
diff --git a/client/src/ag-admin/tpl/plugins.tpl.html b/client/src/ag-admin/tpl/plugins.tpl.html new file mode 100644 index 0000000..64914a6 --- /dev/null +++ b/client/src/ag-admin/tpl/plugins.tpl.html @@ -0,0 +1,149 @@ +
+
+ +
+
+
+
+
+ {{'To reflect plugin changes, you need to' | translate}} {{'refresh' | translate}}. +
+
+ +
+
+
+
+

{{item_plugin.main.name}}

+ +
+

+
+
+ +
+
+

{{plugin.name}}

+ +
+

+
+
+
+ +
+
+

{{plugin.name}}

+ +
+

+
+
+
+
+
+ +
+
+
+ +
+
+
+

{{plugin.name}}

+ +
+

+
+
+
+
+ + + +
+
+
+ +
+
+
+

{{plugin.name}}

+ +
+

+
+
+
+
+ +
+
+
+
diff --git a/client/src/ag-admin/tpl/trip_detail.tpl.html b/client/src/ag-admin/tpl/trip_detail.tpl.html new file mode 100644 index 0000000..9d57fb0 --- /dev/null +++ b/client/src/ag-admin/tpl/trip_detail.tpl.html @@ -0,0 +1,99 @@ +
+
+

{{'Trip Details'|translate}}

+

+ {{'Pick Up'|translate}}:{{VehicleRentalDetails.pickup_counter_location.address}} {{VehicleRentalDetails.item_booking_start_date | date:'MMM d, y h:mm:ss a'}}

+
+

+ {{'Drop Off'|translate}}:{{VehicleRentalDetails.drop_counter_location.address}} {{VehicleRentalDetails.item_booking_end_date | date:'MMM d, y h:mm:ss a'}}

+

+ {{'Total Distance'|translate}}:{{VehicleRentalDetails.total_distance}} {{VehicleRentalDetails.distance_unit}} +

+

{{'Review Your Rate'|translate}}

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
{{'Description'|translate}}{{'Day(s)'|translate}}{{'Total'|translate}}
{{vehicleDetails.name}}{{VehicleRentalDetails.date_diff.total_days}} {{'Day(s)'| translate}}{{VehicleRentalDetails.date_diff.total_hours}} {{'Hour(s)'| translate}}{{siteCurrency}}{{VehicleRentalDetails.booking_amount}}
{{'Tax'|translate}}(+) {{siteCurrency}}{{VehicleRentalDetails.tax_amount}}
{{'Deposit'|translate}}(+) {{siteCurrency}}{{VehicleRentalDetails.deposit_amount}}
{{'Drop Location Differ Additional Fee'|translate}}(+) {{getFormatCurrency(VehicleRentalDetails.drop_location_differ_additional_fee)}}
{{'One way drop off charge'|translate}}(+) {{siteCurrency}}{{VehicleRentalDetails.drop_location_differ_charges}}
{{'Extra Accessory Amount'|translate}}(+) {{siteCurrency}}{{VehicleRentalDetails.extra_accessory_amount}}
{{'Insurance Amount'|translate}}(+) {{siteCurrency}}{{VehicleRentalDetails.insurance_amount}}
{{'Fuel Amount'|translate}}(+) {{siteCurrency}}{{VehicleRentalDetails.fuel_option_amount}}
{{'Surcharge Amount'|translate}}(+) {{siteCurrency}}{{VehicleRentalDetails.surcharge_amount}}
{{'Additional Fee'|translate}}(+) {{siteCurrency}}{{VehicleRentalDetails.additional_fee}}
{{'Special Discount Amount'|translate}}(-) {{siteCurrency}}{{VehicleRentalDetails.special_discount_amount}}
{{'Type Discount Amount'|translate}}(-) {{siteCurrency}}{{VehicleRentalDetails.type_discount_amount}}
{{'Discount'|translate}}(-) {{siteCurrency}}{{VehicleRentalDetails.coupon_discount_amount}}
+ {{'Total Price'|translate}} + {{siteCurrency}}{{VehicleRentalDetails.total_amount}}
+ {{'Continue Payment'|translate}} +
+
\ No newline at end of file diff --git a/client/src/ag-admin/tpl/vehicle.tpl.html b/client/src/ag-admin/tpl/vehicle.tpl.html new file mode 100644 index 0000000..cf1e97b --- /dev/null +++ b/client/src/ag-admin/tpl/vehicle.tpl.html @@ -0,0 +1,105 @@ +
+ +
+
+
+

{{vehicleDetails.name}}

+
+

+ + + {{'Feedback' | translate}} +

+
+
+

{{vehicleDetails.counter_location.data.length}} {{'Location'|translate}}

+
+
    +
  • + {{'Manual' | translate }} +
  • +
  • + {{'Automatic' | translate }} +
  • +
  • + {{'Air Conditioning' | translate }} +
  • +
  • + {{vehicleDetails.no_of_seats}} {{'People' | translate}} +
  • +
  • + {{vehicleDetails.no_small_bags}} {{'Small Bags' | translate}} +
  • +
  • + {{vehicleDetails.no_large_bags}} {{'Large Bags' | translate}} +
  • +
+
+
+

+ {{siteCurrency}}{{vehicleDetails.per_day_amount}} +

+
+
+
+
+

{{'Pickup Locations'|translate}}

+
    +
  • {{location.address}}
  • +
+
+
+

{{'Drop Locations'|translate}}

+
    +
  • {{location.address}}
  • +
+
+
+ + + + \ No newline at end of file diff --git a/client/src/ag-admin/tpl/vehicleAdd.tpl.html b/client/src/ag-admin/tpl/vehicleAdd.tpl.html new file mode 100644 index 0000000..4fe2264 --- /dev/null +++ b/client/src/ag-admin/tpl/vehicleAdd.tpl.html @@ -0,0 +1,308 @@ +
+
+ +
+
+
+
+
+

Basic Details


+
+ + + + Required + +
+
+ + + + Required + +
+
+ + + + Required + +
+
+ + + + Required + +
+
+ + + + Required + +
+
+ + +
+ + Required + + + Age should be greater than {{driver_min_age}} + + + Age should be less than {{driver_max_age}} + +
+
+ +

Attachment


+
+ + +
+ + Required + + + Maximum allowed size is 2 MB. + +
+
+ +

Price Details


+
+ + +
+ + Required + + + You did not enter a valid number + + + Your field value is lesser than minimum price + + + Your field value is greater than maximum price + +
+ +

Minimum Hour Price: {{vehicleType.minimum_hour_price}}

+

Maximum Hour Price: {{vehicleType.maximum_hour_price}}

+
+
+
+ + +
+ + Required + + + You did not enter a valid number + + + Your field value is lesser than minimum price + + + Your field value is greater than maximum price + +
+ +

Minimum Day Price: {{vehicleType.minimum_day_price}}

+

Maximum Day Price: {{vehicleType.maximum_day_price}}

+
+
+ +

Counter Locations


+
+
+
+

Pick Up Locations

+
+
+ +
+
+ +
+ + Choose Pickup locations + +
+
+
+
+
+

Drop Off Locations

+
+
+ +
+
+ +
+ + Choose Drop locations + +
+
+
+
+ +

Specification


+
+ + + + Required + +
+
+ + + + Required + +
+
+ + + + Required + +
+
+ + + + Required + +
+
+ + + + Required + +
+
+ + + + Required + +
+
+
+ +
+
+ + + + Required + +
+
+
+
+ +
+
+ + + + Required + +
+
+
+ + + + Required + +
+
+
+
+ +
+
+ +
+
+
+
+ + +
+
+
+
diff --git a/client/src/ag-admin/tpl/vehicleCompaniesAdd.tpl.html b/client/src/ag-admin/tpl/vehicleCompaniesAdd.tpl.html new file mode 100644 index 0000000..d8b2d9a --- /dev/null +++ b/client/src/ag-admin/tpl/vehicleCompaniesAdd.tpl.html @@ -0,0 +1,100 @@ +
+
+ +
+
+
+
+
+
+ + +
+ Required + {{model.user_idErr}} +
+
+
+ + +
+ Required + {{model.nameErr}} +
+
+
+ + +
+ Required + {{model.full_addressErr}} +
+
+ +
+ + +
+ Required + {{model.latitudeErr}} +
+
+
+ + +
+ Required + {{model.longitudeErr}} +
+
+
+ + +
+
+ + +
+
+ + +
+ Required + {{model.mobileErr}} +
+
+
+ + +
+ Required + Enter valid email + {{model.emailErr}} +
+
+
+ + +
+ Required + {{model.is_activeErr}} +
+
+
+ +
+
+
+
diff --git a/client/src/ag-admin/tpl/vehicleCompaniesEdit.tpl.html b/client/src/ag-admin/tpl/vehicleCompaniesEdit.tpl.html new file mode 100644 index 0000000..efd62bb --- /dev/null +++ b/client/src/ag-admin/tpl/vehicleCompaniesEdit.tpl.html @@ -0,0 +1,101 @@ +
+
+ +
+
+
+
+
+
+ + +
+ Required +
+
+
+ + +
+ Required + {{model.nameErr}} +
+
+
+ + +
+ Required + {{model.full_addressErr}} +
+
+ +
+ + +
+ Required + {{model.latitudeErr}} +
+
+
+ + +
+ Required + {{model.longitudeErr}} +
+
+
+ + +
+
+ + +
+
+ + + +
+ Required + {{model.mobileErr}} +
+
+
+ + + +
+ Required + Enter valid email + {{model.emailErr}} +
+
+
+ + +
+ Required + {{model.is_activeErr}} +
+
+
+ +
+
+
+
diff --git a/client/src/ag-admin/tpl/vehicleEdit.tpl.html b/client/src/ag-admin/tpl/vehicleEdit.tpl.html new file mode 100644 index 0000000..14ce577 --- /dev/null +++ b/client/src/ag-admin/tpl/vehicleEdit.tpl.html @@ -0,0 +1,284 @@ +
+
+ +
+
+
+
+
+

Basic Details


+
+ + + + Required + +
+
+ + + + Required + +
+
+ + + + Required + +
+
+ + + + Required + +
+
+ + + + Required + +
+
+ + +
+ + Required + + + Age should be greater than {{driver_min_age}} + + + Age should be less than {{driver_max_age}} + +
+
+ +
+

Attachment

+
+
+ + +
+ + Required + + + Maximum allowed size is 2 MB. + +
+ {{vehicle.name}} +
+
+ +

Price Details


+
+ + + + Required + +
+
+ + + + Required + +
+ +

Counter Locations


+
+
+
+

Pick Up Locations

+
+
+ +
+
+ +
+ + {{'Choose Pickup locations' | translate}} + +
+
+
+
+
+

Drop Off Locations

+
+
+ +
+
+ +
+ + {{'Choose Drop locations' | translate}} + +
+
+
+
+ +

Specification


+
+ + + + Required + +
+
+ + + + Required + +
+
+ + + + Required + +
+
+ + + + Required + +
+
+ + + + Required + +
+
+ + + + Required + +
+
+
+ +
+
+ + + + Required + +
+
+
+
+ +
+
+ + + + Required + +
+
+
+ + + + Required + +
+
+
+
+ +
+
+ +
+
+
+
+ + +
+
+
+
diff --git a/client/src/ag-admin/tpl/vehicleTypePrice.tpl.html b/client/src/ag-admin/tpl/vehicleTypePrice.tpl.html new file mode 100644 index 0000000..1010196 --- /dev/null +++ b/client/src/ag-admin/tpl/vehicleTypePrice.tpl.html @@ -0,0 +1,99 @@ +
+
+ +
+
+
+
+
+
+
+ +
+
+ +
+ +
+
+ + Required + {{model.vehicle_type_idErr}} +
+
+
+
+
+ +
+
+ +
+ +
+
+ + Required + {{model.is_activeErr}} +
+
+
+ Add field +
+
+
+ + +
+ Required + {{model.minimum_no_of_dayErr}} +
+
+
+
+
+ + +
+ Required + {{model.maximum_no_of_dayErr}} +
+
+
+
+
+ + +
+ Required + {{model.discount_percentageErr}} +
+
+
+ Remove field +
+
+
+ +
+
+ + +
+ {{ choices }} +
+ +
+
+
diff --git a/client/src/ag-admin/tpl/vehicleView.tpl.html b/client/src/ag-admin/tpl/vehicleView.tpl.html new file mode 100644 index 0000000..d72227b --- /dev/null +++ b/client/src/ag-admin/tpl/vehicleView.tpl.html @@ -0,0 +1,215 @@ +
+
+ +
+
+
+
+
+
+

{{vehicle.name}}

+

+ + + +

+
+
+

{{siteCurrency}}{{vehicle.per_day_amount}} / {{'Day'|translate}}

+

{{siteCurrency}}{{vehicle.per_hour_amount}} / {{'Hr'|translate}}

+
+
+
+ +
+
+ +
+
+

{{'Specifications'|translate}}

+
+
+ +
+
{{'Type'|translate}} :
+
{{vehicle.vehicle_type.name}}
+
+
+
{{'Make'|translate}} :
+
{{vehicle.vehicle_make.name}}
+
+
+
{{'Model'|translate}} :
+
{{vehicle.vehicle_model.name}}
+
+
+
{{'Vehicle No'|translate}} :
+
{{vehicle.vehicle_no}}
+
+
+
{{'Fuel Type'|translate}} :
+
{{vehicle.fuel_type.name}}
+
+
+
{{'Mileage'|translate}} :
+
{{vehicle.mileage}}
+
+
+
{{'Vehicle Rental Count'|translate}} :
+
{{vehicle.vehicle_rental_count}}
+
+
+
:
+
{{'Manual' | translate }}
+
+
+
:
+
{{'Automatic' | translate }}
+
+
+
:
+
{{'Air Conditioning' | translate }}
+
+
+
:
+
{{vehicle.no_of_seats}} {{'People' | translate}}
+
+
+
:
+
{{vehicle.no_small_bags}} {{'Small Bags' | translate}}
+
+
+
:
+
{{vehicle.no_large_bags}} {{'Large Bags' | translate}}
+
+
+
:
+
{{vehicle.no_of_gears}} {{'Gears' | translate}}
+
+
+
:
+
{{vehicle.no_of_doors}} {{'Doors' | translate}}
+
+
+
+ +

{{'Prices'|translate}}

+
+
+
+
{{'Per hour amount'|translate}} :
+
{{siteCurrency}}{{vehicle.per_hour_amount}}
+
+
+
{{'Per day amount'|translate}} :
+
{{siteCurrency}}{{vehicle.per_day_amount}}
+
+
+
+ + +
{{'Insurance'|translate}}
+
+
{{data.vehicle_extra_accessory.name}} +
+

{{data.vehicle_extra_accessory.description}}

+
{{data.rate}}
+
+ +

+ {{'Fuel Options'|translate}}

+
+
{{data.vehicle_fuel_option.name}} +
+

{{data.vehicle_fuel_option.description}}

+
{{data.rate}}
+
+ +

+ {{'Insurances'|translate}}

+
+
{{data.vehicle_insurance.name}} +
+

{{data.vehicle_insurance.description}}

+
{{data.rate}}
+
+
+
+
+
+

{{'Pickup Locations'|translate}}

+
    +
  • {{location.address}}
  • +
+
+
+

{{'Drop Locations'|translate}}

+
    +
  • {{location.address}}
  • +
+
+
+
+
+ +
+ + +
+
+
+
+
+
\ No newline at end of file diff --git a/client/src/ag-admin/tpl/vehicle_calendar.tpl.html b/client/src/ag-admin/tpl/vehicle_calendar.tpl.html new file mode 100644 index 0000000..81a5307 --- /dev/null +++ b/client/src/ag-admin/tpl/vehicle_calendar.tpl.html @@ -0,0 +1,45 @@ +
+
+ +
+
+
+
+

{{calendarTitle}}

+ + +
+
+ + +
+
\ No newline at end of file diff --git a/client/src/ag-admin/tpl/vehiclecheckOut.tpl.html b/client/src/ag-admin/tpl/vehiclecheckOut.tpl.html new file mode 100644 index 0000000..7540c00 --- /dev/null +++ b/client/src/ag-admin/tpl/vehiclecheckOut.tpl.html @@ -0,0 +1,74 @@ +
+
+ +
+
+
+
+
+
+ +
+
+
+
+

{{'Checkout Details'|translate}}

+
+
+
+
+ +
+

{{siteCurrency}}{{VehicleRentalDetails.late_checkout_total_fee}}

+
+
+
+
+
+ +
+ + + {{'Enter amount' | translate }} + +
+
+
+
+
+ +
+

{{siteCurrency}}{{claim_amount + VehicleRentalDetails.late_checkout_total_fee}}

+
+
+
+
+
+
{{'Claim to Deposit' | translate}} {{siteCurrency}}{{claimToDeposit}}
+
+
+
{{'Manual Payment' | translate}} {{siteCurrency}}{{manualPay}}
+
+
+
+
+
+ +
+
+
+
+
+ +
diff --git a/client/src/app/App.js b/client/src/app/App.js new file mode 100644 index 0000000..2ace47a --- /dev/null +++ b/client/src/app/App.js @@ -0,0 +1,343 @@ +/** + * BookorRent - v1.0a.01 - 2016-03-28 + * + * Copyright (c) 2016 Agriya + */ +/** + * @ngdoc object + * @name App + * @description + * + * This is the base module. It defines the base configuration and appcontroller and run function etc., + * + * The angular.module is a global place for creating, registering and retrieving Angular modules. + * All modules that should be available to an application must be registered using this mechanism. + * Passing one argument retrieves an existing angular.Module, whereas passing more than one argument creates a new angular.Module + * + * + * @param {!string} App name of the module + * @param {!Array.=} dependencies If specified then new module is being created. If unspecified then the module is being retrieved for further configuration. + * + * [ + * 'BookorRent.Constant', + * 'BookorRent.home', + * 'BookorRent.Constant', + * 'BookorRent.user', + * 'templates-app' + * 'ui.router.state', + * 'ui.router', + * 'angulartics', + * 'angulartics.google.analytics', + * 'angulartics.facebook.pixel', + * 'slugifier' + * ] + * @param {Function=} configFn Optional configuration function for the module. + * @returns {angular.Module} new BookorRent module with the angular.Module api. + **/ +(function (app) { + app.config(function ($stateProvider, $urlRouterProvider, $authProvider, $translateProvider, $analyticsProvider) { + $translateProvider.useStaticFilesLoader({ + prefix: 'assets/js/l10n/', + suffix: '.json' + }); + $translateProvider.preferredLanguage('en'); + $translateProvider.useLocalStorage(); // saves selected language to localStorage + // Enable escaping of HTML + $translateProvider.useSanitizeValueStrategy('escape'); + $urlRouterProvider.otherwise('/'); + }); + /** + * @ngdoc controller + * @name App.controller:AppController + * @module App + * @description + * + * This is AppController which is the base controller for all the controllers + **/ + app.controller('AppController', function ($scope, $auth, $rootScope) { + // Search block close + /** + * @ngdoc method + * @name scrollMoveTop + * @methodOf App.controller:AppController + * @description + * This method is used to scroll the window for top. + **/ + $scope.scrollMoveTop = function () { + $('html, body').stop(true, true).animate({ + scrollTop: 0 + }, 600); + }; + /** + * @ngdoc method + * @name getFormatCurrency + * @methodOf App.controller:AppController + * @description + * This method will provide currency format. + * @param {integer} price Currency symbol changed into other country currency(converted currency). + * @returns {integer} New converted currency with price. + **/ + $scope.getFormatCurrency = function (price, value) { + var currency; + if ($rootScope.settings['site.enabled_plugins'].indexOf('CurrencyConversions') > -1) { + if (value == 'site') { + currency = $rootScope.default_currency; + } else { + currency = localStorage.getItem('convertedCurrency'); + currency_obj = JSON.parse(currency); + if (currency_obj === null) { + currency = $rootScope.default_currency; + } else { + currency = (currency_obj) ? currency_obj : $rootScope.default_currency; + $scope.currency = currency.id; + price = price * currency.rate; + } + } + } else { + currency = $rootScope.default_currency; + } + if (currency.is_prefix_display_on_left) { + return accounting.formatMoney(price, currency.symbol, 2, currency.thousands_sep, currency.dec_point); + } else { + return accounting.formatMoney(price, currency.symbol, 2, currency.thousands_sep, currency.dec_point); + } + }; + }); + app.run(function ($rootScope, $location, $http, $auth) { + $rootScope.is_fresh_call = 1; + var url_array = ['/users/register', '/users/login']; + $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) { + if ($.inArray(toState.url, url_array) !== -1) { + if ($auth.isAuthenticated()) { + $location.path('/'); + } + } + if (toState.authenticate && !$auth.isAuthenticated()) { + $rootScope.returnToState = toState.url; + $rootScope.returnToStateParams = toParams.Id; + $location.path('/users/login'); + } + }); + $rootScope.$on('$viewContentLoaded', function () { + if (!$('#preloader').hasClass('loadAG')) { + $('#status').fadeOut(600); + $('#preloader').delay(600).fadeOut(600 / 2); + } + }); + $rootScope.$on('$stateChangeSuccess', function () { + document.body.scrollTop = document.documentElement.scrollTop = 0; + }); + }); + // Flash message set & get + /** + * @ngdoc service + * @name App.service:Flash + * @module App + * @description + * Flash is a factory service used to set and get the flash messages + * @param {string} Flash The name of the factory service + * @returns {string} New flash message. + */ + app.factory('Flash', ['$rootScope', 'growl', function ($rootScope, growl) { + return { + set: function (message, type, isStateChange) { + if (type === 'success') { + growl.success(message); + } else if (type === 'error') { + growl.error(message); + /*if (isStateChange === true) { + growl.error(message, { + ttl: -1 + }); + } else { + growl.error(message); + }*/ + } else if (type === 'info') { + growl.info(message); + } else if (type === 'Warning') { + growl.warning(message); + } + } + }; + }]); + //Header + /** + * @ngdoc directive + * @name App.directive:header + * @module App + * @scope + * @restrict A + * + * @description + * This directive used to define the header section. + * + * @param {string} header directive name + * + */ + app.directive('header', function () { + /** @type {function} */ + var linker = function (scope, element, attrs) { + // do DOM Manipulation hereafter + }; + return { + restrict: 'A', + templateUrl: 'Common/header.tpl.html', + link: linker, + controller: 'HeaderController as model', + scope: { + header: '=', + currency: '@', + defaultcurrency: '@' + } + }; + }); + // Footer + /** + * @ngdoc directive + * @name App.directive:footer + * @module App + * @scope + * @restrict A + * + * @description + * This directive used to define the footer section. + * + * @param {string} footer directive name + * + */ + app.directive('footer', function () { + var linker = function (scope, element, attrs) { + // do DOM Manipulation hereafter + }; + return { + restrict: 'A', + templateUrl: 'Common/footer.tpl.html', + link: linker, + controller: 'FooterController as model', + scope: { + footer: '=' + } + }; + }); + /** + * @ngdoc filter + * @name App.filter:html + * @description + * It returns the filtered html data. + */ + app.filter('html', function ($sce) { + return function (val) { + return $sce.trustAsHtml(val); + }; + }); + /** + * @ngdoc service + * @name App.service.ResolveService + * @module App + * @description + * It maintains the authentication services. + */ + app.service('ResolveService', function ($auth, $rootScope, GENERAL_CONFIG, AuthFactory, $q, $location, $state, Flash, $filter) { + var promiseSettings; + var promiseAuth; + var deferred = $q.defer(); + if ($auth.isAuthenticated() && $rootScope.auth === undefined) { + promiseAuth = AuthFactory.fetch().$promise.then(function (user) { + if(!user.is_active || !user.is_email_confirmed) { + delete $rootScope.auth; + localStorage.removeItem('userRole'); + localStorage.removeItem('userToken'); + $state.go('home'); + } else { + $rootScope.auth = user; + } + }, function(error) { + Flash.set($filter("translate")("User not found"), 'error', false); + delete $rootScope.auth; + localStorage.removeItem('userRole'); + localStorage.removeItem('userToken'); + $state.go('home'); + }); + } else { + promiseAuth = true; + } + if ($rootScope.is_fresh_call) { + if (angular.isUndefined($rootScope.settings)) { + $rootScope.settings = {}; + } + if (angular.isUndefined($rootScope.currencies)) { + $rootScope.currencies = []; + } + promiseSettings = $.get(GENERAL_CONFIG.api_url + '/settings?type=public_settings', function (response) { + if (response.settings.original) { + $.each(response.settings.original, function (i, settingData) { + $rootScope.settings[settingData.name] = settingData.value; + }); + } + if (response.currencies) { + $.each(response.currencies, function (i, currencyData) { + $rootScope.currencies.push(currencyData); + }); + } + angular.forEach($rootScope.currencies, function (data) { + if (data !== null && data.code !== undefined) { + if (data.code == response.default_currency_code) { + $rootScope.default_currency = data; + } + } + }); + }); + } else { + promiseSettings = true; + } + return { + promiseAuth: promiseAuth, + promiseSettings: promiseSettings + }; + }); + /** + * @ngdoc function + * @name App.function:growlProvider + * @module App + * @description + * Automatic closing of notifications (timeout, ttl) + */ + app.config(['growlProvider', function (growlProvider) { + growlProvider.onlyUniqueMessages(true); + growlProvider.globalTimeToLive(5000); + growlProvider.globalPosition('top-center'); + growlProvider.globalDisableCountDown(true); + //growlProvider.globalEnableHtml(true); + }]); + /** + * @ngdoc function + * @name App.function:cfpLoadingBarProvider + * @module App + * @description + * Loading bar display while page refresh. + */ + app.config(function (cfpLoadingBarProvider) { + // true is the default, but I left this here as an example: + cfpLoadingBarProvider.includeSpinner = false; + }); +}(angular.module("BookorRent", [ + 'BookorRent.home', + 'BookorRent.Constant', + 'BookorRent.user', + 'BookorRent.Wallets', + 'templates-app', + 'ui.router.state', + 'ui.router', + 'ui.bootstrap', + 'ngSanitize', + 'ngAnimate', + 'angular-growl', + 'pascalprecht.translate', + 'ngCookies', + 'BookorRent.common', + 'BookorRent.Messages', + 'BookorRent.Transactions', + 'chieffancypants.loadingBar', + 'angularMoment' +]))); + diff --git a/client/src/app/Common/404.tpl.html b/client/src/app/Common/404.tpl.html new file mode 100644 index 0000000..dfc56a9 --- /dev/null +++ b/client/src/app/Common/404.tpl.html @@ -0,0 +1,5 @@ +
+
+

404 Page Not Found

+
+
diff --git a/client/src/app/Common/Common.module.js b/client/src/app/Common/Common.module.js new file mode 100644 index 0000000..cf18545 --- /dev/null +++ b/client/src/app/Common/Common.module.js @@ -0,0 +1,45 @@ +/** + * @ngdoc object + * @name Common + * @description + * + * This is the common module. + * + * The angular.module is a global place for creating, registering and retrieving Angular modules. + * All modules that should be available to an application must be registered using this mechanism. + * Passing one argument retrieves an existing angular.Module, whereas passing more than one argument creates a new angular.Module + * + * @param {string} common name of the module + * @param {!Array.=} dependencies If specified then new module is being created. If unspecified then the module is being retrieved for further configuration. + * + * [ + * 'ui.router', + * 'angulartics', + * 'angulartics.google.analytics', + * 'angulartics.facebook.pixel', + * 'slugifier' + * ] + * @param {Function=} configFn Optional configuration function for the module. + * @returns {angular.Module} new BookorRent.home module with the angular.Module api. + **/ +(function (module) { + + module.config(function ($stateProvider, $analyticsProvider) { + $stateProvider + .state('howitworks', { + url: '/how-it-works', + views: { + "main": { + templateUrl: 'Common/how_it_works.tpl.html', + } + }, + data: {pageTitle: 'How It Works'} + }); + }); +}(angular.module('BookorRent.common', [ + 'ui.router', + 'angulartics', + 'angulartics.google.analytics', + 'angulartics.facebook.pixel', + 'slugifier' +]))); diff --git a/client/src/app/Common/Footer.js b/client/src/app/Common/Footer.js new file mode 100644 index 0000000..960184e --- /dev/null +++ b/client/src/app/Common/Footer.js @@ -0,0 +1,14 @@ +(function (module) { + /** + * @ngdoc controller + * @name Common.controller:FooterController + * @description + * + * This is Footer Controller which defines the footer section of all pages. + * + * Footer section contains the static pages and copyrights information. + **/ + module.controller('FooterController', function ($scope) { + $scope.currentYear = new Date().getFullYear(); + }); +}(angular.module("BookorRent.common"))); \ No newline at end of file diff --git a/client/src/app/Common/Header.js b/client/src/app/Common/Header.js new file mode 100644 index 0000000..32d12ee --- /dev/null +++ b/client/src/app/Common/Header.js @@ -0,0 +1,98 @@ +(function (module) { + /** + * @ngdoc controller + * @name Common.controller:HeaderController + * @description + * + * This is HeaderController having the methods init(), setMetaData() and logout() and it defines the header section of all the pages. + * + * The header will change according to the user login. If the user logged in, header conotains the user settings, and logout options. + * + * If not logged in, signin and signup options will be available in header. + **/ + module.controller('HeaderController', function ($state, $scope, $rootScope, $auth, ResolveService, AuthFactory, ConstSocialLogin, ConstThumb, $location, $filter) { + var model = this; + /** + * @ngdoc method + * @name setMetaData + * @methodOf Common.controller:HeaderController + * @description + * + * This method will set the meta data dynamically by using the angular.element function + **/ + model.setMetaData = function () { + angular.element('html head meta[name=description]').attr("content", $rootScope.settings['meta.description']); + angular.element('html head meta[name=keywords]').attr("content", $rootScope.settings['meta.keywords']); + angular.element('html head meta[property="og:description"], html head meta[name="twitter:description"]').attr("content", $rootScope.settings['meta.description']); + angular.element('html head meta[name="twitter:creator"]').attr('content', $rootScope.settings['twitter.creator']); + angular.element('html head meta[name="twitter:site"]').attr('content', $rootScope.settings['twitter.site']); + angular.element('html head meta[name="twitter:card"]').attr('content', $rootScope.settings['twitter.card']); + angular.element('html head meta[name="twitter:app:id:iphone"]').attr('content', $rootScope.settings['ios_app_store_id']); + angular.element('html head meta[name="twitter:app:id:ipad"]').attr('content', $rootScope.settings['ipad_app_store_id']); + angular.element('html head meta[property="al:ios:app_store_id"]').attr("content", $rootScope.settings['ios_app_store_id']); + angular.element('html head meta[property="al:ipad:app_store_id"]').attr("content", $rootScope.settings['ipad_app_store_id']); + angular.element('html head meta[property="al:android:package"]').attr("content", $rootScope.settings['android_app_store_id']); + angular.element('html head meta[property="al:windows_phone:app_id"]').attr("content", $rootScope.settings['windows_phone_app_id']); + angular.element('html head meta[property="og:image"], html head meta[name="twitter:image:src"]').attr("content", ''); + angular.element('html head meta[property="og:type"]').attr("content", ''); + }; + /** + * @ngdoc method + * @name init + * @methodOf Common.controller:HeaderController + * @description + * This method will initialze the page and it initializes the settings for header. + * + **/ + model.init = function () { + var promise = ResolveService.promiseAuth; + var promiseSettings = ResolveService.promiseSettings; + promiseSettings.then(function (data) { + model.setMetaData(); + }); + model.ConstSocialLogin = ConstSocialLogin; + model.thumb = ConstThumb.user; + AuthFactory.fetch({}).$promise + .then(function (response) { + $rootScope.vehicle_company = response.vehicle_company; + }); + $scope.$watch(function() { + if($rootScope.settings['site.name'] !== undefined) { + if($location.path() == '/how-it-works') { + $rootScope.pageTitle = $rootScope.settings['site.name'] + " | " + $filter("translate")("How it works"); + } + } + }); + }; + model.init(); + /** + * @ngdoc method + * @name isAuthenticated + * @methodOf Common.controller:HeaderController + * @description + * This mehtod is use to check whether the user logged in or not. + * According to the returned value the site header will be changed. + * @returns {function()} It returns the $auth.isAuthenticated() function + **/ + model.isAuthenticated = function () { + return $auth.isAuthenticated(); + }; + /** + * @ngdoc method + * @name logout + * @methodOf Common.controller:HeaderController + * @description + * This method will be used in logging out the user. + * + **/ + model.logout = function () { + delete $rootScope.auth; + localStorage.removeItem('userRole'); + localStorage.removeItem('auth'); + localStorage.removeItem('enabled_plugins'); + $auth.logout(); + }; + + + }); +}(angular.module("BookorRent.common"))); diff --git a/client/src/app/Common/footer.tpl.html b/client/src/app/Common/footer.tpl.html new file mode 100644 index 0000000..7fd5cf5 --- /dev/null +++ b/client/src/app/Common/footer.tpl.html @@ -0,0 +1,98 @@ + \ No newline at end of file diff --git a/client/src/app/Common/gateway.tpl.html b/client/src/app/Common/gateway.tpl.html new file mode 100644 index 0000000..2fccd5d --- /dev/null +++ b/client/src/app/Common/gateway.tpl.html @@ -0,0 +1,101 @@ + +
+
+
+ +
+
+
+
+ + +
+ +
+
+
+
+
+
+
+

{{'Credit card Details' | translate}}

+
+
+
+

{{'Payer Details' | translate}}

+
+
+
+

{{'Payer Details' | translate}}

+
+
+
+
+
+ +
+

{{'By clicking the "Pay Now" button, you agree to these '|translate}} {{'Terms of Service.'|translate}}

+
+
+ +
+ +
+ +
+ + +
+
+
+
+
+ + diff --git a/client/src/app/Common/header.tpl.html b/client/src/app/Common/header.tpl.html new file mode 100644 index 0000000..e74ada0 --- /dev/null +++ b/client/src/app/Common/header.tpl.html @@ -0,0 +1,119 @@ + diff --git a/client/src/app/Common/how_it_works.tpl.html b/client/src/app/Common/how_it_works.tpl.html new file mode 100644 index 0000000..a9202eb --- /dev/null +++ b/client/src/app/Common/how_it_works.tpl.html @@ -0,0 +1,104 @@ +
+
+

{{'How It Works' | translate }}

+
+
+
+
+
+
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + {{'Rent a Listing' | translate }} + {{'Waiting For Acceptance' | translate }} + {{'Accepted' | translate }} + {{'Attended' | translate }} / {{'Check In' | translate }} + {{'Check Out' | translate }} + {{'Host Review' | translate }} + {{'Booker Review' | translate }} + {{'Dispute' | translate }} + {{'Admin Decision' | translate }} + + {{'Completed' | translate }} + {{'Reject' | translate }} + {{'Expired' | translate }} + {{'Canceled' | translate }} + + + + + + + + {{'Waiting For Payment Cleared' | translate }} + + + + + + + {{'After the threshold day limit - Automated' | translate }} + + + + {{'Cancel by Admin' | translate }} + + + + {{'Waiting for Review' | translate }} + + + + + + + + + + + + {{'Search Item' | translate }} + {{'Make Payment' | translate }} + + + + + +
+
+
+
+
+
\ No newline at end of file diff --git a/client/src/app/Constant.js b/client/src/app/Constant.js new file mode 100644 index 0000000..922cdd3 --- /dev/null +++ b/client/src/app/Constant.js @@ -0,0 +1,72 @@ +var app = angular.module('BookorRent.Constant', []) + .constant('GENERAL_CONFIG', { + 'api_url': '/bookorrent/public/api', + 'preferredLanguage': 'en', + }) + .constant('ConstWithdrawalStatuses', { + 'Pending': 1, + 'UnderProcess': 2, + 'Rejected': 3, + 'Failed': 4, + 'Success': 5 + }) + .constant('ConstSocialLogin', { + 'User':10, + 'Facebook': 1, + 'Twitter': 2, + 'Google': 3, + 'Github': 4 + }).constant('ConstThumb', { + 'user' : { + 'small' : { + 'width': 28, + 'height': 28 + }, + 'medium' : { + 'width': 110, + 'height': 110 + }, + } + + }) + .constant('ConstItemUserStatus', { + 'PaymentPending' : 1, + 'WaitingForAcceptance' : 2, + 'Rejected' : 3, + 'Cancelled' : 4, + 'CancelledByAdmin' : 5, + 'Expired' : 6, + 'Confirmed' : 7, + 'WaitingForReview' : 8, + 'BookerReviewed' : 9, + 'HostReviewed' : 10, + 'Completed' : 11, + 'Attended' : 12, + 'WaitingForPaymentCleared' : 13, + 'PrivateConversation':14 + + }) + .constant('ConstPaymentGateways', { + 'Wallet' :1, + 'SudoPay' :2, + 'PayPal':3 + }) + .constant('ConstDisputeClosedType', { + 'SpecificationFavourBookerRefund' : 1, + 'SpecificationFavourHost' : 2, + 'SpecificationResponseFavourBooker' : 3, + 'FeedbackFavourBooker' : 4, + 'FeedbackFavourHost' : 5, + 'FeedbackResponseFavourHost' : 6, + 'SecurityFavourBooker' : 7, + 'SecurityFavourHost' : 8, + 'SecurityResponseFavourHost' : 9 + }) + .constant('ConstDiscountTypes', { + 'percentage':1, + 'amount':2 + }) + .constant('ConstDurationTypes', { + 'per_day':1, + 'per_rental':2 + }); diff --git a/client/src/app/Home/Home.js b/client/src/app/Home/Home.js new file mode 100644 index 0000000..a979e8b --- /dev/null +++ b/client/src/app/Home/Home.js @@ -0,0 +1,42 @@ +(function (module) { + /** + * @ngdoc controller + * @name Home.controller:HomeController + * @description + * + * This is Home Controller having the methods init(), setMetaData() and it defines the index page. + **/ + module.controller('HomeController', function ($filter, $rootScope, $location) { + var model = this; + /** + * @ngdoc method + * @name setMetaData + * @methodOf Home.controller:HomeController + * @description + * + * This method will set the meta data dynamically by using the method angular.element. + **/ + model.setMetaData = function () { + var pageTitle = $filter("translate")("Home"); + var fullUrl = $location.absUrl(); + var appUrl = $rootScope.settings['scheme_name'] + ":/" + $location.url(); + angular.element('html head meta[property="og:title"], html head meta[name="twitter:title"]').attr("content", $rootScope.settings['site.name'] + " | " + pageTitle); + angular.element('meta[property="al:ios:url"], meta[property="al:ipad:url"], meta[property="al:android:url"], meta[property="al:windows_phone:url"], html head meta[name="twitter:app:url:iphone"], html head meta[name="twitter:app:url:ipad"], html head meta[name="twitter:app:url:googleplay"]').attr('content', appUrl); + angular.element('meta[property="og:url"]').attr('content', fullUrl); + }; + /** + * @ngdoc method + * @name init + * @methodOf Home.controller:HomeController + * @description + * This method will initialze the page and meta data. + * + **/ + model.init = function () { + model.setMetaData(); + $rootScope.pageTitle = $rootScope.settings['site.name'] + " | " + $filter("translate")("Home"); + }; + model.init(); + }); + +}(angular.module("BookorRent.home"))); \ No newline at end of file diff --git a/client/src/app/Home/Home.module.js b/client/src/app/Home/Home.module.js new file mode 100644 index 0000000..4c96e1b --- /dev/null +++ b/client/src/app/Home/Home.module.js @@ -0,0 +1,52 @@ +/** + * @ngdoc object + * @name Home + * @description + * + * This is the home module. It provides the service for the home controller and it's methods + * + * The angular.module is a global place for creating, registering and retrieving Angular modules. + * All modules that should be available to an application must be registered using this mechanism. + * Passing one argument retrieves an existing angular.Module, whereas passing more than one argument creates a new angular.Module + * + * @param {string} BookorRent.home name of the module + * @param {!Array.=} dependencies If specified then new module is being created. If unspecified then the module is being retrieved for further configuration. + * [ + * 'ui.router', + * 'angulartics', + * 'angulartics.google.analytics', + * 'angulartics.facebook.pixel' + * ] + * @param {Function=} configFn Optional configuration function for the module. + * @returns {angular.Module} new BookorRent.home module with the angular.Module api. + **/ +(function (module) { + module.config(function ($stateProvider, $analyticsProvider) { + var ResolveServiceData = { + 'ResolveServiceData': function (ResolveService, $q) { + return $q.all({ + AuthServiceData: ResolveService.promiseAuth, + SettingServiceData: ResolveService.promiseSettings + }); + } + }; + $stateProvider.state('home', { + url: '/', + authenticate: false, + views: { + "main": { + controller: 'HomeController as model', + templateUrl: 'Home/home.tpl.html', + resolve: ResolveServiceData + } + }, + data: {pageTitle: 'Home'} + }); + }); + +}(angular.module("BookorRent.home", [ + 'ui.router', + 'angulartics', + 'angulartics.google.analytics', + 'angulartics.facebook.pixel' +]))); diff --git a/client/src/app/Home/home.tpl.html b/client/src/app/Home/home.tpl.html new file mode 100644 index 0000000..4a5902e --- /dev/null +++ b/client/src/app/Home/home.tpl.html @@ -0,0 +1,77 @@ + + + +
+
+
+
+ +

{{'Today\'s world the scope of vehicle rental was growing big level. With the current marketplace trends, Agriya has developed an impressive as well as comfortable car rental application.' | translate}}. +

+

{{'View all vehicles'|translate}}

+
+
+
+
+ + + +
+
+
+

{{'How it Works'|translate}}

+

{{'Your most economical ride, it has survived not only five countries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing'|translate}}.

+
+
+ car-icon +

{{'Find your Car'|translate}}

+
    +
  • {{'Tell us where you have to go'|translate}}.
  • +
  • {{'Choose a date and time'|translate}}.
  • +
  • {{'User filters to get the car for you'|translate}}.
  • +
+
+
+ make-payment +

{{'Make Payment'|translate}}

+
    +
  • {{'Check to make sure everythings just right'|translate}}.
  • +
  • {{'Enter your payment info, and be on the choose your car way to go'|translate}}.
  • +
  • {{'If you need anything let us book or rent'|translate}}.
  • +
+
+
+ drive +

{{'Drive Yourself'|translate}}

+
    +
  • {{'Get help finding your car and instruction when you drive, all in your way details'|translate}}.
  • +
  • {{'Make edit anytime or cancel upto 24 hours before your choose'|translate}}.
  • +
+
+
+
+
+
+ + + +
+
+

{{'WHY CHOOSE BOOK OR RENT'|translate}}?

+

{{"you'll receive competitive cars from our location within minutes"|translate}}.

+

{{'How do you benefit'|translate}}?

+
    +
  • {{"you'll receive competitive cars from our location within minutes"|translate}}.
  • +
  • {{'Keeping up-to-date is easy with our realtime chat, 24/7 support, time tracker and mobile apps'|translate}}.
  • +
  • {{'pay for work safety and secuirely. Only release payment when you are 100% satified with the work provided'|translate}}!
  • +
+
+
+ + + + \ No newline at end of file diff --git a/client/src/app/Message/Message.js b/client/src/app/Message/Message.js new file mode 100644 index 0000000..0cb7841 --- /dev/null +++ b/client/src/app/Message/Message.js @@ -0,0 +1,163 @@ +(function (module) { + /** + * @ngdoc controller + * @name Message.controller:MessageController + * @description + * + * 1.This is MessageController having the methods setMetaData, init and inbox. + **/ + module.controller('MessageController', function ($state, $auth, $scope, Flash, $http, $filter, $rootScope, $location, InboxFactory, GetMessageFactory, StarMailFactory, SentMailFactory) { + var model = this; + $scope.maxSize = 5; + var params = {}; + $scope.sidebar_tpl = 'Message/message_sidebar.tpl.html'; + /** + * @ngdoc method + * @name setMetaData + * @methodOf Message.controller:MessageController + * @description + * This method is used to set the meta data dynamically by using the angular.element + * + */ + $scope.setMetaData = function () { + var pageTitle = $filter("translate")("Inbox"); + var fullUrl = $location.absUrl(); + var appUrl = $rootScope.settings['scheme_name'] + ":/" + $location.url(); + angular.element('html head meta[property="og:title"], html head meta[name="twitter:title"]').attr("content", $rootScope.settings['site.name'] + " | " + pageTitle); + angular.element('meta[property="al:ios:url"], meta[property="al:ipad:url"], meta[property="al:android:url"], meta[property="al:windows_phone:url"], html head meta[name="twitter:app:url:iphone"], html head meta[name="twitter:app:url:ipad"], html head meta[name="twitter:app:url:googleplay"]').attr('content', appUrl); + angular.element('meta[property="og:url"]').attr('content', fullUrl); + }; + /** + * @ngdoc method + * @name getInboxMessages + * @methodOf Message.controller:MessageController + * @description + * This method is used to get the auth user messages + * + */ + $scope.getInboxMessages = function () { + $scope.messages = []; + params.page = $scope.currentPage; + InboxFactory.list(params).$promise.then(function (response) { + if (response.data) { + $scope.messages = response.data; + $scope._metadata = response.meta.pagination; + } + }); + }; + + /** + * @ngdoc method + * @name getSentMessages + * @methodOf Message.controller:MessageController + * @description + * This method is used to get the auth user sent messages + * + */ + $scope.getSentMessages = function() { + $scope.messages = []; + params.page = $scope.currentPage; + SentMailFactory.list(params).$promise.then(function(response) { + if(response.data) { + $scope.messages = response.data; + $scope._metadata = response.meta.pagination; + } + }); + }; + + /** + * @ngdoc method + * @name getStarMessages + * @methodOf Message.controller:MessageController + * @description + * This method is used to get the auth user messages + * + */ + $scope.getStarMessages = function () { + $scope.messages = []; + params.page = $scope.currentPage; + StarMailFactory.list(params).$promise.then(function (response) { + if (response.data) { + $scope.messages = response.data; + $scope._metadata = response.meta.pagination; + } + }); + }; + /** + * @ngdoc method + * @name getMessages + * @methodOf Message.controller:MessageController + * @description + * This method is used to get the auth user message + * + */ + $scope.getMessage = function () { + GetMessageFactory.get({id: $state.params.id}).$promise.then(function (response) { + $scope.message = {}; + if (response.item_users !== undefined) { + $scope.message = response; + $scope.message.item_users = response.item_users.booking; + } else { + $scope.message = response; + } + }); + }; + /** + * @ngdoc method + * @name init + * @methodOf Message.controller:MessageController + * @description + * This method is used to initialize the meta data that is already set by setmetadata() method. + * + */ + $scope.init = function () { + $scope.setMetaData(); + $scope.currentPage = ($scope.currentPage !== undefined) ? parseInt($scope.currentPage) : 1; + $rootScope.pageTitle = $rootScope.settings['site.name'] + " | " + $filter("translate")("Inbox"); + $scope.type = $state.params.type; + if($scope.type == 'inbox') { + $scope.getInboxMessages(); + } else if($scope.type == 'sentmail') { + $scope.getSentMessages(); + } else if($scope.type == 'starred') { + $scope.getStarMessages(); + } + if ($state.params.id !== undefined && $state.params.action !== undefined) { + $scope.getMessage(); + $scope.message_type = $state.params.action; + } + }; + $scope.init(); + $scope.paginate = function (pageno) { + $scope.currentPage = parseInt($scope.currentPage); + $scope.init(); + }; + /** + * @ngdoc method + * @name StarMessage + * @methodOf Message.controller:MessageController + * @description + * This method is used to store the message to starred + * + */ + $scope.StarMessage = function(message_id, is_star) { + GetMessageFactory.update({id:message_id,stared:is_star}, function(response){ + if(is_star === 1){ + Flash.set($filter("translate")("Message unstarred successfully!"), 'success', true); + } + if(is_star === 0){ + Flash.set($filter("translate")("Message starred successfully!"), 'success', true); + } + if($scope.type == 'inbox') { + $scope.getInboxMessages(); + } else if($scope.type == 'sentmail') { + $scope.getSentMessages(); + } else if($scope.type == 'starred') { + $scope.getStarMessages(); + } + }, function(error){ + Flash.set($filter("translate")("Message could not be updated!"), 'error', false); + }); + }; + }); +}(angular.module("BookorRent.Messages"))); diff --git a/client/src/app/Message/Message.module.js b/client/src/app/Message/Message.module.js new file mode 100644 index 0000000..941fbeb --- /dev/null +++ b/client/src/app/Message/Message.module.js @@ -0,0 +1,67 @@ +/** + * @ngdoc object + * @name Message + * @description + * + * This is the module for Message + * + * The angular.module is a global place for creating, registering and retrieving Angular modules. + * All modules that should be available to an application must be registered using this mechanism. + * Passing one argument retrieves an existing angular.Module, whereas passing more than one argument creates a new angular.Module + * + * @param {string} Message name of the module + * @param {!Array.=} dependencies If specified then new module is being created. If unspecified then the module is being retrieved for further configuration. + * + * [ + * 'ui.router', + * 'ngResource', + * 'angulartics', + * 'angulartics.google.analytics', + * 'angulartics.facebook.pixel' + * ] + * @param {Function=} configFn Optional configuration function for the module. + * @returns {angular.Module} new BookorRent.Message module with the angular.Module api. + **/ +(function (module) { + module.config(function ($stateProvider, $analyticsProvider) { + var ResolveServiceData = { + 'ResolveServiceData': function (ResolveService, $q) { + return $q.all({ + AuthServiceData: ResolveService.promiseAuth, + SettingServiceData: ResolveService.promiseSettings + }); + } + }; + $stateProvider.state('message', { + url: '/messages/{type}', + authenticate: true, + views: { + "main": { + controller: 'MessageController as model', + templateUrl: 'Message/message_list.tpl.html', + resolve: ResolveServiceData + } + }, + data: {pageTitle: 'Inbox'} + }) + .state('view_message', { + url: '/message/{id}/{action}', + authenticate: true, + views: { + "main": { + controller: 'MessageController as model', + templateUrl: 'Message/message_view.tpl.html', + resolve: ResolveServiceData + } + }, + data: {pageTitle: 'View Message'} + }); + + }); +}(angular.module("BookorRent.Messages", [ + 'ui.router', + 'ngResource', + 'angulartics', + 'angulartics.google.analytics', + 'angulartics.facebook.pixel' +]))); diff --git a/client/src/app/Message/MessageService.js b/client/src/app/Message/MessageService.js new file mode 100644 index 0000000..ea7e52f --- /dev/null +++ b/client/src/app/Message/MessageService.js @@ -0,0 +1,71 @@ +(function (module) { + /** + * @ngdoc service + * @name Message.MessageController + * @description + * InboxFactory is a factory service which is used to get the auth user messages + * @param {string} InboxFactory The name of the factory + * @param {function()} function It uses get method, and get the auth user messages + */ + module.factory('InboxFactory', function ($resource, GENERAL_CONFIG) { + return $resource(GENERAL_CONFIG.api_url + '/messages', {}, { + list: { + method: 'GET' + } + }); + }); + + /** + * @ngdoc service + * @name Message.MessageController + * @description + * SentMailFactory is a factory service which is used to get the auth user sent messages + * @param {string} SentMailFactory The name of the factory + * @param {function()} function It uses get method, and get the auth user sent messages + */ + module.factory('SentMailFactory', function ($resource, GENERAL_CONFIG) { + return $resource(GENERAL_CONFIG.api_url + '/sentMessages', {}, { + list: { + method: 'GET' + } + }); + }); + + /** + * @ngdoc service + * @name Message.MessageController + * @description + * StarMailFactory is a factory service which is used to get the auth user star messages + * @param {string} StarMailFactory The name of the factory + * @param {function()} function It uses get method, and get the auth user star messages + */ + module.factory('StarMailFactory', function ($resource, GENERAL_CONFIG) { + return $resource(GENERAL_CONFIG.api_url + '/starMessages', {}, { + list: { + method: 'GET' + } + }); + }); + + /** + * @ngdoc service + * @name Message.MessageController + * @description + * GetMessageFactory is a factory service which is used to get the auth user message + * @param {string} GetMessageFactory The name of the factory + * @param {function()} function It uses get method, and get the auth user message + */ + module.factory('GetMessageFactory', function ($resource, GENERAL_CONFIG) { + return $resource(GENERAL_CONFIG.api_url + '/messages/:id', { + id:'@id', + }, { + get: { + method: 'GET' + }, + update: { + method: 'PUT' + } + }); + }); + +})(angular.module("BookorRent.Messages")); diff --git a/client/src/app/Message/message_list.tpl.html b/client/src/app/Message/message_list.tpl.html new file mode 100644 index 0000000..49be768 --- /dev/null +++ b/client/src/app/Message/message_list.tpl.html @@ -0,0 +1,48 @@ +
+
+

{{'Messages' | translate}} - + {{'Inbox' | translate}} + {{'Sent' | translate}} + {{'Starred' | translate}} +

+
+
+
+
+
+
+
+
+
+
+
+ + + + + + + + + + +
+ + + {{message.from_user.username}} + + + + {{message.created_at}} +
+

{{'No Record Found' |translate}}

+
+
+
+ +
+
+
+
+
+
\ No newline at end of file diff --git a/client/src/app/Message/message_sidebar.tpl.html b/client/src/app/Message/message_sidebar.tpl.html new file mode 100644 index 0000000..375d87d --- /dev/null +++ b/client/src/app/Message/message_sidebar.tpl.html @@ -0,0 +1,5 @@ + diff --git a/client/src/app/Message/message_view.tpl.html b/client/src/app/Message/message_view.tpl.html new file mode 100644 index 0000000..a68815a --- /dev/null +++ b/client/src/app/Message/message_view.tpl.html @@ -0,0 +1,39 @@ +
+
+

{{'Message View' | translate}}

+
+
+
+
+
+
+
+
+
+
+ {{'Back to Sent Mail' | translate}} + {{'Back to Inbox' | translate}} + {{'Back to Starred' | translate}} + + + + + + + + + + + + + + +
{{'From: ' | translate }}{{'To: ' | translate }}{{message.from_user.username}}
{{'Date: ' | translate }}{{message.created_at}}
{{'Subject: ' | translate }}
+
+
+
+
+
+
+
+
diff --git a/client/src/app/Plugins/Analytics/Analytics.js b/client/src/app/Plugins/Analytics/Analytics.js new file mode 100644 index 0000000..7c1916c --- /dev/null +++ b/client/src/app/Plugins/Analytics/Analytics.js @@ -0,0 +1,130 @@ +/** + * BookorRent - v1.0a.01 - 2016-03-28 + * + * Copyright (c) 2016 Agriya + */ +/** + * @ngdoc object + * @name Analytics + * @description + * + * This is the module for analytics. It contains the analytics functionalities. + * + * The analytics module act as a state provider, this module get the url and load the template and call the controller instantly. + * + * @param {string} analytics name of the module + * @param {!Array.=} dependencies If specified then new module is being created. If unspecified then the module is being retrieved for further configuration. + * + * [ + * 'ui.router', + * 'ngResource', + * ] + * @param {Function=} configFn Optional configuration function for the module. + * @returns {BookorRent.Module} new BookorRent.Analytics module. + **/ +(function (module) { + module.config(function () { + + }); + +}(angular.module('BookorRent.Analytics', [ + 'ui.router', + 'ngResource', +]))); + +(function (module) { + /** + * @ngdoc directive + * @name Analytics.directive:facebookPixel + * @scope + * @restrict AE + * @description + * Facebook pixel directive creates a facebook pixel tag. We can use this as a element and attribute. + * @param {string} facebookPixel Name of the directive + **/ + module.directive('facebookPixel', function () { + var linker = function (scope, element, attrs) { + // do DOM Manipulation here + }; + return { + restrict: 'AE', + link: linker, + controller: function ($rootScope, ResolveService) { + var promise = ResolveService.promise; + var promiseSettings = ResolveService.promiseSettings; + promiseSettings.then(function (data) { + if ($rootScope.settings) { + !function (f, b, e, v, n, t, s) { + if (f.fbq)return; + n = f.fbq = function () { + n.callMethod ? + n.callMethod.apply(n, arguments) : n.queue.push(arguments) + }; + if (!f._fbq)f._fbq = n; + n.push = n; + n.loaded = !0; + n.version = '2.0'; + n.queue = []; + t = b.createElement(e); + t.async = !0; + t.src = v; + s = b.getElementsByTagName(e)[0]; + s.parentNode.insertBefore(t, s) + }(window, + document, 'script', '//connect.facebook.net/en_US/fbevents.js'); + fbq('init', $rootScope.settings['analytics.facebook_analytics.pixel']); + } + }); + + }, + scope: {} + }; + }); + + +})(angular.module('BookorRent.Analytics')); + +(function (module) { + /** + * @ngdoc directive + * @name Analytics.directive:googleAnalytics + * @scope + * @restrict AE + * @description + * GoogleAnalytics directive creates a googleAnalytics tag. We can use this as a element and attribute. + * @param {string} googleAnalytics Name of the directive + **/ + module.directive('googleAnalytics', function () { + var linker = function (scope, element, attrs) { + // do DOM Manipulation here + }; + return { + restrict: 'AE', + link: linker, + controller: function ($rootScope, ResolveService) { + var promise = ResolveService.promise; + var promiseSettings = ResolveService.promiseSettings; + promiseSettings.then(function (data) { + if ($rootScope.settings) { + (function (i, s, o, g, r, a, m) { + i['GoogleAnalyticsObject'] = r; + i[r] = i[r] || function () { + (i[r].q = i[r].q || []).push(arguments) + }, i[r].l = 1 * new Date(); + a = s.createElement(o), + m = s.getElementsByTagName(o)[0]; + a.async = 1; + a.src = g; + m.parentNode.insertBefore(a, m) + })(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga'); + ga('create', $rootScope.settings['analytics.google_analytics.profile_id'], 'auto'); + } + }); + + }, + scope: {} + }; + }); + + +})(angular.module('BookorRent.Analytics')); diff --git a/client/src/app/Plugins/Banner/Banner.js b/client/src/app/Plugins/Banner/Banner.js new file mode 100644 index 0000000..df95db2 --- /dev/null +++ b/client/src/app/Plugins/Banner/Banner.js @@ -0,0 +1,63 @@ +/** + * BookorRent - v1.0a.01 - 2016-03-28 + * + * Copyright (c) 2016 Agriya + */ +/** + * @ngdoc object + * @name Banner + * @description + * + * This is the module for banner. It contains the banner functionalities. + * + * The banner module have directive and controller. The directive which is used to load the template and call the controller instantly. + * + * @param {string} banner name of the module + * @param {!Array.=} dependencies The dependencies are included in main BookorRent.Banner module. + * + * [ + * 'ui.router', + * 'ngResource' + * ] + * @returns {BookorRent.Banner} new BookorRent.Banner module. + **/ + +(function (module) { + /** + * @ngdoc directive + * @name Banner.directive:Banner + * @scope + * @restrict A + * @description + * Banner directive creates a banner tag. We can use this only as an attribute. + * @param {string} banner Name of the directive + **/ + module.directive('banner', function () { + var linker = function (scope, element, attrs) { + // do DOM Manipulation here + }; + return { + restrict: 'A', + templateUrl: 'Plugins/Banner/banner.tpl.html', + link: linker, + controller: 'BannerController as model', + bindToController: true, + scope: { + position: '@position' + } + }; + }); + /** + * @ngdoc controller + * @name Banner.controller:BannerController + * @description + * This is BannerController. All banner related functionalities will be declared here. + **/ + module.controller('BannerController', function () { + var model = this; + }); + +}(angular.module("BookorRent.Banner", [ + 'ui.router', + 'ngResource' +]))); diff --git a/client/src/app/Plugins/Banner/banner.tpl.html b/client/src/app/Plugins/Banner/banner.tpl.html new file mode 100644 index 0000000..7fa3b9f --- /dev/null +++ b/client/src/app/Plugins/Banner/banner.tpl.html @@ -0,0 +1,10 @@ + +
+
+
+
+
+
+
+
+ \ No newline at end of file diff --git a/client/src/app/Plugins/Contacts/Contacts.js b/client/src/app/Plugins/Contacts/Contacts.js new file mode 100644 index 0000000..8ebbf0e --- /dev/null +++ b/client/src/app/Plugins/Contacts/Contacts.js @@ -0,0 +1,103 @@ +(function (module) { + /** + * @ngdoc directive + * @name contacts.directive:contactLinks + * @module Contacts + * @scope + * This directive used to load the contact page url link. + * @restrict A + * @description + * This directive used to load the contact page template. + */ + module.directive('contactLinks', function () { + var linker = function (scope, element, attrs) { + // do DOM Manipulation here + }; + return { + restrict: 'A', + replace: true, + templateUrl: 'Plugins/Contacts/contact_links.tpl.html', + link: linker, + controller: 'ContactUsController as model', + bindToController: true + }; + }); + /** + * @ngdoc controller + * @name Contacts.controller:ContactUsController + * @description + * This is contactUs controller having the methods init(), setMetaData(), and contactFormSubmit(). + * It controls the functionality of contact us. + **/ + module.controller('ContactUsController', function ($scope, $rootScope, ContactsFactory, $filter, Flash, $state, $location, vcRecaptchaService) { + var model = this; + /** + * @ngdoc method + * @name setMetaData + * @methodOf Contacts.controller:ContactUsController + * @description + * This method will set the meta data's dynamically by using the angular.element + * @returns {Element} New meta data element. + **/ + model.setMetaData = function () { + var pageTitle = $filter("translate")("Contact Us"); + var fullUrl = $location.absUrl(); + var appUrl = $rootScope.settings['scheme_name'] + ":/" + $location.url(); + angular.element('html head meta[property="og:title"], html head meta[name="twitter:title"]').attr("content", $rootScope.settings['site.name'] + " | " + pageTitle); + angular.element('meta[property="al:ios:url"], meta[property="al:ipad:url"], meta[property="al:android:url"], meta[property="al:windows_phone:url"], html head meta[name="twitter:app:url:iphone"], html head meta[name="twitter:app:url:ipad"], html head meta[name="twitter:app:url:googleplay"]').attr('content', appUrl); + angular.element('meta[property="og:url"]').attr('content', fullUrl); + }; + /** + * @ngdoc method + * @name init + * @methodOf Contacts.controller:ContactUsController + * @description + * This method will initialize the page. It returns the page title. + **/ + model.init = function () { + model.setMetaData(); + model.captcha_site_key = $rootScope.settings['captcha.site_key']; + if($location.path() == '/contactus') { + $rootScope.pageTitle = $rootScope.settings['site.name'] + " | " + $filter("translate")("Contact Us"); + } + }; + $scope.setRecaptchaId = function (widgetId) { + $scope.widgetId = widgetId; + }; + + model.init(); + /** + * @ngdoc method + * @name contactFormSubmit + * @methodOf Contacts.controller:ContactUsController + * @description + * This method handles the form which is used for contact, and add contact details. + * @param {integer} FormDetails Contact form details. + * @returns {Array} Success or failure message. + **/ + model.contactFormSubmit = function ($valid) { + model.emailErr = ''; + model.captchaErr = ''; + var response = vcRecaptchaService.getResponse($scope.widgetId); + if (response.length === 0) { + model.captchaErr = $filter("translate")("Please resolve the captcha and submit"); + } else { + model.captchaErr = ''; + } + if ($valid) { + model.contactForm.recaptcha_response = response; + ContactsFactory.save(model.contactForm).$promise.then(function (response) { + Flash.set($filter("translate")("Thank you, we received your message and will get back to you as soon as possible."), 'success', true); + $state.reload('contact'); + }, function (error) { + var errMsg = error.data.errors; + if (errMsg.email) { + model.emailErr = $filter("translate")(errMsg.email[0]); + } + Flash.set($filter("translate")("Contact message could not be sent. Please, try again."), 'error', false); + }); + } + + }; + }); +}(angular.module("BookorRent.Contacts"))); diff --git a/client/src/app/Plugins/Contacts/Contacts.module.js b/client/src/app/Plugins/Contacts/Contacts.module.js new file mode 100644 index 0000000..54e2916 --- /dev/null +++ b/client/src/app/Plugins/Contacts/Contacts.module.js @@ -0,0 +1,63 @@ +/** + * BookorRent - v1.0a.01 - 2016-03-28 + * + * Copyright (c) 2016 Agriya + */ +/** + * @ngdoc object + * @name Contacts + * @description + * + * This is the module for Contacts. It contains the contact us functionalities. + * + * The contact module act as a state provider, this module get the url and load the template and call the controller instantly. + * + * @param {string} Contacts name of the module + * @param {!Array.=} dependencies If specified then new module is being created. If unspecified then the module is being retrieved for further configuration. + * + * [ + * 'ui.router', + * 'ngResource', + * 'angulartics', + * 'angulartics.google.analytics', + * 'angulartics.facebook.pixel', + * 'vcRecaptcha' + * ] + * @param {string} stateProvider State provider is used to provide a corresponding model and template. + * @param {string} analyticsProvider This service lets you integrate google analytics tracker in your AngularJS applications easily. + * @returns {BookorRent.Contacts} new BookorRent.Contacts module. + **/ +(function (module) { + + module.config(function ($stateProvider, $analyticsProvider) { + var ResolveServiceData = { + 'ResolveServiceData': function (ResolveService, $q) { + return $q.all({ + AuthServiceData: ResolveService.promiseAuth, + SettingServiceData: ResolveService.promiseSettings + }); + } + }; + $stateProvider + .state('contact', { + url: '/contactus', + authenticate: false, + views: { + 'main': { + controller: 'ContactUsController as model', + templateUrl: 'Plugins/Contacts/contacts.tpl.html', + resolve: ResolveServiceData + } + } + }); + + }); + +}(angular.module('BookorRent.Contacts', [ + 'ui.router', + 'ngResource', + 'angulartics', + 'angulartics.google.analytics', + 'angulartics.facebook.pixel', + 'vcRecaptcha' +]))); diff --git a/client/src/app/Plugins/Contacts/ContactsService.js b/client/src/app/Plugins/Contacts/ContactsService.js new file mode 100644 index 0000000..ae17c3a --- /dev/null +++ b/client/src/app/Plugins/Contacts/ContactsService.js @@ -0,0 +1,25 @@ +(function (module) { + /** + * @ngdoc service + * @name Contacts.ContactsFactory + * @description + * ContactsFactory used to store the contact details. + * @param {function()} function It used to save the data. + * @param {string} url Base url accessed in GENERAL_CONFIG. + * @returns {object} The service contains these actions: + * + * { + * 'save': {method:'POST'} + * }; + */ + module.factory('ContactsFactory', function ($resource, GENERAL_CONFIG) { + return $resource( + GENERAL_CONFIG.api_url + '/contacts', {}, { + 'save': { + method: 'POST' + } + } + ); + }); + +})(angular.module("BookorRent.Contacts")); diff --git a/client/src/app/Plugins/Contacts/contact_links.tpl.html b/client/src/app/Plugins/Contacts/contact_links.tpl.html new file mode 100644 index 0000000..6ed73eb --- /dev/null +++ b/client/src/app/Plugins/Contacts/contact_links.tpl.html @@ -0,0 +1 @@ +{{'Contact Us'|translate}} \ No newline at end of file diff --git a/client/src/app/Plugins/Contacts/contacts.tpl.html b/client/src/app/Plugins/Contacts/contacts.tpl.html new file mode 100644 index 0000000..be12e70 --- /dev/null +++ b/client/src/app/Plugins/Contacts/contacts.tpl.html @@ -0,0 +1,77 @@ + +
+
+

{{'Contact Us' | translate}}

+
+
+
+
+
+
+
+ + +
+ {{'You must enter your first name' | translate}} + {{'Minimum length is 2' | translate}} +
+
+
+ + +
+ {{'You must enter your last name' | translate}} + {{'Minimum length is 2' | translate}}. +
+
+
+ + +
+ {{'You must enter your Email' | translate}}. + {{'Enter Valid Email' | translate}} + {{model.emailErr}} +
+
+
+
+
+ + +
+ {{'You must enter your Subject' | translate}} + {{'Minimum length is 5' | translate}} +
+
+
+ + +
+ {{'You must enter your Mobile number' | translate}} + {{'Enter valid number' | translate}} + {{'Minimum length is 10' | translate}} +
+
+
+
+
+ + +
+ {{'You must enter your Message' | translate}} + {{'Minimum length is 10' | translate}} +
+
+
+ +
+ {{model.captchaErr}} +
+
+ + +
+
+
+
+
\ No newline at end of file diff --git a/client/src/app/Plugins/CurrencyConversions/CurrencyConversion.js b/client/src/app/Plugins/CurrencyConversions/CurrencyConversion.js new file mode 100644 index 0000000..1f5d5e4 --- /dev/null +++ b/client/src/app/Plugins/CurrencyConversions/CurrencyConversion.js @@ -0,0 +1,46 @@ +(function (module) { + /** + * @ngdoc directive + * @name CurrencyConversion.directive:currencyConversion + * @module CurrencyConversions + * @scope + * This directive used to load converted currency details. + * @restrict EA + * @description + * This directive used to load the converted currency details in element. + */ + module.directive('currencyConversion', function () { + return { + restrict: 'EA', + templateUrl: "Plugins/CurrencyConversions/currency_conversion.tpl.html", + controller: function ($scope, $rootScope, $element, $attrs, $state, Flash, $filter) { + var model = this; + $scope.getCurrentCurrency = function (currency_id) { + angular.forEach($rootScope.currencies, function (data) { + if (data.id == currency_id) { + localStorage.setItem('convertedCurrency', JSON.stringify(data)); + $scope.currency_code = data.code; + } + }); + }; + $scope.$watch('defaultcurrency', function (currency_id) { + var default_currency, currency_obj, currency; + if ($scope.defaultcurrency !== '') { + default_currency = $scope.defaultcurrency; + currency_obj = localStorage.getItem('convertedCurrency'); + currency_obj = JSON.parse(currency_obj); + currency = (currency_obj) ? currency_obj : default_currency; + $scope.currency = currency.id; + $scope.currency_code = currency.code; + + } + }); + }, + scope: { + getCurrentCurrency: '&', + defaultcurrency: '=' + } + }; + }); + +}(angular.module("BookorRent.CurrencyConversions"))); diff --git a/client/src/app/Plugins/CurrencyConversions/CurrencyConversion.module.js b/client/src/app/Plugins/CurrencyConversions/CurrencyConversion.module.js new file mode 100644 index 0000000..e49a814 --- /dev/null +++ b/client/src/app/Plugins/CurrencyConversions/CurrencyConversion.module.js @@ -0,0 +1,36 @@ +/** + * BookorRent - v1.0a.01 - 2016-03-28 + * + * Copyright (c) 2016 Agriya + */ +/** + * @ngdoc object + * @name CurrencyConversions + * @description + * + * This is the module for CurrencyConversions. It contains the Currency Conversion functionalities. + * + * The contact module act as a state provider, this module get the url and load the template and call the controller instantly. + * + * @param {string} CurrencyConversions name of the module + * @param {!Array.=} dependencies If specified then new module is being created. If unspecified then the module is being retrieved for further configuration. + * + * [ + * 'ui.router', + * 'ngResource', + * 'angulartics', + * 'angulartics.google.analytics', + * 'angulartics.facebook.pixel' + * ] + * @returns {BookorRent.CurrencyConversions} new BookorRent.CurrencyConversions module. + **/ +(function (module) { + + +}(angular.module('BookorRent.CurrencyConversions', [ + 'ui.router', + 'ngResource', + 'angulartics', + 'angulartics.google.analytics', + 'angulartics.facebook.pixel' +]))); diff --git a/client/src/app/Plugins/CurrencyConversions/currency_conversion.tpl.html b/client/src/app/Plugins/CurrencyConversions/currency_conversion.tpl.html new file mode 100644 index 0000000..bc89661 --- /dev/null +++ b/client/src/app/Plugins/CurrencyConversions/currency_conversion.tpl.html @@ -0,0 +1,4 @@ + {{currency_code}} + \ No newline at end of file diff --git a/client/src/app/Plugins/Pages/Pages.js b/client/src/app/Plugins/Pages/Pages.js new file mode 100644 index 0000000..679c54b --- /dev/null +++ b/client/src/app/Plugins/Pages/Pages.js @@ -0,0 +1,76 @@ +(function (module) { + /** + * @ngdoc directive + * @name Pages.directive:footerLinks + * @scope + * @restrict AE + * + * @description + * footerLinks directive creates a footerLinks tag. We can use this as an element. + * + * @param {string} googleAnalytics Name of the directive + * + **/ + module.directive('footerLinks', function () { + var linker = function (scope, element, attrs) { + // do DOM Manipulation here + }; + return { + restrict: 'A', + templateUrl: 'Plugins/Pages/page_links.tpl.html', + link: linker, + controller: 'PagesController as model', + bindToController: true + }; + }); + /** + * @ngdoc controller + * @name Pages.controller:PagesController + * @description + * + * This is pages controller having the methods init(), setMetaData(). It controls the static pages. + **/ + module.controller('PagesController', function ($scope, $http, $filter, $state, $rootScope, $location, PageFactory, $translate, $translateLocalStorage) { + var model = this; + /** + * @ngdoc method + * @name setMetaData + * @methodOf Pages.controller:PagesController + * @description + * + * This method will set the meta data dynamically by using the angular.element + **/ + model.setMetaData = function (title) { + var fullUrl = $location.absUrl(); + var appUrl = $rootScope.settings['scheme_name'] + ":/" + $location.url(); + angular.element('html head meta[property="og:title"], html head meta[name="twitter:title"]').attr("content", $rootScope.settings['site.name'] + " | " + title); + angular.element('meta[property="al:ios:url"], meta[property="al:ipad:url"], meta[property="al:android:url"], meta[property="al:windows_phone:url"], html head meta[name="twitter:app:url:iphone"], html head meta[name="twitter:app:url:ipad"], html head meta[name="twitter:app:url:googleplay"]').attr('content', appUrl); + angular.element('meta[property="og:url"]').attr('content', fullUrl); + }; + /** + * @ngdoc method + * @name init + * @methodOf Pages.controller:PagesController + * @description + * This method will initialze the page. It returns the page title + * + **/ + model.init = function () { + var currentLocale = $translate.preferredLanguage(); + if ($translate.use() !== undefined) { + currentLocale = $translate.use(); + } else if ($translateLocalStorage.get('NG_TRANSLATE_LANG_KEY') !== undefined || $translateLocalStorage.get('NG_TRANSLATE_LANG_KEY') !== null) { + currentLocale = $translateLocalStorage.get('NG_TRANSLATE_LANG_KEY'); + } + if ($state.params.slug !== undefined && $state.params.slug !== null) { + PageFactory.get({slug: $state.params.slug, iso2: currentLocale}).$promise + .then(function (response) { + $scope.page = response; + model.setMetaData(response.title); + $rootScope.pageTitle = $rootScope.settings['site.name'] + " | " + response.title; + }); + } + }; + model.init(); + }); +}(angular.module("BookorRent.Pages"))); diff --git a/client/src/app/Plugins/Pages/Pages.module.js b/client/src/app/Plugins/Pages/Pages.module.js new file mode 100644 index 0000000..469e07d --- /dev/null +++ b/client/src/app/Plugins/Pages/Pages.module.js @@ -0,0 +1,60 @@ +/** + * LumenBase - v1.0a.01 - 2016-03-28 + * + * Copyright (c) 2016 Agriya + */ +/** + * @ngdoc object + * @name Pages + * @description + * + * This is the module for pages. It contains the pages functionalities. + * + * The contact module act as a state provider, this module get the url and load the template and call the controller instantly. + * + * @param {string} pages name of the module + * @param {!Array.=} dependencies If specified then new module is being created. If unspecified then the module is being retrieved for further configuration. + * + * [ + * 'ui.router', + * 'ngResource', + * 'angulartics', + * 'angulartics.google.analytics', + * 'angulartics.facebook.pixel', + * 'vcRecaptcha' + * ] + * @param {string} stateProvider State provider is used to provide a corresponding model and template. + * @param {string} analyticsProvider This service lets you integrate google analytics tracker in your AngularJS applications easily. + **/ +(function (module) { + + module.config(function ($stateProvider, $analyticsProvider) { + var ResolveServiceData = { + 'ResolveServiceData': function (ResolveService, $q) { + return $q.all({ + AuthServiceData: ResolveService.promiseAuth, + SettingServiceData: ResolveService.promiseSettings + }); + } + }; + $stateProvider.state('pages', { + url: '/page/{slug}', + authenticate: false, + views: { + "main": { + controller: 'PagesController as model', + templateUrl: 'Plugins/Pages/pages.tpl.html', + resolve: ResolveServiceData + } + }, + data: {pageTitle: 'Pages'} + }); + }); + +}(angular.module("BookorRent.Pages", [ + 'ui.router', + 'ngResource', + 'angulartics', + 'angulartics.google.analytics', + 'angulartics.facebook.pixel' +]))); diff --git a/client/src/app/Plugins/Pages/Pages.spec.js b/client/src/app/Plugins/Pages/Pages.spec.js new file mode 100644 index 0000000..e69de29 diff --git a/client/src/app/Plugins/Pages/PagesService.js b/client/src/app/Plugins/Pages/PagesService.js new file mode 100644 index 0000000..cb656e4 --- /dev/null +++ b/client/src/app/Plugins/Pages/PagesService.js @@ -0,0 +1,28 @@ +(function (module) { + /** + * @ngdoc service + * @name Pages.PageFactory + * @description + * PageFactory used to fetch the page details. + * @param {function()} function It used to fetch the data. + * @param {string} url Base url accessed in GENERAL_CONFIG. + * @param {string} slug Page slug. + * @param {string} iso2 Content iso. + * @returns {object} The service contains these actions: + * + * { + * 'get': {method:'GET'} + * }; + */ + module.factory('PageFactory', function ($resource, GENERAL_CONFIG) { + return $resource(GENERAL_CONFIG.api_url + '/page/:slug/:iso2', { + slug: '@slug', + iso2: '@iso2' + }, { + 'get': { + method: 'GET' + } + } + ); + }); +})(angular.module("BookorRent.Pages")); diff --git a/client/src/app/Plugins/Pages/page_links.tpl.html b/client/src/app/Plugins/Pages/page_links.tpl.html new file mode 100644 index 0000000..0bc92fb --- /dev/null +++ b/client/src/app/Plugins/Pages/page_links.tpl.html @@ -0,0 +1,15 @@ + + + \ No newline at end of file diff --git a/client/src/app/Plugins/Pages/pages.tpl.html b/client/src/app/Plugins/Pages/pages.tpl.html new file mode 100644 index 0000000..ddac319 --- /dev/null +++ b/client/src/app/Plugins/Pages/pages.tpl.html @@ -0,0 +1,13 @@ + +
+ +
+
+

+
+
+
\ No newline at end of file diff --git a/client/src/app/Plugins/Paypal/Paypal.module.js b/client/src/app/Plugins/Paypal/Paypal.module.js new file mode 100644 index 0000000..5944634 --- /dev/null +++ b/client/src/app/Plugins/Paypal/Paypal.module.js @@ -0,0 +1,28 @@ +/** + * LumenBase - v1.0a.01 - 2016-03-28 + * + * Copyright (c) 2016 Agriya + */ +/** + * @ngdoc object + * @name Paypal + * @description + * + * This is the module for Paypal. It contains the Paypal functionalities. + * + * The Paypal module act as a state provider, this module get the url and load the template and call the controller instantly. + * + * @param {!Array.=} dependencies If specified then new module is being created. If unspecified then the module is being retrieved for further configuration. + * + * [ + * 'ui.router', + * 'ngResource' + * ] + * @returns {BookorRent.Paypal} new BookorRent.Paypal module. + **/ +(function (module) { + +}(angular.module("BookorRent.Paypal", [ + 'ui.router', + 'ngResource' +]))); diff --git a/client/src/app/Plugins/SocialLogins/SocialConnection.js b/client/src/app/Plugins/SocialLogins/SocialConnection.js new file mode 100644 index 0000000..66f8088 --- /dev/null +++ b/client/src/app/Plugins/SocialLogins/SocialConnection.js @@ -0,0 +1,128 @@ +(function (module) { + /** + * @ngdoc controller + * @name SocialLogins.controller:SocialConnectionController + * @description + * This is SocialConnection Controller having the methods init(), setMetaData(), getProviderUsers(), connect() and disconnect(). + * It maintains the functinolities of the social profile. + **/ + module.controller('SocialConnectionController', function ($state, ProvidersFactory, $auth, $scope, $rootScope, $location, AuthFactory, $filter, Flash, ProviderUsersFactory, ConstSocialLogin) { + var model = this; + /** + * @ngdoc method + * @name setMetaData + * @methodOf SocialLogins.controller:SocialConnectionController + * @description + * This method will set the meta data dynamically by using the angular.element. + * @returns {Element} New meta data element. + **/ + model.setMetaData = function () { + var pageTitle = $filter("translate")("Social Connection"); + var fullUrl = $location.absUrl(); + var appUrl = $rootScope.settings['scheme_name'] + ":/" + $location.url(); + angular.element('html head meta[property="og:title"], html head meta[name="twitter:title"]').attr("content", $rootScope.settings['site.name'] + " | " + pageTitle); + angular.element('meta[property="al:ios:url"], meta[property="al:ipad:url"], meta[property="al:android:url"], meta[property="al:windows_phone:url"], html head meta[name="twitter:app:url:iphone"], html head meta[name="twitter:app:url:ipad"], html head meta[name="twitter:app:url:googleplay"]').attr('content', appUrl); + angular.element('meta[property="og:url"]').attr('content', fullUrl); + }; + model.sociallogin = {}; + /** + * @ngdoc method + * @name getProviderUsers + * @methodOf SocialLogins.controller:SocialConnectionController + * @description + * This method will get the list of service providers. + **/ + model.getProviderUsers = function () { + model.fb_connected = false; + ProviderUsersFactory.get().$promise.then(function (response) { + angular.forEach(response.data, function (value, key) { + if (value.provider_id == ConstSocialLogin.Facebook && value.is_connected) { + model.fb_connected = true; + model.fb_img = value.profile_picture_url; + } else if (value.provider_id == ConstSocialLogin.Twitter && value.is_connected) { + model.twitter_connected = true; + model.twt_img = value.profile_picture_url; + } else if (value.provider_id == ConstSocialLogin.Google && value.is_connected) { + model.google_connected = true; + model.goo_img = value.profile_picture_url; + } else if (value.provider_id == ConstSocialLogin.Github && value.is_connected) { + model.github_connected = true; + model.git_img = value.profile_picture_url; + } + }); + }); + }; + /** + * @ngdoc method + * @name init + * @methodOf SocialLogins.controller:SocialConnectionController + * @description + * This method will initialize the meta data and functionalities. + **/ + model.init = function () { + model.setMetaData(); + $rootScope.pageTitle = $rootScope.settings['site.name'] + " | " + $filter("translate")("Social Connection"); + //Get Active social logins + ProvidersFactory.get({'filter': 'active', 'sortby': 'asc', 'sort': 'display_order'}).$promise + .then(function (response) { + model.sociallogin = response; + }); + //check if user connect with social + model.getProviderUsers(); + }; + model.init(); + //Connect with providers + /** + * @ngdoc method + * @name connect + * @methodOf SocialLogins.controller:SocialConnectionController + * @description + * This method will be used in connecting the user to the social websites. + * @param {integer} provider Provider details. + * @returns {Array} Success or failure message. + **/ + model.connect = function (provider) { + $auth.link(provider).then(function (response) { + if (response.data.provider_id == ConstSocialLogin.Facebook && response.data.is_connected) { + model.fb_connected = true; + } else if (response.data.provider_id == ConstSocialLogin.Twitter && response.data.is_connected) { + model.twitter_connected = true; + } else if (response.data.provider_id == ConstSocialLogin.Google && response.data.is_connected) { + model.google_connected = true; + } else if (response.data.provider_id == ConstSocialLogin.Github && response.data.is_connected) { + model.github_connected = true; + } + Flash.set($filter("translate")("Connected Successfully"), 'success', true); + }).catch(function (error) { + Flash.set($filter("translate")(error.data.message), 'error', false); + }); + }; + //Disconnect with providers + /** + * @ngdoc method + * @name connect + * @methodOf SocialLogins.controller:SocialConnectionController + * @description + * This method will be used in disconnecting the user to the social websites. + * @param {integer} provider Provider details. + * @returns {Array} Success or failure message. + **/ + model.disconnect = function (provider) { + $auth.unlink(provider).then(function (response) { + AuthFactory.fetch().$promise.then(function (user) { + $rootScope.auth = user; + }); + if (response.data.provider_id == ConstSocialLogin.Facebook && !response.data.is_connected) { + model.fb_connected = false; + } else if (response.data.provider_id == ConstSocialLogin.Twitter && !response.data.is_connected) { + model.twitter_connected = false; + } else if (response.data.provider_id == ConstSocialLogin.Google && !response.data.is_connected) { + model.google_connected = false; + } else if (response.data.provider_id == ConstSocialLogin.Github && !response.data.is_connected) { + model.github_connected = false; + } + Flash.set($filter("translate")("Disconnected successfully"), 'success', true); + }); + }; + }); +}(angular.module('BookorRent.SocialLogins'))); diff --git a/client/src/app/Plugins/SocialLogins/SocialLogin.js b/client/src/app/Plugins/SocialLogins/SocialLogin.js new file mode 100644 index 0000000..ab93fef --- /dev/null +++ b/client/src/app/Plugins/SocialLogins/SocialLogin.js @@ -0,0 +1,208 @@ +(function (module) { + module.config(function ($authProvider, GENERAL_CONFIG) { + var ResolveServiceData = { + 'ResolveServiceData': function (ResolveService, $q) { + return $q.all({ + AuthServiceData: ResolveService.promiseAuth, + SettingServiceData: ResolveService.promiseSettings + }); + } + }; + var url = GENERAL_CONFIG.api_url + '/providers'; + var params = {}; + $.get(url, params, function (response) { + var credentials = {}; + var url = GENERAL_CONFIG.api_url + '/auth/'; + if (location.hostname == 'localhost') { + url = window.location.protocol + '//' + window.location.host + url; + } + angular.forEach(response.data, function (res, i) { + credentials = { + clientId: res.api_key, + redirectUri: url + angular.lowercase(res.name), + url: GENERAL_CONFIG.api_url + '/auth/' + angular.lowercase(res.name) + }; + if (res.name === 'Facebook') { + $authProvider.facebook(credentials); + } + if (res.name === 'Google') { + $authProvider.google(credentials); + } + if (res.name === 'Twitter') { + $authProvider.twitter(credentials); + } + if (res.name === 'Github') { + credentials = { + redirectUri: url + 'github', + url: url + 'github', + clientId: res.api_key + }; + $authProvider.github(credentials); + } + }); + }); + }); + /** + * @ngdoc directive + * @name SocialLogins.directive:socialLogin + * @module SocialLogins + * @scope + * This directive used to load the social login page url link. + * @restrict E + * @description + * This directive used to load the social login page template. + */ + module.directive('socialLogin', function () { + var linker = function (scope, element, attrs) { + // do DOM Manipulation here + }; + return { + restrict: 'E', + templateUrl: 'Plugins/SocialLogins/social_login.tpl.html', + link: linker, + controller: 'SocialLoginController as model', + bindToController: true, + scope: { + pageType: '@pageType' + } + }; + }); + /** + * @ngdoc controller + * @name SocialLogins.controller:SocialLoginEmailController + * @description + * This is SocialLoginEmailController having the methods init(), setMetaData(), loginnow(). It controls the email related functions. + **/ + module.controller('SocialLoginEmailController', function ($state, ProvidersFactory, $auth, $scope, Flash, SocialLoginFactory, $rootScope, $filter, $location, AuthFactory) { + /** + * @ngdoc method + * @name setMetaData + * @methodOf SocialLogins.controller:SocialLoginEmailController + * @description + * This method will set the meta data's dynamically by using the angular.element + * @returns {Element} New meta data element. + **/ + $scope.setMetaData = function () { + var pageTitle = $filter("translate")("Get Social API Email"); + var fullUrl = $location.absUrl(); + var appUrl = $rootScope.settings['scheme_name'] + ":/" + $location.url(); + angular.element('html head meta[property="og:title"], html head meta[name="twitter:title"]').attr("content", $rootScope.settings['site.name'] + " | " + pageTitle); + angular.element('meta[property="al:ios:url"], meta[property="al:ipad:url"], meta[property="al:android:url"], meta[property="al:windows_phone:url"], html head meta[name="twitter:app:url:iphone"], html head meta[name="twitter:app:url:ipad"], html head meta[name="twitter:app:url:googleplay"]').attr('content', appUrl); + angular.element('meta[property="og:url"]').attr('content', fullUrl); + }; + /** + * @ngdoc method + * @name init + * @methodOf SocialLogins.controller:SocialLoginEmailController + * @description + * This method will initialize the page. It returns the page title. + **/ + $scope.init = function () { + if (!$rootScope.thrid_party_profile) { + Flash.set($filter("translate")("Unable to get provider info, please try again."), 'error', false); + $state.go('login'); + } + // $scope.setMetaData(); + // $rootScope.pageTitle = $rootScope.settings['site.name'] + " | " + $filter("translate")("Get Social API Email"); + }; + $scope.init(); + /** + * @ngdoc method + * @name loginnow + * @methodOf SocialLogins.controller:SocialLoginEmailController + * @description + * This method will be used in authenticating and logging in the user. + * @param {integer} user User details. + * @returns {Array} Success or failure message. + **/ + $scope.loginnow = function (user) { + $scope.user = user; + $scope.user.thrid_party_profile = $rootScope.thrid_party_profile; + SocialLoginFactory.login($scope.user, function (response) { + if (response.userToken) { + $auth.setToken(response.userToken); + localStorage.userRole = response.role; + AuthFactory.fetch().$promise.then(function (user) { + $rootScope.auth = user; + $state.go('dashboard'); + }); + } else { + var errorMessage; + if (response.error.code === 1) { + errorMessage = $filter("translate")("Already registered email"); + } else { + errorMessage = response.error.message; + } + Flash.set(errorMessage, 'error', false); + } + }); + }; + }); + /** + * @ngdoc controller + * @name SocialLogins.controller:SocialLoginController + * @description + * This is SocialLoginController having the methods init(), setMetaData() and it controls the login functionalities using social websites. + **/ + module.controller('SocialLoginController', function ($state, ProvidersFactory, $auth, $scope, $rootScope, $location, AuthFactory, $filter, Flash) { + var model = this; + /** + * @ngdoc method + * @name setMetaData + * @methodOf SocialLogins.controller:SocialLoginController + * @description + * This method will set the meta data's dynamically by using the angular.element + * @returns {Element} New meta data element. + **/ + model.setMetaData = function () { + var fullUrl = $location.absUrl(); + var appUrl = $rootScope.settings['scheme_name'] + ":/" + $location.url(); + angular.element('html head meta[property="og:title"], html head meta[name="twitter:title"]').attr("content", $rootScope.settings['site.name'] + " | " + $rootScope.pageTitle); + angular.element('meta[property="al:ios:url"], meta[property="al:ipad:url"], meta[property="al:android:url"], meta[property="al:windows_phone:url"], html head meta[name="twitter:app:url:iphone"], html head meta[name="twitter:app:url:ipad"], html head meta[name="twitter:app:url:googleplay"]').attr('content', appUrl); + angular.element('meta[property="og:url"]').attr('content', fullUrl); + }; + /** + * @ngdoc method + * @name init + * @methodOf SocialLogins.controller:SocialLoginController + * @description + * This method will initialize the page. It returns the page title. + **/ + model.init = function () { + model.setMetaData(); + ProvidersFactory.get({'filter': 'active', 'sortby': 'asc', 'sort': 'display_order'}).$promise + .then(function (response) { + model.sociallogin = response; + }); + }; + model.init(); + $scope.contentInIframe = false; + if (self !== top) { + $scope.contentInIframe = true; + } + model.sociallogin = {}; + /** + * @ngdoc method + * @name authenticate + * @methodOf SocialLogins.controller:SocialLoginController + * @description + * This method will be used in authenticating the user. + * @returns {Array} Success or failure message. + **/ + model.authenticate = function (provider) { + $auth.authenticate(provider).then(function (response) { + if (response.data.userToken) { + localStorage.userRole = response.data.role; + AuthFactory.fetch().$promise.then(function (user) { + $rootScope.auth = user; + $state.go('dashboard', {}); + }); + } else if (response.data.thrid_party_profile) { + $rootScope.thrid_party_profile = response.data.thrid_party_profile; + $state.go('socialLoginEmail'); + } + }).catch(function (error) { + }); + }; + }); +})(angular.module('BookorRent.SocialLogins')); diff --git a/client/src/app/Plugins/SocialLogins/SocialLogin.module.js b/client/src/app/Plugins/SocialLogins/SocialLogin.module.js new file mode 100644 index 0000000..eebb394 --- /dev/null +++ b/client/src/app/Plugins/SocialLogins/SocialLogin.module.js @@ -0,0 +1,89 @@ +/** + * BookorRent - v1.0a.01 - 2016-03-28 + * + * Copyright (c) 2016 Agriya + */ +/** + * @ngdoc object + * @name SocialLogins + * @description + * + * This is the module for SocialLogins. It contains the social login functionalities. + * + * The social login module act as a state provider, this module get the url and load the template and call the controller instantly. + * + * @param {string} SocialLogin name of the module + * @param {!Array.=} dependencies If specified then new module is being created. If unspecified then the module is being retrieved for further configuration. + * + * [ + * 'ui.router', + * 'ngResource', + * 'satellizer' + * ] + * @param {string} stateProvider State provider is used to provide a corresponding model and template. + * @param {string} analyticsProvider This service lets you integrate google analytics tracker in your AngularJS applications easily. + * @returns {BookorRent.SocialLogins} new BookorRent.SocialLogins module. + **/ +(function (module) { + /** + * @ngdoc directive + * @name Vehicles.directive:socialShare + * @scope + * @restrict EA + * @description + * socialShare directive used to load the social login share. + * @param {string} socialShare Name of the directive + **/ + module.directive('socialShare', function () { + return { + restrict: 'EA', + templateUrl: "Plugins/SocialLogins/social_login_share.tpl.html" + }; + }); + module.config(function ($stateProvider, $authProvider, GENERAL_CONFIG) { + $authProvider.unlinkUrl = GENERAL_CONFIG.api_url + '/auth/unlink'; + var ResolveServiceData = { + 'ResolveServiceData': function (ResolveService, $q) { + return $q.all({ + AuthServiceData: ResolveService.promiseAuth, + SettingServiceData: ResolveService.promiseSettings + }); + } + }; + $stateProvider.state('social', { + url: '/social', + authenticate: true, + views: { + "main": { + controller: 'SocialConnectionController as model', + templateUrl: 'Plugins/SocialLogins/my_connection.tpl.html', + resolve: ResolveServiceData + } + } + }).state('profileImage', { + url: '/profile_image', + authenticate: true, + views: { + "main": { + controller: 'SocialProfileController as model', + templateUrl: 'Plugins/SocialLogins/profile_image.tpl.html', + resolve: ResolveServiceData + } + } + }).state('socialLoginEmail', { + url: '/social-login/email', + authenticate: false, + views: { + "main": { + controller: 'SocialLoginEmailController as model', + templateUrl: 'Plugins/SocialLogins/get_email_from_user.tpl.html', + resolve: ResolveServiceData + } + } + }); + }); +}(angular.module('BookorRent.SocialLogins', [ + 'ui.router', + 'ngResource', + 'satellizer' +]))); diff --git a/client/src/app/Plugins/SocialLogins/SocialLoginService.js b/client/src/app/Plugins/SocialLogins/SocialLoginService.js new file mode 100644 index 0000000..421128b --- /dev/null +++ b/client/src/app/Plugins/SocialLogins/SocialLoginService.js @@ -0,0 +1,77 @@ +(function (module) { + /** + * @ngdoc service + * @name SocialLogins.ProvidersFactory + * @description + * ProvidersFactory is used to listing the providers. + * @param {string} ProvidersFactory The name of the factory service + * @param {function()} function returns the providers list. + * @param {string} url Base url accessed in GENERAL_CONFIG. + */ + module.factory('ProvidersFactory', function ($resource, GENERAL_CONFIG) { + return $resource(GENERAL_CONFIG.api_url + '/providers', {}, {}); + }); + /** + * @ngdoc service + * @name SocialLogins.ProviderUsersFactory + * @description + * ProviderUsersFactory is used to listing provider users + * @param {string} ProviderUsersFactory The name of the factory service + * @param {function()} function It uses get method for get and returns the url + * @param {string} url Base url accessed in GENERAL_CONFIG. + * @returns {object} The service contains these actions: + * + * { + * 'get': {method:'GET'} + * }; + */ + module.factory('ProviderUsersFactory', function ($resource, GENERAL_CONFIG) { + return $resource(GENERAL_CONFIG.api_url + '/provider_users', {}, { + get: { + method: 'GET' + } + }); + }); + /** + * @ngdoc service + * @name SocialLogins.UpdateProfileFactory + * @description + * UpdateProfileFactory is used to update user profile + * @param {string} UpdateProfileFactory The name of the factory service + * @param {function()} function It uses get method for get and returns the url + * @param {string} url Base url accessed in GENERAL_CONFIG. + * @returns {object} The service contains these actions: + * + * { + * 'update': {method:'POST'} + * }; + */ + module.factory('UpdateProfileFactory', function ($resource, GENERAL_CONFIG) { + return $resource(GENERAL_CONFIG.api_url + '/update_profile/', {}, { + update: { + method: 'POST' + }, + }); + }); + /** + * @ngdoc service + * @name SocialLogins.SocialLoginFactory + * @description + * SocialLoginFactory is used to login social user + * @param {string} SocialLoginFactory The name of the factory service + * @param {function()} function It uses get method for get and returns the url + * @param {string} url Base url accessed in GENERAL_CONFIG. + * @returns {object} The service contains these actions: + * + * { + * 'login': {method:'POST'} + * }; + */ + module.factory('SocialLoginFactory', function ($resource) { + return $resource('api/social_login', {}, { + login: { + method: 'POST' + } + }); + }); +})(angular.module('BookorRent.SocialLogins')); diff --git a/client/src/app/Plugins/SocialLogins/SocialProfile.js b/client/src/app/Plugins/SocialLogins/SocialProfile.js new file mode 100644 index 0000000..aa33675 --- /dev/null +++ b/client/src/app/Plugins/SocialLogins/SocialProfile.js @@ -0,0 +1,132 @@ +(function (module) { + /** + * @ngdoc controller + * @name SocialLogins.controller:SocialProfileController + * @description + * This is SocialProfile controller having the methods init(), setMetaData(), and getProviderUsers(). + * It maintains the functinolities of the social profile. + **/ + module.controller('SocialProfileController', function ($state, $auth, $scope, $rootScope, ProvidersFactory, $location, $filter, Flash, ProviderUsersFactory, UpdateProfileFactory, UserAttachmentFactory, AuthFactory, ConstSocialLogin) { + var model = this; + model.updateProfileDetails = []; + /** + * @ngdoc method + * @name setMetaData + * @methodOf SocialLogins.controller:SocialProfileController + * @description + * This method will set the meta data dynamically by using the angular.element. + * @returns {Element} New meta data element. + **/ + model.setMetaData = function () { + var pageTitle = $filter("translate")("Social Profile Image"); + var fullUrl = $location.absUrl(); + var appUrl = $rootScope.settings['scheme_name'] + ":/" + $location.url(); + angular.element('html head meta[property="og:title"], html head meta[name="twitter:title"]').attr("content", $rootScope.settings['site.name'] + " | " + pageTitle); + angular.element('meta[property="al:ios:url"], meta[property="al:ipad:url"], meta[property="al:android:url"], meta[property="al:windows_phone:url"], html head meta[name="twitter:app:url:iphone"], html head meta[name="twitter:app:url:ipad"], html head meta[name="twitter:app:url:googleplay"]').attr('content', appUrl); + angular.element('meta[property="og:url"]').attr('content', fullUrl); + }; + model.sociallogin = {}; + /** + * @ngdoc method + * @name getProviderUsers + * @methodOf SocialLogins.controller:SocialProfileController + * @description + * This method will get the list of service provider usres list. + **/ + model.getProviderUsers = function () { + model.fb_connected = false; + ProviderUsersFactory.get().$promise.then(function (response) { + angular.forEach(response.data, function (value, key) { + model.updateProfileDetails.source_id = value.user.user_avatar_source_id; + if (value.provider_id == ConstSocialLogin.Facebook && value.is_connected) { + model.fb_connected = true; + model.fb_img = value.profile_picture_url; + } else if (value.provider_id == ConstSocialLogin.Twitter && value.is_connected) { + model.twitter_connected = true; + model.twt_img = value.profile_picture_url; + } else if (value.provider_id == ConstSocialLogin.Google && value.is_connected) { + model.google_connected = true; + model.goo_img = value.profile_picture_url; + } else if (value.provider_id == ConstSocialLogin.Github && value.is_connected) { + model.github_connected = true; + model.git_img = value.profile_picture_url; + } + }); + }); + }; + /** + * @ngdoc method + * @name init + * @methodOf SocialLogins.controller:SocialProfileController + * @description + * This method will initialize the meta data and functionalities. + **/ + model.init = function () { + model.setMetaData(); + $rootScope.pageTitle = $rootScope.settings['site.name'] + " | " + $filter("translate")("Profile Images"); + model.user_avatar_source = ConstSocialLogin; + UserAttachmentFactory.get({ + id: $rootScope.auth.id + }).$promise + .then(function (response) { + $scope.media = response; + }); + //Get Active social logins + ProvidersFactory.get({'filter': 'active', 'sortby': 'asc', 'sort': 'display_order'}).$promise + .then(function (response) { + model.sociallogin = response; + }); + //check if user connect with social + model.getProviderUsers(); + }; + model.init(); + //Connect with providers + /** + * @ngdoc method + * @name connect + * @methodOf SocialLogins.controller:SocialProfileController + * @description + * This method will be used in connecting the user to the social websites. + * @param {integer} provider Provider details. + * @returns {Array} Success or failure message. + **/ + model.connect = function (provider) { + $auth.link(provider).then(function (response) { + if (response.data.provider_id == ConstSocialLogin.Facebook && response.data.is_connected) { + model.fb_connected = true; + model.fb_img = response.data.profile_picture_url; + } else if (response.data.provider_id == ConstSocialLogin.Twitter && response.data.is_connected) { + model.twitter_connected = true; + model.twt_img = response.data.profile_picture_url; + } else if (response.data.provider_id == ConstSocialLogin.Google && response.data.is_connected) { + model.google_connected = true; + model.goo_img = response.data.profile_picture_url; + } else if (response.data.provider_id == ConstSocialLogin.Github && response.data.is_connected) { + model.github_connected = true; + model.git_img = response.data.profile_picture_url; + } + Flash.set($filter("translate")("Connected Successfully"), 'success', true); + }).catch(function (error) { + Flash.set($filter("translate")(error.data.message), 'error', false); + }); + }; + //Update profile image + /** + * @ngdoc method + * @name updateProfile + * @methodOf SocialLogins.controller:SocialProfileController + * @description + * This method is used to update the user profile image. + * @param {integer} updateProfileDetails User profile details. + * @returns {Array} Success or failure message. + **/ + model.updateProfile = function (updateProfileDetails) { + UpdateProfileFactory.update({'source_id': updateProfileDetails.source_id}).$promise.then(function (response) { + AuthFactory.fetch().$promise.then(function (user) { + $rootScope.auth = user; + }); + Flash.set($filter("translate")("Profile image updated successfully"), 'success', true); + }); + }; + }); +}(angular.module('BookorRent.SocialLogins'))); diff --git a/client/src/app/Plugins/SocialLogins/get_email_from_user.tpl.html b/client/src/app/Plugins/SocialLogins/get_email_from_user.tpl.html new file mode 100644 index 0000000..04e0abe --- /dev/null +++ b/client/src/app/Plugins/SocialLogins/get_email_from_user.tpl.html @@ -0,0 +1,24 @@ + \ No newline at end of file diff --git a/client/src/app/Plugins/SocialLogins/my_connection.tpl.html b/client/src/app/Plugins/SocialLogins/my_connection.tpl.html new file mode 100644 index 0000000..e198848 --- /dev/null +++ b/client/src/app/Plugins/SocialLogins/my_connection.tpl.html @@ -0,0 +1,88 @@ +
+
+

{{'Social' | translate}}

+
+ +
+
+
+ \ No newline at end of file diff --git a/client/src/app/Plugins/SocialLogins/profile_image.tpl.html b/client/src/app/Plugins/SocialLogins/profile_image.tpl.html new file mode 100644 index 0000000..8d8ffa9 --- /dev/null +++ b/client/src/app/Plugins/SocialLogins/profile_image.tpl.html @@ -0,0 +1,86 @@ +
+
+

{{'Profile Image' | translate}}

+
+ +
+
+
+
+
+
+ +
+ +
+ +
+
+
+ +
+
+
+
\ No newline at end of file diff --git a/client/src/app/Plugins/SocialLogins/social_login.tpl.html b/client/src/app/Plugins/SocialLogins/social_login.tpl.html new file mode 100644 index 0000000..7575781 --- /dev/null +++ b/client/src/app/Plugins/SocialLogins/social_login.tpl.html @@ -0,0 +1,15 @@ +

{{'SIGN IN WITH CONNECT' | translate}}

+
+ + + + +
diff --git a/client/src/app/Plugins/SocialLogins/social_login_share.tpl.html b/client/src/app/Plugins/SocialLogins/social_login_share.tpl.html new file mode 100644 index 0000000..bdcee1b --- /dev/null +++ b/client/src/app/Plugins/SocialLogins/social_login_share.tpl.html @@ -0,0 +1,52 @@ + \ No newline at end of file diff --git a/client/src/app/Plugins/Sudopays/Sudopay.module.js b/client/src/app/Plugins/Sudopays/Sudopay.module.js new file mode 100644 index 0000000..35b90ef --- /dev/null +++ b/client/src/app/Plugins/Sudopays/Sudopay.module.js @@ -0,0 +1,33 @@ +/** + * BookorRent - v1.0a.01 - 2016-03-28 + * + * Copyright (c) 2016 Agriya + */ +/** + * @ngdoc object + * @name Sudopays + * @description + * + * This is the module for Sudopay. It contains the sudopay functionalities. + * + * @param {string} Sudopays name of the module + * @param {!Array.=} dependencies If specified then new module is being created. If unspecified then the module is being retrieved for further configuration. + * + * [ + * 'ui.router', + * 'ngResource', + * 'angulartics', + * 'angulartics.google.analytics', + * 'angulartics.facebook.pixel' + * ] + * @returns {BookorRent.Sudopays} new BookorRent.Sudopays module. + **/ +(function (module) { + +}(angular.module("BookorRent.Sudopays", [ + 'ui.router', + 'ngResource', + 'angulartics', + 'angulartics.google.analytics', + 'angulartics.facebook.pixel' +]))); diff --git a/client/src/app/Plugins/Sudopays/buyer.tpl.html b/client/src/app/Plugins/Sudopays/buyer.tpl.html new file mode 100644 index 0000000..7830aa3 --- /dev/null +++ b/client/src/app/Plugins/Sudopays/buyer.tpl.html @@ -0,0 +1,45 @@ +
+
+ +
+
{{'Required' | translate}}
+
{{'Enter Valid Email' | translate}}
+
+
+
+ +
{{'Required' | translate}}
+
+
+
+
+ +
{{'Required' | translate}}
+
+
+ +
{{'Required' | translate}}
+
+
+
+
+ +
{{'Required' | translate}}
+
+
+ +
+
{{'Required' | translate}}
+
+
+
+
+
+ +
+
{{'Required' | translate}}
+
+
+
\ No newline at end of file diff --git a/client/src/app/Plugins/Sudopays/credit_card.tpl.html b/client/src/app/Plugins/Sudopays/credit_card.tpl.html new file mode 100644 index 0000000..ebc5127 --- /dev/null +++ b/client/src/app/Plugins/Sudopays/credit_card.tpl.html @@ -0,0 +1,45 @@ +
+
+ +
+
{{'Required' | translate}}
+
+ {{ 'Enter valid credit card number!' | translate }} +
+
+
+
+
+
+ +
+
{{'Required' | translate}}
+
{{'Enter valid month' | translate}}
+
+
+
+ +
+
{{'Required' | translate}}
+
{{'Enter valid year' | translate}}
+
+
+
+
{{'Enter valid Expire Month' | translate}}
+
+
+
+
+
+
+ +
{{'Required' | translate}}
+
+
+ +
+
{{'Required' | translate}}
+
{{'Enter Valid ccv numer' | translate}}
+
+
+
\ No newline at end of file diff --git a/client/src/app/Plugins/Sudopays/manual.tpl.html b/client/src/app/Plugins/Sudopays/manual.tpl.html new file mode 100644 index 0000000..5bcebe0 --- /dev/null +++ b/client/src/app/Plugins/Sudopays/manual.tpl.html @@ -0,0 +1,7 @@ +
+
+ +
{{'Required'| translate}} +
+
+
\ No newline at end of file diff --git a/client/src/app/Plugins/Translations/Translations.js b/client/src/app/Plugins/Translations/Translations.js new file mode 100644 index 0000000..19a72b3 --- /dev/null +++ b/client/src/app/Plugins/Translations/Translations.js @@ -0,0 +1,176 @@ +/** + * bookorrent - v0.0.1 - 2016-04-22 + * + * Copyright (c) 2016 Agriya + */ +/** + * @ngdoc object + * @name Translations + * @description + * + * This is the module for translations. It contains the translations functionalities. + * + * @param {string} Translations name of the module + * @param {!Array.=} dependencies If specified then new module is being created. If unspecified then the module is being retrieved for further configuration. + * + * [ + * 'ngResource', + * 'pascalprecht.translate', + * 'tmh.dynamicLocale', + * 'ngSanitize', + * 'ngCookies', + * ] + * @returns {BookorRent.Translations} new BookorRent.Translations module. + **/ +(function (module) { +}(angular.module('BookorRent.Translations', [ + 'ngResource', + 'pascalprecht.translate', + 'tmh.dynamicLocale', + 'ngSanitize', + 'ngCookies' +]))); +(function (module) { + module.config(function (tmhDynamicLocaleProvider) { + tmhDynamicLocaleProvider.localeLocationPattern('assets/js/angular-i18n/angular-locale_{{locale}}.js'); + tmhDynamicLocaleProvider.localeLocationPattern('assets/js/moment/locale/{{locale}}.js'); + }); + /** + * @ngdoc service + * @name Translations.LanguageList + * @function + * @description + * LanguageList is used to list the languages. + * @param {string} LanguageList The name of the factory service + * @param {function()} function It used to list the languages. + * @param {string} url Base url accessed in GENERAL_CONFIG. + * @returns {object} The service return language list. + */ + module.service('LanguageList', function ($sce, $rootScope, $q, GENERAL_CONFIG) { + promise = $.get(GENERAL_CONFIG.api_url + '/languages?filter=active&sort=name&sortby=asc', function (response) { + }); + return { + promise: promise + }; + }); + /** + * @ngdoc service + * @name Translations.LocaleService + * @function + * @description + * LocaleService is used to maintains the locale service of the languages. + * @param {string} LocaleService The name of the factory service + * @param {function()} function It used to maintains the locale service of the languages. + * @param {string} url Base url accessed in GENERAL_CONFIG. + */ + module.service('LocaleService', function ($translate, $rootScope, tmhDynamicLocale, GENERAL_CONFIG, LanguageList, ResolveService, $translateLocalStorage, amMoment) { + 'use strict'; + var localesObj; + var loadedlocalesObj = {}; + var _LOCALES_DISPLAY_NAMES = []; + var _LOCALES; + var promiseLanguages = LanguageList.promise; + promiseLanguages.then(function (response) { + $.each(response.data, function (i, data) { + loadedlocalesObj[data.iso2] = data.name; + }); + localesObj = loadedlocalesObj; + // locales and locales display names + _LOCALES = Object.keys(localesObj); + if (!_LOCALES || _LOCALES.length === 0) { + console.error('There are no _LOCALES provided'); + } + _LOCALES.forEach(function (locale) { + _LOCALES_DISPLAY_NAMES.push(localesObj[locale]); + }); + }); + // STORING CURRENT LOCALE + var currentLocale = $translate.preferredLanguage(); + if ($translate.use() !== undefined) { + currentLocale = $translate.use(); + } else if ($translateLocalStorage.get('NG_TRANSLATE_LANG_KEY') !== undefined && $translateLocalStorage.get('NG_TRANSLATE_LANG_KEY') !== null) { + currentLocale = $translateLocalStorage.get('NG_TRANSLATE_LANG_KEY'); + } + // METHODS + var checkLocaleIsValid = function (locale) { + return _LOCALES.indexOf(locale) !== -1; + }; + var setLocale = function (locale) { + if (!checkLocaleIsValid(locale)) { + console.error('Locale name "' + locale + '" is invalid'); + return; + } + // updating current locale + currentLocale = locale; + // asking angular-translate to load and apply proper translations + $translate.use(locale); + }; + // EVENTS + // on successful applying translations by angular-translate + $rootScope.$on('$translateChangeSuccess', function (event, data) { + amMoment.changeLocale(data.language); + document.documentElement.setAttribute('lang', data.language); // sets "lang" attribute to html + // asking angular-dynamic-locale to load and apply proper AngularJS $locale setting + var dyn_locale = data.language.toLowerCase().replace(/_/g, '-'); + if(dyn_locale == 'en'){ + dyn_locale = 'en-au'; + } + tmhDynamicLocale.set(dyn_locale); + }); + return { + getLocaleName: function(locale) { + var lang_code = ''; + angular.forEach(localesObj, function(value, key){ + if(value == locale) { + lang_code = key; + } + }); + return lang_code; + }, + getLocaleDisplayName: function () { + return localesObj[currentLocale]; + }, + setLocaleByDisplayName: function (localeDisplayName) { + setLocale( + _LOCALES[ + _LOCALES_DISPLAY_NAMES.indexOf(localeDisplayName) // get locale index + ] + ); + }, + getLocalesDisplayNames: function () { + return _LOCALES_DISPLAY_NAMES; + } + }; + }); + /** + * @ngdoc directive + * @name Translations.directive:ngTranslateLanguageSelect + * @module Translations + * @scope + * This directive used to load translated languages. + * @restrict A + * @description + * This directive used to load translated languages. + */ + module.directive('ngTranslateLanguageSelect', function (LocaleService, LanguageList) { + 'use strict'; + return { + restrict: 'A', + replace: true, + templateUrl: 'Plugins/Translations/language_translate.tpl.html', + controller: function ($scope, $rootScope, $timeout, LanguageList, amMoment) { + var promiseSettings = LanguageList.promise; + promiseSettings.then(function (response) { + $scope.currentLocaleDisplayName = LocaleService.getLocaleDisplayName(); + $scope.localesDisplayNames = LocaleService.getLocalesDisplayNames(); + $scope.visible = $scope.localesDisplayNames && $scope.localesDisplayNames.length > 1; + }); + $scope.changeLanguage = function (locale) { + var code = LocaleService.getLocaleName(locale); + amMoment.changeLocale(code); + LocaleService.setLocaleByDisplayName(locale); + }; + } + }; + }); +}(angular.module("BookorRent.Translations"))); diff --git a/client/src/app/Plugins/Translations/language_translate.tpl.html b/client/src/app/Plugins/Translations/language_translate.tpl.html new file mode 100644 index 0000000..ac69559 --- /dev/null +++ b/client/src/app/Plugins/Translations/language_translate.tpl.html @@ -0,0 +1,5 @@ +
+ +
+ diff --git a/client/src/app/Plugins/VehicleCoupons/VehicleCoupons.module.js b/client/src/app/Plugins/VehicleCoupons/VehicleCoupons.module.js new file mode 100644 index 0000000..5922119 --- /dev/null +++ b/client/src/app/Plugins/VehicleCoupons/VehicleCoupons.module.js @@ -0,0 +1,49 @@ +/** + * BookorRent - v1.0a.01 - 2016-03-28 + * + * Copyright (c) 2016 Agriya + */ +/** + * @ngdoc object + * @name VehicleCoupons + * @description + * + * This is the module for VehicleCoupons. It contains the VehicleCoupons functionalities. + * + * @param {string} VehicleCoupons name of the module + * @param {!Array.=} dependencies If specified then new module is being created. If unspecified then the module is being retrieved for further configuration. + * + * [ + * 'ui.router', + * 'ngResource', + * 'angulartics', + * 'angulartics.google.analytics', + * 'angulartics.facebook.pixel' * + * ] + * @returns {BookorRent.VehicleCoupons} new BookorRent.VehicleCoupons module. + **/ +(function (module) { + + /** + * @ngdoc directive + * @name VehicleCoupons.directive:coupon + * @module VehicleCoupons + * @scope + * @restrict E + * @description + * This directive used to define the coupon detail section. + */ + module.directive('coupon', function () { + return { + restrict: 'E', + templateUrl: 'Plugins/VehicleCoupons/vehicle_coupon.tpl.html' + // scope:{} + }; + }); +}(angular.module('BookorRent.VehicleCoupons', [ + 'ui.router', + 'ngResource', + 'angulartics', + 'angulartics.google.analytics', + 'angulartics.facebook.pixel' +]))); diff --git a/client/src/app/Plugins/VehicleCoupons/vehicle_coupon.tpl.html b/client/src/app/Plugins/VehicleCoupons/vehicle_coupon.tpl.html new file mode 100644 index 0000000..532ad43 --- /dev/null +++ b/client/src/app/Plugins/VehicleCoupons/vehicle_coupon.tpl.html @@ -0,0 +1,22 @@ +
+
+

{{'Coupons' | translate}}

+
+
+ + + + {{'You must enter the Coupon Code' | translate}} + +
+
+ + +
+
+
+
\ No newline at end of file diff --git a/client/src/app/Plugins/VehicleDisputes/VehicleDispute.js b/client/src/app/Plugins/VehicleDisputes/VehicleDispute.js new file mode 100644 index 0000000..289605c --- /dev/null +++ b/client/src/app/Plugins/VehicleDisputes/VehicleDispute.js @@ -0,0 +1,108 @@ +(function (module) { + /** + * @ngdoc directive + * @name VehicleDisputes.directive:dispute + * @module VehicleDisputes + * @scope + * This directive used to load the dispute page url link. + * @restrict EA + * @description + * This directive used to load the dispute page template. + */ + module.directive('dispute', function () { + return { + restrict: 'EA', + templateUrl: "Plugins/VehicleDisputes/vehicle_dispute.tpl.html", + controller: function ($scope, $rootScope, $element, $attrs, $state, Flash, $filter, VehicleDisputesFactory, VehicleDisputeFactory, VehicleDisputeResolveFactory, ConstDisputeClosedType) { + var model = this; + $scope.vehicle_dispute = {}; + $scope.vehicle_rental_id = $state.params.vehicle_rental_id ? $state.params.vehicle_rental_id : ''; + $scope.ConstDisputeClosedType = ConstDisputeClosedType; + /** + * @ngdoc method + * @name init + * @methodOf VehicleDisputes.controller:VehicleDisputeController + * @description + * This method will initialize the meta data and functionalities. + **/ + $scope.init = function () { + //Get Dispute Types list + VehicleDisputesFactory.get({'id': $scope.vehicle_rental_id}).$promise.then(function (response) { + $scope.is_under_dispute = false; + $scope.all_dispute_types = false; + $scope.dispute_types = false; + $scope.dispute_array = false; + $scope.dispute_details = false; + $scope.dispute_closed_types = false; + if (response.is_under_dispute) { + $scope.is_under_dispute = true; + } else if (response.all_dispute_types) { + $scope.all_dispute_types = response.all_dispute_types; + } else if (response.dispute_types) { + $scope.dispute_types = response.dispute_types; + } else if (response.dispute_array) { + $scope.dispute_array = true; + $scope.dispute_details = response.dispute_array.dispute; + $scope.dispute_closed_types = response.dispute_array.dispute_close_types; + $scope.dispute_diff_days = response.dispute_array.diff_days; + $scope.feedback = response.dispute_array.feedback[0]; + } + }); + }; + $scope.init(); + /** + * @ngdoc method + * @name disputeSubmit + * @methodOf VehicleDisputes.controller:VehicleDisputeController + * @description + * This method will store vehicle dispute details + * @param {integer} vehicle_dispute Vehicle dispute details. + * @returns {Array} Success or failure message. + **/ + $scope.disputeSubmit = function ($valid) { + if ($valid) { + $scope.vehicle_dispute.item_user_id = $scope.vehicle_rental_id; + $scope.vehicle_dispute.dispute_type_id = $scope.vehicle_dispute.dispute_type; + VehicleDisputeFactory.save($scope.vehicle_dispute, function (response) { + Flash.set($filter("translate")("Dispute Added Successfully!"), 'success', true); + $state.reload(); + }, function (error) { + Flash.set($filter("translate")("Dispute Could not be added!"), 'error', false); + }); + } + }; + /** + * @ngdoc method + * @name resolveDispute + * @methodOf VehicleDisputes.controller:VehicleDisputeController + * @description + * This method will store vehicle dispute rewoove details + * @param {integer} vehicle_dispute Vehicle dispute rewoove details. + * @returns {Array} Success or failure message. + **/ + $scope.resolveDispute = function (close_type_id) { + $scope.vehicle_dispute.item_user_id = $scope.vehicle_rental_id; + $scope.vehicle_dispute.dispute_closed_type_id = close_type_id; + VehicleDisputeResolveFactory.save($scope.vehicle_dispute, function (response) { + Flash.set($filter("translate")("Dispute Resolved Successfully!"), 'success', true); + $state.reload(); + }, function (error) { + Flash.set($filter("translate")("Dispute Could not be resolved!"), 'error', false); + }); + }; + $scope.checkfeedback = function (close_type_id) { + $('#edit_feedback_' + close_type_id).removeClass('hide'); + }; + } + } + }); + /** + * @ngdoc controller + * @name VehicleDisputes.controller:VehicleDisputeController + * @description + * This VehicleDisputes controller contains the VehicleDisputes functionalities. + **/ + module.controller('VehicleDisputeController', function ($state, $scope, $http, Flash, $filter, $rootScope, $location, VehicleDisputesFactory, VehicleDisputeFactory, VehicleDisputeResolveFactory) { + + }); +}(angular.module("BookorRent.VehicleDisputes"))); diff --git a/client/src/app/Plugins/VehicleDisputes/VehicleDisputeService.js b/client/src/app/Plugins/VehicleDisputes/VehicleDisputeService.js new file mode 100644 index 0000000..fd9bfc5 --- /dev/null +++ b/client/src/app/Plugins/VehicleDisputes/VehicleDisputeService.js @@ -0,0 +1,67 @@ +(function (module) { + /** + * @ngdoc service + * @name VehicleDisputes.VehicleDisputesFactory + * @description + * VehicleDisputesFactory used to get the vehicle dispute details. + * @param {function()} function It used to list the data. + * @param {string} url Base url accessed in GENERAL_CONFIG. + * @returns {object} The service contains these actions: + * + * { + * 'get': {method:'GET'} + * }; + */ + module.factory('VehicleDisputesFactory', function ($resource, GENERAL_CONFIG) { + return $resource(GENERAL_CONFIG.api_url + '/vehicle_disputes/:id', { + id: '@id', + }, { + 'get': { + method: 'GET' + } + } + ); + }); + /** + * @ngdoc service + * @name VehicleDisputes.VehicleDisputeFactory + * @description + * VehicleDisputeFactory used to save the vehicle dispute details. + * @param {function()} function It used to store the data. + * @param {string} url Base url accessed in GENERAL_CONFIG. + * @returns {object} The service contains these actions: + * + * { + * 'save': {method:'POST'} + * }; + */ + module.factory('VehicleDisputeFactory', function ($resource, GENERAL_CONFIG) { + return $resource(GENERAL_CONFIG.api_url + '/vehicle_disputes/add', {}, { + 'save': { + method: 'POST' + } + } + ); + }); + /** + * @ngdoc service + * @name VehicleDisputes.VehicleDisputeResolveFactory + * @description + * VehicleDisputeResolveFactory used to save the vehicle dispute resolve details. + * @param {function()} function It used to store the data. + * @param {string} url Base url accessed in GENERAL_CONFIG. + * @returns {object} The service contains these actions: + * + * { + * 'save': {method:'POST'} + * }; + */ + module.factory('VehicleDisputeResolveFactory', function ($resource, GENERAL_CONFIG) { + return $resource(GENERAL_CONFIG.api_url + '/admin/vehicle_disputes/resolve', {}, { + 'save': { + method: 'POST' + } + } + ); + }); +})(angular.module('BookorRent.VehicleDisputes')); diff --git a/client/src/app/Plugins/VehicleDisputes/VehicleDisputes.module.js b/client/src/app/Plugins/VehicleDisputes/VehicleDisputes.module.js new file mode 100644 index 0000000..68b3cde --- /dev/null +++ b/client/src/app/Plugins/VehicleDisputes/VehicleDisputes.module.js @@ -0,0 +1,27 @@ +/** + * BookorRent - v1.0a.01 - 2016-03-28 + * + * Copyright (c) 2016 Agriya + */ +/** + * @ngdoc object + * @name VehicleDisputes + * @description + * + * This is the module for VehicleDisputes. It contains the VehicleDisputes functionalities. + * + * @param {string} VehicleDisputes name of the module + * @param {!Array.=} dependencies If specified then new module is being created. If unspecified then the module is being retrieved for further configuration. + * + * [ + * 'ui.router', + * 'ngResource', + * 'angulartics', + * ] + * @returns {BookorRent.VehicleDisputes} new BookorRent.VehicleDisputes module. + **/ +((angular.module('BookorRent.VehicleDisputes', [ + 'ui.router', + 'ngResource', + 'angulartics' +]))); diff --git a/client/src/app/Plugins/VehicleDisputes/vehicle_dispute.tpl.html b/client/src/app/Plugins/VehicleDisputes/vehicle_dispute.tpl.html new file mode 100644 index 0000000..bf8b400 --- /dev/null +++ b/client/src/app/Plugins/VehicleDisputes/vehicle_dispute.tpl.html @@ -0,0 +1,115 @@ +
+
+
+ +
+
+ + + {{'Required' | translate}} +
+
+ + + {{'Enter Account Details' | translate}} +
    +
  • {{'e.g' | translate}}.,
  • +
  • {{'Bank' | translate}}: {{'HDFC' | translate}},{{'Account No' | translate}}: XXXXXX
  • +
  • {{'IFSC Code' | translate}}: XXXXX
  • +
  • ({{'or' | translate}})
  • +
  • {{'PayPal Account' | translate}}:{{'example@domain.com' | translate}}
  • +
+
+
+ +
+
+ + + \ No newline at end of file diff --git a/client/src/app/Plugins/Withdrawals/user_cashWithdrawals.tpl.html b/client/src/app/Plugins/Withdrawals/user_cashWithdrawals.tpl.html new file mode 100644 index 0000000..3cf21d8 --- /dev/null +++ b/client/src/app/Plugins/Withdrawals/user_cashWithdrawals.tpl.html @@ -0,0 +1,105 @@ +
+
+
+

{{'Withdraw Fund Requests' | translate}}

+

{{'The requested amount will be deducted from your available balance after approval. Once its approved, the requested amount will be manually pay to you.' | translate}}

+ +
+ +
+
+ +
+
+
{{'The requested amount will be deducted from your available balance after approval. Once its approved, the requested amount will be manually pay to you.' | translate}}
+
+
+

{{'Choose your money transfer option'|translate}}

+
+
    +
  • +
    + +
    +
  • +
+ + {{'You must select one account' | translate}} + +
+
+
+ +
+ +
+ + {{'You must enter the amount' | translate}} + + + {{'You did not enter a valid number' | translate}} + + + {{'Your field value is lesser minimum value' | translate}} + + + {{'Your field value is greater maximum value' | translate}} + + + {{amountErr}} + +
+
+
+
+
+ + +
+
+
    +
  • {{'Minimum withdraw amount'|translate}}: {{getFormatCurrency(withdrawals.minimum_withdraw_amount, 'site')}}
  • +
  • {{'Maximum withdraw amount'|translate}}: {{getFormatCurrency(withdrawals.maximum_withdraw_amount, 'site')}}
  • +
+
+
+
+

{{'Cash Withdraw Requests'|translate}}

+
+ + + + + + + + + + + + + + + + + + + +
{{'Date' |translate}}{{'Account'|translate}} + {{'Amount' |translate}}{{'Status' |translate}}
{{userCashWithdrawals.created_at}}{{userCashWithdrawals.money_transfer_account.account}}{{getFormatCurrency(userCashWithdrawals.amount)}}{{userCashWithdrawals.withdrawal_status.name}}
+

{{'No Record Found' |translate}} +

+
+
+ +
+
+
+
\ No newline at end of file diff --git a/client/src/app/README.md b/client/src/app/README.md new file mode 100644 index 0000000..9c0ee8d --- /dev/null +++ b/client/src/app/README.md @@ -0,0 +1,94 @@ +# The `src/app` Directory + +## Overview + +``` +src/ + |- app/ + | |- home/ + | |- about/ + | |- app.js + | |- app.spec.js +``` + +The `src/app` directory contains all code specific to this application. Apart +from `app.js` and its accompanying tests (discussed below), this directory is +filled with subdirectories corresponding to high-level sections of the +application, often corresponding to top-level routes. Each directory can have as +many subdirectories as it needs, and the build system will understand what to +do. For example, a top-level route might be "products", which would be a folder +within the `src/app` directory that conceptually corresponds to the top-level +route `/products`, though this is in no way enforced. Products may then have +subdirectories for "create", "view", "search", etc. The "view" submodule may +then define a route of `/products/:id`, ad infinitum. + +As `ngBoilerplate` is quite minimal, take a look at the two provided submodules +to gain a better understanding of how these are used as well as to get a +glimpse of how powerful this simple construct can be. + +## `app.js` + +This is our main app configuration file. It kickstarts the whole process by +requiring all the modules from `src/app` that we need. We must load these now to +ensure the routes are loaded. If as in our "products" example there are +subroutes, we only require the top-level module, and allow the submodules to +require their own submodules. + +As a matter of course, we also require the template modules that are generated +during the build. + +However, the modules from `src/common` should be required by the app +submodules that need them to ensure proper dependency handling. These are +app-wide dependencies that are required to assemble your app. + +```js +angular.module( 'BookorRent', [ + 'templates-app', + 'templates-common', + 'BookorRent.home', + 'BookorRent.about' + 'ui.state', + 'ui.route' +]) +``` + +With app modules broken down in this way, all routing is performed by the +submodules we include, as that is where our app's functionality is really +defined. So all we need to do in `app.js` is specify a default route to follow, +which route of course is defined in a submodule. In this case, our `home` module +is where we want to start, which has a defined route for `/home` in +`src/app/home/home.js`. + +```js +.config( function myAppConfig ( $stateProvider, $urlRouterProvider ) { + $urlRouterProvider.otherwise( '/home' ); +}) +``` + +Use the main applications run method to execute any code after services +have been instantiated. + +```js +.run( function () { +}) +``` + +And then we define our main application controller. This is a good place for logic +not specific to the template or route, such as menu logic or page title wiring. + +```js +.controller( 'AppCtrl', function AppCtrl ( $scope, $location ) { + $scope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams){ + if ( angular.isDefined( toState.data.pageTitle ) ) { + $scope.pageTitle = toState.data.pageTitle + ' | BookorRent' ; + } + }); +}) +``` + +### Testing + +One of the design philosophies of `ngBoilerplate` is that tests should exist +alongside the code they test and that the build system should be smart enough to +know the difference and react accordingly. As such, the unit test for `app.js` +is `app.spec.js`, though it is quite minimal. diff --git a/client/src/app/Transactions/Transaction.js b/client/src/app/Transactions/Transaction.js new file mode 100644 index 0000000..a768418 --- /dev/null +++ b/client/src/app/Transactions/Transaction.js @@ -0,0 +1,105 @@ +(function (module) { + /** + * @ngdoc directive + * @name Vehicles.directive:vehicleSearch + * @scope + * @restrict EA + * @description + * vehicleSearch directive used to load the search template. + * @param {string} vehicleSearch Name of the directive + **/ + module.directive('myTransactions', function() { + return { + restrict: 'EA', + templateUrl: "Transactions/transaction_list.tpl.html", + controller: "TransactionController" + }; + }); + /** + * @ngdoc controller + * @name Transaction.controller:TransactionController + * @description + * + * This is TransactionController having the methods init(), setMetaData(), and it defines the item list related funtions. + **/ + module.controller('TransactionController', function ($state, $scope, $http, Flash, $filter, TransactionFactory, AuthFactory, $rootScope, $location) { + var model = this; + $scope.maxSize = 5; + $scope.user_available_balance = ''; + /** + * @ngdoc method + * @name setMetaData + * @methodOf Transaction.controller:TransactionController + * @description + * + * This method will set the meta data dynamically by using the angular.element. + **/ + $scope.setMetaData = function () { + var pageTitle = $filter("translate")("My Transactions"); + var fullUrl = $location.absUrl(); + var appUrl = $rootScope.settings['scheme_name'] + ":/" + $location.url(); + angular.element('html head meta[property="og:title"], html head meta[name="twitter:title"]').attr("content", $rootScope.settings['site.name'] + " | " + pageTitle); + angular.element('meta[property="al:ios:url"], meta[property="al:ipad:url"], meta[property="al:android:url"], meta[property="al:windows_phone:url"], html head meta[name="twitter:app:url:iphone"], html head meta[name="twitter:app:url:ipad"], html head meta[name="twitter:app:url:googleplay"]').attr('content', appUrl); + angular.element('meta[property="og:url"]').attr('content', fullUrl); + }; + /** + * @ngdoc method + * @name init + * @methodOf Transaction.controller:TransactionController + * @description + * + * This method will initialize the meta data and functionalities. + **/ + + var params = {}; + $scope.getTransactionList = function () { + params.page = $scope.transaction_currentPage; + TransactionFactory.list(params) + .$promise + .then(function (response) { + $scope.TransactionLists = response.data; + $scope.transaction_metadata = response.meta.pagination; + }); + }; + /** + * @ngdoc method + * @name init + * @methodOf Transaction.controller:TransactionController + * @description + * + * This method will initialize the meta data and functionalities. + **/ + $scope.init = function () { + $scope.setMetaData(); + $rootScope.pageTitle = $rootScope.settings['site.name'] + " | " + $filter("translate")("My Transactions"); + $scope.transaction_currentPage = ($scope.transaction_currentPage !== undefined) ? parseInt($scope.transaction_currentPage) : 1; + AuthFactory.fetch({}).$promise + .then(function (response) { + $scope.user_available_balance = response.available_wallet_amount; + }); + $scope.getTransactionList(); + }; + $scope.init(); + $scope.transaction_paginate = function (pageno) { + $scope.transaction_currentPage = parseInt($scope.transaction_currentPage); + $scope.init(); + }; + $scope.activeMenu = "all"; + $scope.filterTransaction = function (status) { + if (status === undefined) { + $scope.activeMenu = "all"; + $scope.getTransactionList(); + } else { + TransactionFactory.filter({ + 'filter': status, + 'page': $scope.transaction_currentPage + }).$promise.then(function (response) { + $scope.TransactionLists = response.data; + $scope.transaction_metadata = response.meta.pagination; + $scope.activeMenu = status; + }); + } + }; + + }); +}(angular.module("BookorRent.Transactions"))); diff --git a/client/src/app/Transactions/Transaction.module.js b/client/src/app/Transactions/Transaction.module.js new file mode 100644 index 0000000..1033d0e --- /dev/null +++ b/client/src/app/Transactions/Transaction.module.js @@ -0,0 +1,62 @@ +/** + * @ngdoc object + * @name Transaction + * @description + * + * This is the module for transaction. It controls all transaction related functions. + * + * The angular.module is a global place for creating, registering and retrieving Angular modules. + * All modules that should be available to an application must be registered using this mechanism. + * Passing one argument retrieves an existing angular.Module, whereas passing more than one argument creates a new angular.Module + * + * @param {string} transaction name of the module + * @param {!Array.=} dependencies If specified then new module is being created. If unspecified then the module is being retrieved for further configuration. + * + * [ + * 'ui.router', + * 'angulartics', + * 'angulartics.google.analytics', + * 'angulartics.facebook.pixel', + * 'satellizer', + * 'ngFileUpload', + * 'vcRecaptcha' + * ] + * @param {Function=} configFn Optional configuration function for the module. + * @returns {angular.Module} new BookorRent.transaction module with the angular.Module api. + **/ +(function (module) { + module.config(function ($stateProvider, $authProvider, GENERAL_CONFIG, $analyticsProvider) { + var ResolveServiceData = { + 'ResolveServiceData': function (ResolveService, $q) { + return $q.all({ + AuthServiceData: ResolveService.promiseAuth, + SettingServiceData: ResolveService.promiseSettings + }); + } + }; + //$authProvider.tokenPrefix = ""; + //$authProvider.tokenName = "userToken"; + //$authProvider.loginUrl = GENERAL_CONFIG.api_url + '/users/login'; + //$authProvider.signupUrl = GENERAL_CONFIG.api_url + '/users/register'; + $stateProvider.state('transactions', { + url: '/transactions', + authenticate: false, + views: { + "main": { + controller: 'TransactionController as model', + templateUrl: 'Transactions/transaction_list.tpl.html', + resolve: ResolveServiceData + } + } + }); + }); +}(angular.module("BookorRent.Transactions", [ + 'ui.router', + 'angulartics', + 'angulartics.google.analytics', + 'angulartics.facebook.pixel', + 'satellizer', + 'ngFileUpload', + 'vcRecaptcha' +]))); + diff --git a/client/src/app/Transactions/TransactionService.js b/client/src/app/Transactions/TransactionService.js new file mode 100644 index 0000000..2c5454f --- /dev/null +++ b/client/src/app/Transactions/TransactionService.js @@ -0,0 +1,21 @@ +(function (module) { + /** + * @ngdoc service + * @name Transaction.TransactionFactory + * @description + * TransactionFactory used in list and filter the transaction. + * @param {string} TransactionFactory The name of the factory + * @param {function()} function It uses get method for listing, defines the url + */ + module.factory('TransactionFactory', function ($resource, GENERAL_CONFIG) { + return $resource(GENERAL_CONFIG.api_url + '/transactions', {}, { + 'list': { + method: 'GET' + }, + 'filter': { + method: 'GET' + } + } + ); + }); +})(angular.module("BookorRent.Transactions")); diff --git a/client/src/app/Transactions/transaction_list.tpl.html b/client/src/app/Transactions/transaction_list.tpl.html new file mode 100644 index 0000000..d9a1f3e --- /dev/null +++ b/client/src/app/Transactions/transaction_list.tpl.html @@ -0,0 +1,61 @@ +
+
+
+
+

{{'My Transactions' | translate}}

+

{{'We found '|translate}} {{transaction_metadata.total}} {{' results provides our transaction listed'| translate}}

+
+
+ +
+
+
+
+
+ +
+ + + + + + + + + + + + + + + + + + + + +
{{'Date'|translate}}{{'Description'|translate}}{{'Credit' |translate}}{{'Debit' |translate}}
{{transaction.created_at}}
{{getFormatCurrency(transaction.credit_amount)}}{{getFormatCurrency(transaction.debit_amount)}}
+

{{'No Record Found' |translate}}

+
+
+
+
+ +
+
+
\ No newline at end of file diff --git a/client/src/app/User/ChangePassword.js b/client/src/app/User/ChangePassword.js new file mode 100644 index 0000000..594fe38 --- /dev/null +++ b/client/src/app/User/ChangePassword.js @@ -0,0 +1,63 @@ +(function (module) { + /** + * @ngdoc controller + * @name User.controller:ChangePasswordController + * @description + * + * 1.This is change password controller having the methods setmMetaData, init and change_password. + * + * 2.It is used to change the password of the user. + **/ + module.controller('ChangePasswordController', function ($state, $auth, $scope, Flash, $http, $filter, $rootScope, $location, UserChangePasswordFactory) { + $scope.user = {}; + /** + * @ngdoc method + * @name setMetaData + * @methodOf User.controller:ChangePasswordController + * @description + * This method is used to set the meta data dynamically by using the angular.element + * + */ + $scope.setMetaData = function () { + var pageTitle = $filter("translate")("Change Password"); + var fullUrl = $location.absUrl(); + var appUrl = $rootScope.settings['scheme_name'] + ":/" + $location.url(); + angular.element('html head meta[property="og:title"], html head meta[name="twitter:title"]').attr("content", $rootScope.settings['site.name'] + " | " + pageTitle); + angular.element('meta[property="al:ios:url"], meta[property="al:ipad:url"], meta[property="al:android:url"], meta[property="al:windows_phone:url"], html head meta[name="twitter:app:url:iphone"], html head meta[name="twitter:app:url:ipad"], html head meta[name="twitter:app:url:googleplay"]').attr('content', appUrl); + angular.element('meta[property="og:url"]').attr('content', fullUrl); + }; + /** + * @ngdoc method + * @name init + * @methodOf User.controller:ChangePasswordController + * @description + * This method is used to initialize the meta data that is already set by setmetadata() method. + * + */ + $scope.init = function () { + $scope.setMetaData(); + $rootScope.pageTitle = $rootScope.settings['site.name'] + " | " + $filter("translate")("Change Password"); + }; + $scope.init(); + /** + * @ngdoc method + * @name change_password + * @methodOf User.controller:ChangePasswordController + * @description + * This method used for changing the password by the user. + * @param {!Array.} changePasswordForm The form contains the array of string that holds the [old_password, new_password] + */ + $scope.change_password = function (changePasswordForm, user) { + $scope.disableButton = true; + if (changePasswordForm) { + UserChangePasswordFactory.changePassword({id: $rootScope.auth.id}, user, function (response) { + $translate = $filter("translate")("Password changed successfully"); + Flash.set($translate, 'success', true); + $state.reload('ChangePassword'); + }, function (error) { + Flash.set($filter("translate")(error.data.message), 'error', false); + }); + } + }; + }); +}(angular.module("BookorRent.user"))); diff --git a/client/src/app/User/Dashboard.js b/client/src/app/User/Dashboard.js new file mode 100644 index 0000000..af3185c --- /dev/null +++ b/client/src/app/User/Dashboard.js @@ -0,0 +1,85 @@ +(function (module) { + /** + * @ngdoc controller + * @name User.controller:DashboardController + * @description + * + * This is dashboard controller. It contains all the details about the user. It fetches the data of the user by using AuthFactory. + **/ + module.controller('DashboardController', function ($state, $scope, $http, Flash, AuthFactory, GENERAL_CONFIG, $filter, $rootScope, ConstThumb, ConstSocialLogin, MyVehiclesFactory, statsFactory, $uibModal) { + var model = this; + /** + * @ngdoc method + * @name init + * @methodOf User.controller:DashboardController + * @description + * This method will initialze the page. It returns the user's details. + * + **/ + model.init = function () { + $rootScope.pageTitle = $rootScope.settings['site.name'] + " | " + $filter("translate")("User Dashboard"); + //Get user details + AuthFactory.fetch({}).$promise + .then(function (response) { + $scope.user = response; + $rootScope.vehicle_company = response.vehicle_company; + }); + model.ConstSocialLogin = ConstSocialLogin; + model.thumb = ConstThumb.user; + model.getStats(); + model.myVehicles(); + model.myvehicleTpl = "Plugins/Vehicles/my_vehicles.tpl.html"; + + }; + + model.maintenance = function (vehicle_id) { // This function is used in Plugins/Vehicles/my_vehicles.tpl.html for maintenance + $state.go("maintenanceVehicles", {'vehicle_id': vehicle_id}); + }; + + model.myVehicles = function() { + MyVehiclesFactory.get({'user_id': $rootScope.auth.id, 'page':model.currentPage}).$promise.then(function (response) { + model.vehicles = response.data; + angular.forEach(model.vehicles , function(value, key) { + value.roundedRating = value.feedback_rating | 0; + }); + model._metadata = response.meta.pagination; + }); + //Vehicle rating + $scope.maxRatings = []; + $scope.maxRating = 5; + for (var i = 0; i < $scope.maxRating; i++) { + $scope.maxRatings.push(i); + } + }; + model.paginate = function (pageno) { + model.currentPage = parseInt(model.currentPage); + model.myVehicles(); + }; + model.getStats = function() { + statsFactory.get().$promise.then(function(data) { + if(data.response) { + model.bookingStats = data.response.booking; + model.hostStats = data.response.host; + model.orderCount = data.response.total_order_count; + model.bookingCount = data.response.total_booking_count; + } + }); + }; + model.init(); + $scope.modalOpen = function (size, vehicle_id) { + var modalInstance = $uibModal.open({ + templateUrl: 'Plugins/Vehicles/vehicle_feedback_modal.tpl.html', + controller: 'VehicleModalController', + size: size, + resolve: { + vehicle_id: function () { + return vehicle_id; + } + } + }); + }; + model.payNow = function(vehicle_id) { + $state.go("vehiclePaynow", {'vehicle_id':vehicle_id}); + }; + }); +}(angular.module("BookorRent.user"))); diff --git a/client/src/app/User/ForgetPassword.js b/client/src/app/User/ForgetPassword.js new file mode 100644 index 0000000..88b0b58 --- /dev/null +++ b/client/src/app/User/ForgetPassword.js @@ -0,0 +1,37 @@ +(function (module) { + /** + * @ngdoc controller + * @name User.controller:ForgotPasswordController + * @description + * + * This is forgot password controller having the service forgot_password. It is used for reset the password if the users forgot their password. + **/ + module.controller('ForgotPasswordController', function ($state, $window, $scope, $rootScope, $location, Flash, $filter, ForgotPasswordFactory) { + var model = this; + $scope.user = {}; + $rootScope.pageTitle = $rootScope.settings['site.name'] + " | " + $filter("translate")("Forgot Password"); + /** + * @ngdoc method + * @name forgot_password + * @methodOf User.controller:ForgotPasswordController + * @description + * This method uses the forgot_password factory service to change the password. + * + **/ + $scope.forgot_password = function (forgotPassword, user) { + $scope.user = user; + $scope.disableButton = true; + if (forgotPassword) { + ForgotPasswordFactory.forgot_password($scope.user, function (response) { + Flash.set($filter("translate")("Password changed Successfully. New password is sent in mail."), 'success', true); + $state.go('login'); + }, function (error) { + Flash.set($filter("translate")(error.data.message), 'error', false); + $scope.disableButton = false; + }); + } + }; + + }); + +}(angular.module("BookorRent.user"))); diff --git a/client/src/app/User/Login.js b/client/src/app/User/Login.js new file mode 100644 index 0000000..9cfce51 --- /dev/null +++ b/client/src/app/User/Login.js @@ -0,0 +1,96 @@ +(function (module) { + /** + * @ngdoc controller + * @name User.controller:UserLoginController + * @description + * + * This is user login controller having the methods init, setMetaData, and login. It is used for controlling the login functionalities. + **/ + module.controller('UserLoginController', function ($auth, $state, Flash, $rootScope, $filter, AuthFactory, $location, cfpLoadingBar) { + var model = this; + /** + * @ngdoc method + * @name setMetaData + * @methodOf User.controller:UserLoginController + * @description + * + * This method will set the meta data dynamically by using the angular.element of function. + **/ + model.setMetaData = function () { + var pageTitle = $filter("translate")("Login"); + var fullUrl = $location.absUrl(); + var appUrl = $rootScope.settings['scheme_name'] + ":/" + $location.url(); + angular.element('html head meta[property="og:title"], html head meta[name="twitter:title"]').attr("content", $rootScope.settings['site.name'] + " | " + pageTitle); + angular.element('meta[property="al:ios:url"], meta[property="al:ipad:url"], meta[property="al:android:url"], meta[property="al:windows_phone:url"], html head meta[name="twitter:app:url:iphone"], html head meta[name="twitter:app:url:ipad"], html head meta[name="twitter:app:url:googleplay"]').attr('content', appUrl); + angular.element('meta[property="og:url"]').attr('content', fullUrl); + }; + /** + * @ngdoc method + * @name init + * @methodOf User.controller:UserLoginController + * @description + * This method will initialze the page and it uses the setmetadata() function. + * + **/ + model.init = function () { + model.setMetaData(); + $rootScope.pageTitle = $rootScope.settings['site.name'] + " | " + $filter("translate")("Login"); + }; + model.init(); + /** + * @ngdoc method + * @name login + * @methodOf User.controller:UserLoginController + * @description + * This method will validate the credentials and log in the user. + * + * @param {Boolean} isvalid Boolean flag to indicate whether the function call is valid or not + **/ + model.login = function (isvalid) { + if (isvalid) { + cfpLoadingBar.start(); + var credentials = { + email: model.email, + password: model.password + }; + // Use Satellizer's $auth service to login + /** + * @ngdoc service + * @name User.login + * @kind function + * @description + * The auth service get the credentials from the user and validate it. + * @params {string=} credentials login credentials provided by the user + **/ + $auth.login(credentials).then(function (response) { + // If login is successful, redirect to the home page + if (response.data.userToken) { + localStorage.userRole = response.data.role; + $translate = $filter("translate")("Login successfully"); + Flash.set($translate, 'success', true); + AuthFactory.fetch().$promise.then(function (user) { + $rootScope.auth = user; + cfpLoadingBar.complete(); + var selected_vehicle = JSON.parse(localStorage.getItem('vehicle_search_value')); + if(selected_vehicle != null) { + $state.go('vehicleView', {'id':selected_vehicle.id, 'slug':selected_vehicle.slug}); + } else { + $state.go('dashboard'); + } + }); + } + + }).catch(function (error) { + cfpLoadingBar.complete(); + if(error.data.error) { + Flash.set($filter("translate")(error.data.error), 'error', false); + } else { + Flash.set($filter("translate")("Sorry, login failed. Your email or password are incorrect."), 'error', false); + } + }); + } + }; + }); +}(angular.module("BookorRent.user"))); + + diff --git a/client/src/app/User/Register.js b/client/src/app/User/Register.js new file mode 100644 index 0000000..0b6e54f --- /dev/null +++ b/client/src/app/User/Register.js @@ -0,0 +1,116 @@ +(function (module) { + /** + * @ngdoc controller + * @name User.controller:UserRegisterController + * @description + * + * This is user register controller having the methods setmMetaData, init, and signup. It controls the register functionalities. + **/ + module.controller('UserRegisterController', function ($auth, $state, Flash, $rootScope, $filter, AuthFactory, $location, vcRecaptchaService, $scope) { + var model = this; + /** + * @ngdoc method + * @name setMetaData + * @methodOf User.controller:UserRegisterController + * @description + * + * This method will set the meta data dynamically by using angular.element function + **/ + model.setMetaData = function () { + var pageTitle = $filter("translate")("Register"); + var fullUrl = $location.absUrl(); + var appUrl = $rootScope.settings['scheme_name'] + ":/" + $location.url(); + angular.element('html head meta[property="og:title"], html head meta[name="twitter:title"]').attr("content", $rootScope.settings['site.name'] + " | " + pageTitle); + angular.element('meta[property="al:ios:url"], meta[property="al:ipad:url"], meta[property="al:android:url"], meta[property="al:windows_phone:url"], html head meta[name="twitter:app:url:iphone"], html head meta[name="twitter:app:url:ipad"], html head meta[name="twitter:app:url:googleplay"]').attr('content', appUrl); + angular.element('meta[property="og:url"]').attr('content', fullUrl); + }; + /** + * @ngdoc method + * @name init + * @methodOf User.controller:UserRegisterController + * @description + * This method will initialze the page. It uses setMetaData() and captcha_site_key. + * + **/ + model.init = function () { + model.setMetaData(); + model.captcha_site_key = $rootScope.settings['captcha.site_key']; + $rootScope.pageTitle = $rootScope.settings['site.name'] + " | " + $filter("translate")("Register"); + }; + $scope.setRecaptchaId = function(widgetId) { + $scope.widgetId = widgetId; + }; + model.init(); + /** + * @ngdoc method + * @name signup + * @methodOf User.controller:UserRegisterController + * @description + * This method will validate the credentials and signup the user. + * + * @param {Boolean} isvalid Boolean flag to indicate whether the function call is valid or not + **/ + model.signup = function (isvalid) { + model.captchaErr = ''; + var response = vcRecaptchaService.getResponse($scope.widgetId); + if(response.length === 0){ + model.captchaErr = $filter("translate")("Please resolve the captcha and submit"); + }else{ + model.captchaErr = ''; + } + if (isvalid && model.password == model.confirm_password) { + var credentials = { + username: model.username, + email: model.email, + password: model.password, + confirm_password: model.confirm_password, + is_agree_terms_conditions: model.terms_conditions, + 'g-recaptcha-response': response + }; + /** + * @ngdoc service + * @name User.signup + * @kind function + * @description + * The auth service get the credentials from the user and validate it. + * @params {string} credentials login credentials provided by the user + **/ + $auth.signup(credentials).then(function (response) { + if (response.data.token) { + $auth.setToken(response.data.token); + localStorage.userRole = response.data.role; + AuthFactory.fetch().$promise.then(function (user) { + $rootScope.auth = user; + localStorage.auth = user; + $state.go('home'); + }); + } else { + $state.go('login'); + } + Flash.set($filter("translate")(response.data.Success), 'success', true); + + }).catch(function (error) { + model.emailErr = ''; + model.nameErr = ''; + model.passwordErr = ''; + model.confirmPasswordErr = ''; + var errorResponse = error.data.errors; + if (errorResponse.email) { + model.emailErr = $filter("translate")(errorResponse.email[0]); + } + if (errorResponse.username) { + model.nameErr = $filter("translate")(errorResponse.username[0]); + } + if (errorResponse.password) { + model.passwordErr = $filter("translate")(errorResponse.password[0]); + } + if (errorResponse.confirm_password) { + model.confirmPasswordErr = $filter("translate")(errorResponse.confirm_password[0]); + } + Flash.set($filter("translate")(error.data.message), 'error', false); + }); + } + }; + }); + +}(angular.module("BookorRent.user"))); \ No newline at end of file diff --git a/client/src/app/User/User.js b/client/src/app/User/User.js new file mode 100644 index 0000000..18fba35 --- /dev/null +++ b/client/src/app/User/User.js @@ -0,0 +1,50 @@ +(function (module) { + /** + * @ngdoc controller + * @name User.controller:UserController + * @description + * + * This is user controller having the methods setmMetaData, init, upload and user_profile. + **/ + module.controller('UserController', function ($scope, $auth, $state, UsersFactory, $rootScope, $filter, UserActivateFactory, Flash, AuthFactory, $location, ConstSocialLogin ) { + var model = this; + model.maxSize = 5; + /** + * @ngdoc method + * @name setMetaData + * @methodOf User.controller:UserController + * @description + * + * This method will set the meta data dynamically by using the angular.element function. + * + * It defines the angular elements + **/ + model.setMetaData = function () { + var pageTitle = $filter("translate")("User"); + var fullUrl = $location.absUrl(); + var appUrl = $rootScope.settings['scheme_name'] + ":/" + $location.url(); + angular.element('html head meta[property="og:title"], html head meta[name="twitter:title"]').attr("content", $rootScope.settings['site.name'] + " | " + pageTitle); + angular.element('meta[property="al:ios:url"], meta[property="al:ipad:url"], meta[property="al:android:url"], meta[property="al:windows_phone:url"], html head meta[name="twitter:app:url:iphone"], html head meta[name="twitter:app:url:ipad"], html head meta[name="twitter:app:url:googleplay"]').attr('content', appUrl); + angular.element('meta[property="og:url"]').attr('content', fullUrl); + }; + /** + * @ngdoc method + * @name init + * @methodOf User.controller:UserController + * @description + * This method will initialze the page. It returns the page title. + * + **/ + model.init = function () { + model.setMetaData(); + $scope.currentPage = ($scope.currentPage !== undefined) ? parseInt($scope.currentPage) : 1; + model.ConstSocialLogin = ConstSocialLogin; + $rootScope.pageTitle = $rootScope.settings['site.name'] + " | " + $filter("translate")("User") + ":" + $state.params.username; + UsersFactory.get({username: $state.params.username}).$promise.then(function (response) { + model.user = response; + }); + }; + model.init(); + + }); +}(angular.module("BookorRent.user"))); \ No newline at end of file diff --git a/client/src/app/User/User.module.js b/client/src/app/User/User.module.js new file mode 100644 index 0000000..2ddf50c --- /dev/null +++ b/client/src/app/User/User.module.js @@ -0,0 +1,166 @@ +/** + * @ngdoc object + * @name User + * @description + * + * This is the module for user. It controls all user related functions. + * + * The angular.module is a global place for creating, registering and retrieving Angular modules. + * All modules that should be available to an application must be registered using this mechanism. + * Passing one argument retrieves an existing angular.Module, whereas passing more than one argument creates a new angular.Module + * + * @param {string} user name of the module + * @param {!Array.=} dependencies If specified then new module is being created. If unspecified then the module is being retrieved for further configuration. + * + * [ + * 'ui.router', + * 'angulartics', + * 'angulartics.google.analytics', + * 'angulartics.facebook.pixel', + * 'satellizer', + * 'ngFileUpload', + * 'vcRecaptcha' + * ] + * @param {Function=} configFn Optional configuration function for the module. + * @returns {angular.Module} new BookorRent.user module with the angular.Module api. + **/ +(function (module) { + module.directive('passwordMatch', function() { + return { + require: 'ngModel', + scope: { + otherModelValue: '=passwordMatch' + }, + link: function(scope, element, attributes, ngModel) { + ngModel.$validators.compareTo = function(modelValue) { + return modelValue === scope.otherModelValue; + }; + scope.$watch('otherModelValue', function() { + ngModel.$validate(); + }); + } + }; + }); + module.config(function ($stateProvider, $authProvider, GENERAL_CONFIG, $analyticsProvider) { + var ResolveServiceData = { + 'ResolveServiceData': function (ResolveService, $q) { + return $q.all({ + AuthServiceData: ResolveService.promiseAuth, + SettingServiceData: ResolveService.promiseSettings + }); + } + }; + $authProvider.tokenPrefix = ""; + $authProvider.tokenName = "userToken"; + $authProvider.loginUrl = GENERAL_CONFIG.api_url + '/users/login'; + $authProvider.signupUrl = GENERAL_CONFIG.api_url + '/users/register'; + $stateProvider.state('login', { + url: '/users/login', + authenticate: false, + views: { + "main": { + controller: 'UserLoginController as model', + templateUrl: 'User/login.tpl.html', + resolve: ResolveServiceData + } + } + }).state('register', { + url: '/users/register', + authenticate: false, + views: { + "main": { + controller: 'UserRegisterController as model', + templateUrl: 'User/register.tpl.html', + resolve: ResolveServiceData + } + } + }).state('activate', { + url: '/users/:id/activate/:hash', + views: { + "main": { + controller: 'UserActivateController as model', + resolve: ResolveServiceData + } + } + }).state('ChangePassword', { + url: '/users/change_password', + authenticate: true, + views: { + "main": { + controller: 'ChangePasswordController as model', + templateUrl: 'User/change_password.tpl.html', + resolve: ResolveServiceData + } + } + }).state('UserProfile', { + url: '/users/user_profile', + authenticate: true, + views: { + "main": { + controller: 'UserProfileController as model', + templateUrl: 'User/user_profile.tpl.html', + resolve: ResolveServiceData + } + } + }).state('userView', { + url: '/user/:username', + authenticate: false, + views: { + "main": { + controller: 'UserController as model', + templateUrl: 'User/user_view.tpl.html', + resolve: ResolveServiceData + } + } + }).state('dashboard', { + url: '/users/dashboard', + authenticate: true, + views: { + "main": { + controller: 'DashboardController as model', + templateUrl: 'User/dashboard.tpl.html', + resolve: ResolveServiceData + } + } + }).state('ForgotPassword', { + url: '/users/forgot_password', + authenticate: false, + views: { + "main": { + controller: 'ForgotPasswordController as model', + templateUrl: 'User/forgot_password.tpl.html', + resolve: ResolveServiceData + } + } + }); + }); + /** + * @ngdoc directive + * @name User.directive:dashboardSettings + * @module User + * @scope + * @restrict E + * + * @description + * This directive used to maintain the dashboard settings. + * + * @param {string} dashboardSettings directive name + * + */ + module.directive('dashboardSettings', function () { + return { + restrict: 'E', + templateUrl: 'User/dashboard_settings.tpl.html' + }; + }); +}(angular.module("BookorRent.user", [ + 'ui.router', + 'angulartics', + 'angulartics.google.analytics', + 'angulartics.facebook.pixel', + 'satellizer', + 'ngFileUpload', + 'vcRecaptcha', + 'slugifier' +]))); + diff --git a/client/src/app/User/UserActivate.js b/client/src/app/User/UserActivate.js new file mode 100644 index 0000000..93672e9 --- /dev/null +++ b/client/src/app/User/UserActivate.js @@ -0,0 +1,44 @@ +(function (module) { + /** + * @ngdoc controller + * @name User.controller:UserActivateController + * @description + * + * This is user controller having the methods setmMetaData, init, upload and user_profile. + **/ + module.controller('UserActivateController', function ($auth, $state, $rootScope, $filter, UserActivateFactory, Flash, AuthFactory, $location) { + var model = this; + /** + * @ngdoc method + * @name init + * @methodOf User.controller:UserActivateController + * @description + * This method will confirm the email and return token or error message + * + **/ + model.init = function () { + // activate users link + UserActivateFactory.activate({ + id: $state.params.id, + hash: $state.params.hash + }).$promise.then(function (response) { + if (response.token) { + $auth.setToken(response.token); + localStorage.userRole = response.role; + AuthFactory.fetch().$promise.then(function (user) { + $rootScope.auth = user; + Flash.set($filter("translate")(response.Success), 'success', true); + $state.go('home'); + }); + } else { + Flash.set($filter("translate")(response.Success), 'success', true); + $state.go('login'); + } + }, function (error) { + Flash.set($filter("translate")(error.data.message), 'error', true); + $state.go('login'); + }); + }; + model.init(); + }); +}(angular.module("BookorRent.user"))); \ No newline at end of file diff --git a/client/src/app/User/UserProfile.js b/client/src/app/User/UserProfile.js new file mode 100644 index 0000000..0e83521 --- /dev/null +++ b/client/src/app/User/UserProfile.js @@ -0,0 +1,107 @@ +(function (module) { + /** + * @ngdoc controller + * @name User.controller:UserProfileController + * @description + * + * This is user profile controller having the methods setmMetaData, init, upload and user_profile. It controld the user profile functions. + **/ + module.controller('UserProfileController', function ($state, $scope, Flash, UserProfilesFactory, $filter, $rootScope, $location, Upload, GENERAL_CONFIG, ConstSocialLogin, ConstThumb) { + var model = this; + /** + * @ngdoc method + * @name setMetaData + * @methodOf User.controller:UserProfileController + * @description + * + * This method will set the meta data dynamically by using the angular.element function. + **/ + model.setMetaData = function () { + var pageTitle = $filter("translate")("User Profile"); + var fullUrl = $location.absUrl(); + var appUrl = $rootScope.settings['scheme_name'] + ":/" + $location.url(); + angular.element('html head meta[property="og:title"], html head meta[name="twitter:title"]').attr("content", $rootScope.settings['site.name'] + " | " + pageTitle); + angular.element('meta[property="al:ios:url"], meta[property="al:ipad:url"], meta[property="al:android:url"], meta[property="al:windows_phone:url"], html head meta[name="twitter:app:url:iphone"], html head meta[name="twitter:app:url:ipad"], html head meta[name="twitter:app:url:googleplay"]').attr('content', appUrl); + angular.element('meta[property="og:url"]').attr('content', fullUrl); + }; + /** + * @ngdoc method + * @name init + * @methodOf User.controller:UserProfileController + * @description + * This method will initialze the page. It returns the page title + * + **/ + model.init = function () { + model.setMetaData(); + $rootScope.pageTitle = $rootScope.settings['site.name'] + " | " + $filter("translate")("User Profile"); + model.ConstSocialLogin = ConstSocialLogin; + model.thumb = ConstThumb.user; + //Get user details + UserProfilesFactory.get().$promise.then(function (response) { + model.user_profile = response; + $scope.user = response.User; + $rootScope.auth.attachmentable.thumb = $scope.user.attachmentable.thumb; + }); + }; + model.init(); + // upload on file select or drop + /** + * @ngdoc method + * @name upload + * @methodOf User.controller:UserProfileController + * @description + * This method will save the user profile data + * + * @param {!Array.} profileData contains the array of user profile data + **/ + model.upload = function (profileData, file) { + Upload.upload({ + url: GENERAL_CONFIG.api_url + '/user_profiles', + data: { + file: file, + 'first_name': profileData.first_name, + 'last_name': profileData.last_name, + 'about_me': profileData.about_me, + 'website': profileData.website, + 'facebook_profile_link': profileData.facebook_profile_link, + 'twitter_profile_link': profileData.twitter_profile_link, + 'google_plus_profile_link': profileData.google_plus_profile_link, + 'linkedin_profile_link': profileData.linkedin_profile_link, + 'youtube_profile_link': profileData.youtube_profile_link + } + }).then(function (resp) { + Flash.set($filter("translate")("UserProfile has been updated"), 'success', true); + $state.reload('UserProfile'); + }, function (resp) { + Flash.set($filter("translate")("UserProfile could not be updated. Please, try again."), 'error', false); + }, function (evt) { + var progressPercentage = parseInt(100.0 * evt.loaded / evt.total); + console.log('progress: ' + progressPercentage + '% ' + evt.config.data.file.name); + }); + }; + //Update user details + /** + * @ngdoc method + * @name userProfile + * @methodOf User.controller:UserProfileController + * @description + * This method will upload the file and returns the success message. + * + **/ + model.userProfile = function ($valid) { + if($valid) { + if ($scope.file) { + model.upload(model.user_profile, $scope.file); + } else { + UserProfilesFactory.update(model.user_profile) + .$promise + .then(function (response) { + Flash.set($filter("translate")(response.Success), 'success', true); + $state.reload('UserProfile'); + }); + } + } + }; + }); +}(angular.module("BookorRent.user"))); diff --git a/client/src/app/User/UsersService.js b/client/src/app/User/UsersService.js new file mode 100644 index 0000000..c745a16 --- /dev/null +++ b/client/src/app/User/UsersService.js @@ -0,0 +1,161 @@ +(function (module) { + /** + * @ngdoc service + * @name User.AuthFactory + * @description + * Authfactory is a factory service which is used to authenticate the user + * @param {string} AuthFactory The name of the factory + * @param {function()} function It uses get method, and defines the url + */ + module.factory('AuthFactory', function ($resource, GENERAL_CONFIG) { + return $resource(GENERAL_CONFIG.api_url + '/users/auth', {}, { + fetch: { + method: 'GET' + } + }); + }); + /** + * @ngdoc service + * @name User.UserProfilesFactory + * @description + * UserProfilesFactory is a factory service which updates and displays the user profile. + * @param {string} UserProfilesFactory The name of the factory + * @param {function()} function It uses get method for get the user profile, uses post method for update the user + profile and defines the url + */ + module.factory('UserProfilesFactory', function ($resource, GENERAL_CONFIG) { + return $resource(GENERAL_CONFIG.api_url + '/user_profiles', {}, { + update: { + method: 'POST' + }, + get: { + method: 'GET' + } + }); + }); + /** + * @ngdoc service + * @name User.UsersFactory + * @description + * UsersFactory is a factory servce which is used to get the users list. + * @param {string} UsersFactory The name of the factory + * @param {function()} function It uses get method, and defines the url + */ + + module.factory('UsersFactory', function ($resource, GENERAL_CONFIG) { + return $resource(GENERAL_CONFIG.api_url + '/user', {}, { + get: { + method: 'GET' + } + }); + }); + /** + * @ngdoc service + * @name User.UserActivateFactory + * @description + * UserActivateFactory is a factory service which is used for activating the user. + * @param {string} UserActivateFactory The name of the factory + * @param {function()} function It uses get method, and defines the url + */ + + module.factory('UserActivateFactory', function ($resource, GENERAL_CONFIG) { + return $resource(GENERAL_CONFIG.api_url + '/users/:id/activate/:hash', { + id: '@id', + hash: '@hash' + }, { + 'activate': { + method: 'PUT' + } + } + ); + }); + /** + * @ngdoc service + * @name User.ForgotPasswordFactory + * @description + * ForgotPasswordFactory is a factory service which will be used in resetting the password if the user forgot his password. + * @param {string} ForgotPasswordFactory The name of the factory + * @param {function()} function It uses get method, and defines the url + */ + + module.factory('ForgotPasswordFactory', function ($resource, GENERAL_CONFIG) { + return $resource(GENERAL_CONFIG.api_url + '/users/forgot_password', {}, { + forgot_password: { + method: 'PUT' + } + }); + }); + /** + * @ngdoc service + * @name User.UserAttachmentFactory + * @description + * UserAttachmentFactory is a factory service which is used for getting user upload image detail. + * @param {string} UserAttachmentFactory The name of the factory + * @param {function()} function It uses get method, and defines the url + */ + + module.factory('UserAttachmentFactory', function ($resource, GENERAL_CONFIG) { + return $resource(GENERAL_CONFIG.api_url + '/users/:id/attachment', { + id: '@id' + }, { + 'get': { + method: 'GET' + } + } + ); + }); + /** + * @ngdoc service + * @name User.UserChangePasswordFactory + * @description + * UserChangePasswordFactory is a factory service which is used to change password. + * @param {string} UserChangePasswordFactory The name of the factory + * @param {function()} function It uses put method, and defines the url + */ + + module.factory('UserChangePasswordFactory', function ($resource, GENERAL_CONFIG) { + return $resource(GENERAL_CONFIG.api_url + '/users/:id/change_password', { + id: '@id' + }, { + 'changePassword': { + method: 'PUT' + } + } + ); + }); + + /** + * @ngdoc service + * @name User.MyVehiclesFactory + * @description + * MyVehiclesFactory is a factory service which is used to get the vehicles. + * @param {string} MyVehiclesFactory The name of the factory + * @param {function()} function It uses get method, and get the vehicles + */ + + module.factory('MyVehiclesFactory', function ($resource, GENERAL_CONFIG) { + return $resource(GENERAL_CONFIG.api_url + '/vehicles/me', {}, { + 'get': { + method: 'GET' + } + } + ); + }); + /** + * @ngdoc service + * @name User.statsFactory + * @description + * statsFactory is a factory service which is used to get the stats of user. + * @param {string} statsFactory The name of the factory + * @param {function()} function It uses get method, and get the stats of user + */ + + module.factory('statsFactory', function ($resource, GENERAL_CONFIG) { + return $resource(GENERAL_CONFIG.api_url + '/users/stats', {}, { + 'get': { + method: 'GET' + } + } + ); + }); +})(angular.module("BookorRent.user")); diff --git a/client/src/app/User/change_password.tpl.html b/client/src/app/User/change_password.tpl.html new file mode 100644 index 0000000..cbc42f8 --- /dev/null +++ b/client/src/app/User/change_password.tpl.html @@ -0,0 +1,47 @@ +
+
+

{{'Change Password' | translate}}

+
+ +
+
+
+
+
+
+
+ + +
+ {{'Enter Current Password' | translate}} + {{'Minimum length is' | translate}} 6 + {{user.oldPassErr}} +
+
+
+ + +
+ {{ 'Enter New Password' | translate }} + {{ 'Minimum length is 6' | translate }} + {{ 'Maximum length is 20' | translate }} + {{user.passwordErr}} +
+
+
+ + +
+ {{'Re-type New Password' | translate}} + {{'Minimum length is 6' | translate}} + {{'Maximum length is 20' | translate }} + {{'Password Mismatch' | translate }} + {{user.confirmPasswordErr}} +
+
+
+ +
+
+
+
\ No newline at end of file diff --git a/client/src/app/User/dashboard.tpl.html b/client/src/app/User/dashboard.tpl.html new file mode 100644 index 0000000..870dcaf --- /dev/null +++ b/client/src/app/User/dashboard.tpl.html @@ -0,0 +1,107 @@ +
+
+ +
+
+
+ +
+

{{user.username}}

+

{{user.user_profile.about_me}}

+
+ +
+
+
+
+ +
+
+

{{'Company Details' | translate}}

+
+

{{$root.vehicle_company.name}}

+
+
+

{{$root.vehicle_company.email}}

+
+
+

{{$root.vehicle_company.address}}

+
+
+

{{$root.vehicle_company.mobile}}

+
+
+

{{$root.vehicle_company.fax}}

+
+
+ +
+ +
+
+
+

{{'Booking Details' | translate}}

+ +
+
+

{{'Order Details' | translate}}

+ +
+
+ +
+ + +
+
+
+
+ +
+
+ +
\ No newline at end of file diff --git a/client/src/app/User/dashboard_settings.tpl.html b/client/src/app/User/dashboard_settings.tpl.html new file mode 100644 index 0000000..3480779 --- /dev/null +++ b/client/src/app/User/dashboard_settings.tpl.html @@ -0,0 +1,29 @@ + \ No newline at end of file diff --git a/client/src/app/User/forgot_password.tpl.html b/client/src/app/User/forgot_password.tpl.html new file mode 100644 index 0000000..028b2fb --- /dev/null +++ b/client/src/app/User/forgot_password.tpl.html @@ -0,0 +1,21 @@ + \ No newline at end of file diff --git a/client/src/app/User/login.tpl.html b/client/src/app/User/login.tpl.html new file mode 100644 index 0000000..f8ea843 --- /dev/null +++ b/client/src/app/User/login.tpl.html @@ -0,0 +1,33 @@ + \ No newline at end of file diff --git a/client/src/app/User/register.tpl.html b/client/src/app/User/register.tpl.html new file mode 100644 index 0000000..b23a552 --- /dev/null +++ b/client/src/app/User/register.tpl.html @@ -0,0 +1,63 @@ + \ No newline at end of file diff --git a/client/src/app/User/user_profile.tpl.html b/client/src/app/User/user_profile.tpl.html new file mode 100644 index 0000000..bd6e153 --- /dev/null +++ b/client/src/app/User/user_profile.tpl.html @@ -0,0 +1,125 @@ +
+
+
+
+

{{'Edit Profile' | translate}}

+

{{'Please enter your personal information and company information' | translate}}

+
+
+ +
+
+
+
+
+
+ +
+
+
+

{{'Personal Info' | translate }}

+
+
+ +
+ + {{'Required' | translate }} +
+
+
+ +
+ + {{'Required' | translate }} + + {{'Enter the Last Name without Numbers and Blankspace'|translate}} + +
+
+
+
+
+ +
+ + {{'Required' | translate }} +
+
+
+ +
+ + {{'File too large, please upload less than 2MB file'|translate}} +
+
+
+
+ + + +
+
+
+
+
+ +
diff --git a/client/src/app/User/user_view.tpl.html b/client/src/app/User/user_view.tpl.html new file mode 100644 index 0000000..e62afd1 --- /dev/null +++ b/client/src/app/User/user_view.tpl.html @@ -0,0 +1,67 @@ +
+
+
+ +
+
+

+ + {{model.user.username}} + +

+

+ {{model.user.user_profile.about_me}} +

+
+
+
+
+

{{'Reference' | translate }}

+
    +
  • + +
  • +
  • + +
  • +
  • + +
  • +
  • + +
  • +
  • + +
  • +
  • + +
  • +
+
+
+

{{'Connect' | translate }}

+ +
+
+
+ \ No newline at end of file diff --git a/client/src/app/Wallets/Wallet.js b/client/src/app/Wallets/Wallet.js new file mode 100644 index 0000000..36a8098 --- /dev/null +++ b/client/src/app/Wallets/Wallet.js @@ -0,0 +1,190 @@ +(function (module) { + /** + * @ngdoc controller + * @name Wallets.controller:WalletsStatusController + * @description + * + * This is Wallets Status Controller used for payment after return flash message set. + **/ + module.controller('WalletsStatusController', function ($state, Flash, $stateParams, $filter) { + if ($stateParams.status == 'fail') { + Flash.set($filter("translate")("Amount could not be added, please try again."), 'error', false); + } else if ($stateParams.status == 'success') { + Flash.set($filter("translate")("Amount Added successfully"), 'success', true); + } + $state.go('wallets'); + + }); + /** + * @ngdoc controller + * @name Wallets.controller:WalletsController + * @description + * + * This is wallets controller having the methods init(), setMetaData(), WalletSubmit() + **/ + module.controller('WalletsController', function ($state, $scope, $http, Flash, $filter, WalletsFactory, $rootScope, $location, $window, GetGatewaysFactory, $sce, GetCountries, ConstPaymentGateways) { + $scope.ConstPaymentGateways = ConstPaymentGateways; + $scope.buyer = {}; + $scope.paynow_is_disabled = false; + /** + * @ngdoc method + * @name setMetaData + * @methodOf Wallets.controller:WalletsController + * @description + * + * This method will set the meta data dynamically by using the angular.element. + **/ + $scope.setMetaData = function () { + var pageTitle = $filter("translate")("Add To Wallet"); + var fullUrl = $location.absUrl(); + var appUrl = $rootScope.settings['scheme_name'] + ":/" + $location.url(); + angular.element('html head meta[property="og:title"], html head meta[name="twitter:title"]').attr("content", $rootScope.settings['site.name'] + " | " + pageTitle); + angular.element('meta[property="al:ios:url"], meta[property="al:ipad:url"], meta[property="al:android:url"], meta[property="al:windows_phone:url"], html head meta[name="twitter:app:url:iphone"], html head meta[name="twitter:app:url:ipad"], html head meta[name="twitter:app:url:googleplay"]').attr('content', appUrl); + angular.element('meta[property="og:url"]').attr('content', fullUrl); + }; + + $scope.getGatewaysList = function () { + GetGatewaysFactory.get({'page': 'wallet'}).$promise.then(function (response) { + $scope.wallet_enabled = false; + if (response.paypal) { + $scope.paypal_enabled = (response.paypal.paypal_enabled) ? true : false; + } + if (response.sudopay) { + $scope.gateway_groups = response.sudopay.gateway_groups; + $scope.payment_gateways = response.sudopay.payment_gateways; + $scope.form_fields_tpls = response.sudopay.form_fields_tpls; + $scope.sel_payment_gateway = response.sudopay.selected_payment_gateway_id; + $scope.show_form = []; + $scope.form_fields = []; + $scope.group_gateway_id = response.sudopay.selected_gateway_id; + angular.forEach($scope.form_fields_tpls, function (key, value) { + if (value == 'buyer') { + $scope.form_fields[value] = 'Plugins/Sudopays/buyer.tpl.html'; + } + if (value == 'credit_card') { + $scope.form_fields[value] = 'Plugins/Sudopays/credit_card.tpl.html'; + } + if (value == 'manual') { + $scope.form_fields[value] = 'Plugins/Sudopays/manual.tpl.html'; + } + $scope.show_form[value] = true; + }); + } + if ($scope.paypal_enabled) { + $scope.gateway_id = ConstPaymentGateways.PayPal; + } else { + $scope.gateway_id = ConstPaymentGateways.SudoPay; + } + }); + }; + $scope.paneChanged = function (pane) { + var keepGoing = true; + $scope.buyer = {}; + $scope.PaymentForm.$setPristine(); + $scope.PaymentForm.$setUntouched(); + angular.forEach($scope.form_fields_tpls, function (key, value) { + $scope.show_form[value] = false; + }); + if (pane == 'paypal') { + $scope.gateway_id = ConstPaymentGateways.PayPal; + } else { + $scope.gateway_id = ConstPaymentGateways.SudoPay; + angular.forEach($scope.gateway_groups, function (res) { + if (res.display_name == pane) { + var selPayment = ''; + angular.forEach($scope.payment_gateways, function (response) { + if (keepGoing) { + if (response.group_id == res.id) { + selPayment = response; + keepGoing = false; + $scope.rdoclick(selPayment.id, selPayment.form_fields); + } + } + }); + $scope.sel_payment_gateway = "sp_" + selPayment.id; + $scope.group_gateway_id = selPayment.group_id; + } + }); + } + }; + + $scope.rdoclick = function (res, res1) { + $scope.paynow_is_disabled = false; + $scope.sel_payment_gateway = "sp_" + res; + $scope.array = res1.split(','); + angular.forEach($scope.array, function (value) { + $scope.show_form[value] = true; + }); + }; + + /** + * @ngdoc method + * @name init + * @methodOf Wallets.controller:WalletsController + * @description + * + * This method will initialize the meta data and functionalities. + **/ + $scope.init = function () { + $scope.setMetaData(); + $rootScope.pageTitle = $rootScope.settings['site.name'] + " | " + $filter("translate")("Add To Wallet"); + $scope.min_wallet_amount = $rootScope.settings['wallet.min_wallet_amount']; + $scope.max_wallet_amount = $rootScope.settings['wallet.max_wallet_amount']; + //Get gateways list + $scope.getGatewaysList(); + $scope.gatewayTpl = 'Common/gateway.tpl.html'; + //Get countries list + GetCountries.get({'sort': 'name', 'sortby': 'asc'}).$promise.then(function (response) { + $scope.countries = response.data; + }); + + }; + $scope.init(); + /** + * @ngdoc method + * @name WalletSubmit + * @methodOf Wallets.controller:WalletsController + * @description + * + * This method will be used in submitting the wallet amount to the user's account. + **/ + $scope.PaymentSubmit = function (form) { + if ($scope.sel_payment_gateway) { + payment_id = $scope.sel_payment_gateway.split('_')[1]; + $scope.buyer.payment_id = payment_id; + } + $scope.buyer.gateway_id = $scope.gateway_id; // Paypal or sudopay + if($scope.buyer.credit_card_expire_month || $scope.buyer.credit_card_expire_year) { + $scope.buyer.credit_card_expire_month = $scope.buyer.credit_card_expire_month > 9 ? $scope.buyer.credit_card_expire_month: "0" + $scope.buyer.credit_card_expire_month; + $scope.buyer.credit_card_expire = $scope.buyer.credit_card_expire_month + "/" + $scope.buyer.credit_card_expire_year; + } + if($scope.wallet) { + $scope.buyer.amount = $scope.wallet.amount; + } + if ($scope.gateway_id == ConstPaymentGateways.PayPal && form.amount.$valid) { //if Paypal checkonly amount field + form.$valid = true; + } + if (form.$valid) { + $scope.paynow_is_disabled = true; + WalletsFactory.save($scope.buyer, function (response) { + if (response.url !== undefined) { + $window.location.href = response.url; + } else { + Flash.set($filter("translate")("Amount Added successfully"), 'success', true); + $state.reload(); + } + $scope.paynow_is_disabled = false; + }, function (error) { + $scope.paynow_is_disabled = false; + Flash.set($filter("translate")("Amount could not be added"), 'error', false); + $scope.amountErr = ''; + var errorResponse = error.data.errors; + if (errorResponse.amount) { + $scope.amountErr = $filter("translate")(errorResponse.amount[0]); + } + }); + } + }; + + }); +}(angular.module("BookorRent.Wallets"))); diff --git a/client/src/app/Wallets/Wallet.module.js b/client/src/app/Wallets/Wallet.module.js new file mode 100644 index 0000000..16bc54e --- /dev/null +++ b/client/src/app/Wallets/Wallet.module.js @@ -0,0 +1,65 @@ +/** + * @ngdoc object + * @name Wallets + * @description + * + * This is the module for wallet + * + * The angular.module is a global place for creating, registering and retrieving Angular modules. + * All modules that should be available to an application must be registered using this mechanism. + * Passing one argument retrieves an existing angular.Module, whereas passing more than one argument creates a new angular.Module + * + * @param {string} wallets name of the module + * @param {!Array.=} dependencies If specified then new module is being created. If unspecified then the module is being retrieved for further configuration. + * + * [ + * 'ui.router', + * 'ngResource', + * 'angulartics', + * 'angulartics.google.analytics', + * 'angulartics.facebook.pixel' + * ] + * @param {Function=} configFn Optional configuration function for the module. + * @returns {angular.Module} new BookorRent.wallet module with the {@link angular.Module} api. + **/ +(function (module) { + module.config(function ($stateProvider, $analyticsProvider) { + var ResolveServiceData = { + 'ResolveServiceData': function (ResolveService, $q) { + return $q.all({ + AuthServiceData: ResolveService.promiseAuth, + SettingServiceData: ResolveService.promiseSettings + }); + } + }; + $stateProvider.state('wallets', { + url: '/wallets', + authenticate: true, + views: { + "main": { + controller: 'WalletsController as model', + templateUrl: 'Wallets/wallet.tpl.html', + resolve: ResolveServiceData + } + }, + data: {pageTitle: 'Add to Wallet'} + }).state('walletsRedirect', { + url: '/wallets/:status', + authenticate: true, + views: { + "main": { + controller: 'WalletsStatusController as model', + resolve: ResolveServiceData + } + }, + data: {pageTitle: 'Add to Wallet'} + }); + }); +}(angular.module("BookorRent.Wallets", [ + 'ui.router', + 'ngResource', + 'angulartics', + 'angulartics.google.analytics', + 'angulartics.facebook.pixel', + 'credit-cards' +]))); diff --git a/client/src/app/Wallets/WalletService.js b/client/src/app/Wallets/WalletService.js new file mode 100644 index 0000000..3d0c15c --- /dev/null +++ b/client/src/app/Wallets/WalletService.js @@ -0,0 +1,52 @@ +(function (module) { + /** + * @ngdoc service + * @name Wallets.WalletsFactory + * @description + * WalletsFactory is used in wallets + * @param {string} WalletsFactory The name of the factory + * @param {function()} function It uses post method for save and returns the url + */ + module.factory('WalletsFactory', function ($resource, GENERAL_CONFIG) { + return $resource(GENERAL_CONFIG.api_url + '/wallets', {}, { + 'save': { + method: 'POST' + } + } + ); + }); + + /** + * @ngdoc service + * @name Wallets.GetGatewaysFactory + * @description + * GetGatewaysFactory is used in wallets + * @param {string} GetGatewaysFactory The name of the factory + * @param {function()} function It uses get method for get the gateways + */ + module.factory('GetGatewaysFactory', function ($resource, GENERAL_CONFIG) { + return $resource(GENERAL_CONFIG.api_url + '/get_gateways', {}, { + 'get': { + method: 'GET' + } + } + ); + }); + + /** + * @ngdoc service + * @name Wallets.GetCountries + * @description + * GetCountries used in list and store the items. + * @param {string} GetCountries The name of the factory + * @param {function()} function It uses get method for listing, countries + */ + module.factory('GetCountries', function ($resource, GENERAL_CONFIG) { + return $resource(GENERAL_CONFIG.api_url + '/countries', {}, { + 'get': { + method: 'GET' + } + } + ); + }); +})(angular.module('BookorRent.Wallets')); diff --git a/client/src/app/Wallets/wallet.tpl.html b/client/src/app/Wallets/wallet.tpl.html new file mode 100644 index 0000000..8564428 --- /dev/null +++ b/client/src/app/Wallets/wallet.tpl.html @@ -0,0 +1,58 @@ +
+
+

{{'Add to Wallet' | translate}}

+
+ +
+
+
+ +
+
+
+
+
+
+ +
+ +
+ + {{'Enter Amount'|translate }} + + + {{'You did not enter a valid number' | translate}} + + + {{'Your field value is lesser than the minimum value' | translate}} + + + {{'Your field value is greater than the maximum value' | translate}} + + {{amountErr}} +
+
+
+
+
+ +
+
+
    +
  • {{'Minimum wallet amount'|translate}}: {{getFormatCurrency(min_wallet_amount, 'site')}}
  • +
  • {{'Maximum wallet amount'|translate}}: {{getFormatCurrency(max_wallet_amount, 'site')}}
  • +
+
+
+
+
+
+
+
+
+
+ +
+
+
+
\ No newline at end of file diff --git a/client/src/assets/README.md b/client/src/assets/README.md new file mode 100644 index 0000000..3040eac --- /dev/null +++ b/client/src/assets/README.md @@ -0,0 +1,4 @@ +# The `src/assets` Directory + +There's really not much to say here. Every file in this directory is recursively transferred to `dist/assets/`. + diff --git a/client/src/assets/apple-touch-icon-114x114.png b/client/src/assets/apple-touch-icon-114x114.png new file mode 100644 index 0000000000000000000000000000000000000000..c08d424bfd825551b3ed7151a4c3d9d64eb756f1 GIT binary patch literal 12053 zcmaKSbyOTrx9#9g1`7_u;O_1)xFo^d2X}_x4he%xa0mo<3oe5MOYopcumHg&xWnW3 z-TU49{&?T(wYsaS*WUY_I(52Mt?Gim)>Oj7roaXO0C+0O5UuCZ^Pd|N{rQ==92N9j zki!%VVA^iBFds`#C_vW6%?b)qaj~?6YC$b+{5-xwB>(^vCI=k@n1P16n6;Y=m*qbg zE?*b-XEp#JA?@pKY3&4sfvli*4z7~m_vCHAvpg z6ABXK65_Px5fTOoi*oS_3JVJebAb4Gcm=t6___IcIQjU+1bD;*_(1=CfuF5;+SrO| zK@|Vn)^ke|Y!8FEi*a-N`1o-7@N>C&+Hv!Wii&dc@Nx6;aXuqBz5HBZmcE>>UiAM~ zfIz*hJssR(4sNcXe-tgP+`M6u;Ac<&s|zmf|0C<__1|H74j8wur8_q-7tcRk`ZrKR zUxr5~8{}nY5i@t-ajhl}b>%TY}8e%H0UNB2nYp4oD68x;f<=|i=CMPQ^ zEGMWaC@dtR$jhrBBq{`v7nK(j5)l*@6%iGY`!^TjX6@|)b%p(#YxBQcq5sJJCmmee zpDjb6o(^xJHj18ZE}(yPTg>4<`@;Vp_5Pb{^PhbY_>WxfXJ@$o8QlMCu>bw)IfMSG z{!i*YH~uI2p{~yv@A;hCVmS8k004WG3Pe`N_vb;LpO=n)_SP%MRbd7?R5FgsAPmZg zz9FH~`qA3jY_6+Wh=!85?PJyr@dHVRxRoPVjLFJ&Nl;REj_dd?9Ep<0BF-=lFLMx+ z0f>3nd3$5ptyDadRgn|xyt%HJJEFsOw&FE$c61yt0gp>a=m=Pt?Eznfc42IG@6#k* z)dt9{boQgPTMs8xOkIJS4IR(sw#w%!b<5L?*>y&BN3C-mQ5?TGN;;Cx;+IpuanjC7 znY~{LIF9d`%qc`QsJtxrDUWWG7p7mR=M37e`a_lp5Ves(-XU!EbDWu5(Q?Y#qY@i=yI;L*mUN_Lx}hob&4RB7Zmf(tmK|Jh(~M~Gzs5c|4sOOL@;RyH%bC6Vy!c+R zx!G|PuYks>8(kp(iHdUSobC3i^rr{PQ^C)L%OAbw;3T{uyq!*RTTwIJJBUmE&zkb% zt!!BoVXkq{9xuFdg&|YB_?d|+&ewNQKW+D|U5Sx2`IGYXe!2Nyx)Xx$zakmBiDAWh z6={I1JO@m|bT5AdZzSD0%h{1DapW-+7G6}CzPVGZ`SG#+YiMk@>eykHHKEnVb^+kJ z9g}Hrip)z&7Bbczoq%2lw7NXcoO3+@5He5D4Pv98#_A*3ze}SRW0HXQG-q#^e0hrJ=MkOx}W+ zn7FOKzke-l$PR!JDlaeZYGKiPae0Y;TojfI$x}PuZTYD`Uy7R)s!Vn6*KC@lXfCnM zdlGya8xv!qtD9C;Tlovu=6W2Dk@k|P!Lk4q@<+m{=ot4 z@bFM}e`g1?cgyEqN?2IfH@{EUHF%Hjb984Ja#H*J@9nWCHq|S|kFnvJTYu0jkSrV= zDsqHevU4N@S~`yrcS~{P{7dJ%Go~6E@m1B;xNSURXrZmH%bqSSF0~~kgQkc;QTy@n z@xJYQS{aAX7YoRa*-OT@T(iF`kQt~~T)7nAFq!Q1MY01NSGxRM`@+#&kCxhNTUvww zO1}wFLTz(Z`WRHZq9mdA%gf8P&CPQ`cZaRAsnJv)l&R7` zQWBQS-)hz(%)vlE>S=y-*pn=h5S!*iTEaL{!{+WvJHOoot_aaOlJfxnfP4hYM85Q~ z)Wf;9&%t5?;I#-b@<|YWU&(+=UDh-|VJ`t7O%UdvN?Lgb~0c3X?rw-yKZ5%`|k2koC&CjJ)()E z%UWBlpTnh@S93fuE-diN>-0TY2iQdKZGKHfDreTrCEK0=%IIa^MI|`r zVav$*nRhg-ogKi>L3#`zK1=nbZ)xnyKbxJFD|M@edVJ2dG<2nrv$UHmSIMkq(G?oe zNw&Qinh^6?UhnAWz`m%^0ZWCKm(?vDCo9olL7rB+1D2I&gNUQe1~?XksJHL6nJo%^I$rZck8sl*Osk*XIs6QeVD(ktWeElPSz1z?HEc> zjiWg?q+{caemxC?rTcs-W*PH}_JQ0k5+-7r6s(5~th z<=hs%$z?WIv#@gWR@b~=Z64MI!-MTe1zo}SC&Nd*VJKk}m#(V0Z7yMGbAB%k^VE(s z^WG$q%V!*;gPb@@JC?(TS33&~WFobTdys+8A2kITg~>vlxsQ49P08KC=gBGgR@8M? zc;6S~BW-dzTBj5Q)(=uXMsI&T1i6+Ua>d)i>zbq0Pj=JMy;R@b623)?G0Oeq81*h` z^KNJpd~tHjX@C17gRk_J)D6SbM%)Y$lY|TfWG|9JoexO#o0-=U4AUR7 zS@uP(*3!$|UwrgY_djkDIWUFa=9vec407A>)Ffxt`L4s6!R&g~m~p&j(`W8`zubDL zcg7j4(t{6#JhH8WC9pbW(`I2kdALW7VN7#%7pbz#erJ zfUxcpr^a)?6IpJAs`2ntYf&BOoB2T@xxR)U9#dd5 z$AXsmSOe;#3~W{qCxPB;m@r@4l>=a|Z9*08KJWIS4Z!(4HRuE7K9ua!1RON7$JPdVi&r^wx=U%#Xhsfs134S5ovi6i))yxE9Z+9~hK5;1L-}!Z`W+`^(Xv4D+FS zQP!YqyP)G2j%DgPc3=EIzQjLHe3mOL^5n7Ab05W@Zj;q1WzT&pbB6P5NVxb z9RT&i#s&BG3dp5Y7Rn;qoj!d%d_TU8l@@MQkBeROPC-`6Of_0#sCTC?0%OvF@KGW4 zr0yl&w-#yRJiwX*SAd{QQ3|+C;mLPnD85yobj4@IkGbBc-TlqqWZu88xuxlQ0w3v`@{=U0{P$mjeGZc2cmdiqtWL z5$L2kz79bieXDFO!jbf7XeIPK;Ra1AzuLO%Vl7OM6eOqUj~g1dbnEHU`S}}ewMgW_ zka|*1F8pZ_e;oxslA=MU`?DKCl4jP?ag5wk!Ew-TV^49-n2{!7a?V^Ahyc9Xo5%n+ z17^Nwu)TXjTTT#;h6+qlM_p;K4@vw=6c)D zL@VFMUETzk&hNcve)X|SRVL3yV2!}W91-Zp!)$QM>JIH5wBIg6u^Gs{pXwlBi}+Hn z{u=^et3?N=g*M7`{a9GILZDxy8!2Mx#i5(0hry5YT>!eT05%skNDg5UYFd;0t#l2vm$j*>72@3K^fdFOG!)lL(Jw#tN`9z) zdMVkLc_Feo;F?vOVdl>|BK9F8gETtRQ6LKn-xej@Q4XbtkXo%)~`T&fPx zq$GB2FE&`e`c_swShtBNr&d*VT}4ojWqEjH7DsZg>}jBlkSn6iEThi-4z72{`px=X z+Z~7am0_e&VqBhe=8h|e{71x$?PP!6kL~~;Krwe$VfwqKxgVeHs%&1TrNmnl20ju^ z0l(}i!Ho#Qu$hF71e2)JrODL!mau#~mQFTA zWKz`^G6Pa{6%CiO721A4Qb@w=x*@}qywQ==u0#@B(r1l~$ZQ>oV0ti#OqNX{r9oBU z-wi?^ZU?ZNjGt6{E_}c5xF{ZtX}GPx#C4KtcY^JlfPkc~3M*q;iGYl%UFMyVcTmuS z&&&DV_{Tfe4$Re53Pt7d6nt82Pl;yO|ht0gS3R7k7l+={xNu zjce=|Myo3;D_;U-mH;ZV7@#bENHup5oL&Lnuf{``sj?VQq$hWyY*Wc=Gt|1BoEpw_8rQc(!73+1GeZ>QzQ3_vZ6g z&B7)-vB&gQ@sIW?ycBPDo~kWv;CK1Xjar76LyFqT<@#||=wZCtF6keoV?EVX%G$x@ zOyk42yQhJ;eEHwO^pU^iukoq#0m`=*(o2h~I|x{)go^#Fji)T1t4%-9g-pz>EUAUA zBIY+ee#JbhYto_-m+5rrTWypMMvGq;hMl;djCY8Z%XI4&1eLYa7iyXr37Lm@bxIqC zBA1puE7$AAc#Sftj$r{ug&~d3UaG^Y7ug)&_($a|>I{F5Fg9#rWxbIztO}UfW3+rN zD@b9T7Ts>ttBX_2);%A+?|5N|--6t(QteCe7Io+)o@o|@HZ`$pQ*IWU895~$xY%gZ z9<{?psNe}KiRK-Me2R)>VWDA62zjDa zjt6fACh_&nN*O#yU3hvDpJ&UjcSni76Wa89ka*zNBerTSxiEJSC`E{3`fh2dfi7Xu z6ZKW7duVi-D$#X0l1^zrPxZXqP4P`Gz^wXsp?q#XBwpac=^csSq>fV(Cg%WH0Zi~N z;uniG5-3{rYQJbp*_!)9nD&T??EO7DfM{nU`T{55kFjuH0v$ZGc1xGDL8pKo?c2Egd;G(hyFk_}&h-gZ2$nw%uR2G1zge4pL{-u+87IPe6v7@9 z3JL1%X3~>bGR1tX(Aew`o*IM>f{u}unV8WSJnbPt4=`Z~DbZvWE*g}kqK&tJO7pu< zyucq%#><_3jl57|u6+c9FS!ApcZ1^x-Ir^1F*(=*wGut`nDmLEn2zXjg|tnGZ5xo0{Gg5Ss}AV*}?j=9L0Drr;++aWsLRuK1yEEJz4U%~^)!sp4ih zOAIPp9*y&U68PFtMD3Xv}S5n5j>AO!Cx;m)}EXAjSjsK znwb5M%Q@L#DJiKV2-Oy>2f1>Y^-d4Cr^WASvTvCp@ZBGhn)__9D0ogfPd38B~Q- znmB-<8HH)23_g{m2-pjhuuh&#V9&MDl6H^MSX!-dt1EtN0FT+4%)PD|I~yC6&RC$~ zs)O>-G2O($qX@-xHm_5;Vb*dNM#}2qPV$GuwW({&JJt(8xPfv+>@l8#BN!`#UW=LE z_d8lWrpg`&GKowZ{fs4B2%eoJxM|gGrDg`j#2|6wT~ldZ zM%jCWRySi(`roTF$!t+5=rEw9s6M3B3G}FYP#P z?bC06a7CmjR|8q9-IH&1xyl?`W5Xuz8n`UA8lZHT@}|GBoV z7<)4`s0<`a#sH39+$<3GMkav8Vo=89|dM*dv09B+2r8-MQ8p4$Z` zWpyKdLyY>4fNID4*G3RWhXxnRwN95 zrZi9@x`GI`XDSciY{ka=$@gUwdKRGc1=-LMq30msT1>BA>SG(^ZbU@Q5%XpkgIW0o zHH)iFzwUVNYIL?G7N^AtoDt0uliB-1`kn_^F)4ND49r7PhP+Ju=ybA`%zn2#@%m)+$&$f2ggln6o)6$7C(p}9~$YlA@VfoSaI#yRL zw{P`Kyo{_RORoH*@0J2Pb-dEL!Qai6d&rXaTT@SD-YMt&A!llP_x=k2Ze}w#b*6We z%t9&kvGa_&f#EPoiWXMkwk&9`cj~d+X>^FSd{+lARz@YEe}~99g~y@n`u`C;zZmF9 zfcG7Avs&+T#p1#`!oTxoFp5b>AN2zXNLOYzLkdssr62Y;aIO0naZ#i^EL!9%Jxt95 zO(|Mzw^szCY9UlVtdM@m64f|y{W6%j(59L%rx$)$ zyrVo;5yTl3Cu2}DG5;RZ2ve|p0VctFqJ%#&x?fSJurG20-54-Ol$TX+;OtBGXMMb< zv1QCk)g*s9pI3Wp!dyMG-m6EjoQe~T2k4XM4`8{T7qxM z>>8p!E$%Dy&}m~=e5Mp|2t6nQ;1di2msDYWMyCZ%>_uV3v zBmJ&ExW^=)(ObIfSQUsY?_|(x(Y`enIMV)$bV+&P5AT(=0Mo3PBj{xeCB=MauHg%{ zUvX*v=NIe6KHsoujHTd=Dvv4KLv6Hk$lf`(Z8|{@j7RTRn7yS7=g58yzW&tvK#nr+ zeva^^<9gZuxDxMj^eY292~80V1>Q)T`A4b?HK~Q$1TH43@x&d|8U&ZB(=x6_;y6P> z65U`gdzDWk3gP~BHex+V_E!jgxHd|k?c5Ar7BPdAiCs%#@9CG%>PR~aE0#+_q- zYVWyS+nm#5)q#axXlb72?;;TNg}cI3n$8({5G#3@jgv3eBfEzM&a~i&#*dmwnrE4c zRoQ6Gf|W~g9c&IArS`F*9IHd+&0wA^+yu=VK!-cW z!V`tUr`Hzsk}*Hgy@ed6sA~VpdiC&X=}ZNx<6;~1aKAW0y6Oq)lmyPmPIWnc95p?4 z5*7<^>Mv+#FDGMH+o$|RNBCy@YJ~3LeBRiN5igtQL+Fk{lhcw>L2zShuX^|DZp2o0 zqU7Gb-)AS!3n;(0_kTC)$~dUO}oJg9r~%E9O1qI502r*W40T&Nam_Mq1D_CDW5(V0()6A{6+>ox08ur2!5tq|<8OfI~H=6oTqZB0>yOPeU& zGNo65A*eWQS{GiQZ*M|haS$;~`|N=*X}=fu1e+&We zW{aAe8C@$d=tKsxF{a*=)hO$?7i(&v~)kF%eq=#;wf^WdZq|3*($((B#l zk+RleRAu$7w6W6IzIexqNI|F?1^&4T)b4bAig2VQz~Iy$J*g_`)}=1HX7g8j6&x_z zh*h_{Vz&`BHs-^rMLQf@w>YW^G2jL#7zZ-Wy(!Wgm3aNJVwIS#CP{Va1+rqy^>Q{5 zz;9XOb>{Q-$0&#W$EMkA{N7|1XEDXHOpbGmSrx{-UNBj(keO&P(^ia;(Vryrc^XQV zuuId9W5|WQy_}kqVfHzD&aWTL3Qz_f(ebl-FDDlWtyqS8n!m|kzM*-F*e7qu9>q|L=g!;9pu z^Tv9_0+1vt?RUyhRsWc*Gsi%}k}u4BLl19YJ|F9ulO$CjW%05!q!(n7pDqq5kU~@n znHA)&^GiI91FllrT)`JscZK?j!Ba1x^O((eSw*GP59lQs`Ek zz||VVw9Haozb@C+{Pn7x%y^?tCi$O1&-DQ{{=xT5?R#9Q^B5L}$>Z+F7IW zksj9B?<*~t5NmxNJBT--d$D;@hxoT0(R8+?j4wuNk8NloDV~@;(v*2a$0>s?TG$Wd zaDJiSHUhp<5xNtI-5kMTOLW=U^A-_lBCYfa7Y}77hyhho7``5X@uJW;V4%c&)W0ig zpNHmV>i9u#VLIyp#+^gzXwe$mroa2G=pzYuXbMHSN8<|hEbOX&Cf-FP^RG@mL?#%D z7>(SPzd^E|0;x8bO(&9(5WiMgnvnKbA8_@)t;gV-VfSaHAUf^G;l74?ANWO7eP@-S z$Yja41b_-f_VjzCIvYZs9#33!0$IkntIjATp`OW@uccd~NA*XpzgoW`pqhNBkhoI& zE>9>Z`}>FO=VIa??T+Y>*c^*^8(2Ah1V#vOhH^OL&-Ql|Mr2<>a@1Jz7AP`^6wr0~ z(`f_8)DYVa#}tDR@e8^GyR(nSpl)!b{9aUa2Lix!;_Ru+clJ>59PE-XFpg&=Kc<^G zThWx?{Ry8kY#DaK7PnNeVoQ>H{!v8`H93x#^;ZI&36PKJ_(j(Cf$o-YRV!F0{;^g5 zcCAb7sl~-N=Vi1>G!rhn8(a=TCiLM?)iN=_6iyC3XIe$!=!xW_DYI)s?KXJ$$s+fw z#s6Z@h=FKQo>opm`9(NV!(={4=V#s+-d7buj_nUxxks-lg#iqjM-|#-L&B~vJaxXy zBR9VmbI2(_$C`g_!)Anp-yNMPM|Ha$s|+AK$-^8mOT|P%s55pz-DT7SN+1G5oZo+U z+As@fsT|L^jp0Qe-BDepGg0THk{5`o1dqK)Y)hj2>$jiQ#y-#f5-f(D+~4Q~|3v|B zRT3P@bMDP}V;GS)7D4l_vgm$L_6(ylr8v^HU7+O#H=w}`g8DGq2vjt~V*dV* zs#x@hHMgD!5kai>#LIl+7U!=S1d-Ec`s)Q3S*}qjYaLmrBV59M?~O=h3c$0g%FJ9= zbzYd6u|TFsjknB$-NxPQz9Sm$X3CnFEv3NA&pL60VzK65SG=MPxF8$>Gb&^0`uh6P zOebfw=iP%`cf*Ho4JlQ6lMOMnP_x*9thzVx)wA*I19IU6(K>+!gmX#>R9NR?kUV5z zGvSNNafp@&7<4y|g;&EK^kKlQ7Kc&ME#PJ|^;P4ZV=ZiH2KjV>Pyy#N?p8sk7j6(Z zfocpK?MH#4wdEJqMp^L%Jv>+&*90$6uTX^b2zQqQ^RF3M1V3)#)h|40PdZ_>s|2oj z@(m#9^8_Xid9s{||0Gl~q9&{7rRZL=`w@~evpq0madH!l=(;=VL{ezX;VaCLV=^A@ zQ8zKBJL}S#eFz9jk00L^FRY#k7XjEs7U?3nYMVc4>g{guZ4L>ST}@L)lY$zwf{^sE zNhxLSe<1U5<;dJJY^$XUslrSK)_rq#*?-@E6n<>O{02UMqPmIjVh9hOo1dQ_`NT;9 zD;-vVL3aDY$r8rScX}AVKS>iINzKg8HYvW-NS5XT7hLZzpcMWAk*-%bpssa}yWRK7 z6&s@QiJ`0gI!1(qs%3Pi4;Mml!KDjlQY?plz;j^-rp!tRTQgi z2xP+&boQb*u3NM0HCUHQ^~!_Crq6s-v+v~|(qhcNB&%+)cFMd|4GR3*hq0l=rr|zv z8LAdo{Jp2G;dJ<;&TV$h&bN9r{QJ_@94k}o9@~iG$``9AE3}@9k~qdb*kcmpnDP0+ zx4V-9qF#e&#-f{JZ_i!?j2PO*sCq-{U{U2>PX1;yNfAo5g*Q1>0g7A~B59itn`gHQ;4d zzRDFjN$NFWT!3oW*=?uP599x|X^;q<60sf$-)&`D>%}JL#d9v|Z-_v)uDS240XH5~ zi;pOv#(F?##YOsLIiuh1MLcG7#wJpqgX8f{`B7L1Ct+7ns);~|Q9i8`}DKJXClws2l2JSsV z;x)e^5r=Vz0Cypl3~%(-WPU#L6gyOAisB-;qCCW|vB=L*29lcr%wqCW4%ztLt4hXE zO z&Vs(GiX^J^ouZh87zm}IKNdKOTtA;ODOsNw)UP!$%-yMX-fe!l?9~GEXg3`5I}j-u zJ|cF{(H7+hkO%-ZsPtI97)6(Oaf&)GHGG2DVEP^S$3kiY3UdEB(*^jOKl@RW_kkZ# zN~5X%Hn7{=MEu9_LV#q(!L@&nxL5Qw>!+3;A8QP#-C-u~QtsFF5lbTa;Boiz(QV%M z5qM8xLkp0kN7=YHV&S}-iC>~(RamUaPTCLsvbpg;p`{*^{{9)cU4NT}gMV6*7`zLx z{9=HD)~hT|;8=9hTGuEqSWM>0-U3i98Fe?mqE&5rYit1Lglv`ES~JZYBS%fb4HH*v ze&c{{(fC8LFcJ5w`O~?!mtX+K`iULfVg&fNlnppcQ+OIM!}MdE_s5?X1a;YLGHtcADxbzug6$v21KUA|mq_S@HuWE^#8X zSWML!DpFp)T6U57ZprucK;?^SmMPc3_XtROP2J#$aS@$dJFuNhikP2{!lnJr_e}8v zX-IG?W1TrcyFqs7pZ4T{oG5Wb{m@+`>$@L>1lJ3On2S#qGGbn?(!8r!*h`kYi%r^! zX76w9vDO;XQ6^5xsC;Wr!u)!~-(wI?pexJ7tc3R2IRv6KsVBgdflx6=)D_9J&~u9; z{va9D2o#~M&Vvl^0rVD>jUg|cCYJO0_U#E@RDLY|{C27*+q1P&iXaaO;=UbM0GgQ(b<&2VTJyqq%0{skK4sqT zBPzOcIJv6Sp8523c#aF?`BsT9{SCO?dKJzc9!p@AhrH zycZ$+Lyv!Nka}Z{yz6bph9Dsd`UzPL=eYRvqxcIPbyD7BrR5mdJ=r?RO}TCM)~7FR zyL9EE9p2zbdV0T&b$%%&+;?fAC{cF2rIJ-C1CII1RL|I z^x-w>-Kg2*c-0zwv2L$F;#On2F!9pdS?_% z@qBny02rijAByzDx<}jsb$TlpS>GmQo@J%;2+8lb17p+t@5M1PE`XIXpM(IJ1oY2A Obrl6oNUfYj`2PV?H*>TA literal 0 HcmV?d00001 diff --git a/client/src/assets/apple-touch-icon-57x57.png b/client/src/assets/apple-touch-icon-57x57.png new file mode 100644 index 0000000000000000000000000000000000000000..80a078f2d2c7561e783959bc0d01aedad1676878 GIT binary patch literal 4942 zcmaJ_c{r5&-yX!+l6^gxA!BD|?8Y{Bnz1hlWtfq51~b+ok|jHXtQieLk&r?}$ey84 zQc8~Hkg`>T-s$|#IluRh_q@+_J*4lNJ~crrlF;!uB8NmLtz@KP&HLGs4`qlR~@RW4hQ{p zNzuK9VSRNSOwIrDMPKPl`H@H=x~i&?k&!BqYAS@Vi>fdk9UWCDTon#irduczqwyq6 zlro+u{WpUtj_4ESA42jc;6c9_G2Vo5lD-sO>3>294*7=`Py8!Q^n|HKVM0`4D$rjc z{cVUw|No}J!T(qjNe;OG>is{7iB8cWI8_H6kq{o{Lob}K^e(YjW6A_;@{!C9H=OVL?W{Qa@INE4*F ziKeNJmZr8j3}&XOt*HSu*4ETChe6d$&D1ph#+nj*!h>;m(%)F@f3e7a#r|rC;1IfJ zQ(TyT1P*H+MhFJ|8MdzfziZL@SH8cn*niie{jXS6x){}8#rBWo$_M~B)oo>pbc&i=atD%}oJEginHj;{yvB^+m)9Uumw;>N4$Dw~ zmETHMZ-E$rH>8?aS*-;;>zh(RUD92a9G32^yvDYyl_!ixH@UcpgK?f zm-?bNkE3^5P~A(pT82&<&nGhfJ*uyE3)? zXEbJogw^}vC}ET?3J*n$0;d@G7p(wkNZL1wH6;Rqj%1GI5Cx_k>lg3Na31yTely#v zX$+{T5L=eRw-gJ=iXf-eb+R}q=P8;L3}x*JkSv3Ae9$j$Q3TPrsTVDENf7>m$VJiIip)V!iV`XLK6a~p7?{c>&U&Zs>_VW08*dkfh)*6egy47{* zo3)2W8E?jo8!sBBFFT_&o4j+n%^GM*J4?gTT`_xk9pUTNZ9%VJ{t(l`4;3oAFCFgh z{IS3Jwo}~=(Hg+P$(hf{%r1xImv=Codk`oqq~eiNpy)bM?|f(JU~fGS=3}lnelyD1 zK!hm~F`P2_DD)%e-ukT2q4``}u%crPD)&L)tOA2W%PvMg zEdideSyO0L3YO7IO^GG|hh|gru~0od4}*hMX?fSiGWawzhv3lm@1xl!fummdGn5BZ zbp)Qf;=|7JID)t|lso$Q$apx~wIoiu?xi}Fg%FW#b z5KGf46&C4T5WHRZp%a{16^$Gewij`OMJygYS9EPeJu7=#*~>ul(+w!>KKhU%IkNR} zFbUGwP%H1(>6<5d#J-C@$8$;~kTZb!K&ZT&>?r-xi(V(}_R?@#FWq*u3DZ~DSD}!6 z?HUScof^q2PAr|_Y#O0L7cS6691l-YE$*BYhQ5cY-(wU(KaAR1w5Fm=AT7$Z$l)Nn zPpwc93T9d%)A*nW-5T_|8GiYD$X*}VB$-tcE?64KaPnrjW83dA{S;j$PJRgEY+MoH z({(=CI9rTEBGn?hFg2C6AOe+9GPrWCrOrDnU;5zvQ&tIHK|#pJXPJ)s_*GhEv-dz6 z&np^8t9@KJx*Qrbtiw4;PZFs z18}ug$a|xNXV_;MBF&_=Db*I=ab2a8xq7#g);h5H$7w@zZ0ij;Ztwc&Z*L=IU@&{I zd^&8X-YW##%p})B6%_Fk)d)E4T?%cXtxQk6T?jy=gS?k_9ooCYgkYChp>J;>~ z21-Ui!O70@y5Fd=cDo16t#3=_0Wx)_31cFoVLIh!xvftv3DF!vW&Nge`pWSk{L1lV zx{5P4r>_toB$k|~NgO|B8a)w%x6IP7y}V_{QEh)QkrC9hGDlnp2v$jCs?ouqb25RIfg zVeL*rPbHp7c^p2Ny?O3S4Z5_-rQsYHU8-5$18AZ%D%OfNGF6*`tt46c2D!JhKd5nu zb(ZJn_qRXk*VDfo8$0d$-1JD{ri3ON=a4mDL)y2%Vmx^4zOKbVUyN~%)T^&@2@CnA zc+NZaRP&JEM+y>!Ul-fB+&drqdA_|R^QkOF3)cRwenwrb{nSh2Gkq25a9N%kQy%et z_+LFq3~Gy;u6GVJQq!>uU(ya;G-dPZFU;tO56^zzC-fx}fhj?K4+ovt+TAXU-$3TM zxyruO3A8+$Af#!)qGHeTYL;*AUOY%BWBk(OXJHPn<*O8F8YpyY3e*fIfFy%|&D%x#9sEt~Y!I zbq(M>>%b*xfSQkDLA~k85ch2dh#qlq&L)!#d%VLLs=Cgef!8-5E-rtPc$e0@v_+N^Wc;Z}Z_>bSY<@uc2lxxGwjT-U(`6w{ z2suGkrTk;`A?oKWig#jjDsI0(fb3>89^S1^DTqN@rdURZLyCAuC=FPp$7~MsC*)^) zk`Ij11=t0Zgw0L!Q-@YcPj06nsEc=Nr6 zdur^xd}UAQNiZ5C|v*-u4x>pD_|Mw+5(L zx$xxlvQ5piEO=W4vtQEO%^u7-kgn+#lO4EO3(G$G89IMcSn=zf6q&$6l>8d|Rn*hV zl0J=%sWr0N**-DB8S< z=4Y-D|8(WR#fXhGH{wA^C|pLXUlPORo z^WtSvFSNlI-FC>g4T@`H;T%_Orzg+Kbk4U+NOy}&u}MJ?91>rKS(lbrzhej-yE@xkF>axOI+@n|D`M)lq0H=kjow4pBib zT~FTewvE7`o?G|jeY>h;-4k515)dmRQ?dINtyZB$-)~1d?DNMD@SYCWi*W&Pa&nzI zWjjp18`pyZE)8>WFOG;KB21+seVyJuC=#A_Uo^;Q%aTsaLcw!Y)DBF_+|M5<0jDBz!&x{qb6jvbwL1ouNE_T1jou<%Sm3?B+ljq;kZoA?ZAJy4%&wQ zF+@M~++%!~N$hW|VIfZzQ*HASZhntLY`+2(?X2@KZ|jF2yFaujB5S>@lx<#{ZSMSH$+f1;XIMM6NJ8bV#@ z^^hzxh>hWeoCh{|zP|)t5@r~d+p5n>=BV7W->9BSX$yYyjOz!PjSoWV>qKW1y71%? z9pXKh*2|y8jC$2CERWup;9B4}Lg5-A^9mhko&EyI!-V9L3-I`!56z5i1bSX-baS)~xC0k1W$+Li zX&s=ZCIV0C9^8UGUp;^S41{XLA%3Ob!<>yCuS>aXb6rwQ^C|Vi3H8>~s--tos|t}t z+j@6rb1Yc&mVG9J{1&`3CV`Il($R|5KJme<;xu2q_ZatUneTkZOHP_)iS<$5D{vRL zUd-@|NG$9L&~2U_c_7kX)afSfR`iXBcK9-a_7S6N};7JGL|XnoQ(eE6zQkzcc5)pP>hpr>{7%cbyoGrz(4 z0E1~b?0b4&-Av&^80(p2LkgSE$8Hv?<=E7NKv!HhxtrOx>}u zVM}kj%Im!EJ3DjDkisYBwK!F#mJh7&m5WaTO|l}_GXkOVk?W8A51bS>XR3Xhly{y+ zuAg60Se1^w<&Kn;FQaLx)~|C#D91K#d*r}}F!L{1*Yz9ZEyfVe9GgkPmwC`7gJ8Rh zjdF$>~I_-rEiMswTfQp?A#t6TW50zycVN%KWVLQB&^MA1*618`DN( HudDw9yA;n9 literal 0 HcmV?d00001 diff --git a/client/src/assets/apple-touch-icon-72x72.png b/client/src/assets/apple-touch-icon-72x72.png new file mode 100644 index 0000000000000000000000000000000000000000..a39cabe82def51c51a0ce197c1f88a8dd42d6fcd GIT binary patch literal 6399 zcmaJ`XH-+$whp~Fkt#?8rT5+;5Fm8vO{672Xn`bjr1xF~>C!|9hzf)%H6Vy69i<3L zFH!^q5zrUUz31NdCjNJQvv`08eIt36kkLBJmjSK z(qgYk2Vb$FwXD%*2v>BV6A}ghK@rX{psu%*8_X2u1P%6k15*Y7h^KVh^LDJlv_;|s2rq-SKtjpI{|~dy?juLK`PvT=~cwH{|t+91OF01d#Z5%%P4EZ zyFg6@5(bnJl@)Ojmz4v`DTqqQ$jM2|2?Hg?C1k|JrNpGfMI@yZrNtGcC4v9Gxbd?g zp{|OiVC{d;h3~0wyQ9&*ieh4cfq|ldQlbc?o0x=xf`XX1q?n|n2wp-273_m{3KH=_ z@%*g;3`4mf;l5}%!UyDfGtq8XTL?BAwFN~p~qOK1L?d0PE(*>(=i} zSrAxGR$f~|LQ7U2EGG?;){qsKlavtGkk$Mf3r4v3d&7Lte`BHl#cKT{_75GreepAc zVMurY462Ppcmw}(TM_=xwrKpLzJFt(|7?rqKVrr3#)$n{-2b)Me-Ggq^r!hB>f$^9 zAwSFq&v+!B+9QOvPXGWWgf19l9yI^;9tGN5tD|B6wmS1Q2=F$623RAKm^-l|vXSg& z9V9k5k&wGl9(fm>K{;072j+-#^2HH=&3(y7fpuPuF=fJp6u{8_>^Nc#a!-ilvQ=#n z3N_Vw5kR&&sx+(cdwWmR!r|)e*>8(h@4>;rl~&iKuRWl{8|q9ROF!xCJJ7ZD7qijL zaRZ>8nlXY*!Ax!l!EK^OKqI56^;~b**{8sD0!*xHjI;?+hSg(lqjWBcVA`Ye=LD0_ zot(on1A!tlUEa(;&q!}i_93D&`G-|9Gk-HjzM6Jq7nqW0`I)Keb3X@g5)IysbSEt! z(T(DW5{|vCp%G!iW!^VSe^hlX-~F21?!15!$H|@^CiM)6X{Ob-J-dSzJ-U zZDMWBzrWbd6L%m4aU4>&1cm%6^^xU?H`Rlb@2yR%FT3=G`z z^48P!HfF@c#N-hX5fp?VA%1>(tLOKb+S}V#MskI?rKHS?)gtag-Q4thgOnXaNXxB& zyFe=;Dxh|*Sbe0XV}pGsFZKy2hLl@Y)>0Zi2_6_27(OE&)Kfxjq{@f=c=6+W^YP$B zrH+=KUh?qUw>jzz<}A--Z<97YZ3OI4)^1K8wDX+&2<_=awP*6{AtW-tI$SD0|JIby0aIv>n-Kn*x zV+xg-lM8oNZJ;d^7>_LtJJOxNdRk4i`6c~+KQ_kF8F-LasQyeoaDP#YTK@aWV9F2x z;sW@{Uj2~5dybKveTRh6%lfHN$=2{N#10ovqm{xeQnm4YdrIeIXGY&^vCX937OUs= zsl$SBXLr|gV^Pe?H6KA_<2=pnL1UPNS$<|GC*k{9{aY{5onJT96Y-Hwy1F=tcJ;D_I%$!DObD-RC{bHa0dD+G*_CnLZjD8m~3?&9y~eLmM#+9MqK{I2OJ2R!OE$$QC3OF*lo0lx3I}V3Rof1D7VcL<2apabEAr_q~gez3)NP+QW z%~#CtpXKG{&2HeqoPl3IN(AA(PrEqX6S^6)bt_oSW4l-ZH9)6!3H12T@Qf@;c`q2E zxTY!dQY$%X*`JXrVf1dgaSg#62oCh>u%D{Jp(p$(^e0(#3@sv-ceMU~*H2!KBDa;M zONlZF(~9Sclv%bttUv2hIOAuZ^4?aF^V0HKh}ZR`guC1lBLIFECpkg+P&_ub{@mY*3x9iuTP)6N_*2R&zV%b zg{#_^&R!5niv{SR@(+4`t6~#K8kRwxvu%ALF*HU!>FeTO_evtWD>kk*I-~Ve7Y`r=J9)LHfx~NUo?bqf(X7mdM|X_}7&Q zmq7RE0hDsJYQjeD1tqNn7iq@<)tw(#FqXVP^GTfLsX#TP1TE?;N?nDv0~ zV?JVp5UDcIabN9Ppi0O|CUtSxn>f-lOA@uGfH`wPhHc^2ou#hMHLftaCP7k$OGd?( zevg$A;gVbSEO&SWF`y@R48@*@<)3#t>Zd*zsZ$!fH(_wIyrh;W!R0xjRR_M-$=VDT*7JM|5R6&W{2-y(twanZ6PV6F*@2Nh}HEDT}elL)H0GxxB&^)()wN?;iB!$+cHhh+hM?#ITMI0o5eg_ zjkkCgMLIuj6%l*B<4g9TFC(4jTPl~hV`O4R#v?d6HaDlra~ty_Z=bSE(^bYrQHgNC z>b%#x)0>Oz7D4jehM6*t>?$r7X{E zvDYRhCRWDFHMJvu0c^mIP^#IeaoE*!k2a#F@ zIwDuM)F%>_i6W_)vSVy0quOO~p27xV%;6ZD7*ZN9X&wO2g?@LuZs*H@z4?mfX6Xp# zPu6pn--fuJw6imFC0a)bManPWW_Ia$)blO2!ND%0qxE=_t~*+mMml(C4ZY(?tOlfE z;0tY6R?iG<-yU?&^#$Tsj$o*{WdQg|FX9l(H?x>c=&qx%dk?f&I6h~6%zF# z!f|)){?Pq)9ZPoj=}B5!%e022;3HA{!t*I(HE&hFl>t|Sk;v7djKKAm(hl0DOAc0X zUe0+I@_LrfG0|ack>k2-r3(C`+Nxe*Y~9P_>Gy|-diM``=qh#Xxa53_iFZHu z#bg^)G)c$l#M5#LYRXmuci*5dS7z^+Jf!sOK;HBlaQLWEl*0bS8=Te)@H_o#)4oE` zltM)Ar<|}&lw*pN;H@+W#pgs`si4K(dwO~!w2LmH>JDRD398M|2_r=t1L-OHQxF+F z%CKQ}zm+gE!*)_&HAXu3w)$u0+8_JbKYvm7UhwpW(7pGSmfTu86e@8)s3I2EEMSDo zxWDIiYiBKfSi%$xUwJ>z0yY^zLVE=#XDF{P*)K7)Z1Aj0*c22@o~c}&Ohp4w;z`)qz@Ghlt-gmH89IGUd}Hd zwn;Qih^Zo_PjL}{DSS`aEX8^!e^=fWzx|=TSbKMRkn1DFkuWz%#9EdPl(V2@<1;(h z6ou6K@{^&$eVNpW%5sM74dfWyceEMTipW2NU$zbRgq!{7Gk&=bzT5p{g{mO)NQHMp z9fNQWJhOEPLDSX!R=GIoo|&&xRf3-0a}KcUuUQOw+$0rTSpQOX=9`GF4Wq0KBs zraNPdr!@_P47x!Ap4KlM2|UN;GUvYzLA^-Gb<+)SnU(gHynezQWJ8tu{;A%QYeK^$ zIsiYb*Iq6=V+G^PJJZ@P*mW9&7UEsTQpG<4<3$D?@kmKLma z->V2DA5X<0d=20j&F zV<^6|`K_eo!>~nNzo;jSj&GjF>gks5XxLp@XgAXKnap0f4P1eGhH-~8vWWO|t6jPx zk;sks)eGFKDmv$Za{RL*98dh{VWHRed8+4a4Hdo_l2YCs4Uc*~Gl*7euJKQ%m(Z7E zHP^b@XXAbMsko+@Rcl1{Wg=C{Q@c~?Bn@7u9jm6tt&U^LdG|yh)ph&moS*;az^7PLv~OjWQ#9Hc9(@wbCWG66N)V6#2~w`Pp3K3S#37Say4m#;i|zqV zPFek(2g)Yb9rDQL`WJ>TV8v=el`QS_Z)>TyLv9XO4aQUi94uW?M}wkE$^1+Rrf&;c z!$rkhVQJs$uZ1&4@P}T?g@|*Y* z-$gN2+~K@=%-N0Xg5!@3D|@ZW;Z!YG1(tOEqf1C%RMRO9RBY6XRr=Vto^0ZSZ$K`5 zU$f&#(jeqfPBw*`3XA%>;A15H=JN#YpR1QU;xAcGJYRo&>9VRoTByovN!Q)I=r>{V z2FJQ9SzPa|7wN8t&QCRh++dF>ckN9T1ucr?y)02dZH!WapQH%)Nlr5S*enfA$5ww& zG$@kxt-pW6)-qLhL?>dZd?x%5F)`neOGHKsaqy@if!7H}_`T>bHHrz~XEts4s`t*( zl}1N^hwQ_ktk0r6K+c|0r(;-^v z&qNIUeiX%V!fas@#Ec3U`_6!H^f17#_p*4;!?TLnV5)=wOfz3~^b(1M2BbUXkx2b4 ze_x^$%2SmdZ;L=#w0(H*rt>&xg#xZOnsHc|FxL&pv=yWoA9km$jeFf4tom*k!<&@> zdK)SM+NkoHYmCdf>yAb6ZD*M=R-Wd25KXu}Tyf zHa*;SnTkV~d_RhWJ<@#PPAk~;(yLYcsu}`yAd$ac&ysZ)DOZ^1ThvSxLh4OQj~gb{ zW|a~FLdc7v{qJ`h8yGZ4xm!SckX(x%F-W zQYNINM+Q}-s#W^@`ef5RQHf5<2Mn633Ut`W(cr_+eFmh0M;4G;Ev^F zl({*9*peDk=IOC(a!s@D3c+Tv<}LUDYy>!zO`viwHS-um3q+wY{78E*{O1N_JSh$P zK*>$vvIugw`DvoaMj;GH+As20xnkCC(Ln3kh`Kmp>D8oULe8lb1f#UzVBK2+)h>1C zy&d5AJbHK8YcZS*D7yCN1XrFdIK2Q@Y5J@;Mi|*84EUJ`VcYq`Iq* zY#4RR&$Q~ozeY`gS2akchJxHYxn>LpBScZX<&i^p!NzNmkl*SFp>5w@4c@_FT&rgo z%d!5BJBY!70RtXy;FOzgOi`^YVoCVT)0FU66bjz9Y3OQfva+8-hf-D1xVOcs;r2K7LZS`=NjBuW|#<1K_JK{r_y%Ctrs>x6Bax5Pdhs)$!g zWkCz~kruyr?d2p`>|?)KyBl&J)lJ$rR8iN{%FnIqX?GhxTwX7Wav6laYRh{Zao~cDQoiBkGhtnh%h6-RP9bQ@VF#N|pExzW90h=0`IfDDYb| z9l;LYVp!P|Zh)WhH_I<8S^V!#!fQ7NgX~krQY2#OuKTEpS!N~J1mT{>#qrVB>T(cA zRRs8!8K4hdGbY$FENN6CF6MC8hgWqZvDt}F+$<@s8zyMX8@pj<;y(qu=2nfptGJi7 zg0vF40W3Gq!@Paw=~7<`rr$F74l|C{5UD&2jP74nskyteAmFN=OdYZ)_|sZG<&&5| zS$Y9SPF1?p0hr=hh8J@Y+?$s3G_1v zygKlse22-J7mVi*{@C-l$OM&pYjs1ApX)=2{ll-qBgf5zHgkY>kNV)_+ChlZ-tU-X zbJ|>2XJl{>Izi}0nRD)K-o)RB5oO5yl&jhO@ciEq%fCc=0XwH{yEpY!*#G>J(A6>m JH)uFU{||OSc3l7f literal 0 HcmV?d00001 diff --git a/client/src/assets/apple-touch-icon.png b/client/src/assets/apple-touch-icon.png new file mode 100644 index 0000000000000000000000000000000000000000..d769d1c0f2a0c5716fd9d4f6e124f57197b8e0f1 GIT binary patch literal 1994 zcmaJ?c~ld39*<9@a$2GlP}w&PDPV1mNg$9c0YfH0gh)t&hE&jy3=l~&aWayCS8b#( zBFI&i)zXT}x?AzFu&`(a)_O%^K|pFnwbkju=piy&4 zTY^P&k%13qXkv0uSemm*rpn1wvDKuAa3IXg!3A_MrUcA7t=`Bnb4hP?Ir!YMO(Ows zAy_7t^ovt+kr?13C=3KsnG_Wr1OXO{3I+wUSl}lBgAOuibo^yez#vXAi^B*3-aRDT z8mdm?NT8^9w(u2~l!0Le4vl6qnW!cv6+zQ!Ae+s0XfPNQ96>Q=>oKL7qBr`@DL}AM zg=!3#2GIi!MP(|o3*(Y-Pk#wPXPB4O8{ee~PZ-UtG|)gQ-4W6pP$c?os7^PJHewR^ zfByceuu+z6fN2ugi0ndDc;V9g9HtB$J_;)_1eGC(b}ozJ3w4mNQu6jXVK*54s z8tx3uQP}@0^xPKSJ&x&o+v1D)#)tKIx1)Gl>j+vtfv_Z82=Qd*dy}6I#7dRk`_6r> z8-HX-$#}EuAUV19Nc9M519r|F>iKv74U4ywmX)Xes!21mvrO&jX%Z(B>mw1QOnO>!*0V(rTYmT!i&oo z--z=DDYkXDm^I9C-i*hX?>R8w&I|qt8#$oZe(=%JFz1q;?LtmP)qb*@G&+DN6N`(w zJ*OroJNx@nHjmH+w;pG8x3#&6;^ImMrt1&=NF9iw-M)Q00eJuYJJ9zHp=&)}2`_A= z`iJtk+!k44BJ3(uyWjCyox>Lh1Tv}dh(e)&mg;o6yYa-K*;h+1&CH;?WuMpQY7Vqr zO9d73e@E5VdyY>|R_5io#6ktl(nAm`c$(8f+Wo{_VY`0)+Q5aT>Ei3do>2RjHQgK8 zkEf>c4&Psttrzx;;b#Z_DD%=M&t@;KdLX{pm`1ep^z>9-)HasE-47Y9BkS)SKLxmQ zGZ17&s`|86RD9LhrK$>Q<7+$`7^A{MZEXql@R}W2LlHzLZcFOM*w||$+WMm=CvJD- z8?SG+PDNG;i)@PaX3SYyWE^6jJv#`=tk8w{FA5s&xr;XvEthJls;f(PWM-E2gsTl& zZT`!bze`Xml|O~VYy82`4T8ZvXAVZ+t?2FVUv)eYCXPrG&itokqAn$}cIoA<#mT|z zo`fGq23~#}$g~#ZJ-j0E@1k5u+w8I7(^`sq}I|y_Z-|Ky~~CRcBWx z>Rf^<9^{j!s1I7|>WZVHqjQ}%u;BeGJE*ehs5kbCgZ~_SvE=3PuF-f!a&q6c^?#Ra zu|{TQt}m}HbaHZnsyip1S!X1gTTIp7y?qkP4?)83hCjQ3ABKcL><^cR=pvD*tGCzd zV=A?=fV{QngZox5KQVG`^CQbdg zq`!f1;gmsH=B~^g3S~Ll1)JYK8x(L$4b{a+21=>y2q`ApTGPVaZ=f44=InY z%t}04p1pF#mwWtvPc1L{!1nM*#P?^v;njaiITE)mAOfU{X9hfupc_=CoPOU8Kj(!?mG+PPnD70Td(ZvO zJ@-53UX-%K-=IN?zbdttQqD@L5dc1^SpdK53vHb*5m9sI%;_%r!e%Tm6L9RVJvnXB zP5Th^PX+RTBH##M>wo`F@3w9F*_OMT^Iw3mh4Az9vqd7l`2m?g1MoTE4g3c;zjcFu z3i@XQ2f-HvSiHTxW&HT@GGfFCad&r@;lqdP=ZO<1ijR+v_6hy9kGLlRCg3N2ydi%u z?AigDH*cOynKDI&3>hNi-@JLV#Kpx)a&oeqJb6+M9y};()~pdvPfr;-bf|cFd1)Kk z0uzDm@~@^XV?2BIY#BUwupTchElnOhdL$1XJditg?nr)qe$%a6x0>(Xy(<+J6;e`C zB8iEKGHKEz9hk5|AGG+ZD-7wAp-{vl-SrgMJ)X!PjOUJDm4j6@vrii(OF=}Ty6sJ5m5@Zkzna z!-fsB)x?+JfA7EWyP-V_{7sy9YHF(HMl9kG`+r17N2eerLop{cfBt+G7#OJVuAn;w zf0c)ahs%Wv7izX`+m?>D1RC$$x%1hWF=N^>rlHAF#(*&V=y)HFdn4mcT}MVnYVHji zHdq`S98^R^#DUV%QdzKIK~Dev{T14^eMUxxp1-TB>)VG89jeXE&6VKb;NK!v3hy_{ z%gc+fHigjdxA5U>aQJudb>{yIz6;|%ZrnJjt*wPnc`1C7$s(jsYp{hYR?)J8|VG(XnG;p)|^jr5zf!QjFDH#YocerNq+ePMp@ z+qbU)x>2YpYU9R@3c0SZ{wgyoE9}|R8kn|AX6e5qui^!sMIOQi8d*qxZTXQu3h~UM zc91uMcEg7NnCUeHH}?=h9x>*^zTx5FMbM0zHEWiF-)i;h)vB_xlKroXG)VOIc2N55XnSvF6{hWlJG7L|$kraP8W)e~*ukm)e?YguYoqbHKm#g{aULS(??3p<3mK z@1Ihet&0~gPK1s}Q-6$qP*6}5=f7&zD!q?%@Xxj3U&C+AJ>vfT`>eTD(D4@3^B<_~ z%alwlDhj?Yk8k_o%L}`2*}A zyw)FY_{DW#>C&a{y?XVUhZ^-!OiWBRYUcMzNlDMLv$N}=U!B|FDJC}o8zcTMcy9%C zAJ*-vsw!&rZvzGl(76oVDAe+ob?@H2d;Xc3nR5R8mvZX#>4@@s`MO4Q)*mz<1l{U= zk!J;PaQ^E6TYma;4bVBr^9Aar96NTb6*fItgW!wK1EcOD4n217-rcl+|9-9Myym%p96$!pnct0V(5^nyU~IjoqxPh*rXc=5;eS8Fs-VZp6DLmaT;lpF ze(3o_F3jP>hxJ~{vB?3v2Xy9V4EC{|Im%kV^9?U>|B3xs2aNfXALABbPoQSr>dcRv z34ZeAi4+zV>T?tF(%`({433;k^QkzW^a{;EYK zRt7)nt!dGsMF+^u{fIT6b+2RY&%xnt@O8oeYsAeS{cmx-c=qC%s;#XJT07r>ef`ha z2d3k!@e7=V5|LvC*q?h~zN5gq^VF$RWlc>@?907VpT%%~>gjpx_!hoGOX3G`#agbBJfus-5kp=$)|62ZOg=+UG442-j&5QZ)9z(~ND*US5B z_}P#DQ}DcGoZ)I&qY-MY4dyfJ6?MXM1NRTsIMy-R08fDrfR~)M&u_p_ySIRFAOPqM z><0Asdvia) I7tP;>6rry-8T`jew*1p-6WqFe=*?33ZWUivA<*V!4%>6$;fV&E^G%dW)t4=|QDzI3#q>BiqI`ypfeR`eg=e96YW zL%}+JNSmokD4%KN{XmvwPb*PmIr;Wf0dpLc&t(dzT(k_qG6S>Hpy zY$jUeZw#*`KaVlA;rqvoZ;Lz8Pt^YmUTQJ;*cN7H+fe99jQJRD!S?|doEelg20t^h zEakAW3g0c1HQ&IRcq#hjWg8R)|7Tsp*!?5SKa4)&zeNj{EMVRoI8&6X)6tPZ8f@EK-Q{=%y9-3s2pYEc~gCFW6XW1VQT zpp>Ds@h_&%qkjOU8>JD&k5a1EKGYQ`4Jbj;AHT&tM(94Gu4S#5r(gMfDy7`WhLn3* z5YHV_4zMN4GPcB!D?j76gZ!P;-;`(2UWWGLY{<}n(ueO4pdLd_zwco-6tnVsTtCVb z!)vJ|e#4X-Q*WSO2=^JFF{8HA^Z7fNdsgcExThE2&%qoc)DQQF023zlx`k)48ua^> zQp@N%VVGbo=+mNXLSOuj`tdK~yI-(U)F$y=EuPIvL8hWh6y z&jDBY8XgE2nFV9*6Zj!qWEP1F!f}g$JHdWh0Y1F~7r+DILMwzTnj`8{1RDW=4G)Bi z%tAD_iMa$ksE<~F3xPALY2Nhg={4w3JpV$qq|p$~pKvc=MB^k_eLyYf8T~I*<9{!VF{`u%z8 ze+1<@wP?Sm&)W3`Ym5!NHT5{^HsyQZoBxYN1&v!j(fJ4U zBR(>F{df3@hEtN2B(F3Yk^BR+tKsGXHE7_BfGc=8%}=An8MWje^^$*p?~Bjr`jn8z zkcl(u3-A?$F$f%EooG5Otqp<&#!_R*M~UH@XeP##tY+MUelOZm?-^pL z_p+K(@1cJ}=pmp3p>uA4jzRqAFOaK?pwmIep>bneZOUHeH-uOtzYRL@ZLk=mj@^&C zU%8aUfsahxiFhpW)5lRXUQ2xTHawGfZUu@P#R9#80na2qOn8nRg>+Cm>ojSQIwA4pLj>|*L+_xi2^+)`M;8n34_Cczf?T1a`2z>06x)`2Uf|gsE@I0 zn27~h0XxJKd;veiKhGcIXZg$gPyEk{TPauKNihU9^6{-k?{CE6S{uX~v@hK6E@s#p7#`qk@$P6ZRj3GmvA!g{CWsJ}I znC}kXE55h=Hh-z#Z7U4QF`U} zzT|rG^ou`y@xd3r{o*%XJoe&OU)=M;8!!Cvg%@9V;f3G5@Y@%jd*P`Uj=%7w7bgFs zsr-Cyes*3~GV5H{`&ln%{aVrhAo>60|4d3Q4G%;rC^loLJZ^^p!eTV%E`yP9MJ;+Y5@3V*5DfR>Q zi1G;A2cO4QwgY_gAp08I%XTSGvIA_V@>g~vyG?nQeMEU*`5Sy9A64E|{!4j_KLbv; zn_bDzuy3=I>{_;&?NR>BdzAOUl`mmeDUY#D>^k;I_C;>tR^>tE`&e}kD<_nP*h9)W z_83nn|B6-kW92lsM1k@{_A%w8@&n~Z?0R++`vm(eJIp@EjQRt9Ib;*s8$szSZvZ<<`}!J8+*Yx(|MW?uS?74m;I5pcYLH=h4YnyU>5! z5E)suY}N5==DLsf&0Xyd1pM=kKRUAN_@i^(fz_+g%ak4|Mts$dQgzH`jM-F;@3ZAy zMsW|^V)fy}bkEUMp}_G+4)|wwe5X8ak{SX9N zixZ50YM)Ywh0GTALr9Wp{4DcER>*)RNDUXhlee}(YS69qhuQJ{lpCGIEuj8koW+ts zfce#c33Ie6a^wcOcmz|ZfRK_8%&vI^0!|+{eKuo^`uFS++(I8Abx<mjZVf|XA~TpXiGGEXX>y~^|1X~oK>bvP`$q&zI2zX}iD zX>_;aN8gqIcp)F*PbqgAKA*KS>oD}k_l>p2b;g6nBgW^9@0)HkJ!q~qKc8KjeJrOn zXFRtx_o=+$ygT#Gg1Nzi!FNKHq3c3F4g16E!cT`^uh>%YZTveIxg~0f zPF7}DHdiTC2dmfB1ZxIrHq~5FyTA6Py6n2Sbw91&Q~&t}f5Ujgt+D)AEcV^lGmUE+ zUu$|LentF-_~+xd$M23m82?doYm2|7wxz9QZp%o^x|Z!N`&+JQIoF!qYH#(o*0#2_ z&TZY2@FXe|&56FmqQt7iPumW)9d4U!JJxnz+sU@a+n?z;(Q&%tOvl-d*E-(mWS#k) zrJe6~DP4tKuC7Q|Q&&&do!x7?C%X4_AL>5bJ=xRKGu*SXXH(Cfo-2Coebs%feFJ?< z`quPK^zG|A)OWaVvhP^GumAb}SNq@YPY&b`lnew19-ec{oIB>+Gv~yd({s+uIXmaI zIq%G6bMxnx&JEAKbzb$n)_DW-mdsl-Z(`oQd9M#18@zAuH-j$?zB%~*eA9gEeBb=) z`K|K@<}aDQX8y$dee(~^e|m@w61%;v-G8^ z%^h`(R*$xh4va1tT{Ai{x^MK*=;6`H(PN|cjh-BReDs;o-;KUL`tF!ARygJwi;Ojm z^^6UVtsL7lwrA{$u^YxdKX&`r-D3}q{b=mzvFFEL9eaC)vckF|xT0xA&x+v{YgX)B zabU%DE1p^L{EC-W=CABoxpL*?%I7ZXy6Bcwrd30$Mpo@!b>pggR$EtBuHLiyzBQ3G zN7lT(HoSIZ?e%M)T>I)e&$?UIy}Lel{Wa^)u77_+?S{P@ZrE`1hRF@bHr&18!3~dW zNM3wwJT`vI_|fq@$L|?GF@Add%=p>y*T&!3$TsG0EZrF17~9yjacJY%#_^52Hy+%0 z{l+63k8ZqY*hN*AK(1&=AUkU zcJm9H-`M=#maHwsTRdATw={3*+p=iOsx4c#?B8vViR2x zLla{Y;}g3l4o+M@ab)7?#J49Nm^eN0?8GY*?`&h+^0$?43vY{U>)JN7ZEV~4w%ywf zZo7Wlk!?q}eS6yj+aBHa)VAlgy|V4CZRfUUZ?|vvZ?E0nwtepQk?rfYZ{NOu`!(Bd z+J1EVJ=-7N{?zuf+uzuJZb$wO&yLz1T{{--Shr*Mjw^TEwBzWGdv-j$L^MRd@?tE(Jb30$z`PR;JyRvuLcZGK~ z@0z=7Y}b}u`*&Tx>y}-2?s{O?qr0Bk_1vykcD=Rh-0tk%_TB#7wY%GP&)vOh_wLmmRq5x_z#Fw|u1SBYhuv?jtXJ zF^c)w?V?f$;~i}sK0AK$-s|H1v&?7wmUk^Q&szjOZs`ybu^)BVrxe`WuB zmuFp`e|hQUm6yjZZ@awj@}UFy2NoT;{=hv49zAgOqxO&Xee~6XBL|=USpLUWe(a8q z{pMqDUXgo6{T0ivxb=#2AGd#e?#I9V@v~PJUs-$Qz?G}6%Dw8zLqmr~4y`&gerWrl zy;s|>j$OUz>WQnbx%$4V&t9|pn)j}4y>>gKM-~c1nesH`R{$chiv7n)RF%w7b5fXg zhMH6O%0yk!;)3Z%-$WrD4J6Bop}L%>(tuIT3vVVKG}{1jIqT*Vp_EpbN!Z%*`Z{NK_X2?b5& zXb+D!l{oAsGyXZ8mVkw${I0DC}6WUpHOz3|DtmAd=nt6uZm6RHj0j7c;Dvib|oy+72VE;UUb(cut$XLbFverf;JL8%>`~xvX=zn;92Q zlqiZ}eXOw}WQiM^dz5&SPjT1_l~Ax=;Z>89-zqE%+HAqHLalzCKY#x7nGN^?4_gLH z^7~@kX0{gQ6>yS+!q3vsOaN>)Fq8#sWnr*z5~K&qXlw|gNaHGt8nV;|U_-%xVYK0= z<}O_&G7_^BP2>F5i*BtxW0C5+%h)q+34Afl5u^0vt{!WYYwe>0{_X1f9((` zr6_fu(rzdLE@SYB{OuIveU?pcOXg+fHxmF|*{E5Y-xT~b}qD2jhT7$;H zUzvPn@MB%d(kS<5WNB}I8gGtgj6ynRBH_#Xy^bUJJ0~)1#af0aWexI zMFjaGN&iMry;BUP8&?g2fQob;7QZ?QH5Z_4tq(wsg-}wcTOJV z=gM1#s;Y)s%C(w@6P1+-D(8N$wQ05f9q$=SZeDb%YN)lmycIWCK=p#E%C@%3sJ7wODsT$gAiXsjeDs4?4mP?zQvo zOK$a6=35*&`JU3^s>MZKXJN4`WDUj3zV)p+b(Jm{Z^7=Siac8|QtgV(t+hL9`s@6y z4HbnOH~d%FS5W4(XPa$KcTssDc_zo^^x5tHk^)}|mJdL*g5S-4CFE9^R0Fx*G})nZ zEh&a#jW&p$6;kZT-`A$L@CxND)^g+&@N2@lQKhvJ7&ZdKMgRzY1sf1+r~!+Tb9b5r zKWgpeyuud?SgnDWZ<{i2;lg=}az|{{+RYsuo7b+2b!Bb)^_5rtdK;84&K!7Fp?FsP zDLlu7TdN$w2qH0pNa$H7SP_=D<1C(;ho{mros!W-6M`+8inwFiBgbcbB0bZ?>-gh< zPa&&3g&CV5IZ3;tnwYN!sRE)e`1*TRV}=Q*8PhXI6L?@toL79p_leQbv1QA~KI#9& zgwj!SarM6LkL>Bbr2gWD!}N?!L?~UX^kcY*QxLHxG?7w9Vw2<(N1by9K6WF%Fo~~> zXd)42LY)hVYKuczgB%6B4|V?P(68`6-$Q?YMfbO)Ze;%npNN5#6OPTep!?H(jc0LR zuvn7q08}Dw2(3M`=9**BC^%sH175_j@R*Z2Q6OVh4fao;siU8NUsC4+aQY^ux@ zkxmszy`wZJXE3KIyXyq2gicq5QmG<<(Pu)!Sv&yj!49q@W^Bid?U*r%Boa6e!NVoK z$`P(EABfe5ue5O)X&A-~bs!TeWg5>Z160Z|kTP*oBW@a!UuEN>6r~b{0A`y8u!P_? zJz!4t&}<8pfU|RA>C%Z#r&doIOX{jB>r0HrlKRT3x)LMb)O+2|IdgVi*Q?c@B|}Y3 zLrXkr4SaV4$j7lZOst*g)+q3;%}52T4rz6Yf(1icX9g@Ez#Pkj)LH+{EB-{BpqE$3Am{l>^Ft6bH0vJcl3*H6CEd0vNLdFv@|1yfY|JuXE7_ozX&C zr>8+1QZWI!I0MLDYVb-iQ4DC3iiLY;_lC}`q1@6r_2u; z^J1?fz7cguA{JcbE5g=H>9p$RiKVa6tm>LFSn&;lFMof>4P26Spbrv}jpLB;?@ zBE8tGG-GQ92vp?9Yq0WOC~g^W@zNFCM> zeq_Xt=_ckgCm|F7Bth2|ffkr*f+bsE((uK}pYgz*Yu6r8zVg+Z5AhSpp+h$-4Dl>! z{GWyee(fpTz=%Psa*g(hOM%Q%Kovp&PYI`o7@!daGEiAa4TW-u6lCtjUEm!6D)A7I zib5>{bA@PgXqa;Va}Hq6Auz`S=2nfar{an1e_KE?CjVe?R<^F`4_6Is?pSxF^DCz2 zXsq4a(BZ9E7|Q1ND1Db?`@1h{?b^^ET(dSDY3QmC)wy#E^ZBPR1RrR<9{4B&PkxX* z6>vVFL@+fn9j){k*V$)JV$@cajq#E#s;+q#e&+%_T!IwKfKF26B)t-;WATy|QG!C- zA3A?6CD@c^0816v0-q$$2w3z;ufX34RsayG%+-twCrVUhuAH18x|e`7y>m}ncHUsdQVw|x2gb-nR;FBSe1LsqzFMJ%zpFBIxqorv_d#occw zt75&qF%+VS3eath;H_!)HN&l;b5v|bt7ryC4YULtJj6edJf@hEzrSDUIDGy2M=2_& z0k98%&jjEpXy@6dKyZ?0pMn8t6iXif%)vz&N)-w%_*~Q$0p;9=lb|p8NkBRXNCyFF zc(~B99^ea#j`d)|Zo!_)(`_UID>XbK#vLE3P>8NAKzL`Gu4jls-9K>(U@^e3AXF8i zuE5hy!mf~4Sc-T?jmEZWfbSYSfoyl|YvQX$jpQ4F&qm<05np8rOX5(%ZkCFCYoeu| zCxp2rd6^;Oy0fBxWn<&YzDRF--`uKsYZ@EZ%&VH)*WNoBi$-Hq@>}cbTB#@njSCt} zOYx^;xka(89*8fAyIlA)uo@qiR|M+o1OEE@jh)wKc>2gq>&IUlfAag zbgh<;PFHgkq1(TOxs$(iVv4_Xs)m&5FD0o}mY%gL*)VI}5+GSa9#f%>XXBz2r4mJG z<1iAYE0|<7M742iHLM7waQcwJ+eTQmGORR1(WyI$fkPF9oFeBSnKV@Aknu*2Uvi+6 z*U=0*17|ZjjE;(y3S~I?W8R%K@%Q;XS1MQD`1qm6!DbZLQAd=EIr-=n^BuxYQA1tYU--jIITv z9KrB@%->I%zMDC|*3|oo1-_90G`-uUKSX-B$kxH0xAbmhg9Nj&B(nwIq9q+u;(z2%En75(6!D9_tytm9C7vR;OLX0KgR>U^&eIx@+!jpRnwFyCO#ULzXT}Jlws#L~ABy_D!;2G}KD}(@#x3nNV;^7IvZOU=H3#kXU|DTXMeVZQ3Rig@Qz-6N zp>vdG=skU!;i&t;REemnVvvYxgYI7>`9m=@&A&v#8u@^{aYUN(eh?#DA7Sm_PyJDGY}5jX=(T*(=#K&w^aACV?mf<*#lCg^3k z>ZgYgQ>rS<9(4Dh*&`Nv5O@uNw#Yfwn5NkoGt+k+Xn&AHsUumRi`prkMNWM?Yb0b zoU#CbDZt{w{w}mfUJti#A@&TVKNrhG^8%B?<5Zl^IkmM56XZp&jt!SyS9f^9=uH#t z?GrbR`ucl2oJzjO7wjHuY#QwjR)#nBb~SH2ykf=Sjm>$bm0nB{%z^0R*PxGlOl}`M z)DQq}6c;c_5|eyTZd{w-9kD@F^pg&6Lth(^Pa+##Fn)MQ&uMU&f%ZHCOdd%LIZ^o& z*r9}8O>?W^i40`EzT!*!=JfA5vNUycS?l__(dfYH#&yc+$ch^`uKdL6`XeRr(XQsj zO|(@5JT1W-`Z0$*wt^gp((aJb-hAeQ!^)*$5gZMZW2nLya@fLuU<~R8s?dICj)ACOKG_ml!hf55 zj7O9IeiRQqawPeNN}o@FJ}cPmx)#sQN{d%&@`M_JHS+J2pip$5hP6Nj)@CT?y7TfB zLdUa65e0Zi9migoq+>hi*bX|DenaA)z7zk=~?acqk5x|1z_!s|wI!R6TuDJmBa^4&xcbJ7ve5dg$C({YfSr(Rmb7wurD1ya4AT z{)UE*@`j^FlfMM&lJD{C^Ig0t`80YCf_h)Vm|=F38mZB(>N~&Ch;;cNo)Q{7iu;mZ zGxfLBoBToC&&CEx-8RDVhEH9+&kXOJZsF6Gy}I+154`0AZ}}2$nGQ7wWlNktXo;;J z8ryIAoT19)_7xhA{;6@@{F;#!Ay?R4*jMz5R z$Ed;TLR27F7;y)QUvPt?Jdm6N@IR%}pkX`iS;QWIzYp|hK`BntpmauTc9*`z|Vf{m1rQf+Y4e7E1LoVxAfkrJ8Rd*{^X?s!1^jc8@kSj!`|P>I3V5 z(?VD+hiHQXTNEgs3@Y~G+5{;>_#{spa1Z*W4Qz*|AvgdI2Q&oo`(AKSWx7d=K~A)j zFYoHgRQ(F!#kYhqw7wy3PHb9GQ#m-^w(scC?T%=LM1rqXe7(a*FT?(>*d{JV-3(;r6Q8oQ;c86r4j9 z%(#lH5dfOXWOl?WrtQ5MmL^9>KReOUIdORD(!&#-mSAi6@$;7lJD1eeE$Iwub>oH` zR*u{--qJe$$&tuVU%XiP@A?t?dZb>h!JwpWc#Ys^IN>Vkz(@1|SZTVUk6;M6m1uAy z9is$r!%SgE5Sx*vADNzc_%RU;SrK3k7ZwE{z{JR%%pso0a>zj~y~mOir`QWN!NaDI zjkR^-f|?}@A2@Z(;-g2`IT|8mCBa(9gmT)^INGytMUo{l@y>7n+ypl5; zYyc~02e#7*7Q+M@QDT^N6cdWV7Y(~W5<{j)|fD_vt$%WiIacR*6+21{r1>`u?4Z( zg_{%e4#Y1lT@bZlVKok~9B!;zxT(2oZ=K>Sb!J;Uc7L$6w05|sb5)0@y5S0cD97rt z`72zm+M&+&l^xz-CBY3FjX1|jwr)Q;%cO3jv4R=94Vhw0+igIQ0sv&B2m~mI4si5e zKB>f>Jc>Ps!{;9t@&~y23Z7BMF4rv=(tpW%p&-Is;D_X?Bs<#F)J8C4mCo42$yAT5 z8hovQuNCmMO8Ba=oY0Fb+CsF%m9In=?p-jvcVXnHBZ3gA=7{4cxAg8@Qd_%ZXD|Pk zoFOAh%=u4AevD zhe`0k*Ts51puyqqYZxQ$`KAVxB1VV&=HyV3+7H%7 zrmqI_uh~LTxYx2i|G>?c?)@xC^9ygjiCg07EcFRwOZpz3TmWcjG4HWP2iO#U=c*>; z!9!lKX7(DMYhZ|dqxdG;BG8_r^FP`@7v@AL8h`Ejd!JI83H0dfO}&GB0B^$|7UKpf zb($b~{17Q*wqq55zj2aBn1N@QQ;&Lj^l35CzP_$`e1L&Q{FOn!GiMkXhnDFNcG;XffaH4 z;R;KpqWDz8Mh-5@P^wULl~I*` zIu_JmA{`4(!h%yWG}1tW(q7NT1)buoRMk|n@1&Ya5l2XqA+-Vze(C}K$yrN-DrO!G ziiCwFJ~iGTiYUL#P3bw4ifdUz^YZrcVDG9{SAEo*qZ~fm+uq(wMR_OrNXT0=v_76# zH>aYo#9h$$--)?%6DTxs76A>v2pUGDvgDNx5D%a*b*n^M6fK zb^j?%RgEVi0B0V&5dKp&ZXz+odkVGZP+p~z=1~?d*c`gJrfu_r>golX+iETj@dd>W znng*`_OLfRXG2HFhB>$p>oNpdh^w^l3!N59u`XrM6b(+gvxzZ;M{A(NSBx~T+#$Xz@Y)j^CR2vke61+j-JJ9BO;X>>G0%08zIxu%U<`bWEw#0m)y@J~vb@&P73z+@JOrBCtl zfDgQ;H4$wEFmUui;o&`<8pSlP==3M=%;~DFh}%kdb5&WyUBt)gn>5Oyx}hc>aD6(` zT3i;ukz%Y3GA^!$)=QC$F6?&JI?M$nh2ij}mrn9M2Uk|kZ!OO6nn4>fW+{kaHH-C9VK?bvY~5U!P~xPQ6LHf<%`8x3 zW0m-4Ztg$SG8$T3Kd)bLEe>i6$=_1#18Ys*U=7r`%4#WQy|&C%6R=ht{+ze^N^fvZ zb3@2WYb&;Hutu=jw@PaQc6*?vRILd&9J~Ka$pL@zurExt*y$9K8}<;z@JP8uR+55N z1-K$Rz5qOo@T8$Y)uMG2=nflI>(mc(!Iut**)@n|?hKIHWoC9MaUgJH#3r;g6(*41 zmY*rc(qO&2eK1-$X(%f9dc!u;B*e?{LQhFysAsG(`Oce;x=5)bR9pHsW~acD!`Q#W zF2@NicB72TA(a&JVQNG;#ocAGTtRdU)0f)-6q{q2uJ-8@RcEgIaCD!$oT$2AmkkB5 z6r~bHL^ePHH8dl}k&ZEfG!m1O`SEZ#PKCdkbSYQM>p0;`N&PBSEaqSZ*Ex9#tiUXo z7UnQ@kByF%V9!m=p%`<3Yab{q!yNqSIjBdx^f{=JZTcKkA)>Dr)xt#sxl(YX0uM;X zbI`#WCrT8Bm?g!yAD`j($hra8-YxUi?C9iD?((;)2ev_?bgsT*_HL5KLMLZAimJ zNE4Q76X|eP=}2!-cNp}B%#Ck>iE`rIg2WOmr4$B>0#fV%3I}8 z0FAe5mKpI^4X4Ck3&CFzbCKq+9~!c{9pENFx>Y~|Zt$;5xH$kf2jE5ycL_JbEm5O{ z6e6sqa9j;CQ#q~*jOh$l%KUc_iA-^j<#bksPE63*a6jgy`GU!`{19hVW(~O3R<+8L zbXv*`lSIr2&33vTN0GTmi!K4-1t7ctgjX=+>0y$YwoQn%eNBg>dQ!7%{+smuOzkbL z#gZ-PQAPm=vIU>j^?%Y^={RyJRyK~NLDwNWK)Sxk8YJ2Jfi~dZCkE99)cJR&zC$_| zbbbkg=|-UzI-Owzm_fu-jY7=`$eXD6*^sywo$W#bHDn&Dy4 z19Mezs;4o4;tpbhLL-SOQ^O&uHn9T1k#oTcXb)TEF_gQ(>5%bC#Ca!`(t)M|S6*?s zrKZW9J;`6i7L;Q6w9!~v(-r=i;HRbV4}2eUsb=3mh6!*J3O^-D7{p2nVkKeUfCfR1 zNBz8~+_=jJ!H`)fl%>o-OO2C6iB%$yA#EOH9)hQw6!09%8PY)>1uO#%P;@N#3ho8^ zicV@#K1JGx6ZTU`hG}1Ryh61g&a7BB6dqq{>NHo4Zyw(v9x~fG>sC_sR z+Z5y%Rar}{mVzRGqQ0TKqR3mZ)#Wa-+iV3zzC?XZPo>R6z6RKcfX_9`0nGC=rhqQP!hotjvpj(^~<=0%FRp>3vkLH%Ox*~ls_xSka^?c7Ud!V$ym~&N* zsW{YD`G=K>Lo;pF$_?bU8Xh|4^l*4vN3) zKbiHw5>b1$(2-(|8LkodxmByKo5z)$BT9A|RE+ld(E{Cc5jq8lQJ$~cEdr(Pg+I$`w&olD6TNc$?Z?&MC2a_r;EzArxdRah7g^5LY5o|F0;usew76d@p2 zUE(vi!i?w4Q0;UTTD^x(Lo^a?hv&oW^%(Eitc>2dMp=97y|-*t)_f78{RM9n#l`0& ze}FN+2iP=Y%rp0TbWqF~^FO}V6Q#W#()-P!6UV-@a`aobpZd~Q7w|)zB=?r+fK3o`x=A9jUQL|gh({fsOktFinaITI1nZzZ@_dn{#)PrZIXq$C(3$f%NJs|O zL*0jCf_8Kuchuc|3PK}M1Ne|jvYV4$--6h1T=giO+(G)jmqSURv!A%|p^0Y_vPE1 zxnB!aI?P<*CP!uHSgz9s6Ap8XrA+KTC_9)J{lZOHHLNR|ZKJGiD zym^k2e@}tUE_sT;FMdb-+k_~1Iz=dB{Ud-8;;^7KM$>JiS<{h>0@N*Zk{)~dFpCIA zSlWOcT_H>lKa>D35cy+>Eg&{nfFthEAXLL!D7sca4hPQ+0+=C<~*=0{H24Hw_YB2vXJjL)ubNbs{hy+F?+AADJhXDX9S|$8_vi zX6GQ-e_@u)PUn&lWzTHqPZp)_SNzy3q*$W|PGL|KD?xz5$qNikMnuVI2BHXxw4$1X zF|F;8%q0}Tj3VM6&4_YU_%S1G9x4~tndl7PxhfiTL(@;JO>FxS1xn8zJ(>6&o%f{# zIpkEs;*|MFD5IB55EQZy2A#kz{L11$hm*IqT+|&1bYIlc6<;15w?{3eB1c*AT3dZX zou#Xxrluj^P(61|bIYoMYSX}gH!xwhCX-6GwP=^Mw9qt<|7*@rL;WC~jgA4it8sR* zoZ&Pc0*TN>FcNDKFrhd#XIdwk5#^!A=wqG~l!An7;>Q%6FO?w*zp`qkq!ntP6?!2B zd(in$Y2lI9<-(H)`egTep%NwHh+&@US0~m)C$!^^Kx}+`+~2#dyM0gf7JJ+tsB`BX zJ$gP_uyR#%z=WLvKd>_$nm~BvMl?kk&7Iy6k)(WjSfzpa6YPyga zPfp;o{VX(AT$9g+bV54e77#VrGphESd6bsAQk;>hIoE=v)B>Ayv>xj;3UI>9CpZh` zNuYI_pxjQ_`bY?8ONkR1NZ{V2EF`4X> zW76u%JZOCqxr%UxQ*;`T$sz_oS_2@h0o+4|VUZtOb~=fi!rDETrCp63#B@3+1nv}e zddPu7OS=Q~YS3)8%&lKFz)iKtOlJLfHIkA+nrLBet%8DO$|R>j_xkGkWAXVeduO<| zuiBpLsxD7nWXH*UOMx+Ak6O!Yg-|N+4xM`Br>C=s5%F zwDBOLI=nERJ}>}R6$3i`s}`bYpwliOcWDvhJ&X8&I6iUnV)D4AU))x1 zt!S(8yZTz&27MK+nZKjocWhf!SGQO{GMKh9hCul?#**B%mo|9Wrt>#uj;EB@m5lq>9J zh0eGeDVLX)ZC1)QGg%;Xx`{+07%%dG;FQIS$u&y&5Fa^|e3X9wkLC2rO7j2<_CK5O zHo_R0gyh;KE5{vlMAhSCpQp8&_hr(?*e&zlKC}sc=V9o*cwi2|+~1QOV%6 zl0c%&@-izv%udNKx^ahY+_YQp3re*$l;#&!%@Qya{jyCX)Ht>!%jd!$xcc3SzD2(3>Xp}bq%EJdqc>|al zN!J1N9027Ffbs?;??@j7K#D*L-O`Ux8mAqjpUycrKV00_T8VfR%a$FhEfZU-avawD ze5)g;D*2$sEwp+D*HEgmO5+W%&Cl-t#UtT$)Op} zg0hqh%Hp-jd-#~LbR59-@Pm9m^!+?w^;TUby1`#Sp;8ecyVw9cLQ4Q3{Xhh%#1@E4 zoIj8ZB?q|A0b8LwQyN3jcgV@4RzNs}N80FyFqZto1U%q_!~;>G33xCO`hW)$@BrGR zEH9L8N;-#2oN3u8vl{%gA|9`x67FemyBm7KYR#XL%@y&nj8^e24Mxw~S40u?6tOBT z9pW~m{R_R1yeI|uf=pYoXg*91KRQvW=J69bDjvJ$nnTxI^KCUxMJW&P9e}r&cKHNH z16QNnOO3X*-9F;oHedlGlUSIVGmR`MBvyr~=mK!1Vknd0YT#F0i9*|>crCI!G4~05wOS6$G_NFJ2 z_wy@m&-WBLtmRJA{5i$GI_xQW& z+|^aJF;A>7Jg}kY5~JVijTXBCmNKQ%kZUb0wm2R3zNSJC!u{fA#n@5dkNJyR`%0Yd z5|_o6L#vwOy~53WsfdNHB})dI3j);idQl1;mXsE_uG$>XTOLY){EBYA5nMLSZyiaR#o->ZO(-pJxc(jjwn(l>TX1JHo3#Ohx^Wh7lSg>TO>+w>mF$B~~=1-ngxY+;} zq5e_!WeYH70mdv4+!hFK3j{Z5eEpPt*#f~$x*^43QTPFQ%AF!rMMe%nb>UGO%BxH2 zz=mpKHs3r~S$@=&59e~I$YS&N%;_>(0v>myB-c{VV9Ym|^K-4m+1~XMu3_-w5Z-hK zomff%Qoy9nsh?X=efq#2ph-`&gucJJB(rRziCE0qE%zzj3E7M@d*} z96f+*J$^$KoHNh7x3o6K2EIajr;WFeFr+ra6;ffQ1 zTE2{ItSp=W0)HXT5cy}w6GSqTxKR=6A|z7D2Rtb2;7P1Kc|`{y=vOj!M1$gtv-N5LqnkVEKm+Eat+ZCD05^HgaRdT6FGG$=${->B6Fmq70OMk zJoU?;9B6Oft!&K{gVOa(wCzG=@et?!>0|dS-XZ^_wDGW^n4s}8O^a8qr@`{8F zLQz30mxET~ct6zuY#T^EA0SaDVA6#v%0iE2WI}TZN(6=A;6fLln1Bl+iy}Qwf(>bH zPP9SgM4LO^)&)4V0bb3hdx7mf{HjY3S-*O9f>9scwwXa*-2}^S-L`2Gqr?FpK$CEo z0J8gVMK~m-`XAFp+%WEBR@ZL)x?K=#KL$Jig2l^gL9hcDUI$ue3Z3L_l6H)$vt*=r zRTC&q)mgAVnMu?J;PN_MjkzQ{P}f%e0gB9$G~rJO4C{)Gzs8+^Vbvyit-dsrPKkGg zxl_gbUF>B-lYcV961+L>8$uX$n@%)N#;%!+(ih8wLB z@DEmOR?f5k!r8i+?a2$Yr)F3(4C5aqZVlBaKFV+&sZI<>VUh_0tdumEM ztr>A2tQpZi^#oSP`{Mq!xW7p`Psf;Wf9%KdjT!Ap*`E42+Sg{Zr_}c6&^}_I`-}S+ z=nad~`6Ba>6@zoa&l7|N6G91s;x%WEnnecdAcR)3`(S5CRWuhQNm=UT2_Fl-wx^e= z8l|HzQ+;ontWj+fnD(|Iwz2vgxPsn_E81hDr<0{>6LN`mbmhhpvXYpwzlRib(%n$Q zUwQm-Jz3e&t}Z=^8NYMlJ}qV0yA#~6