Диплом: Автоматизация продаж билетов на лекции в организации «Лекторий правое полушарие интроверта»

Внимание! Если размещение файла нарушает Ваши авторские права, то обязательно сообщите нам
88
}
self.pay()
}, myPurchase: myPurchase, arrayPromo: arrayPromo, getСode: getСode, invitationСode:
invitationСode)
}
func pay() {
DispatchQueue.main.async {
let docData: [String : Any] = [
"price": Int(self.totalCash),
"title": "Билет"]
self.payAction(dic: docData)
}
}
@objc fileprivate func goBack() {
cartApiClient.updateCartFromLocal(cartItems: localCart)
dismiss(animated: true, completion: nil)
}
func payAction(dic: [String: Any]) {
guard let price = dic["price"] as? Int, let name = dic["title"] as? String else { return }
token = nil
paymentMethodType = nil
payApi.settings.price = Decimal(integerLiteral: price)
payApi.settingsService.saveSettingsToStorage(settings: payApi.settings)
let amount = Amount(value: payApi.settings.price, currency: .rub)
DispatchQueue.main.async {
89
let tokenizationModuleInputData = TokenizationModuleInputData(clientApplicationKey:
"live_NjIwNjE0V4DSbWw-DKMZ4gkYGTuffhAeWXXP7lTAHf4", shopName: "Лекторий",
purchaseDescription: name, amount: amount, tokenizationSettings:
self.payApi.makeTokenizationSettings(), applePayMerchantIdentifier: self.applePayMerchantID,
customizationSettings: CustomizationSettings(mainScheme: UIColor(red:1.00, green:0.90, blue:0.00,
alpha:1.0)), savePaymentMethod: .userSelects)
let inputData: TokenizationFlow = .tokenization(tokenizationModuleInputData)
let viewController = TokenizationAssembly.makeModule(inputData: inputData,
moduleOutput: self)
self.present(viewController, animated: true, completion: nil)
}
}
fileprivate func updateResultView() {
let promo = UserDefaults.standard.string(forKey: "я15")
if self.promoCoreUsd.lowercased() == promo {
AlertDialog.showAlert("Ошибка", message: "Вы уже использовали этот промокод",
viewController: self)
}else{
if let c = localCart {
var totalCount = Int()
var totalPrice = Int()
var totalAmount = Int()
for mony in localCart! {
let itemPrice = mony.price
let itemQty = mony.count
let itemAmount = mony.count
totalAmount = itemPrice! * itemQty!
totalPrice = totalPrice + totalAmount
totalCount += itemAmount!
90
}
ticketCountLabel.text = "Количество: " + String(totalCount)
totalCash = Double(totalPrice)
self.totalPrice = totalPrice
salesValue = 0
switch totalCount {
case 0:
closeCartAndShowAlert()
break
case 3..<5:
salesLabel.isHidden = false
salesLabel.text = "Скидка \(10 + valueSales) %"
salesValue = 10
break
case 5...:
salesLabel.isHidden = false
salesLabel.text = "Скидка \(15 + valueSales) %"
salesValue = 15
break
default:
salesLabel.isHidden = true
}
if salesValue != 0 {
totalCash = (100.0 - (salesValue + Double(valueSales))) / 100 * totalCash
}else{
totalCash = (100.0 - Double(valueSales)) / 100 * totalCash
salesLabel.isHidden = false
salesLabel.text = "Скидка \(valueSales) %"
91
print(444444)
}
if Int(bonusCountTF.text ?? "0") ?? 0 <= bonus {
if Int(bonusCountTF.text ?? "0") ?? 0 <= Int(totalCash - 1) {
let cash = Int(totalCash) - (Int(bonusCountTF.text ?? "0") ?? 0)
totalCash = Double(cash)
self.usedBonus = Int(self.bonusCountTF.text!) ?? 0
}else if Int(bonusCountTF.text ?? "0") ?? 0 > Int(totalCash) {
AlertDialog.showAlert("Ошибка", message: "Вы не можете использовать больше
чем \(Int(totalCash - 1))", viewController: self)
}
}else{
AlertDialog.showAlert("Ошибка", message: "Вы не можете использовать больше чем
\(bonus)", viewController: self)
}
cashLabel.text = "Стоимость: " + String(Int(totalCash)) + " ₽"
} else {
closeCartAndShowAlert()
}
}
}
fileprivate func closeCartAndShowAlert() {
DispatchQueue.main.async {
self.localCart = nil
self.salesValue = 0
self.totalCash = 0.0
self.cartApiClient.updateCartFromLocal(cartItems: self.localCart)
92
let alert = UIAlertController(title: nil, message: "Корзина пуста", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ок", style: .default, handler: { action in
self.dismiss(animated: true, completion: nil)
}))
self.present(alert, animated: true, completion: nil)
}
}
fileprivate func configureCell(cell: CartCell, indexPath: IndexPath) {
let cart = self.localCart?[indexPath.row]
let itemCount = cart?.count ?? 0
cell.nameLabel.text = cart?.title
cell.priceLabel.text = "Цена: " + String(cart?.price ?? 0) + " ₽"
cell.countLabel.text = String(cart?.count ?? 0)
self.typeValue.append(cart?.type ?? "")
if cart?.type == "ПакетВидео" || cart?.type == "ВидеоКурс" || cart?.type == "Видео" {
cell.stackView.isHidden = true
}else{
cell.stackView.isHidden = false
}
if let imageUrl = cart?.imageUrl {
let url = URL(string: imageUrl)
cell.iconImageView.kf.setImage(with: url)
}
cell.minusActionHandler = {
if itemCount > 1 {
self.localCart?[indexPath.row].count = itemCount - 1
} else {
93
self.localCart?.remove(at: indexPath.row)
}
DispatchQueue.main.async {
self.tableView.reloadData()
self.updateResultView()
}
}
cell.plusActionHandler = {
self.localCart?[indexPath.row].count = itemCount + 1
DispatchQueue.main.async {
self.tableView.reloadData()
self.updateResultView()
}
}
}
@IBAction func applePayAction(_ sender: UIButton) {
PromoVoidObject.presentAlert(viewController: self, saleValue: { [weak self] (saleValue) in
guard let `self` = self else { return }
self.valueSales = saleValue
}, promoCoreUsd: { [weak self] (promoCore) in
guard let `self` = self else { return }
self.promoCoreUsd = promoCore
}, updateResultView: {
self.updateResultView()
}, pay: {
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
let promo = UserDefaults.standard.string(forKey: "я15")
94
if self.promoCoreUsd.lowercased() == promo {
AlertDialog.showAlert("Ошибка", message: "Вы уже использовали этот промокод",
viewController: self)
}else{
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
self.payApi.settings.price = Decimal(integerLiteral: Int(self.totalCash))
self.payApi.settingsService.saveSettingsToStorage(settings: self.payApi.settings)
if PKPaymentAuthorizationViewController.canMakePayments(usingNetworks:
self.paymentNetworks) {
let request = PKPaymentRequest()
request.merchantIdentifier = self.applePayMerchantID
request.supportedNetworks = self.paymentNetworks
request.merchantCapabilities = PKMerchantCapability.capability3DS
request.countryCode = "RU"
request.currencyCode = "RUB"
request.paymentSummaryItems = [
PKPaymentSummaryItem(label: "Лекторий", amount:
NSDecimalNumber(decimal: self.payApi.settings.price))
]
let applePayController = PKPaymentAuthorizationViewController(paymentRequest:
request)
applePayController?.delegate = self
//self.definesPresentationContext = true
self.present(applePayController!, animated: true, completion: nil)
} else{
AlertDialog.showAlert("Error", message: "Apple Pay is not available on this
device.", viewController: self)
}
}
}
}
95
}, myPurchase: myPurchase, arrayPromo: arrayPromo, getСode: getСode, invitationСode:
invitationСode)
}
}
extension CartViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 100
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return localCart?.count ?? 5
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) ->
UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cartCell", for: indexPath) as! CartCell
if localCart != nil {
cell.stopAnim()
configureCell(cell: cell, indexPath: indexPath)
}
return cell
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
96
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle,
forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
DispatchQueue.main.async {
self.localCart?.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .automatic)
self.updateResultView()
}
}
}
}
extension CartViewController: SuccessViewControllerDelegate, UNUserNotificationCenterDelegate
{
func didPressClose(on successViewController: SuccessViewController) {
if let it = self.localCart {
for item in it {
let current = UNUserNotificationCenter.current()
current.delegate = self
let content = UNMutableNotificationContent()
content.title = item.title!
content.body = "У Вас сегодня лекция, не забудьте прийти!"
content.sound = UNNotificationSound.default
content.badge = 1
let calendar = Calendar.current
let components = calendar.dateComponents([.hour, .minute, .day, .month, .year], from:
Date(timeIntervalSince1970: TimeInterval(Int(truncating: item.timestamp!) + 1*9*60*60)))
97
var dateCompo = DateComponents()
dateCompo.hour = components.hour
dateCompo.minute = components.minute
dateCompo.day = components.day
dateCompo.month = components.month
dateCompo.year = components.year
dateCompo.calendar = Calendar.current
let trigger = UNCalendarNotificationTrigger(dateMatching: dateCompo, repeats: false)
let request = UNNotificationRequest(identifier: "alarm-id", content: content, trigger:
trigger)
UNUserNotificationCenter.current().add(request)
}
}
cartApiClient.deleteAllCartItem() {[weak self] (action) in
guard let `self` = self else { return }
DispatchQueue.main.async {
self.dismiss(animated: true) {
if self.promoCoreUsd.lowercased() == "я15" {
UserDefaults.standard.set("я15", forKey: "я15")
}
self.localCart = nil
self.salesValue = 0
self.totalCash = 0
DispatchQueue.main.async {

Смотрите также:

"Автоматизация обработки заявок ООО "Проектно-Строительная Компания"
"Автоматизация процесса аттестации персонала для ООО "Нэт Бай Нэт Холдинг"
"Анализ интернет-активности конкурентов ( на примере конкурентов "Газпром нефть")
"Бухгалтерский учёт и аудит расчётов с подотчётними лицами в организации на примере ООО "ЛОЦ 10""
«Психологическое сопровождение персонала в организации на примере ООО «Крокус»
Agile-методология в управлении проектами на примере ООО «Ресурсный центр «Академия КлассИнфо»
Aвтoмaтизaция пpoцecca вeдeния инфopмaциoннoй бaзы o дoлжнocтяx и вaкaнcияx c укaзaниeм тpeбoвaний к уpoвню знaний и нaвыкoв кaндидaтoв для гpуппы кaдpoв вoйcкoвoй чacти 3474»
Cовершенствование деловой оценки персонала в организации (на примере ООО "Даймонд кейтеринг развитие")
Cовершенствование управления рентабельности предприятия (на примере гуипп «бендерская типография «полиграфист»)
Event - менеджмент: реализация проекта (на примере ООО "АГРОПАК")