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

Внимание! Если размещение файла нарушает Ваши авторские права, то обязательно сообщите нам
98
self.dismiss(animated: true, completion: {
if let appDelegate = AppDelegate.shared.rootTabBarController {
for i in self.typeValue {
if i == "Лекция" {
appDelegate.presentMyTicket()
}else{
appDelegate.presentFeed()
}
}
}
})
}
}
}
}
}
}
extension CartViewController: PKPaymentAuthorizationViewControllerDelegate {
func paymentAuthorizationViewController(_ controller: PKPaymentAuthorizationViewController,
didAuthorizePayment payment: PKPayment, completion: @escaping
((PKPaymentAuthorizationStatus) -> Void)) {
completion(PKPaymentAuthorizationStatus.success)
print(payment.token.transactionIdentifier)
let paymentData = String(data: payment.token.paymentData.base64EncodedData(), encoding:
.utf8)
99
let cartApiClient = CartApiClient()
let indKey = cartApiClient.generateIdempotenceKey()
let user = "620614"
let password = "live_WD1cxV5jClzAIXjnk0QWF01Gj0acxdKW6RtGt4zGQf4"
guard let credentialData = "\(user):\(password)".data(using: .utf8) else { return }
let base64Credentials = credentialData.base64EncodedString()
let headers: HTTPHeaders = [
"Authorization": "Basic \(base64Credentials)",
"Idempotence-Key": indKey,
"Content-Type": "application/json"
]
let param: [String: Any] = [
"amount": ["value":Int(self.totalCash), "currency": "RUB"],
"payment_method_data": ["type": "apple_pay", "payment_data": paymentData],
"capture": true,
"description": "Оплата заказа"
]
let status = PKPaymentAuthorizationStatus(rawValue: 0)!
switch status.rawValue {
case 0:
self.status = "approved"
//completion(PKPaymentAuthorizationStatus.success)
print(111)
sessionManager?.post(endpoint: NetworkEndpointType.payment.name, parameters: param,
headers: headers, completion: { (result, error) in
100
print(result ?? "")
print("Validation Successful")
if error != nil {
print(error!.localizedDescription)
//completion(PKPaymentAuthorizationStatus.failure)
}
if result != nil {
let responsee = result as! NSDictionary
let confirmation = responsee["payment_method"] as? [String : AnyObject]
let id = confirmation!["id"] as? String
self.id = id ?? ""
self.didAddMyPayment(self.id, true)
let storyBoard : UIStoryboard = UIStoryboard(name: "Success", bundle:nil)
let nextViewController = storyBoard.instantiateViewController(withIdentifier:
"successViewController") as! SuccessViewController
nextViewController.delegate = self
self.present(nextViewController, animated:true, completion:nil)
}else{
print(error!.localizedDescription)
//completion(PKPaymentAuthorizationStatus.failure)
}
})
default:
print(222)
self.status = "failed"
//completion(PKPaymentAuthorizationStatus.failure)
101
}
}
func paymentAuthorizationViewControllerDidFinish(_ controller:
PKPaymentAuthorizationViewController) {
controller.dismiss(animated: true, completion: nil)
print("DidFinish")
}
}
extension CartViewController: Themeable {
func applyTheme(_ theme: AppTheme) {
view.backgroundColor = theme.backgroundColor
tableView.backgroundColor = theme.backgroundColor
cashView.backgroundColor = theme.carcdBackView
salesLabel.textColor = theme.textColor
ticketCountLabel.textColor = theme.textColor
cashLabel.textColor = theme.textColor
bonusCountLabel.textColor = theme.textColor
bonusTitleLabel.textColor = theme.textColor
self.navigationController?.navigationBar.tintColor = theme.barForegroundColor
}
}
import YandexCheckoutPayments
import YandexCheckoutPaymentsApi
import Alamofire
102
import Firebase
import FirebaseFirestore
import FBSDKCoreKit
extension CartViewController: TokenizationModuleOutput {
func tokenizationModule(_ module: TokenizationModuleInput, didTokenize token: Tokens,
paymentMethodType: PaymentMethodType) {
self.token = token
self.paymentMethodType = paymentMethodType
let cartApiClient = CartApiClient()
let indKey = cartApiClient.generateIdempotenceKey()
let user = "620614"
let password = "live_WD1cxV5jClzAIXjnk0QWF01Gj0acxdKW6RtGt4zGQf4"
guard let credentialData = "\(user):\(password)".data(using: .utf8) else { return }
let base64Credentials = credentialData.base64EncodedString()
let headers: HTTPHeaders = [
"Authorization": "Basic \(base64Credentials)",
"Idempotence-Key": indKey,
"Content-Type": "application/json"
]
let param: [String: Any] = ["payment_token": token.paymentToken,
"amount": ["value":Int(self.totalCash), "currency": "RUB"],
"confirmation": ["type":"redirect", "enforce": false, "return_url":
"https://www.merchant-website.com/return_url"],
"capture": true,
103
"description": "Оплата заказа"
]
sessionManager?.post(endpoint: NetworkEndpointType.payment.name, parameters: param,
headers: headers, completion: { (result, error) in
print(result ?? "")
print("Validation Successful")
if result != nil {
let responsee = result as! NSDictionary
let confirmation = responsee["confirmation"] as? [String : AnyObject]
let requestUrl = confirmation!["confirmation_url"] as? String
self.id = responsee.object(forKey: "id") as! String
DispatchQueue.main.async {
module.start3dsProcess(requestUrl: requestUrl!)
}
self.didAddMyPayment(self.id, false)
}else{
print(error!.localizedDescription)
}
})
}
func didAddMyPayment(_ token: String, _ applePay: Bool) {
var ref: DocumentReference? = nil
let parameters: [String: String] = [AppEvents.ParameterName.currency.rawValue: "RUB"]
104
AppEvents.logEvent(.purchased, valueToSum: self.totalCash, parameters: parameters)
let docData: [String: Any] = [
"date": self.date!,
"uid": Auth.auth().currentUser!.uid,
"amount": Int(self.totalCash),
"total" : 0,
"token": token,
"type": "cart",
"apple_pay": applePay,
"currency": "RUB",
"bonus": self.usedBonus,
"paySystem": "yandex",
"status": "wait"]
ref =
self.db.collection("users").document(Auth.auth().currentUser!.uid).collection("my_newpay").addDoc
ument(data: docData) { (error) in
if let err = error {
print("Error adding document: \(err)")
} else {
print("Document added with ID: \(ref!.documentID)")
self.transactionId = ref!.documentID
if let it = self.localCart {
for i in it {
let docData: [String : Any] = [
"type": i.type ?? "",
"lectionId": i.lectionId ?? "",
"price": i.price ?? 0,
"count": i.count ?? 1,
"timestamp": i.timestamp ?? Date().timeIntervalSince1970,
"timestampStart": i.timestamp!,
"timesdate": i.timesdate ?? "",
105
"title": i.title ?? "",
"imageUrl": i.imageUrl ?? "",
"location": i.location ?? "",
"isVisited": i.isVisited ?? false,
"usageTicket": i.usageTicket ?? i.timestamp!,
"abstract": i.abstract ?? "",
"presentation": i.presentation ?? "",
"course": i.course ?? ""
]
self.db.collection("users").document(Auth.auth().currentUser!.uid).collection("my_newpay").docume
nt(ref!.documentID).collection("lections").addDocument(data: docData)
}
}
}
}
}
func didFinish(on module: TokenizationModuleInput, with error:
YandexCheckoutPaymentsError?) {
DispatchQueue.main.async { [weak self] in
guard let strongSelf = self else { return }
strongSelf.dismiss(animated: true)
}
}
func didSuccessfullyPassedCardSec(on module: TokenizationModuleInput) {
DispatchQueue.main.async { [weak self] in
guard let strongSelf = self else { return }
strongSelf.db.collection("users").document(Auth.auth().currentUser!.uid).collection("my_newpay").d
ocument(strongSelf.transactionId).addSnapshotListener { (snapshot, error) in
if snapshot != nil {
106
let status = snapshot!.get("status") as? String
print("=======================\(status)")
if status == "success" {
strongSelf.dismiss(animated: true, completion: {
let storyBoard : UIStoryboard = UIStoryboard(name: "Success", bundle:nil)
let nextViewController = storyBoard.instantiateViewController(withIdentifier:
"successViewController") as! SuccessViewController
nextViewController.delegate = self
strongSelf.present(nextViewController, animated:true, completion:nil)
})
return
}else if status == "wait" {
}else if status == "fail" {
let alertController = UIAlertController(title: nil, message: "При оплате произошла
ошибка, повторите попытку...", preferredStyle: .alert)
let action = UIAlertAction(title: "Ок", style: .default)
alertController.addAction(action)
strongSelf.dismiss(animated: true)
strongSelf.present(alertController, animated: true)
return
}
}
}
}
}
}
107
import UIKit
import Firebase
import FirebaseFirestore
class PromoVoidObject {
class func PromoVoid(arrayPromo: @escaping ([Promo]) -> (), invitationСode: @escaping (String)
-> (), myPurchase: @escaping (Bool) -> (), getСode: @escaping ([GetPromo]) -> ()) {
Firestore.firestore().collection("users").document(Auth.auth().currentUser!.uid).collection("my_purch
ase").getDocuments { (snapshot, error) in
if snapshot != nil {
if snapshot!.documents.count > 0 {
myPurchase(true)
}else{
myPurchase(false)
}
}
}
Firestore.firestore().collection("promoCodes").getDocuments { (snapshot, error) in
if snapshot != nil {
let promo = snapshot!.documents.compactMap({Promo(dictionary: $0.data())})
arrayPromo(promo)
}
}
Firestore.firestore().collection("users").document(Auth.auth().currentUser!.uid).getDocument {
(snapshot, error) in

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

"Автоматизация обработки заявок ООО "Проектно-Строительная Компания"
"Автоматизация процесса аттестации персонала для ООО "Нэт Бай Нэт Холдинг"
"Анализ интернет-активности конкурентов ( на примере конкурентов "Газпром нефть")
"Бухгалтерский учёт и аудит расчётов с подотчётними лицами в организации на примере ООО "ЛОЦ 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 - менеджмент: реализация проекта (на примере ООО "АГРОПАК")