Файл: Проектирование реализации операций бизнес-процесса «Транспортная доставка заказов»(Выбор комплекса задач автоматизации).pdf
Добавлен: 14.03.2024
Просмотров: 59
Скачиваний: 0
СОДЕРЖАНИЕ
1.1. Выбор комплекса задач автоматизации
1.2. Характеристика существующих бизнес-процессов
1.3. Характеристика документооборота, возникающего при решении задачи
1.4. Обоснование проектных решений по информационному обеспечению
1.5. Обоснование проектных решений по программному обеспечению
2.1. Информационная модель и её описание
2.2. Характеристика нормативно-справочной, входной и оперативной информации
2.3. Характеристика результатной информации
2.4. Общие положения (дерево функций и сценарий диалога)
2.5. Характеристика базы данных
2.6. Структурная схема пакета (дерево вызова программных модулей)
2.7 Описание программных модулей
2.8. Контрольный пример реализации проекта и его описание
ПРИЛОЖЕНИЯ
<?php
namespace WebLogist\DoctrineBundle\Entity;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\HttpFoundation\File\UploadedFile;
class Attachment extends AbstractEntity
{
const PUBLIC_PATH = 'www';
const UPLOAD_DIR = '/upload/attachments';
/** @var string */
protected $description;
/** @var UploadedFile */
protected $file;
/** @var string */
protected $name;
/** @var string */
protected $path;
/**
* @return string
*/
public function getDescription()
{
return $this->$description;
}
/**
* @return UploadedFile
*/
public function getFile()
{
return $this->file;
}
/**
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* @return string
*/
public function getPath()
{
return $this->path;
}
/**
* @param string $description
* @return $this
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* @param UploadedFile $file
* @return $this
*/
public function setFile(UploadedFile $file)
{
$this->file = $file;
return $this;
}
/**
* @param string $name
* @return $this
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* @param string $path
* @return $this
*/
public function setPath($path)
{
$this->path = $path;
return $this;
}
/**
* @return File|null
*/
public function upload()
{
if (is_null($this->file)) return null;
$this->name = $this->file->getClientOriginalName();
$basename = basename($this->name, $this->file->getClientOriginalExtension());
$path = $this->name;
$i = 1;
while (file_exists($this->getUploadRootDir() . '/' . $path)) {
$path = $basename . $i . '.' . $this->file->getClientOriginalExtension();
$i++;
}
$this->path = self::UPLOAD_DIR . '/' . $path;
return $this->file->move($this->getUploadRootDir(), $path);
}
protected function getUploadRootDir()
{
return __DIR__ . '/../../../../' . self::PUBLIC_PATH . self::UPLOAD_DIR;
}
}
<?php
namespace WebLogistik\DoctrineBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
class Comment extends AbstractEntity
{
/** @var ArrayCollection|Attachment[] */
protected $attachments;
/** @var User */
protected $author;
/** @var string */
protected $text;
public function __construct()
{
parent::__construct();
$this->attachments = new ArrayCollection();
}
/**
* @return ArrayCollection|Attachment[]
*/
public function getAttachments()
{
return $this->attachments;
}
/**
* @return User
*/
public function getAuthor()
{
return $this->author;
}
/**
* @return string
*/
public function getText()
{
return $this->text;
}
/**
* @param User $author
* @return $this
*/
public function setAuthor(User $author)
{
$this->author = $author;
return $this;
}
/**
* @param string $text
* @return $this
*/
public function setText($text)
{
$this->text = $text;
return $this;
}
}
<?php
namespace WebLogistik\SiteBundle\Controller;
use WebLogistik\SiteBundle\Form\LoginFormType;
use WebLogistik\SiteBundle\Form\UserRegisterFormType;
use WebLogistik\SiteBundle\Controller\InitializableController;
use WebLogistik\SiteBundle\Entity\Role;
use WebLogistik\SiteBundle\Entity\User;
use Sensio\Bundle\FrameworkExtraBundle\Configuration as Config;
use Symfony\Component\Form\FormError;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoder;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
lass SecurityController extends InitializableController
{
/**
* @return RedirectResponse|Response
* @Config\Route("/login", name = "site_security_login")
*/
public function loginAction()
{
if ($this->authChecker->isGranted(Role::USER)) return $this->redirectToRoute('site_general_index');
$error = null;
if ($this->request->attributes->has(Security::AUTHENTICATION_ERROR))
$error = $this->request->attributes->get(Security::AUTHENTICATION_ERROR);
else {
$error = $this->session->get(Security::AUTHENTICATION_ERROR, null);
$this->session->remove(Security::AUTHENTICATION_ERROR);
}
$form = $this->createForm(new LoginFormType(), new User());
if (!is_null($error))
$form->addError(new FormError('Неправильный логин или пароль'));
$this->forms = array(
'login' => $form->createView(),
'last_username' => $this->session->get(Security::LAST_USERNAME, null)
);
return $this->render('WebLogistikSiteBundle:General:login.html.twig');
}
/**
* @return RedirectResponse|Response
* @Config\Route("/register", name = "site_security_register")
*/
public function registerAction()
{
$user = new User();
$user->getRolesCollection()->add($this->getRepository('Role')->findOneByRole(Role::USER));
$form = $this->createForm(new UserRegisterFormType(), $user);
$form->handleRequest($this->request);
if ($form->isSubmitted() && $form->isValid()) {
$valid = true;
$samesname = $this->getRepository('User')->createQueryBuilder('u')
->select('COUNT(u.id) AS id')
->where('u.username = :username')
->setParameters(array('username' => $user->getUsername()))
->getQuery()->getSingleScalarResult();
if ($samesname > 0) {
$form->get('username')->addError(new FormError('Пользователь с таким именем уже существует.'));
$valid = false;
}
if (is_null($form->get('password')->getData())) {
$form->get('password')->addError(new FormError('Пожалуйста, укажите пароль пользователя.'));
$valid = false;
}
if (preg_match("/[а-я]/i", $form->get('username')->getData() )) {
$form->get('username')->addError(new FormError('В имени пользователя нельзя использовать кириллицу '));
$valid = false;
}
if ($valid) {
/** @var UserPasswordEncoder $encoder */
$encoder = $this->get('security.password_encoder');
$user->setSalt(User::generateSalt())
->setPassword($encoder->encodePassword($user, $user->getPassword()));
$this->manager->persist($user);
$this->manager->flush();
$token = new UsernamePasswordToken($user, null, 'user_provider', $user->getRoles());
$this->get('security.context')->setToken($token);
return $this->redirectToRoute('site_general_index');
}
}
$this->forms['user'] = $form->createView();
return $this->render('WebLogistikSiteBundle:General:register.html.twig');
}
/**
* @throws NotFoundHttpException
* @Config\Route("/login_check", name = "site_security_login_check")
*/
public function loginCheckAction()
{
throw $this->createNotFoundException();
}
/**
* @throws NotFoundHttpException
* @Config\Route("/logout", name = "site_security_logout")
*/
public function logoutAction()
{
throw $this->createNotFoundException();
}
/**
* @return RedirectResponse|Response
* @Config\Route("/profile", name = "site_security_profile")
*/
public function profileAction()
{
}
}
<?php
namespace WebLogistik\SiteBundle\Controller;
use WebLogistik\SystemBundle\Controller\InitializableController;
use WebLogistik\SystemBundle\Entity\City;
use WebLogistik\SystemBundle\Entity\FormFieldValue;
use WebLogistik\SystemBundle\Entity\FormHandler;
use WebLogistik\SystemBundle\Entity\Page;
use WebLogistik\SystemBundle\Entity\Project;
use WebLogistik\SystemBundle\Entity\Replacement;
use WebLogistik\SystemBundle\Entity\ReplacementDictionary;
use WebLogistik\SystemBundle\Entity\vkhunter;
use WebLogistik\SystemBundle\Entity\VkhunterMessagesline;
use WebLogistik\SystemBundle\Entity\Vkhunterusers;
use WebLogistik\SystemBundle\Entity\Vkhunterfriendsline;
use Sensio\Bundle\FrameworkExtraBundle\Configuration as Config;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\DomCrawler\Crawler;
class ApiController extends InitializableController
{
/**
* @param $code
* @param Project $project
* @param Page $page
* @return JsonResponse|RedirectResponse
* @Config\Route("/api/form-handler/{code}/{project}/{page}/handle-request", name = "site_api_formhandler_handle",
*requirements = {"code": "[0-9a-f]+", "project": "\d+", "page": "\d+"}
* )
* @config\ParamConverter("project", options = {"mapping": {"project": "id"}})
* @Config\ParamConverter("page", options = {"mapping": {"page": "id", "project": "project"}})
*/
//принятие данных обработчика форм
public function handleFormRequestAction($code, Project $project, Page $page)
{
if ($project->getOwner()->getCode() !== $code) throw $this->createNotFoundException();
//if ($project->getOwner()->getBalance() < 0) { return new Response();}
if ($this->request->query->has('hunter_form_id')) {
/** @var FormHandler $handler */
$handler = $this->getRepository('FormHandler')->createQueryBuilder('f')
->leftJoin('f.page', 'p')
->where('p = :page')
->andWhere('f.id = :id')
->setParameters(array('page' => $page, 'id' => $this->request->query->get('hunter_form_id')))
->getQuery()->getOneOrNullResult();
if (is_null($handler)) throw $this->createNotFoundException();
$response = new Response();
$response->headers->set('Content-Type', 'application/json');
$callback = $this->request->query->get('callback', 'hunter_formhandler_callback');
// $handlerid = $this->request->query->get('handlerid', 'hunter_form_id');
$values = array();
$empty = false;
$formfieldvalues='';
foreach ($handler->getFields() as $field) {
$value = trim($this->request->query->get($field->getName(), null, true));
if (empty($value)) { $empty = true; break; }
$values[$field->getName()] = $value;
if ($field->isEmail()){
$formemail=$value;
}
else {
$formfieldvalues = $formfieldvalues.$field->getCaption().': '.$value.', ';
}
}
if ($empty) {
$response->setContent(sprintf('%s(%s);', $callback, json_encode('validation')));
return $response;
}
$formfieldvalue = new FormFieldValue();
$formfieldvalue->setCaption($handler->getCaption());
$formfieldvalue->setForm($handler);
$formfieldvalue->setValue($formfieldvalues);
$formfieldvalue->setUtm($this->request->query->get('hunter_query', 'unknown'));
$ref=$this->request->query->get('refer', 'unknown');
if (strrpos($ref,"link.2gis.ru")) {$ref="link.2gis.ru";}
if (strrpos($ref,"yandex.ru") && (!(strrpos($ref,"?text=")))) {$ref="https://www.yandex.ru/";}
$formfieldvalue->setRef($ref);
if (isset($formemail)) {$formfieldvalue->setEmail($formemail);}
$this->manager->persist($formfieldvalue);
$this->manager->flush();
$amoaddclient=false;
$clientemailsend=false;
if ($handler->getAmocrm()) {
$Responseaccount = json_decode($out, true);
$account = $Responseaccount['response']['account'];
$need = array_flip(array('PHONE', 'EMAIL'));
$fields = array();
if (isset($account['custom_fields'], $account['custom_fields']['contacts'])) {
foreach ($account['custom_fields']['contacts'] as $custom_field)
if (is_array($custom_field) && isset($custom_field['id'])) {
if (isset($custom_field['code']) && isset($need[$custom_field['code']]))
$fields[$custom_field['code']] = (int)$custom_field['id'];
$diff = array_diff_key($need, $fields);
}
}
$custom_fields = isset($fields) ? $fields : false;
$contact = array(
'name' => $values[$handler->getAmocrmname()],
'tags' => $handler->getAmocrmtags(),
'custom_fields' => array(
array(
'id' => $custom_fields['PHONE'],
'values' => array(
array(
'value' => $values[$handler->getAmocrmphone()],
'enum' => 'MOB'
)
)
),
array(
'id' => $custom_fields['EMAIL'],
'values' => array(
array(
'value' => $values[$handler->getAmocrmemail()],
'enum' => 'WORK'
)
)
)
)
);
$set['request']['contacts']['add'][] = $contact;
$out = curl_exec($curl); #Инициируем запрос к API и сохраняем ответ в переменную
$code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
$code=(int)$code;
if (!($code!=200 && $code!=204)) {$amoaddclient = true;}
if ($amoaddclient && !is_null($handler->getAmocrmusertask())) {
$Responsecontact=json_decode($out, true);
$Responsecontact=$Responsecontact['response']['contacts']['add'];
foreach($Responsecontact as $v){
if(is_array($v)) {
$contactid = $v['id'];
$tasks['request']['tasks']['add'] = array(
array(
'element_id' => $contactid, #ID контакта
'element_type' => 1, #Показываем, что привязываем к контакту
'task_type' => 1, #Звонок
'text' => 'WebLogistiker: Обработать заявку с формы '.$handler->getCaption().' из проекта '.$project->getCaption(),
'responsible_user_id' => $handler->getAmocrmusertask(),
'complete_till' => '23:59'
));
}
}
/**
* @param $code
* @param Project $project
* @param Page $page
* @return Response
* @Config\Route("/api/form-handler/{code}/{project}/{page}", name = "site_api_formhandler",
*requirements = {"code": "[0-9a-f]+", "project": "\d+", "page": "\d+"}
* )
* @config\ParamConverter("project", options = {"mapping": {"project": "id"}})
* @Config\ParamConverter("page", options = {"mapping": {"page": "id", "project": "project"}})
*/
//Запрос на инициализацию обработчика форм
public function formHandlerAction($code, Project $project, Page $page)
{
if ($project->getOwner()->getCode() !== $code) throw $this->createNotFoundException();
if ($project->getOwner()->getBalance() < 0) { return new Response();}
if (!($page->isFormhandler())) { return new Response();}
$formHandlers = $this->getRepository('FormHandler')->createQueryBuilder('f')
->where('f.page = :page')
->setParameters(array('page' => $page))
->getQuery()->getResult();
$handlers = array();
/** @var FormHandler $form */
foreach ($formHandlers as $form) {
$handlers[] = array(
'id' => $form->getId(),
'selector' => $form->getSelector(),
'success_redirect' => $form->getSuccessRedirect(),
'error_redirect' => $form->getErrorRedirect(),
'ajax' => $form->getAjax(),
'ajaxsuccescolor'=>$form->getAjaxsuccescolor(),
'ajaxsuccesheader'=>$form->getAjaxsuccesheader(),
'ajaxsuccestext'=>$form->getAjaxsuccestext(),
'ajaxerrorcolor'=>$form->getAjaxerrorcolor(),
'ajaxerrorheader'=>$form->getAjaxerrorheader(),
'ajaxerrortext'=>$form->getAjaxerrortext()
);
}
$response = new Response($this->renderView('WebLogistikSiteBundle:api:form_handler.js.twig', array(
'action' => $this->generateUrl('site_api_formhandler_handle',
array('code' => $code, 'project' => $project->getId(), 'page' => $page->getId()),
UrlGeneratorInterface::ABSOLUTE_URL
),
'handlers' => json_encode($handlers)
)));
$response->headers->set('Content-Type', 'text/javascript');
return $response;
}
/**
* @param string $code
* @param Project $project
* @param Page $page
* @return Response
* @Config\Route("/api/replacement/{code}/{project}/{page}", name = "site_api_replacement",
*requirements = {"code": "[0-9a-f]+", "project": "\d+", "page": "\d+"}
* )
* @config\ParamConverter("project", options = {"mapping": {"project": "id"}})
* @Config\ParamConverter("page", options = {"mapping": {"page": "id", "project": "project"}})
*/
//инициализация замен
public function replacementAction($code, Project $project, Page $page)
{
if ($project->getOwner()->getCode() !== $code) throw $this->createNotFoundException();
if ($project->getOwner()->getBalance() < 0) { return new Response();}
if (!($page->isReplacement())) { return new Response();}
$cities = array();
/** @var City $city */
foreach ($project->getCities() as $city)
$cities[] = array(
'latitude' => $city->getLatitude(),
'longitude' => $city->getLongitude(),
'caption' => $city->getCaption(),
'ablative' => $city->getAblative(),
'accusative' => $city->getAccusative(),
'dative' => $city->getDative(),
'genitive' => $city->getGenitive(),
'prepositional' => $city->getPrepositional()
);
$mainReplacements = array();
$parameters = array();
$replacements = array();
/** @var ReplacementDictionary $dictionary */
foreach ($page->getReplacementDictionaries() as $dictionary) {
if ($dictionary->isWithParameter()) {
$parameter = $dictionary->getParameter();
$parameters[] = $parameter;
$selector = array('selector' => $dictionary->getSelector());
/** @var Replacement $replacement */
foreach ($dictionary->getReplacements() as $replacement) {
$selector['replacements'][$replacement->getPhrase()]['default'] = $replacement->getReplacement();
$selector['replacements'][$replacement->getPhrase()]['city'] = $replacement->getCityReplacement();
}
$replacements[$parameter][] = $selector;
}
else {
$mainReplacements[] = array(
'selector' => $dictionary->getSelector(),
'replacement' => $dictionary->getReplacement()
);
}
}
$response = new Response($this->renderView('WebLogistikSiteBundle:api:replacement.js.twig', array(
'cities' => json_encode($cities),
'main_replacements' => json_encode($mainReplacements),
'parameters' => json_encode($parameters),
'replacements' => json_encode($replacements)
)));
$response->headers->set('Content-Type', 'text/javascript');
return $response;
}